@qitqode/qitqode-android-arm64 0.2.2 → 0.2.4
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/bun +2 -2
- package/bundle/{chunk-2hv2c8d5.js → chunk-0428v6mw.js} +1 -1
- package/bundle/{chunk-0f3ft9dh.js → chunk-05ck7acg.js} +1 -1
- package/bundle/{chunk-xmjntwjc.js → chunk-09geev0j.js} +2 -2
- package/bundle/{chunk-j5ymkhry.js → chunk-0cnwsf8p.js} +1 -1
- package/bundle/chunk-0ppnq3a4.js +2 -0
- package/bundle/{chunk-6kf4vw2g.js → chunk-0qd3567w.js} +1 -1
- package/bundle/{chunk-jw114bbt.js → chunk-0smnwqk6.js} +2 -2
- package/bundle/chunk-0te0vcdn.js +2 -0
- package/bundle/{chunk-q4fn41ex.js → chunk-0xrb12s8.js} +2 -2
- package/bundle/chunk-11h06z17.js +2 -0
- package/bundle/{chunk-vyh300ac.js → chunk-1rtx2zsc.js} +2 -2
- package/bundle/{chunk-3jms025t.js → chunk-1t0c86bz.js} +1 -1
- package/bundle/{chunk-6dfjtzqb.js → chunk-21rq4592.js} +2 -2
- package/bundle/{chunk-y3dfk6n5.js → chunk-24rkf2gk.js} +1 -1
- package/bundle/{chunk-rdwma0de.js → chunk-24ygjbpf.js} +2 -2
- package/bundle/{chunk-q46pzk9z.js → chunk-25ganjcn.js} +2 -2
- package/bundle/chunk-28yv4fqe.js +2 -0
- package/bundle/{chunk-3tmq81kq.js → chunk-2drzgtv3.js} +2 -2
- package/bundle/{chunk-xd3xc1vv.js → chunk-2md6sx8d.js} +1 -1
- package/bundle/chunk-2mm37s1w.js +2 -0
- package/bundle/chunk-2prf30p3.js +2 -0
- package/bundle/{chunk-v9rg0a8g.js → chunk-313zqzc1.js} +1 -1
- package/bundle/{chunk-zfd70p01.js → chunk-32j0q58h.js} +1 -1
- package/bundle/chunk-34a52hyr.js +2 -0
- package/bundle/{chunk-86jsqc7d.js → chunk-39z96pc6.js} +3 -3
- package/bundle/chunk-3hcr2bzt.js +2 -0
- package/bundle/{chunk-e6wp96vm.js → chunk-3jf3jhrs.js} +1 -1
- package/bundle/{chunk-4sxg9cgr.js → chunk-3kpse7zy.js} +1 -1
- package/bundle/chunk-3n3gb3vd.js +2 -0
- package/bundle/chunk-3sq60y9f.js +2 -0
- package/bundle/{chunk-2qwmrp16.js → chunk-3vvd7j14.js} +1 -1
- package/bundle/{chunk-h10wjk96.js → chunk-3zrr4n6k.js} +2 -2
- package/bundle/{chunk-rcyzqa3g.js → chunk-450fef7h.js} +2 -2
- package/bundle/{chunk-kxjrrdj0.js → chunk-45a4n21f.js} +1 -1
- package/bundle/{chunk-xny5ecn0.js → chunk-47k5jy1p.js} +2 -2
- package/bundle/{chunk-0gab4v98.js → chunk-48r70n4s.js} +1 -1
- package/bundle/chunk-49mbnqvc.js +2 -0
- package/bundle/{chunk-t9zbp2qw.js → chunk-4agaj51z.js} +1 -1
- package/bundle/chunk-4fr6kae9.js +2 -0
- package/bundle/chunk-4v2pzx22.js +2 -0
- package/bundle/chunk-516w1nc4.js +2 -0
- package/bundle/chunk-535nm66j.js +2 -0
- package/bundle/{chunk-1p6jjrea.js → chunk-55fcmswd.js} +2 -2
- package/bundle/{chunk-n7kqdqkh.js → chunk-55ykn8nz.js} +4 -4
- package/bundle/chunk-58dpxf8r.js +2 -0
- package/bundle/chunk-58w8c6c2.js +2 -0
- package/bundle/{chunk-as845ya4.js → chunk-5c2438af.js} +1 -1
- package/bundle/chunk-5kpxpm8e.js +2 -0
- package/bundle/chunk-5nm5s0h2.js +2 -0
- package/bundle/{chunk-07s30fpb.js → chunk-5nrc5rhh.js} +1 -1
- package/bundle/{chunk-jwph7tpc.js → chunk-5pwv2p3s.js} +1 -1
- package/bundle/{chunk-q5abwn50.js → chunk-5pzs51sp.js} +1 -1
- package/bundle/{chunk-r0s28gnb.js → chunk-5tky3csh.js} +1 -1
- package/bundle/{chunk-yajd975f.js → chunk-5w76kdjr.js} +1 -1
- package/bundle/{chunk-wcqfr8vr.js → chunk-5ysbwr4x.js} +1 -1
- package/bundle/{chunk-85xh72hk.js → chunk-5zkj5xv9.js} +2 -2
- package/bundle/chunk-620dpezx.js +5 -0
- package/bundle/{chunk-fgn83bs7.js → chunk-65bmsp2t.js} +1 -1
- package/bundle/{chunk-9jrxrjzt.js → chunk-68v3b6ns.js} +2 -2
- package/bundle/{chunk-7ntw4rrn.js → chunk-6ar91jvd.js} +1 -1
- package/bundle/{chunk-bbbh69ys.js → chunk-6evh2ke8.js} +1 -1
- package/bundle/{chunk-9bm9z52r.js → chunk-6fc3gw3e.js} +1 -1
- package/bundle/chunk-6gpf2bjs.js +2 -0
- package/bundle/{chunk-a2dz9nqh.js → chunk-6m9jb0s9.js} +2 -2
- package/bundle/{chunk-e374shb8.js → chunk-6pe60dsw.js} +2 -2
- package/bundle/{chunk-yvjke593.js → chunk-6scf311w.js} +1 -1
- package/bundle/{chunk-epa576pa.js → chunk-6v5867cy.js} +3 -3
- package/bundle/{chunk-5wwd40t3.js → chunk-70q8qcb2.js} +1 -1
- package/bundle/{chunk-pfkm3j8g.js → chunk-73r8bjjz.js} +2 -2
- package/bundle/{chunk-hs3vfhar.js → chunk-7bcm7gg1.js} +1 -1
- package/bundle/chunk-7bgzcpdw.js +2 -0
- package/bundle/{chunk-ezfzb8qc.js → chunk-7g66qc1v.js} +2 -2
- package/bundle/{chunk-fd7fmvyw.js → chunk-7hvf9dgx.js} +1 -1
- package/bundle/{chunk-7zc04q43.js → chunk-7j4qne3q.js} +2 -2
- package/bundle/chunk-7kjvcbwa.js +2 -0
- package/bundle/{chunk-6j339s7a.js → chunk-7mppvhv9.js} +2 -2
- package/bundle/{chunk-7z884mz2.js → chunk-7msfwk15.js} +2 -2
- package/bundle/{chunk-kmwy6c9g.js → chunk-7vmx8bg9.js} +2 -2
- package/bundle/{chunk-7njz51r4.js → chunk-7x6yrtzn.js} +1 -1
- package/bundle/{chunk-yhsnmpzv.js → chunk-7zx1ve4w.js} +1 -1
- package/bundle/{chunk-skv9ww0s.js → chunk-804vmbcd.js} +1 -1
- package/bundle/chunk-8jma2btf.js +2 -0
- package/bundle/{chunk-543pt030.js → chunk-8q38721t.js} +2 -2
- package/bundle/{chunk-kdcnder5.js → chunk-8wwdrwf2.js} +1 -1
- package/bundle/{chunk-4fk46ngj.js → chunk-920z7g7j.js} +1 -1
- package/bundle/chunk-93e0w75z.js +2 -0
- package/bundle/{chunk-pzefsndd.js → chunk-953pqp3w.js} +1 -1
- package/bundle/chunk-97gp818s.js +2 -0
- package/bundle/chunk-9epf2zbh.js +2 -0
- package/bundle/{chunk-4hd3v58j.js → chunk-9hz56z6a.js} +1 -1
- package/bundle/chunk-9pmmf4k1.js +2 -0
- package/bundle/chunk-9y03z65a.js +2 -0
- package/bundle/{chunk-rk2bk4s7.js → chunk-9zm6r55d.js} +2 -2
- package/bundle/{chunk-t1475j9f.js → chunk-a3edstpn.js} +1 -1
- package/bundle/{chunk-8d6e4jg7.js → chunk-ab4dq1bn.js} +2 -2
- package/bundle/{chunk-w7em72p8.js → chunk-ac7482n2.js} +2 -2
- package/bundle/chunk-agv04nt7.js +2 -0
- package/bundle/{chunk-sjreby6e.js → chunk-aj1sgq1d.js} +1 -1
- package/bundle/chunk-ak8e1nrf.js +2 -0
- package/bundle/{chunk-cbmwhvxw.js → chunk-at22twxx.js} +2 -2
- package/bundle/{chunk-frsd6e1h.js → chunk-avefgbjg.js} +2 -2
- package/bundle/chunk-b034nf8g.js +2 -0
- package/bundle/chunk-b2p54yka.js +2 -0
- package/bundle/{chunk-z2h1gxyx.js → chunk-bbng1cea.js} +1 -1
- package/bundle/{chunk-5az84brc.js → chunk-bd21p9zz.js} +2 -2
- package/bundle/chunk-be7smmar.js +2 -0
- package/bundle/chunk-bghqsh7r.js +2 -0
- package/bundle/{chunk-y4e7e42x.js → chunk-bne5w117.js} +4 -4
- package/bundle/{chunk-j3jqk62r.js → chunk-bqn6bqws.js} +1 -1
- package/bundle/chunk-bryx5cx9.js +2 -0
- package/bundle/{chunk-tge53d52.js → chunk-bwbqkfv0.js} +1 -1
- package/bundle/chunk-c13rrw41.js +2 -0
- package/bundle/chunk-c2kkv619.js +2 -0
- package/bundle/{chunk-64c8q9zg.js → chunk-c36p881g.js} +3 -3
- package/bundle/chunk-c5xj1y5v.js +2 -0
- package/bundle/{chunk-91z7azf7.js → chunk-cdja76vj.js} +1 -1
- package/bundle/{chunk-7ab3yw9j.js → chunk-ckb1y6gv.js} +2 -2
- package/bundle/chunk-ckpm4dvv.js +2 -0
- package/bundle/{chunk-732yr6qq.js → chunk-cmb62jkt.js} +2 -2
- package/bundle/chunk-ct8twng1.js +2 -0
- package/bundle/{chunk-s77qktcn.js → chunk-cx78hhbx.js} +2 -2
- package/bundle/{chunk-1q1cddy4.js → chunk-cz5vta94.js} +1 -1
- package/bundle/{chunk-fpm2vgz6.js → chunk-d0x5pbkm.js} +1 -1
- package/bundle/chunk-d38y7bvh.js +2 -0
- package/bundle/chunk-d5qgc18n.js +2 -0
- package/bundle/chunk-d6hxsfm6.js +2 -0
- package/bundle/{chunk-29zm623f.js → chunk-d6jhs818.js} +2 -2
- package/bundle/chunk-descb9jz.js +2 -0
- package/bundle/{chunk-ssdw9zre.js → chunk-dj1jen1p.js} +1 -1
- package/bundle/{chunk-mswx4k75.js → chunk-dnnkq5y4.js} +2 -2
- package/bundle/{chunk-6pcmv8vs.js → chunk-dnsh1v42.js} +2 -2
- package/bundle/chunk-dvr2b9r1.js +2 -0
- package/bundle/chunk-dwhjgd8j.js +2 -0
- package/bundle/{chunk-s0ty36qg.js → chunk-dxdggn90.js} +1 -1
- package/bundle/chunk-dypdyrmy.js +2 -0
- package/bundle/{chunk-w30b563s.js → chunk-e8p92vz4.js} +2 -2
- package/bundle/chunk-ea5fktnn.js +2 -0
- package/bundle/{chunk-t1jgx17a.js → chunk-eg3syjtv.js} +2 -2
- package/bundle/{chunk-2a9rzgk6.js → chunk-ehb4hd9c.js} +1 -1
- package/bundle/{chunk-9jsgs71h.js → chunk-ejqzcdcx.js} +1 -1
- package/bundle/{chunk-5t0w9ecw.js → chunk-et3804wr.js} +1 -1
- package/bundle/{chunk-yd8bzhv6.js → chunk-ezrqhqkp.js} +1 -1
- package/bundle/chunk-f0t7rryn.js +3 -0
- package/bundle/{chunk-p635phfw.js → chunk-f31yvp20.js} +1 -1
- package/bundle/chunk-f4mf6tpp.js +2 -0
- package/bundle/chunk-f97k17t8.js +2 -0
- package/bundle/{chunk-yx1h0b5v.js → chunk-faee8zgc.js} +1 -1
- package/bundle/{chunk-p9mj4zyk.js → chunk-ff548b0j.js} +2 -2
- package/bundle/{chunk-bgng3rdj.js → chunk-fhqfqd5v.js} +2 -2
- package/bundle/{chunk-zek5c15t.js → chunk-fjbv3jht.js} +1 -1
- package/bundle/{chunk-hq9bgnqb.js → chunk-g22e4gw7.js} +1 -1
- package/bundle/chunk-g26tersc.js +2 -0
- package/bundle/{chunk-s0ptrw0z.js → chunk-g3wvtyw3.js} +1 -1
- package/bundle/{chunk-x4pdpka8.js → chunk-g42krp0z.js} +1 -1
- package/bundle/chunk-g4ehhdzp.js +2 -0
- package/bundle/{chunk-a9y27zd2.js → chunk-gbkz04ke.js} +1 -1
- package/bundle/chunk-gd6qpdjw.js +2 -0
- package/bundle/chunk-gehn9fd9.js +2 -0
- package/bundle/{chunk-0zxwjsvz.js → chunk-ggxzf22k.js} +1 -1
- package/bundle/{chunk-45fyv9f1.js → chunk-grnjm8ev.js} +2 -2
- package/bundle/{chunk-kzvvvj79.js → chunk-gszvgz76.js} +2 -2
- package/bundle/{chunk-g3kd4957.js → chunk-gy21fw82.js} +2 -2
- package/bundle/{chunk-cbf1y12x.js → chunk-h62chdmw.js} +1 -1
- package/bundle/{chunk-c1g8n10t.js → chunk-ha1w0xzh.js} +1 -1
- package/bundle/{chunk-rpfhgncs.js → chunk-has2rz35.js} +1 -1
- package/bundle/{chunk-6f8qqbac.js → chunk-hg4039nz.js} +166 -205
- package/bundle/chunk-hhax4mxw.js +2 -0
- package/bundle/{chunk-087tnr8a.js → chunk-hwrrrbqd.js} +1 -1
- package/bundle/chunk-hz3h6e19.js +2 -0
- package/bundle/{chunk-yd2emszh.js → chunk-j0bwa5dk.js} +2 -2
- package/bundle/{chunk-9b4aqcde.js → chunk-j164q40b.js} +2 -2
- package/bundle/{chunk-et5dnymk.js → chunk-j4ad3mde.js} +2 -2
- package/bundle/{chunk-qhnpq5gb.js → chunk-j8fcfhr2.js} +2 -2
- package/bundle/chunk-j8nkz81m.js +7 -0
- package/bundle/{chunk-9ea1n338.js → chunk-j9h1sp4g.js} +2 -2
- package/bundle/{chunk-zcp0wx4j.js → chunk-jdx3jshm.js} +2 -2
- package/bundle/chunk-jebss7x8.js +2 -0
- package/bundle/{chunk-yrfq22a5.js → chunk-jg1ccs3j.js} +1 -1
- package/bundle/chunk-jqekpprn.js +3 -0
- package/bundle/{chunk-d307vb2d.js → chunk-jqk3v8d6.js} +1 -1
- package/bundle/chunk-jvkzdap1.js +2 -0
- package/bundle/{chunk-pp9neaaz.js → chunk-jww55nk9.js} +1 -1
- package/bundle/{chunk-fvy24yhq.js → chunk-k1nh5sd2.js} +1 -1
- package/bundle/chunk-k2g8346v.js +3 -0
- package/bundle/chunk-k2vsezeb.js +2 -0
- package/bundle/{chunk-wfggztm4.js → chunk-k4gsktts.js} +1 -1
- package/bundle/{chunk-qaz100ht.js → chunk-k5q9px67.js} +1 -1
- package/bundle/{chunk-mrn44msr.js → chunk-k6y2vw0d.js} +2 -2
- package/bundle/chunk-kg8fcv91.js +2 -0
- package/bundle/chunk-kgptyf7n.js +3 -0
- package/bundle/{chunk-b50t4jc5.js → chunk-khzzmyk2.js} +1 -1
- package/bundle/chunk-kjjjrjnb.js +2 -0
- package/bundle/{chunk-dbztxdea.js → chunk-kp6gh35c.js} +2 -2
- package/bundle/{chunk-g7k6ecb2.js → chunk-kqhczjf6.js} +1 -1
- package/bundle/{chunk-jvjq554f.js → chunk-ksme3gj1.js} +1 -1
- package/bundle/chunk-m5cfmhwh.js +2 -0
- package/bundle/{chunk-4v61ysex.js → chunk-m5dm7a1t.js} +1 -1
- package/bundle/{chunk-yr35q7q1.js → chunk-m7ganre7.js} +1 -1
- package/bundle/chunk-m7qxxbns.js +2 -0
- package/bundle/{chunk-y287zwkr.js → chunk-mh19kwzw.js} +1 -1
- package/bundle/{chunk-7my2231h.js → chunk-mhhtf0v3.js} +1 -1
- package/bundle/{chunk-grw4gg9j.js → chunk-mjjaezwq.js} +2 -2
- package/bundle/{chunk-03mbn7nj.js → chunk-mmjgf680.js} +2 -2
- package/bundle/{chunk-jv4th87b.js → chunk-mn9end71.js} +1 -1
- package/bundle/{chunk-3h49k2ck.js → chunk-n23d0q00.js} +1 -1
- package/bundle/{chunk-mpe8zxc0.js → chunk-n78f8hfk.js} +1 -1
- package/bundle/chunk-n8wg5h5p.js +2 -0
- package/bundle/{chunk-gr4bctqj.js → chunk-nj1ntakd.js} +2 -2
- package/bundle/{chunk-wdaf713t.js → chunk-nrat6ncm.js} +1 -1
- package/bundle/{chunk-rm5ntsvn.js → chunk-nty5z2cj.js} +1 -1
- package/bundle/{chunk-rp8asmq7.js → chunk-p169ee92.js} +1 -1
- package/bundle/{chunk-fbm6qczy.js → chunk-p4027t94.js} +1 -1
- package/bundle/{chunk-94qhpkfx.js → chunk-p54bzjtv.js} +1 -1
- package/bundle/{chunk-cp39f96a.js → chunk-p5be5ddp.js} +1 -1
- package/bundle/{chunk-ngvp6zc2.js → chunk-p6crzjtf.js} +2 -2
- package/bundle/chunk-p6hcj3kv.js +2 -0
- package/bundle/{chunk-p4ewy9xh.js → chunk-pb30kkbs.js} +6 -6
- package/bundle/chunk-pdjafjry.js +3 -0
- package/bundle/chunk-pexmns0j.js +2 -0
- package/bundle/{chunk-my3cswnp.js → chunk-ph8hn1wt.js} +2 -2
- package/bundle/chunk-pkn85169.js +2 -0
- package/bundle/{chunk-99148b1k.js → chunk-pmg53fdd.js} +1 -1
- package/bundle/{chunk-wf4x5cjc.js → chunk-pr7z5dj8.js} +1 -1
- package/bundle/chunk-pt603np4.js +2 -0
- package/bundle/{chunk-4mvg7jt1.js → chunk-ptqk1j2r.js} +1 -1
- package/bundle/{chunk-a92hh67a.js → chunk-pxm4qvqk.js} +2 -2
- package/bundle/{chunk-3qfpw8f6.js → chunk-qey1efpx.js} +1 -1
- package/bundle/chunk-qk5bfcv8.js +2 -0
- package/bundle/{chunk-9s785py4.js → chunk-qk9x8j8d.js} +1 -1
- package/bundle/chunk-qnaw8k98.js +2 -0
- package/bundle/{chunk-ks1cs80p.js → chunk-qnvsqnz5.js} +2 -2
- package/bundle/{chunk-bcx2vkv4.js → chunk-qp1n7kwe.js} +1 -1
- package/bundle/chunk-qr06byhp.js +2 -0
- package/bundle/{chunk-gtjn3yc4.js → chunk-qxcyz5hc.js} +2 -2
- package/bundle/{chunk-tj3rem3q.js → chunk-r5zy4za0.js} +2 -2
- package/bundle/chunk-r6p0bd2w.js +8251 -0
- package/bundle/chunk-r7sq3maz.js +2 -0
- package/bundle/{chunk-f83wv08n.js → chunk-r9w0thdk.js} +1 -1
- package/bundle/chunk-rmgs9nmj.js +2 -0
- package/bundle/{chunk-p887g1xj.js → chunk-rn83r0js.js} +1 -1
- package/bundle/{chunk-n90eh3e7.js → chunk-rrv0n73b.js} +1 -1
- package/bundle/chunk-rv08wm9j.js +2 -0
- package/bundle/chunk-rytavefg.js +2 -0
- package/bundle/{chunk-yz0pwv2m.js → chunk-s4vx9x1v.js} +1 -1
- package/bundle/{chunk-x2cavpa9.js → chunk-sfw5qddj.js} +1 -1
- package/bundle/chunk-sh9vjnsh.js +2 -0
- package/bundle/{chunk-6avjq7my.js → chunk-smznrv7k.js} +1 -1
- package/bundle/{chunk-vtw0wwch.js → chunk-snqa3zsm.js} +3 -3
- package/bundle/chunk-st0c5wwc.js +2 -0
- package/bundle/{chunk-vqss3e48.js → chunk-t0761rhq.js} +2 -2
- package/bundle/{chunk-vqpfpmha.js → chunk-t239rvej.js} +2 -2
- package/bundle/{chunk-5js6a6gf.js → chunk-t2n7vgsq.js} +1 -1
- package/bundle/chunk-t6yzrmww.js +2 -0
- package/bundle/{chunk-bggybm9k.js → chunk-t8c4cs6z.js} +1 -1
- package/bundle/chunk-teb3k2sf.js +2 -0
- package/bundle/{chunk-ve3np791.js → chunk-tg226j37.js} +1 -1
- package/bundle/chunk-thrfabyv.js +35 -0
- package/bundle/{chunk-73fz0cf4.js → chunk-tkrwcjkr.js} +2 -2
- package/bundle/{chunk-v5z6sx6j.js → chunk-tm34qp8j.js} +1 -1
- package/bundle/chunk-tr6rdr6h.js +4 -0
- package/bundle/chunk-ts798jvf.js +2 -0
- package/bundle/{chunk-a550vst5.js → chunk-twp3mjj0.js} +9 -9
- package/bundle/chunk-tx5aj02v.js +2 -0
- package/bundle/chunk-v1t51rrq.js +2 -0
- package/bundle/{chunk-vk88jj60.js → chunk-v3arcn10.js} +1 -1
- package/bundle/{chunk-e586sjb0.js → chunk-vcygx6hs.js} +2 -2
- package/bundle/{chunk-86yk21g4.js → chunk-venprxdp.js} +1 -1
- package/bundle/{chunk-ywkvq7zb.js → chunk-vf492zs6.js} +1 -1
- package/bundle/chunk-vh9ptqn0.js +2 -0
- package/bundle/{chunk-w79jzf8w.js → chunk-vnrjk2be.js} +1 -1
- package/bundle/{chunk-8q5ns61h.js → chunk-vshycswk.js} +1 -1
- package/bundle/{chunk-8e6gx3gg.js → chunk-vsz4s6zt.js} +1 -1
- package/bundle/{chunk-vhe92p7a.js → chunk-vygkwwjd.js} +2 -2
- package/bundle/{chunk-9rxyq6f9.js → chunk-w46g7kdq.js} +2 -2
- package/bundle/{chunk-q128vfc6.js → chunk-w4brava0.js} +1 -1
- package/bundle/{chunk-drwqag0f.js → chunk-w4synhfg.js} +1 -1
- package/bundle/chunk-w72rctxz.js +2 -0
- package/bundle/{chunk-h2bmss2m.js → chunk-w88ve2pm.js} +1 -1
- package/bundle/{chunk-mxhb5adq.js → chunk-w9gzfsy7.js} +2 -2
- package/bundle/chunk-wbw9zv3h.js +2 -0
- package/bundle/{chunk-1sfcxdbw.js → chunk-wkg3c643.js} +2 -2
- package/bundle/{chunk-2bgqy6z7.js → chunk-wwdpw27v.js} +1 -1
- package/bundle/{chunk-km1n4ttr.js → chunk-wy3a4cab.js} +1 -1
- package/bundle/{chunk-tczbhj0e.js → chunk-wyj8cpx5.js} +1 -1
- package/bundle/{chunk-3888asr7.js → chunk-x65xbskr.js} +1 -1
- package/bundle/chunk-x6mw98c2.js +2 -0
- package/bundle/chunk-x749e61j.js +2 -0
- package/bundle/{chunk-8rh0femq.js → chunk-xdd3553a.js} +1 -1
- package/bundle/{chunk-2jpmxt4v.js → chunk-xdteq9bd.js} +1 -1
- package/bundle/{chunk-9y15zjxa.js → chunk-xe69cnsk.js} +1 -1
- package/bundle/chunk-xpjhe9gz.js +2 -0
- package/bundle/{chunk-8v6x712g.js → chunk-xv5z1bj6.js} +2 -2
- package/bundle/{chunk-bk3z400e.js → chunk-y0527cg0.js} +1 -1
- package/bundle/{chunk-hrw5rmj1.js → chunk-y29ejqg2.js} +1 -1
- package/bundle/{chunk-42r7z6sq.js → chunk-y67kaj0b.js} +1 -1
- package/bundle/chunk-y6p57wgh.js +2 -0
- package/bundle/chunk-y6xs8v17.js +2 -0
- package/bundle/{chunk-zdzxsyxs.js → chunk-y7hgevfv.js} +2 -2
- package/bundle/{chunk-k1gddnkm.js → chunk-ybane1en.js} +1 -1
- package/bundle/{chunk-k6cbfrzc.js → chunk-yhj01dz9.js} +2 -2
- package/bundle/chunk-ym09zrxe.js +3 -0
- package/bundle/{chunk-2xqqkf86.js → chunk-ypdt9mmr.js} +2 -2
- package/bundle/chunk-ytetprwr.js +2 -0
- package/bundle/{chunk-vm1ek7yf.js → chunk-yz25607t.js} +1 -1
- package/bundle/{chunk-ypcc3cnb.js → chunk-z1932c3f.js} +1 -1
- package/bundle/chunk-z3xsfpc6.js +2 -0
- package/bundle/{chunk-6ypafpg8.js → chunk-z6sbjvtv.js} +1 -1
- package/bundle/{chunk-ta7mfkms.js → chunk-zc0cdvcv.js} +2 -2
- package/bundle/chunk-zn5pw733.js +2 -0
- package/bundle/chunk-ztn9e8g1.js +2 -0
- package/bundle/{chunk-ywdtp534.js → chunk-ztyy3ga3.js} +2 -2
- package/bundle/chunk-zxwvnmea.js +2 -0
- package/bundle/chunk-zzznad30.js +2 -0
- package/bundle/index.js +18 -18
- package/bundle/parser.worker.js +2 -2
- package/bundle/qffi-compat.so +0 -0
- package/bundle/qffi.node +0 -0
- package/bundle/worker.js +1 -1
- package/package.json +1 -1
- package/bundle/chunk-0cdtq1r3.js +0 -2
- package/bundle/chunk-0ych0f5w.js +0 -2
- package/bundle/chunk-0yjdatm6.js +0 -3
- package/bundle/chunk-0ykeedfm.js +0 -2
- package/bundle/chunk-22hr3ndh.js +0 -2
- package/bundle/chunk-23tyxyyj.js +0 -2
- package/bundle/chunk-2517cev8.js +0 -2
- package/bundle/chunk-28g1ndpx.js +0 -2
- package/bundle/chunk-2avxtbv3.js +0 -2
- package/bundle/chunk-2faah8w1.js +0 -2
- package/bundle/chunk-2qk0k2eb.js +0 -2
- package/bundle/chunk-3c3xzz0g.js +0 -3
- package/bundle/chunk-42wdfks8.js +0 -2
- package/bundle/chunk-44y6dffe.js +0 -2
- package/bundle/chunk-4f19vqxf.js +0 -2
- package/bundle/chunk-4m3k1atq.js +0 -2
- package/bundle/chunk-4n2ytddp.js +0 -2
- package/bundle/chunk-4yg42p6y.js +0 -2
- package/bundle/chunk-4zx3ze68.js +0 -2
- package/bundle/chunk-637sjdzq.js +0 -2
- package/bundle/chunk-6h8f89tt.js +0 -2
- package/bundle/chunk-6sjj203r.js +0 -2
- package/bundle/chunk-79aka9xe.js +0 -2
- package/bundle/chunk-7nqdhe7x.js +0 -2
- package/bundle/chunk-7q003wdd.js +0 -4
- package/bundle/chunk-7x88b2n2.js +0 -2
- package/bundle/chunk-8apeexas.js +0 -3
- package/bundle/chunk-8mthftwc.js +0 -2
- package/bundle/chunk-8wdara3b.js +0 -2
- package/bundle/chunk-8xhzpnph.js +0 -2
- package/bundle/chunk-96sqbyvf.js +0 -2
- package/bundle/chunk-9akz8w0d.js +0 -2
- package/bundle/chunk-9etpppyv.js +0 -3
- package/bundle/chunk-9pnpmtb2.js +0 -2
- package/bundle/chunk-a5pbvp1f.js +0 -7
- package/bundle/chunk-a7p0x4sw.js +0 -2
- package/bundle/chunk-ae0a496j.js +0 -2
- package/bundle/chunk-aq1j9y18.js +0 -2
- package/bundle/chunk-aq8nz9hp.js +0 -2
- package/bundle/chunk-b4zy78be.js +0 -2
- package/bundle/chunk-basjzwqp.js +0 -2
- package/bundle/chunk-bhetpmgq.js +0 -3
- package/bundle/chunk-bm7xpjh6.js +0 -2
- package/bundle/chunk-c1bw1q75.js +0 -2
- package/bundle/chunk-c2k556rk.js +0 -2
- package/bundle/chunk-c47vp7ne.js +0 -2
- package/bundle/chunk-cbhgf058.js +0 -2
- package/bundle/chunk-d41mg7at.js +0 -2
- package/bundle/chunk-d50kpss6.js +0 -2
- package/bundle/chunk-day0rb5p.js +0 -2
- package/bundle/chunk-dp7cww4v.js +0 -2
- package/bundle/chunk-dy31mchw.js +0 -3
- package/bundle/chunk-e5rda9mx.js +0 -2
- package/bundle/chunk-e999xtfj.js +0 -2
- package/bundle/chunk-ehfxypks.js +0 -7610
- package/bundle/chunk-eyr0vf92.js +0 -2
- package/bundle/chunk-gbmmbhy4.js +0 -2
- package/bundle/chunk-gp877cq5.js +0 -2
- package/bundle/chunk-h4f582d6.js +0 -2
- package/bundle/chunk-h57c6ne3.js +0 -2
- package/bundle/chunk-hk8vvc10.js +0 -2
- package/bundle/chunk-hnrqhcgq.js +0 -2
- package/bundle/chunk-hwavzxdm.js +0 -2
- package/bundle/chunk-hwnc2sa5.js +0 -2
- package/bundle/chunk-hy86wfad.js +0 -2
- package/bundle/chunk-j17421hz.js +0 -2
- package/bundle/chunk-j2gvpa15.js +0 -2
- package/bundle/chunk-j7n8khk7.js +0 -2
- package/bundle/chunk-jkh98wby.js +0 -2
- package/bundle/chunk-k5a652s4.js +0 -2
- package/bundle/chunk-k6w32q2p.js +0 -2
- package/bundle/chunk-kghwk0yh.js +0 -2
- package/bundle/chunk-kh8de8re.js +0 -2
- package/bundle/chunk-mce8aa9y.js +0 -2
- package/bundle/chunk-me1ja46g.js +0 -2
- package/bundle/chunk-mgadsp7r.js +0 -2
- package/bundle/chunk-n0k0pp4k.js +0 -2
- package/bundle/chunk-n393nnh5.js +0 -2
- package/bundle/chunk-n5vyed7w.js +0 -2
- package/bundle/chunk-pasm65wq.js +0 -2
- package/bundle/chunk-phpmxjf8.js +0 -2
- package/bundle/chunk-q2q3dmg3.js +0 -2
- package/bundle/chunk-qvzvxsjw.js +0 -2
- package/bundle/chunk-racrb1b3.js +0 -2
- package/bundle/chunk-s0c0t6qr.js +0 -5
- package/bundle/chunk-sghy9s7m.js +0 -2
- package/bundle/chunk-skpkjnyy.js +0 -2
- package/bundle/chunk-skxhg212.js +0 -2
- package/bundle/chunk-snt4kwab.js +0 -2
- package/bundle/chunk-sq47t8f1.js +0 -2
- package/bundle/chunk-sqhgnvvs.js +0 -2
- package/bundle/chunk-t114r59h.js +0 -2
- package/bundle/chunk-t1f56k0j.js +0 -2
- package/bundle/chunk-t69jx6fz.js +0 -2
- package/bundle/chunk-tsb3jsx4.js +0 -2
- package/bundle/chunk-ttpbpzbh.js +0 -2
- package/bundle/chunk-v667egp5.js +0 -2
- package/bundle/chunk-vrv67tt0.js +0 -2
- package/bundle/chunk-wcx7hc2p.js +0 -635
- package/bundle/chunk-wv8qx8sa.js +0 -2
- package/bundle/chunk-xxrtr6sd.js +0 -2
- package/bundle/chunk-y2ptjam9.js +0 -3
- package/bundle/chunk-y6h35v4a.js +0 -2
- package/bundle/chunk-y72p79v2.js +0 -2
- package/bundle/chunk-y8eggnrr.js +0 -2
- package/bundle/chunk-y9q0f9qz.js +0 -2
- package/bundle/chunk-yck5h49c.js +0 -2
package/bundle/chunk-wcx7hc2p.js
DELETED
|
@@ -1,635 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$g as sB,Ah as r4,Bh as A5,Ch as P$,Dh as H1,Eh as g4,Fh as i4,Gh as F7,Hh as $W,Ih as LJ,Jh as e9,Kh as K0,Lh as E2,Mh as M5,Nh as _5,Oh as R5,Ph as C5,Qh as U6,Rh as I5,Sh as n5,_g as G8,ah as j8,bh as o$,ch as rB,dh as CY,eh as z$,fh as y$,gh as cJ,hh as uJ,ih as Q7,jh as zY,kh as j1,mh as f5,oh as C6,ph as F1,rh as tB,th as G$,vh as BB,wh as eB,xh as Y$,zh as M0}from"./chunk-ehfxypks.js";import{Th as yQ}from"./chunk-9rxyq6f9.js";import{Li as R7}from"./chunk-a2dz9nqh.js";import{$j as O8,Ek as x5,Nj as p,Nk as L5,Oj as I$,Ok as y2,Qk as b5,Rk as U5,Sj as p8,Sk as U2,Uj as v9,Xj as s4,Yj as yZ,ak as R1,bk as P2,bl as lQ,ck as w2,cl as T6,dk as Y2,dl as _2,el as t8,fk as Q4,fl as H2,gk as J$,gl as n2,il as z2,jl as XW,kk as MJ,kl as o,lk as _J,ll as SY,nl as A2,ok as q0,ol as s9,pk as $1,pl as S6,qk as t0,ql as N7,rk as N5,rl as v2,sk as aZ,sl as l0,tk as sZ,tl as J2,uk as w5,ul as B2,yk as pK,zk as iK}from"./chunk-a550vst5.js";import{wl as ZW}from"./chunk-e374shb8.js";import{$l as lJ,Hl as Y7,Kl as DB,Ll as zZ,Ml as T0,Rl as q1,Ul as t2,Vl as u$,Wl as P8,Xl as k$,Yl as P5,am as M$,cm as S2,dm as d,em as RB,fm as D0,gm as iZ}from"./chunk-zcp0wx4j.js";import{im as s1,jm as r1,km as t1,nm as aJ,om as O2}from"./chunk-epa576pa.js";import{Lm as K1,Mm as Q0,Nm as Z8,Om as h4,Rm as j0,Tm as vQ,Zm as dQ,_m as mQ,an as tY,nn as eY,on as u8}from"./chunk-y287zwkr.js";import{Hn as aB}from"./chunk-vtw0wwch.js";import{$n as ZB,bo as XB}from"./chunk-e586sjb0.js";import{Xo as Z0}from"./chunk-8d6e4jg7.js";import{Ap as K$,Bp as aQ,Mp as t$,Np as gX}from"./chunk-my3cswnp.js";import{nq as xQ,oq as GQ}from"./chunk-4mvg7jt1.js";import{Hq as z6}from"./chunk-1sfcxdbw.js";import{Mq as _0,Rq as nB,Sq as t5}from"./chunk-s77qktcn.js";import{Uq as d0,Vq as Z7,Yq as X7}from"./chunk-8v6x712g.js";import{ir as j$,jr as SJ,pr as GZ,qr as TJ}from"./chunk-pfkm3j8g.js";import{Rr as P6,Wr as dB,Zr as g6}from"./chunk-h2bmss2m.js";import{_r as M4,cs as DJ}from"./chunk-ywdtp534.js";import{ds as IK}from"./chunk-03mbn7nj.js";import{rs as x2}from"./chunk-73fz0cf4.js";import{ts as D8}from"./chunk-0cdtq1r3.js";import{Es as b6,Ps as q5,us as U1,ys as D5}from"./chunk-xmjntwjc.js";import{Vs as d5,Ys as D$}from"./chunk-tj3rem3q.js";import{et as L0,nt as a}from"./chunk-7q003wdd.js";import{Dt as w$,qt as nJ,tt as EB,ut as s2,yt as B$}from"./chunk-cbmwhvxw.js";import{Et as N}from"./chunk-9etpppyv.js";import{$t as rX,Ft as KX,Ht as x,It as nX,Jt as D2,Kt as M2,Lt as S7,Mt as aX,Nt as u2,Ot as c,Pt as u,Qt as a2,Rt as R2,St as T7,Tt as h7,Ut as h2,Vt as I0,Wt as i,Xt as o2,Yt as HX,Zt as g7,_t as sX,au as F2}from"./chunk-9ea1n338.js";import{bu as iX,xu as O9}from"./chunk-ngvp6zc2.js";import{gz as $7,rz as _7}from"./chunk-1p6jjrea.js";import{$I as F6,AK as iJ,BB as j5,CF as vJ,EB as Y0,FI as e8,GE as l2,HF as dJ,OJ as F5,PJ as z5,QJ as y5,RJ as Y8,SB as Z2,TC as L6,TJ as o5,UG as OZ,VJ as J8,WE as _,YF as mJ,YG as FZ,YJ as p5,cE as W2,hK as p9,jE as i2,jK as i5,kK as B8,kO as p0,oK as c2,pF as y8,qE as T2,rC as O5,vF as fJ,xH as Q}from"./chunk-ks1cs80p.js";import{LO as V9,NO as b2,PO as H$,QO as iQ,RO as nQ}from"./chunk-f83wv08n.js";var z0={};b2(z0,{layer:()=>pZ,defaultLayer:()=>yW,SessionStatus:()=>z0,Service:()=>K6,Info:()=>oZ,Event:()=>P7});var oZ=N.union([N.object({type:N.literal("idle")}),N.object({type:N.literal("retry"),attempt:N.number(),message:N.string(),next:N.number()}),N.object({type:N.literal("busy"),message:N.string().optional()})]).meta({ref:"SessionStatus"}),P7={Status:O2.define("session.status",N.object({sessionID:P2.zod,status:oZ})),Idle:O2.define("session.idle",N.object({sessionID:P2.zod}))};class K6 extends Z2.Service()("@qitqode/SessionStatus"){}var pZ=_.effect(K6,Q.gen(function*(){let $=yield*p.Service,Z=yield*d.make(Q.fn("SessionStatus.state")(()=>Q.succeed(new Map))),X=Q.fn("SessionStatus.get")(function*(B){return(yield*d.get(Z)).get(B)??{type:"idle"}}),Y=Q.fn("SessionStatus.list")(function*(){return new Map(yield*d.get(Z))}),J=Q.fn("SessionStatus.set")(function*(B,W){let G=yield*d.get(Z);if(yield*$.publish(P7.Status,{sessionID:B,status:W}),W.type==="idle"){yield*$.publish(P7.Idle,{sessionID:B}),G.delete(B);return}G.set(B,W)});return K6.of({get:X,list:Y,set:J})})),yW=pZ.pipe(_.provide(p.layer));var y0={};b2(y0,{layer:()=>nZ,defaultLayer:()=>DW,SessionRunState:()=>y0,Service:()=>G6});class G6 extends Z2.Service()("@qitqode/SessionRunState"){}var H6=($,Z)=>`${$}:${Z}`,nZ=_.effect(G6,Q.gen(function*(){let $=yield*z0.Service,Z=d0.create({service:"SessionRunState"}),X=yield*d.make(Q.fn("SessionRunState.state")(function*(){let V=yield*l2.Scope,K=new Map;return yield*Q.addFinalizer(Q.fnUntraced(function*(){yield*Q.forEach(K.values(),(y)=>y.cancel,{concurrency:8,discard:!0}),K.clear()})),{runners:K,scope:V}})),Y=Q.fn("SessionRunState.runner")(function*(V,K,y){let j=H6(V,K),q=yield*d.get(X),z=q.runners.get(j);if(z)return z;let D=K==="main",U=iZ.make(q.scope,{label:j,onReentryWarn:(P)=>Z.warn("runner-reentry",P),onIdle:D?Q.gen(function*(){q.runners.delete(j),yield*$.set(V,{type:"idle"})}):Q.sync(()=>{q.runners.delete(j)}),onBusy:D?$.set(V,{type:"busy"}):Q.void,onInterrupt:y,busy:()=>{throw new N7(V)}});return q.runners.set(j,U),U}),J=Q.fn("SessionRunState.assertNotBusy")(function*(V){if((yield*d.get(X)).runners.get(H6(V,"main"))?.busy)throw new N7(V)}),B=Q.fn("SessionRunState.cancel")(function*(V){let K=H6(V,"main"),j=(yield*d.get(X)).runners.get(K);if(!j||!j.busy){yield*$.set(V,{type:"idle"});return}yield*j.cancel}),W=Q.fn("SessionRunState.cancelActor")(function*(V,K){let y=H6(V,K),q=(yield*d.get(X)).runners.get(y);if(!q||!q.busy)return;yield*q.cancel}),G=Q.fn("SessionRunState.ensureRunning")(function*(V,K,y,j){return yield*(yield*Y(V,K,y)).ensureRunning(j)}),H=Q.fn("SessionRunState.startShell")(function*(V,K,y){return yield*(yield*Y(V,"main",K)).startShell(y)});return G6.of({assertNotBusy:J,cancel:B,cancelActor:W,ensureRunning:G,startShell:H})})),DW=nZ.pipe(_.provide(z0.defaultLayer));var m0={};b2(m0,{startReminder:()=>PW,parseVerdictFromCompletion:()=>$5,layer:()=>rZ,defaultLayer:()=>NW,clearGoalIfCurrent:()=>tZ,bumpReactIfCurrent:()=>eZ,Verdict:()=>L1,Service:()=>O6,Goal:()=>m0,Event:()=>x1});var L1=N.object({ok:N.boolean(),impossible:N.boolean().optional(),reason:N.string()}),x1={Updated:O2.define("session.goal",N.object({sessionID:P2.zod,goal:N.object({condition:N.string()}).optional(),lastVerdict:L1.extend({attempt:N.number(),messageID:N.string().optional(),error:N.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
|
-
BEFORE reading the transcript, examine the condition itself for logical impossibility. If the condition is self-contradictory \u2014 it requires two things that cannot both be true at once (e.g. "the reply must contain the string X AND contain zero occurrences of the string X", "the value must be both greater than 5 and less than 3") \u2014 no transcript can ever satisfy it. In that case you MUST return {"ok": false, "impossible": true} immediately; returning plain {"ok": false} for a self-contradictory condition is wrong, because it forces endless futile retries.
|
|
12
|
-
|
|
13
|
-
Beyond self-contradiction, also use {"ok": false, "impossible": true} when the condition is genuinely unachievable in this session \u2014 for example: 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 the condition is achievable but unmet, return {"ok": false} without "impossible".`;function PW($){return U2({source:"goal",trust:"local-policy",body:[`A stop-condition goal has been set for this session: "${$}".`,"Start working toward it now.","An independent judge will review the transcript, and you will not be allowed to stop until it agrees the condition is genuinely met.","Do not consider the work finished until the goal is genuinely met or impossible."].join(`
|
|
14
|
-
`)})}var w7=($)=>`Based on the conversation transcript above, has the following stopping condition been satisfied? Answer based on transcript evidence only.
|
|
15
|
-
|
|
16
|
-
Condition: ${$}`;class O6 extends Z2.Service()("@qitqode/SessionGoal"){}var rZ=_.effect(O6,Q.gen(function*(){let $=yield*z2.Service,Z=yield*I$.Service,X=yield*B2.Service,Y=yield*p.Service,J=d0.create({service:"SessionGoal"}),B=yield*d.make(Q.fn("SessionGoal.state")(function*(){return{goals:new Map,generation:0}})),W=F6.makeUnsafe(1),G=Q.fn("SessionGoal.set")(function*(q,z){yield*W.withPermits(1)(Q.gen(function*(){let D=yield*d.get(B);D.generation+=1,D.goals.set(q,{condition:z,react:0,generation:D.generation}),yield*J.info("goal set",{sessionID:q,condition:z}),yield*Y.publish(x1.Updated,{sessionID:q,goal:{condition:z}})}))}),H=Q.fn("SessionGoal.get")(function*(q){return(yield*d.get(B)).goals.get(q)}),V=Q.fn("SessionGoal.clear")(function*(q,z){return yield*W.withPermits(1)(Q.gen(function*(){let D=yield*d.get(B);if(!tZ(D.goals,q,z))return!1;return yield*J.info("goal cleared",{sessionID:q}),yield*Y.publish(x1.Updated,{sessionID:q,goal:void 0}),!0}))}),K=Q.fn("SessionGoal.bumpReact")(function*(q,z){return yield*W.withPermits(1)(Q.gen(function*(){let D=yield*d.get(B);return eZ(D.goals,q,z)}))}),y=Q.fn("SessionGoal.commitVerdict")(function*(q){return yield*W.withPermits(1)(Q.gen(function*(){let z=yield*d.get(B),D=z.goals.get(q.sessionID);if(!D||D.generation!==q.expectedGeneration)return"stale";if(q.verdict.ok||q.verdict.impossible)return z.goals.delete(q.sessionID),yield*J.info("goal cleared",{sessionID:q.sessionID}),yield*Y.publish(x1.Updated,{sessionID:q.sessionID,goal:void 0,lastVerdict:{...q.verdict,attempt:D.react,messageID:q.judgedMessageID,error:q.verdict.judgeFailed?!0:void 0}}),"satisfied";if(D.react+=1,D.react>q.maxReact)return z.goals.delete(q.sessionID),yield*J.info("goal cleared",{sessionID:q.sessionID}),yield*Y.publish(x1.Updated,{sessionID:q.sessionID,goal:void 0,lastVerdict:{...q.verdict,attempt:D.react,messageID:q.judgedMessageID}}),"capped";return yield*Y.publish(x1.Updated,{sessionID:q.sessionID,goal:{condition:D.condition},lastVerdict:{...q.verdict,attempt:D.react,messageID:q.judgedMessageID}}),yield*q.reenter(D,D.react),"reentered"}))}),j=Q.fn("SessionGoal.evaluate")(function*(q){if(q.model.providerID==="qlex"){let E=q.msgs.slice(-20).map((w)=>{let A=w.parts.map((R)=>{let C=R;return C.type==="text"?String(C.text??""):""}).filter(Boolean).join(" ").slice(0,2000);return A?`${w.info.role}: ${A}`:null}).filter((w)=>w!==null).join(`
|
|
17
|
-
|
|
18
|
-
`);if(!E)return yield*Q.die(Error("goal judge: empty transcript \u2014 nothing to evaluate"));let L=`${j6}
|
|
19
|
-
|
|
20
|
-
${E}
|
|
21
|
-
|
|
22
|
-
${w7(q.condition)}`,S=yield*Q.promise(()=>Z0.resolveChatCompletion(L,{temperature:0,timeoutMs:20000}).then((w)=>({ok:!0,result:w}),(w)=>({ok:!1,error:w})));if(!S.ok)return yield*Q.die(Error(`goal judge chatCompletion failed: ${S.error instanceof Error?S.error.message:String(S.error)}`));let T=$5(S.result.content??"");if(!T)return yield*Q.die(Error(`goal judge returned a malformed verdict: ${String(S.result.content).slice(0,300)}`));return T}let z=yield*X.get(),D=yield*$.getModel(q.model.providerID,q.model.modelID),U=yield*$.getLanguage(D),P=z.experimental?.openTelemetry?Y0.getOrUndefined(yield*Q.serviceOption(z6)):void 0,F=yield*Z.get(q.model.providerID).pipe(Q.orDie),b=q.model.providerID==="openai"&&F?.type==="oauth",O=yield*o.toModelMessagesEffect(q.msgs,D),M=(E,L)=>typeof L==="string"&&L.length>500?`\xAB${L.length} chars: ${L.slice(0,200)}\u2026\xBB`:L,I=[...b?[]:[{role:"system",content:j6}],...O,{role:"user",content:w7(q.condition)}];if(a.enabled("DEBUG"))yield*J.debug("goal judge transcript",{condition:q.condition,messageCount:I.length,messages:JSON.stringify(I,M)});let k={experimental_telemetry:{isEnabled:z.experimental?.openTelemetry,tracer:P,metadata:{userId:z.username??"unknown"}},temperature:0,messages:[...b?[]:[{role:"system",content:j6}],...O,{role:"user",content:w7(q.condition)}],model:U,schema:L1};if(b)return yield*Q.promise(async()=>{let E=sZ({...k,providerOptions:n2.providerOptions(D,{instructions:j6,store:!1}),onError:()=>{}});for await(let L of E.fullStream)if(L.type==="error")throw L.error;return L1.parse(await E.object)});return yield*Q.promise(()=>aZ(k).then((E)=>L1.parse(E.object)))});return O6.of({set:G,get:H,clear:V,bumpReact:K,commitVerdict:y,evaluate:j})})),NW=rZ.pipe(_.provide(z2.defaultLayer),_.provide(I$.defaultLayer),_.provide(B2.defaultLayer),_.provide(p.layer));function tZ($,Z,X){let Y=$.get(Z);if(!Y)return!1;if(X!==void 0&&Y.generation!==X)return!1;return $.delete(Z),!0}function eZ($,Z,X){let Y=$.get(Z);if(!Y)return;if(X!==void 0&&Y.generation!==X)return;return Y.react+=1,Y.react}function $5($){try{let Z=$.match(/\{[\s\S]*\}/);if(!Z)return null;let X=L1.safeParse(JSON.parse(Z[0]));return X.success?X.data:null}catch{return null}}var c0={};b2(c0,{layer:()=>a5,defaultLayer:()=>dW,SessionProcessor:()=>c0,Service:()=>h6});var k2={};b2(k2,{subscribe:()=>Q5,jsonByteLength:()=>Y5,getInstallationID:()=>P6,ToolCall:()=>D6,ModelCall:()=>y6,Metrics:()=>k2,AgentRequest:()=>q6});var y6=O2.define("metrics.model_call",N.object({sessionID:N.string(),finish_reason:N.string(),ttft_ms:N.number().optional(),latency_ms:N.number(),cached_read_tokens:N.number(),model_id:N.string(),provider:N.string(),total_tokens_in:N.number(),total_tokens_out:N.number()})),D6=O2.define("metrics.tool_call",N.object({sessionID:N.string(),tool_name:N.string(),input_bytes:N.number(),output_bytes:N.number(),tool_call_id:N.string(),tool_call_status:N.enum(["success","error","cancelled"])})),q6=O2.define("metrics.agent_request",N.object({sessionID:N.string(),phase:N.string(),task_type:N.string(),surface:N.string(),total_tokens_in:N.number(),total_tokens_out:N.number(),files_changed:N.number(),validation_status:N.string()}));function Z5($,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 X5($){await fetch("https://telemetry.qitqode.com",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify($),signal:AbortSignal.timeout(60000)}).catch(()=>{})}var wW=!1;function x7($,Z,X){return X5([{H:Z5($,Z),B:X}])}var Q5=Q.fn("Metrics.subscribe")(function*(){if(!wW)return;yield*Q.promise(()=>P6().catch(()=>"")),yield*p.Service.use(($)=>Q.all([$.subscribeCallback(y6,(Z)=>{let X=Z.properties;return x7("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(D6,(Z)=>{let X=Z.properties;return x7("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(q6,(Z)=>{let X=Z.properties;return x7("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 Y5($){try{let Z=JSON.stringify($);if(typeof Z!=="string")return 0;return Buffer.byteLength(Z,"utf8")}catch{return 0}}var f2={};b2(f2,{persistentRetrySchedule:()=>k5,layer:()=>S5,isTransientCapacityError:()=>C7,hasToolCalls:()=>T5,defaultLayer:()=>IW,Service:()=>A6,OUTPUT_TOKEN_MAX:()=>_W,LLM:()=>f2});import b1 from"path";var V$={};b2(V$,{providerPromptName:()=>J5,providerPrompt:()=>xW,layer:()=>B5,defaultLayer:()=>bW,SystemPrompt:()=>V$,Service:()=>N6,CONCISE_RESPONSE_GUIDANCE:()=>LW});function J5($){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 xW($){let Z=await Z0.resolvePrompt(J5($));return Z?[Z]:[]}var LW=`# Response style
|
|
23
|
-
|
|
24
|
-
Default to concise, outcome-focused replies:
|
|
25
|
-
- Lead with the outcome: what is now true, what you changed, what is blocked.
|
|
26
|
-
- Report only the actions that matter to the user. Do not narrate routine internal work ("reading the file", "now I will search", "let me check").
|
|
27
|
-
- Give the answer you settled on. Do not enumerate every option, alternative, or caveat you considered.
|
|
28
|
-
- Keep progress updates to a single short line.
|
|
29
|
-
- No preamble, no restatement of the request, no closing summary that repeats what you just said.
|
|
30
|
-
- Prefer a short paragraph or a few bullets over a long structured report.
|
|
31
|
-
|
|
32
|
-
Exception: when the user explicitly asks for a detailed explanation, a plan, an analysis, a review, a walkthrough, or otherwise asks for more depth, give them that depth in full.`;class N6 extends Z2.Service()("@qitqode/SystemPrompt"){}var B5=_.effect(N6,Q.gen(function*(){let $=yield*z$.Service;return N6.of({environment(Z,X){let Y=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}`,"Precedence rule: the user's most recent message overrides earlier plans, goals, summaries, and reminders. Treat machine-generated context as guidance, not as new user instructions.","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: ${Y.vcs==="git"?"yes":"no"}`,` Platform: ${process.platform}`,` Today's date: ${new Date(X).toDateString()}`,"</env>"].join(`
|
|
33
|
-
`),"IMPORTANT: Your response must ALWAYS strictly follow the same major language as the user."]},skills:Q.fn("SystemPrompt.skills")(function*(Z){if(y2.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.",z$.fmt(X,{verbose:!0})].join(`
|
|
34
|
-
`)})})})),bW=B5.pipe(_.provide(z$.defaultLayer));var b7=2;function W5($){return $.toLowerCase().replace(/\s+/g," ").trim().split(" ").filter(Boolean)}function V5($,Z,X){if($.length<Z||X<2)return!1;let Y=new Map;for(let J=0;J<=$.length-Z;J++){let B=$.slice(J,J+Z).join("\x00"),W=(Y.get(B)??0)+1;if(W>=X)return!0;Y.set(B,W)}return!1}var L7=["write","write_file","edit","edit_file","question","bash","read","read_file","glob","grep"],UW=["tool_call","tool_use","function_call","function_calls","invoke_name","invoke"],AW="<\\/?[a-z][\\w-]*__[\\w-]+\\b[^>]*>",MW=new RegExp(`(?:<\\/?(?:${L7.join("|")})\\b[^>]*>|\\b(?:${L7.join("|")})\\s*=\\s*"[^"]*"|\\/(?:${L7.join("|")})\\b|<\\/?(?:${UW.join("|")})\\b[^>]*>|${AW})`,"i");function w6($){return MW.test($)}var K5=`# Tool invocation rules
|
|
35
|
-
|
|
36
|
-
Tools are ONLY invoked through the structured tool-calling interface of this API. NEVER write tool calls as plain text in your response:
|
|
37
|
-
- NEVER emit XML-style tags like <tool_call>, <invoke>, <function_call>, <toolname>, or namespaced tags like <agent__toolname> in your text output
|
|
38
|
-
- NEVER write pseudo-syntax like toolname="..." or /toolname as text
|
|
39
|
-
- Text like that is NEVER executed \u2014 the user just sees garbled output and nothing happens
|
|
40
|
-
If you want to use a tool, issue a real structured tool call. If no tool fits, answer in plain prose.`;class U7{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=W5(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&&w6(this.buffer))this.fakeToolTag=!0;return V5(this.tokens,this.n,this.threshold)||this.fakeToolTag}reset(){this.buffer="",this.tokens=[],this.fakeToolTag=!1}}function x6(){return{_tag:"TextNgramRepeat"}}function A7($){return typeof $==="object"&&$!==null&&"_tag"in $&&$._tag==="TextNgramRepeat"}function H5($){return U2({source:"recovery",trust:"runtime-safety",body:`
|
|
41
|
-
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.
|
|
42
|
-
|
|
43
|
-
STOP and retry with a different approach:
|
|
44
|
-
- Vary your wording and reasoning \u2014 do not reuse the same phrases
|
|
45
|
-
- 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.
|
|
46
|
-
- If you are blocked, explain what is blocking you instead of looping or faking a tool call
|
|
47
|
-
|
|
48
|
-
Do NOT output the same phrases again, and do NOT describe tool usage as inline text tags.
|
|
49
|
-
`})}var M7=U2({source:"recovery",trust:"runtime-safety",body:`
|
|
50
|
-
CRITICAL: You are STILL producing malformed output (repeated phrases or fake tool-call syntax written as plain text) after a recovery attempt.
|
|
51
|
-
|
|
52
|
-
You MUST completely replan before continuing:
|
|
53
|
-
1. Abandon your current approach entirely \u2014 it is stuck in repetition or fake tool-call text
|
|
54
|
-
2. Write out a NEW plan with different steps and a different strategy
|
|
55
|
-
3. State what you were trying to do, why it failed, and how your new plan differs
|
|
56
|
-
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
|
|
57
|
-
|
|
58
|
-
Do NOT continue the same line of reasoning, reuse the same wording, or fake a tool call as text.
|
|
59
|
-
`});var G5=a.create({service:"llm"}),_W=n2.OUTPUT_TOKEN_MAX;function C7($){if($ instanceof Error&&($.category==="stream_failed"||$.category==="stream_truncated"))return!1;return M5($)}var k5=y8.exponential(L6.millis(_5),R5).pipe(y8.modifyDelay(($,Z)=>{let X=L6.millis(C5);return Q.succeed(L6.isLessThanOrEqualTo(Z,X)?Z:X)}),y8.both(y8.recurs(U6)));function RW($,Z,X){let Y=b1.join(X,"projects",Z,"MEMORY.md"),J=b1.join(X,"sessions",$,"checkpoint.md"),B=b1.join(X,"sessions",$),W=b1.join(X,"global","MEMORY.md");return`# Memory system
|
|
60
|
-
|
|
61
|
-
You have a persistent file-based memory system. Four file types:
|
|
62
|
-
|
|
63
|
-
- Project memory at \`${Y}\` \u2014 persistent across all sessions in this project. Contains: project context, rules, architecture decisions, durable cross-task knowledge.
|
|
64
|
-
- 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.
|
|
65
|
-
- Per-task progress at \`${b1.join(B,"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.
|
|
66
|
-
- Global memory at \`${W}\` \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.
|
|
67
|
-
|
|
68
|
-
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.
|
|
69
|
-
|
|
70
|
-
## When to Edit MEMORY.md directly
|
|
71
|
-
|
|
72
|
-
You may Edit MEMORY.md when:
|
|
73
|
-
- User states a project-level rule that should hold across sessions \u2192 ## Rules
|
|
74
|
-
- User states a project-level architectural decision \u2192 ## Architecture decisions
|
|
75
|
-
- A clearly durable cross-session fact emerges that you want available immediately, before the next checkpoint \u2192 ## Discovered durable knowledge
|
|
76
|
-
|
|
77
|
-
These are exceptions, not the norm. The writer covers most extraction at checkpoint time.
|
|
78
|
-
|
|
79
|
-
## Notes scratchpad
|
|
80
|
-
|
|
81
|
-
You have a single legal scratchpad at \`${b1.join(B,"notes.md")}\`. Append entries to it when you want to record:
|
|
82
|
-
|
|
83
|
-
- A quote (from the user, an article, a known engineer) that has lasting value but isn't a task-specific decision
|
|
84
|
-
- An unresolved question \u2014 something you noticed but won't answer this turn
|
|
85
|
-
- A cross-project observation \u2014 "we did this in project X, similar pattern here"
|
|
86
|
-
- A note for future-self \u2014 context that would matter weeks later but doesn't fit any current task
|
|
87
|
-
|
|
88
|
-
Format each entry as:
|
|
89
|
-
## [turn N \xB7 YYYY-MM-DDTHH:MM:SSZ]
|
|
90
|
-
Free-form body. The writer reorganizes structured content at checkpoint time.
|
|
91
|
-
|
|
92
|
-
This is your ONLY legal scratchpad \u2014 don't create \`learning.md\`, \`scratch.md\`, or any other ad-hoc memory file.
|
|
93
|
-
|
|
94
|
-
## Subagent return format
|
|
95
|
-
|
|
96
|
-
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:
|
|
97
|
-
|
|
98
|
-
**Status**: success | partial | failed | blocked
|
|
99
|
-
**Summary**: <one-line description>
|
|
100
|
-
|
|
101
|
-
<deliverable body>
|
|
102
|
-
|
|
103
|
-
**Files touched**: <comma-separated paths or "(none)">
|
|
104
|
-
**Findings worth promoting**: <bullet list, or "(none)">
|
|
105
|
-
|
|
106
|
-
If your spawn prompt didn't include this format (e.g., explore/title/summary agents have their own contracts), follow whatever your prompt specifies.
|
|
107
|
-
|
|
108
|
-
## What NOT to do
|
|
109
|
-
|
|
110
|
-
- Don't Edit checkpoint.md \u2014 that's the writer's domain.
|
|
111
|
-
- Don't create memory files other than notes.md (no learning.md, no scratch.md). Use notes.md for any free-form entry.
|
|
112
|
-
- Don't ask the user about something memory may already record \u2014 search first via Grep / Read.
|
|
113
|
-
|
|
114
|
-
## Active recall protocol
|
|
115
|
-
|
|
116
|
-
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):
|
|
117
|
-
|
|
118
|
-
- checkpoint.md (full or budget-truncated)
|
|
119
|
-
- MEMORY.md (full or budget-truncated)
|
|
120
|
-
- notes.md (full or budget-truncated)
|
|
121
|
-
- global/MEMORY.md (full or budget-truncated)
|
|
122
|
-
|
|
123
|
-
If these dumps are visible in your context:
|
|
124
|
-
|
|
125
|
-
- Do NOT Read them again as whole files. The bytes are already in front of you.
|
|
126
|
-
- 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.
|
|
127
|
-
- 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.
|
|
128
|
-
|
|
129
|
-
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.
|
|
130
|
-
|
|
131
|
-
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.
|
|
132
|
-
|
|
133
|
-
Don't ask the user about something memory may already record.
|
|
134
|
-
`}class A6 extends Z2.Service()("@qitqode/LLM"){}var CW=_.effect(A6,Q.gen(function*(){let $=yield*I$.Service,Z=yield*B2.Service,X=yield*z2.Service,Y=yield*H2.Service,J=yield*y2.Service,B=yield*_2.Service,W=yield*y$.Service,G=Q.fn("LLM.buildSystemArray")(function*(K){let y=[],j=K.agentID?yield*B.isSystemSpawned(P2.make(K.sessionID),K.agentID):!1,q=K.agent.prompt?[K.agent.prompt]:yield*Q.promise(()=>V$.providerPrompt(K.model));if(y.push([...q,K5,...j?[]:[V$.CONCISE_RESPONSE_GUIDANCE],...K.system,...K.user.system?[K.user.system]:[]].filter((D)=>D).join(`
|
|
135
|
-
`)),!j){let D=A5()??P5.global;yield*Q.promise(()=>x5(D)).pipe(Q.ignore),y.push(RW(P2.make(K.sessionID),D,yield*W.root()))}let z=y[0];if(yield*Y.trigger("experimental.chat.system.transform",{sessionID:K.sessionID,model:K.model},{system:y}),y.length>2&&y[0]===z){let D=y.slice(1);y.length=0,y.push(z,D.join(`
|
|
136
|
-
`))}return y}),H=Q.fn("LLM.run")(function*(K){let y=G5.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??b5(K.agent));y.info("stream",{modelID:K.model.id,providerID:K.model.providerID});let[j,q,z,D]=yield*Q.all([X.getLanguage(K.model),Z.get(),X.getProvider(K.model.providerID),$.get(K.model.providerID)],{concurrency:"unbounded"}),U=z.id==="openai"&&D?.type==="oauth",P=K.prebuiltSystem??(yield*G({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]:{},b=K.small?n2.smallOptions(K.model):n2.options({model:K.model,sessionID:K.sessionID,providerOptions:z.options}),O=D5(b,b6(K.model.options),b6(K.agent.options),b6(F));if(U)O.instructions=P.join(`
|
|
137
|
-
`);let M=j instanceof R7,I=U?K.messages:M?K.messages:[...P.map((C)=>({role:"system",content:C})),...K.messages],k=yield*Y.trigger("chat.params",{sessionID:K.sessionID,agent:K.agent.name,model:K.model,provider:z,message:K.user},{temperature:K.model.capabilities.temperature?K.agent.temperature??n2.temperature(K.model):void 0,topP:K.agent.topP??n2.topP(K.model),topK:n2.topK(K.model),maxOutputTokens:K.model.providerID==="qlex"?void 0:n2.maxOutputTokens(K.model),options:O}),{headers:E}=yield*Y.trigger("chat.headers",{sessionID:K.sessionID,agent:K.agent.name,model:K.model,provider:z,message:K.user},{headers:{}}),L=kW(K);if((z.options?.litellmProxy===!0||K.model.providerID.toLowerCase().includes("litellm")||K.model.api.id.toLowerCase().includes("litellm")||K.model.providerID.includes("github-copilot"))&&Object.keys(L).length===0&&T5(K.messages))L._noop=t$({description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:K$({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:async()=>({output:"",title:"",metadata:{}})});if(j instanceof R7){let C=j;C.sessionID=K.sessionID,C.systemPrompt=P.join(`
|
|
138
|
-
`),C.toolExecutor=async(h,f,v)=>{let e=L[h];if(!e||!e.execute)return{result:"",error:`Unknown tool: ${h}`};try{let n=await e.execute(JSON.parse(f),{toolCallId:v,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 g=y2.merge(K.agent.permission??[],K.permission??[]);C.sessionPreapprovedTools=Object.keys(L).filter((h)=>{let f=g.findLast((v)=>q5.match(h,v.permission));return!f||f.action!=="ask"});let l=yield*D0.make(),m=new Set;C.approvalHandler=S2.bind(async(h)=>{let f=[...new Set(h.map((n)=>n.name))];if(f.every((n)=>m.has(n)))return{approved:!0};let v=L5.ascending(),e;try{e=p.subscribe(y2.Event.Replied,(G2)=>{if(G2.properties.requestID===v)G2.properties.reply});let n=h.map((G2)=>{try{let C2=JSON.parse(G2.args),t=C2?.title??C2?.name??"";return t?`${G2.name}: ${t}`:G2.name}catch{return G2.name}}),s=[...new Set(n)];await l.promise(J.ask({id:v,sessionID:P2.make(K.sessionID),permission:"workflow_tool_approval",patterns:s,metadata:{tools:h},always:s,ruleset:[]}));for(let G2 of f)m.add(G2);return C.sessionPreapprovedTools=[...C.sessionPreapprovedTools??[],...f],{approved:!0}}catch{return{approved:!1}}finally{e?.()}})}let T=q.experimental?.openTelemetry?j5(yield*Q.serviceOption(z6)):void 0,w=T?new Proxy(T,{get(C,g,l){if(g!=="startSpan")return Reflect.get(C,g,l);return(...m)=>{let h=C.startSpan(...m);return h.setAttribute("session.id",K.sessionID),h}}}):void 0,A=Date.now(),R=K.model.providerID==="qlex"?U5(K.agent,Object.keys(L)):void 0;return y.debug("streamText starting",{messageID:K.user.id,msgCount:I.length,toolCount:Object.keys(L).length,qortexPosture:R?.posture??null,qortexDirective:R?.directive??null}),N5({onError(C){y.debug("streamText error",{messageID:K.user.id,error:C instanceof Error?C.message:String(C),elapsedMs:Date.now()-A}),y.error("stream error",{error:C})},async experimental_repairToolCall(C){let g=C.toolCall.toolName.toLowerCase();if(g!==C.toolCall.toolName&&L[g])return y.info("repairing tool call",{tool:C.toolCall.toolName,repaired:g}),{...C.toolCall,toolName:g};return{...C.toolCall,input:JSON.stringify({tool:C.toolCall.toolName,error:C.error.message}),toolName:"invalid"}},temperature:k.temperature,topP:k.topP,topK:k.topK,providerOptions:n2.providerOptions(K.model,{...k.options,...R??{}}),activeTools:Object.keys(L).filter((C)=>C!=="invalid"),tools:L,toolChoice:K.toolChoice,maxOutputTokens:K.user.outputBudgetRecoveryTokens??k.maxOutputTokens,abortSignal:K.abort,headers:{"x-session-affinity":K.sessionID,...K.parentSessionID?{"x-parent-session-id":K.parentSessionID}:{},...K.model.headers,...E,"User-Agent":`qitqode/${U1}`},maxRetries:K.model.providerID==="qlex"?0:K.retries??2,messages:I,model:w5({model:j,middleware:[{specificationVersion:"v3",async transformParams(C){if(C.type==="stream")C.params.prompt=n2.message(C.params.prompt,K.model,O);return C.params}}]}),experimental_telemetry:{isEnabled:q.experimental?.openTelemetry,functionId:"session.llm",tracer:w,metadata:{userId:q.username??"unknown",sessionId:K.sessionID}}})}),V=(K)=>y5(z5(Q.gen(function*(){let y=yield*Q.acquireRelease(Q.sync(()=>new AbortController),(U)=>Q.sync(()=>U.abort())),j=yield*_7.make(0),q=(U,P)=>Q.gen(function*(){if(G5.debug("retry attempt",{sessionID:K.sessionID,messageID:K.user.id,attempt:P,reason:U instanceof Error?U.message:String(U)}),P>U6)return;let F=I5(P);yield*Q.promise(()=>p.publish(A2.RetryAttempt,{sessionID:P2.make(K.sessionID),messageID:K.user.id,attempt:P,maxAttempts:U6,reason:U instanceof Error?U.message:String(U),nextDelayMs:F}))}),D=yield*H({...K,abort:y.signal}).pipe(Q.tapError((U)=>{if(!C7(U))return Q.void;return _7.updateAndGet(j,(P)=>P+1).pipe(Q.flatMap((P)=>q(U,P)))})).pipe(Q.retry({while:C7,schedule:k5}));return F5(D.fullStream,(U)=>U instanceof Error?U:Error(String(U)))})));return A6.of({stream:V,buildSystemArray:G})})),S5=CW.pipe(_.provide(y2.defaultLayer)),IW=_.suspend(()=>S5.pipe(_.provide(I$.defaultLayer),_.provide(B2.defaultLayer),_.provide(z2.defaultLayer),_.provide(H2.defaultLayer),_.provide(_2.defaultLayer),_.provide(y$.defaultLayer)));function kW($){let Z=y2.disabled(Object.keys($.tools),y2.merge($.agent.permission,$.permission??[]));return O5.filter($.tools,(X,Y)=>$.user.tools?.[Y]!==!1&&!Z.has(Y))}function T5($){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 P0={};b2(P0,{layer:()=>h5,defaultLayer:()=>TW,SessionSummary:()=>P0,Service:()=>_6,DiffInput:()=>hW});function M6($){return{additions:$.reduce((Z,X)=>Z+X.additions,0),deletions:$.reduce((Z,X)=>Z+X.deletions,0),files:$.length}}function SW($){if(!$.startsWith('"'))return $;if(!$.endsWith('"'))return $;let Z=$.slice(1,-1),X=[];for(let Y=0;Y<Z.length;Y++){let J=Z[Y];if(J!=="\\"){X.push(J.charCodeAt(0));continue}let B=Z[Y+1];if(!B){X.push(92);continue}if(B>="0"&&B<="7"){let H=Z.slice(Y+1,Y+4).match(/^[0-7]{1,3}/);if(!H){X.push(B.charCodeAt(0)),Y++;continue}X.push(parseInt(H[0],8)),Y+=H[0].length;continue}let W=B==="n"?`
|
|
139
|
-
`:B==="r"?"\r":B==="t"?"\t":B==="b"?"\b":B==="f"?"\f":B==="v"?"\v":B==="\\"||B==='"'?B:void 0;X.push((W??B).charCodeAt(0)),Y++}return Buffer.from(X).toString()}class _6 extends Z2.Service()("@qitqode/SessionSummary"){}var h5=_.effect(_6,Q.gen(function*(){let $=yield*v2,Z=yield*q0.Service,X=yield*k$.Service,Y=yield*p.Service,J=Q.fn("SessionSummary.computeDiff")(function*(G){let H,V;for(let K of G.messages){if(!H){for(let y of K.parts)if(y.type==="step-start"&&y.snapshot){H=y.snapshot;break}}for(let y of K.parts)if(y.type==="step-finish"&&y.snapshot)V=y.snapshot}if(H&&V)return yield*Z.diffFull(H,V);return[]}),B=Q.fn("SessionSummary.summarize")(function*(G){let H=yield*$.messages({sessionID:G.sessionID,agentID:"main"});if(!H.length)return;let V=yield*J({messages:H});yield*$.setSummary({sessionID:G.sessionID,summary:M6(V)}),yield*X.write(["session_diff",G.sessionID],V).pipe(Q.ignore),yield*Y.publish(A2.Diff,{sessionID:G.sessionID,diff:V});let K=H.filter((q)=>q.info.id===G.messageID||q.info.role==="assistant"&&q.info.parentID===G.messageID),y=K.find((q)=>q.info.id===G.messageID);if(!y||y.info.role!=="user")return;let j=yield*J({messages:K});y.info.summary={...y.info.summary,diffs:j},yield*$.updateMessage(y.info)}),W=Q.fn("SessionSummary.diff")(function*(G){let H=yield*X.read(["session_diff",G.sessionID]).pipe(Q.catch(()=>Q.succeed([]))),V=H.map((y)=>{let j=SW(y.file);if(j===y.file)return y;return{...y,file:j}});if(V.some((y,j)=>y.file!==H[j]?.file))yield*X.write(["session_diff",G.sessionID],V).pipe(Q.ignore);return V});return _6.of({summarize:B,diff:W,computeDiff:J})})),TW=_.suspend(()=>h5.pipe(_.provide(l0),_.provide(q0.defaultLayer),_.provide(k$.defaultLayer),_.provide(p.layer))),hW=N.object({sessionID:P2.zod,messageID:w2.zod.optional()});function R6(){return new U7(L0.QITQODE_TEXT_NGRAM_N,L0.QITQODE_TEXT_REPEAT_THRESHOLD,L0.QITQODE_TEXT_WINDOW_TOKENS)}var g5=H5(L0.QITQODE_TEXT_WINDOW_TOKENS);var b0=($)=>$;function E5($,Z){let{context:X,handleEvent:Y,cleanup:J,halt:B,setAborted:W,recordOverhead:G}=Z,H=new AbortController,V={inputTokens:0,outputTokens:0,totalTokens:0};return Q.gen(function*(){X.currentText=void 0,X.reasoningMap={},yield*Y(b0({type:"start"})),yield*Y(b0({type:"start-step",request:{},warnings:[]}));let y=[$.selection?`[max mode] selected candidate ${$.selection.winner+1} of ${$.selection.total}`:void 0,$.reasoning].filter(Boolean).join(`
|
|
140
|
-
|
|
141
|
-
`);if(y){let q=$.thinkingMs?Date.now()-$.thinkingMs:void 0;yield*Y(b0({type:"reasoning-start",id:"reasoning-replay",providerMetadata:$.reasoningMetadata,...q?{time:{start:q}}:{}})),yield*Y(b0({type:"reasoning-delta",id:"reasoning-replay",text:y,providerMetadata:$.reasoningMetadata})),yield*Y(b0({type:"reasoning-end",id:"reasoning-replay",providerMetadata:$.reasoningMetadata}))}if($.text)yield*Y(b0({type:"text-start",id:"text-replay",providerMetadata:$.textMetadata})),yield*Y(b0({type:"text-delta",id:"text-replay",text:$.text,providerMetadata:$.textMetadata})),yield*Y(b0({type:"text-end",id:"text-replay",providerMetadata:$.textMetadata}));for(let j of $.toolCalls){if(X.needsOverflowHandling)break;yield*Y(b0({type:"tool-input-start",id:j.toolCallId,toolName:j.toolName,providerMetadata:j.providerMetadata})),yield*Y(b0({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,providerMetadata:j.providerMetadata}));let q=$.tools[j.toolName];if(!q?.execute){yield*Y(b0({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:Error(`Tool "${j.toolName}" has no executor`)}));continue}let z=yield*Q.tryPromise({try:()=>q.execute(j.input,{toolCallId:j.toolCallId,messages:$.messages,abortSignal:H.signal}),catch:(D)=>D}).pipe(Q.map((D)=>({ok:!0,output:D})),Q.catch((D)=>Q.succeed({ok:!1,error:D})));if(!z.ok){yield*Y(b0({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:z.error}));continue}yield*Y(b0({type:"tool-result",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,output:z.output}))}if(yield*Y(b0({type:"finish-step",usage:$.usage??V,finishReason:$.finishReason,providerMetadata:$.providerMetadata})),$.overhead&&($.overhead.cost>0||$.overhead.tokensIn>0||$.overhead.tokensOut>0))yield*G($)}).pipe(Q.onInterrupt(()=>{if(W(),H.abort(),Z.context.assistantMessage.error)return Q.void;return B(new DOMException("Aborted","AbortError"))}),Q.catchCauseIf((K)=>!W2.hasInterruptsOnly(K),(K)=>Q.fail(W2.squash(K))),Q.catch(B),Q.ensuring(J()),Q.map(()=>{if(X.needsOverflowHandling)return"overflow";if(X.blocked||X.assistantMessage.error)return"stop";return"continue"}))}function v5($){let{ctx:Z,session:X}=$,Y=Q.fn("SessionProcessor.settleToolCall")(function*(K){let y=Z.toolcalls[K]?.done;if(delete Z.toolcalls[K],y)yield*T2.succeed(y,void 0).pipe(Q.ignore)}),J=Q.fn("SessionProcessor.readToolCall")(function*(K){let y=Z.toolcalls[K];if(!y)return;let j=yield*X.getPart({partID:y.partID,messageID:y.messageID,sessionID:y.sessionID});if(!j||j.type!=="tool"){delete Z.toolcalls[K];return}return{call:y,part:j}}),B=Q.fn("SessionProcessor.updateToolCall")(function*(K,y){let j=yield*J(K);if(!j)return;let q=yield*X.updatePart(y(j.part));return Z.toolcalls[K]={...j.call,partID:q.id,messageID:q.messageID,sessionID:q.sessionID},q}),W=Q.fn("SessionProcessor.completeToolCall")(function*(K,y){let j=yield*J(K);if(!j||j.part.state.status!=="running")return;if(yield*X.updatePart({...j.part,state:{status:"completed",input:j.part.state.input,output:y.output,metadata:y.metadata,title:y.title,time:{start:j.part.state.time.start,end:Date.now()},attachments:y.attachments}}),y.metadata?.declined===!0)Z.blocked=Z.shouldBreak;yield*Y(K)}),G=Q.fn("SessionProcessor.failToolCall")(function*(K,y){let j=yield*J(K);if(!j||j.part.state.status!=="running")return!1;let q=f5(y);if(yield*X.updatePart({...j.part,state:{status:"error",input:j.part.state.input,error:D$(y),...q?{metadata:{...j.part.state.metadata,recoverable:!0}}:{},time:{start:j.part.state.time.start,end:Date.now()}}}),y instanceof y2.RejectedError||y instanceof C6.RejectedError)Z.blocked=Z.shouldBreak;return yield*Y(K),!0});return{settleToolCall:Y,readToolCall:J,updateToolCall:B,completeToolCall:W,failToolCall:G,isBackendAuthRejection:(K)=>{let y=K;for(let j=0;j<5&&y!==void 0&&y!==null;j++){if(y instanceof Z0.BackendAuthRejectedError)return!0;if(y instanceof Error&&y.name==="BackendAuthRejectedError")return!0;y=y instanceof Error?y.cause:void 0}return!1},backendBillingFailureMessage:(K)=>{let y=K;for(let j=0;j<5&&y!==void 0&&y!==null;j++){let q=y instanceof Error?y.name:void 0;if(y instanceof Z0.BackendInsufficientBalanceError||q==="BackendInsufficientBalanceError")return D8.copy().insufficientBalance();if(y instanceof Z0.BackendRateLimitError||q==="BackendRateLimitError")return D8.copy().rateLimit;y=y instanceof Error?y.cause:void 0}return}}}var I6=Q.fn("SessionProcessor.applySnapshotPatch")(function*($){if(!$.ctx.snapshot)return 0;let Z=yield*$.snapshot.patch($.ctx.snapshot);if(Z.files.length)yield*$.session.updatePart({id:Y2.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 m5($){let{ctx:Z,session:X,snapshot:Y,readToolCall:J}=$;return Q.fn("SessionProcessor.cleanup")(function*(){if(yield*I6({ctx:Z,session:X,snapshot:Y}),Z.currentText){let B=Date.now();Z.currentText.time={start:Z.currentText.time?.start??B,end:B},yield*X.updatePart(Z.currentText),Z.currentText=void 0}for(let B of Object.values(Z.reasoningMap)){let W=Date.now();yield*X.updatePart({...B,time:{start:B.time.start??W,end:W}})}Z.reasoningMap={},yield*Q.forEach(Object.values(Z.toolcalls),(B)=>T2.await(B.done).pipe(Q.timeout("250 millis"),Q.ignore),{concurrency:"unbounded"});for(let B of Object.keys(Z.toolcalls)){let W=yield*J(B);if(!W)continue;let G=W.part,H=Date.now(),V="metadata"in G.state&&d5(G.state.metadata)?G.state.metadata:{};yield*X.updatePart({...G,state:{...G.state,status:"error",error:"Tool execution aborted",metadata:{...V,interrupted:!0},time:{start:"time"in G.state?G.state.time.start:H,end:H}}})}Z.toolcalls={},Z.assistantMessage.time.completed=Date.now(),yield*X.updateMessage(Z.assistantMessage)})}var gW=20000,EW=20000;function A1($){let Z=$.model.limit.context;if(Z===0)return 0;let X=$.cfg.compaction?.reserved??Math.min(gW,n2.maxOutputTokens($.model)),Y=Math.min(n2.maxOutputTokens($.model),EW);return $.model.limit.input?Math.max(0,$.model.limit.input-X):Math.max(0,Z-Y-X)}function M1($){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)>=A1($)}function k6($){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=A1($);if(X===0)return 0;let Y=Z/X;if(Y<0.5)return 0;if(Y<0.7)return 1;if(Y<0.85)return 2;return 3}function l5($){let{ctx:Z,session:X,snapshot:Y,bus:J,config:B,summary:W,scope:G}=$;return Q.fnUntraced(function*(H){let V=S6({model:Z.model,usage:H.usage,metadata:H.providerMetadata});if(Z.assistantMessage.finish=H.finishReason,Z.assistantMessage.cost+=V.cost,V.costCredits!==void 0)Z.assistantMessage.costCredits=(Z.assistantMessage.costCredits??0)+V.costCredits;if(Z.assistantMessage.tokens=V.tokens,V.contextWindow!==void 0)Z.assistantMessage.contextWindow=V.contextWindow;yield*X.updatePart({id:Y2.ascending(),reason:H.finishReason,snapshot:yield*Y.track(),messageID:Z.assistantMessage.id,sessionID:Z.assistantMessage.sessionID,type:"step-finish",tokens:V.tokens,cost:V.cost,costCredits:V.costCredits,contextWindow:V.contextWindow}),yield*X.updateMessage(Z.assistantMessage);let K=yield*I6({ctx:Z,session:X,snapshot:Y}),y=V.tokens.input+V.tokens.cache.read+V.tokens.cache.write,j=V.tokens.output+V.tokens.reasoning;if(Z.agentMetrics)Z.agentMetrics.tokens_in+=y,Z.agentMetrics.tokens_out+=j,Z.agentMetrics.files_changed+=K;if(yield*J.publish(k2.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:V.tokens.cache.read,model_id:Z.model.id,provider:Z.model.providerID,total_tokens_in:y,total_tokens_out:j}).pipe(Q.ignore),yield*W.summarize({sessionID:Z.sessionID,messageID:Z.assistantMessage.parentID}).pipe(Q.ignore,Q.forkIn(G)),!Z.assistantMessage.summary&&M1({cfg:yield*B.get(),tokens:V.tokens,model:Z.model}))Z.needsOverflowHandling=!0})}var c5=3,fW=a.create({service:"session.processor.events"});function u5($){let{ctx:Z,session:X,snapshot:Y,agents:J,permission:B,plugin:W,bus:G,status:H,isMain:V,checkTextNgram:K,updateToolCall:y,completeToolCall:j,failToolCall:q,isBackendAuthRejection:z,backendBillingFailureMessage:D,finishStep:U}=$;return Q.fnUntraced(function*(F){switch(F.type){case"start":if(V)yield*H.set(Z.sessionID,{type:"busy"});return;case"reasoning-start":if(F.id in Z.reasoningMap)return;Z.reasoningMap[F.id]={id:Y2.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 b=yield*X.updatePart({id:Z.toolcalls[F.id]?.partID??Y2.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(b.id),Z.toolcalls[F.id]={done:yield*T2.make(),partID:b.id,messageID:b.messageID,sessionID:b.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*y(F.toolCallId,(L)=>({...L,tool:F.toolName,state:{...L.state,status:"running",input:F.input,time:{start:Date.now()}},metadata:L.metadata?.providerExecuted?{...F.providerMetadata,providerExecuted:!0}:F.providerMetadata}));let I=o.parts(Z.assistantMessage.id).slice(-c5),k=JSON.stringify(F.input);if(I.length!==c5||!I.every((L)=>L.type==="tool"&&L.tool===F.toolName&&L.state.status!=="pending"&&JSON.stringify(L.state.input)===k))return;let E=yield*J.get(Z.assistantMessage.agent);yield*B.ask({permission:"doom_loop",patterns:[F.toolName],sessionID:Z.assistantMessage.sessionID,metadata:{tool:F.toolName,input:F.input},always:[F.toolName],ruleset:E.permission,interactive:!T6.has(Z.assistantMessage.agent)});return}case"tool-result":{yield*j(F.toolCallId,F.output);return}case"tool-error":{yield*q(F.toolCallId,F.error);let M=z(F.error)?D$(F.error):D(F.error);if(M)yield*G.publish(A2.Error,{sessionID:Z.sessionID,error:new x2.Unknown({message:M}).toObject()});yield*G.publish(k2.ToolCall,{sessionID:Z.sessionID,tool_name:F.toolName,input_bytes:k2.jsonByteLength(F.input),output_bytes:0,tool_call_id:F.toolCallId,tool_call_status:"error"}).pipe(Q.ignore);return}case"error":throw F.error;case"start-step":if(Z.stepStartedAt=Date.now(),Z.firstTokenAt=void 0,!Z.snapshot)Z.snapshot=yield*Y.track();let O=Y2.ascending();yield*X.updatePart({id:O,messageID:Z.assistantMessage.id,sessionID:Z.sessionID,snapshot:Z.snapshot,type:"step-start"}),Z.stepPartIds.push(O);return;case"finish-step":yield*U(F);return;case"text-start":Z.currentText={id:Y2.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*W.trigger("experimental.text.complete",{sessionID:Z.sessionID,messageID:Z.assistantMessage.id,partID:Z.currentText.id},{text:Z.currentText.text})).text;{let M=Date.now();Z.currentText.time={start:Z.currentText.time?.start??M,end:M}}if(F.providerMetadata)Z.currentText.metadata=F.providerMetadata;yield*X.updatePart(Z.currentText),Z.currentText=void 0;return;case"finish":return;default:fW.info("unhandled",{event:F.type,value:F});return}})}var vW=a.create({service:"session.processor"});class h6 extends Z2.Service()("@qitqode/SessionProcessor"){}var a5=_.effect(h6,Q.gen(function*(){let $=yield*v2,Z=yield*B2.Service,X=yield*p.Service,Y=yield*q0.Service,J=yield*E2.Service,B=yield*f2.Service,W=yield*y2.Service,G=yield*H2.Service,H=yield*P0.Service,V=yield*l2.Scope,K=yield*z0.Service,y=Q.fn("SessionProcessor.create")(function*(j){let q=yield*Y.track(),z={assistantMessage:j.assistantMessage,sessionID:j.sessionID,model:j.model,agentMetrics:j.agentMetrics,toolcalls:{},shouldBreak:!1,snapshot:q,blocked:!1,needsOverflowHandling:!1,currentText:void 0,reasoningMap:{},stepStartedAt:void 0,firstTokenAt:void 0,stepPartIds:[],textNgramMonitor:void 0,textNgramRepeat:!1},D=!1,U=!z.assistantMessage.agentID||z.assistantMessage.agentID==="main",P=vW.clone().tag("session.id",j.sessionID).tag("messageID",j.assistantMessage.id),F=(m)=>o.fromError(m,{providerID:j.model.providerID,aborted:D}),b=v5({ctx:z,session:$}),{settleToolCall:O,readToolCall:M,updateToolCall:I,completeToolCall:k,failToolCall:E,isBackendAuthRejection:L,backendBillingFailureMessage:S}=b,T=(m)=>{if(z.textNgramRepeat||!z.textNgramMonitor)return;if(z.textNgramMonitor.append(m))z.textNgramRepeat=!0},w=l5({ctx:z,session:$,snapshot:Y,bus:X,config:Z,summary:H,scope:V}),A=u5({ctx:z,session:$,snapshot:Y,agents:J,permission:W,plugin:G,bus:X,status:K,isMain:U,checkTextNgram:T,updateToolCall:I,completeToolCall:k,failToolCall:E,isBackendAuthRejection:L,backendBillingFailureMessage:S,finishStep:w}),R=m5({ctx:z,session:$,snapshot:Y,readToolCall:M}),C=Q.fn("SessionProcessor.halt")(function*(m){P.error("process",{error:D$(m),stack:m instanceof Error?m.stack:void 0});let h=F(m);if(o.ContextOverflowError.isInstance(h)){z.needsOverflowHandling=!0,yield*X.publish(A2.Error,{sessionID:z.sessionID,error:h});return}if(z.assistantMessage.error=h,yield*X.publish(A2.Error,{sessionID:z.assistantMessage.sessionID,error:z.assistantMessage.error}),U)yield*K.set(z.sessionID,{type:"idle"})}),g=Q.fn("SessionProcessor.process")(function*(m){return P.info("process"),z.needsOverflowHandling=!1,z.shouldBreak=(yield*Z.get()).experimental?.continue_loop_on_deny!==!0,yield*Q.gen(function*(){if(yield*Q.gen(function*(){z.currentText=void 0,z.reasoningMap={},z.stepPartIds=[],z.toolcalls={},z.textNgramRepeat=!1,z.textNgramMonitor=R6(),yield*B.stream(m).pipe(o5((f)=>A(f)),p5(()=>z.needsOverflowHandling||z.textNgramRepeat),i5)}).pipe(Q.onInterrupt(()=>Q.gen(function*(){if(D=!0,!z.assistantMessage.error)yield*C(new DOMException("Aborted","AbortError"))})),Q.catchCauseIf((h)=>!W2.hasInterruptsOnly(h),(h)=>Q.fail(W2.squash(h))),Q.tapError(()=>Q.gen(function*(){if(z.currentText){let v=Date.now();z.currentText.time={start:z.currentText.time?.start??v,end:v},yield*$.updatePart(z.currentText),z.currentText=void 0}let h=new Set(z.stepPartIds),f=new Set;for(let v of o.parts(z.assistantMessage.id)){if(!h.has(v.id))continue;if(v.type!=="text"&&v.type!=="reasoning")continue;if(v.text.trim().length>0)f.add(v.id)}if(f.size>0){for(let v of o.parts(z.assistantMessage.id))if(h.has(v.id)&&v.type==="step-start")f.add(v.id)}for(let v of z.stepPartIds){if(f.has(v))continue;yield*$.removePart({sessionID:z.sessionID,messageID:z.assistantMessage.id,partID:v})}z.stepPartIds=[]})),Q.retry(n5.policy({parse:F,set:(h)=>U?K.set(z.sessionID,{type:"retry",attempt:h.attempt,message:h.message,next:h.next}):Q.void})),Q.catch(C),Q.ensuring(R())),z.needsOverflowHandling)return"overflow";if(!z.textNgramRepeat&&!z.assistantMessage.error){let h=new Set(z.stepPartIds);for(let f of o.parts(z.assistantMessage.id)){if(!h.has(f.id))continue;if(f.type!=="text"&&f.type!=="reasoning")continue;if(w6(f.text)){P.info("fake tool tag detected in end-of-turn sweep",{partID:f.id}),z.textNgramRepeat=!0;break}}}if(z.textNgramRepeat){let h=new Set(z.stepPartIds),f=new Set;for(let v of o.parts(z.assistantMessage.id)){if(!h.has(v.id))continue;if(v.type!=="text"&&v.type!=="reasoning")continue;yield*$.removePart({sessionID:z.sessionID,messageID:z.assistantMessage.id,partID:v.id}),f.add(v.id)}return z.stepPartIds=z.stepPartIds.filter((v)=>!f.has(v)),"text-repeat"}if(z.blocked||z.assistantMessage.error)return"stop";return"continue"})}),l=Q.fn("SessionProcessor.replay")(function*(m){return P.info("replay",{toolCalls:m.toolCalls.length,finish:m.finishReason}),z.needsOverflowHandling=!1,z.shouldBreak=(yield*Z.get()).experimental?.continue_loop_on_deny!==!0,yield*E5(m,{context:z,handleEvent:A,cleanup:R,halt:C,setAborted:()=>{D=!0},recordOverhead:(h)=>{let f=h.overhead;if(!f)return Q.void;return z.assistantMessage.cost+=f.cost,Q.gen(function*(){if(yield*$.updateMessage(z.assistantMessage),z.agentMetrics)z.agentMetrics.tokens_in+=f.tokensIn,z.agentMetrics.tokens_out+=f.tokensOut;yield*X.publish(k2.ModelCall,{sessionID:z.sessionID,finish_reason:"max-mode-overhead",latency_ms:0,cached_read_tokens:0,model_id:z.model.id,provider:z.model.providerID,total_tokens_in:f.tokensIn,total_tokens_out:f.tokensOut}).pipe(Q.ignore)})}})});return{get message(){return z.assistantMessage},updateToolCall:I,completeToolCall:k,process:g,replay:l}});return h6.of({create:y})})),dW=_.suspend(()=>a5.pipe(_.provide(l0),_.provide(q0.defaultLayer),_.provide(E2.defaultLayer),_.provide(f2.defaultLayer),_.provide(y2.defaultLayer),_.provide(H2.defaultLayer),_.provide(P0.defaultLayer),_.provide(z0.defaultLayer),_.provide(p.layer),_.provide(B2.defaultLayer)));var q$={};b2(q$,{prune:()=>iW,layer:()=>ZX,isOverflow:()=>pW,extractQortexSummary:()=>e5,defaultLayer:()=>XX,create:()=>nW,SessionCompaction:()=>q$,Service:()=>q8,PRUNE_PROTECT:()=>I7,PRUNE_MINIMUM:()=>_1,Event:()=>$X});var _1=20000,I7=40000,mW=["skill"];function E6($){let Z=0,X=0,Y=[],J=0;$:for(let B=$.length-1;B>=0;B--){let W=$[B];if(W.info.role==="user")J++;if(J<2)continue;if(W.info.role==="assistant"&&W.info.summary)break $;for(let G=W.parts.length-1;G>=0;G--){let H=W.parts[G];if(H.type==="tool"){if(H.state.status==="completed"){if(mW.includes(H.tool))continue;if(H.state.time.compacted)break $;let V=g6.estimate(H.state.output);if(Z+=V,Z>I7)X+=V,Y.push(H)}}}}return{total:Z,pruned:X,toPrune:Y}}function f6($,Z){return Q.gen(function*(){for(let X of $){if(X.state.status!=="completed")continue;X.state.time.compacted=Date.now(),yield*Z(X)}})}function s5($,Z){let X=(Y)=>{let J;try{J=$.parse(Y)}catch(B){if(B instanceof F2.ZodError){let W=JSON.stringify(B.issues,null,2);throw Error(`Schema validation failed:
|
|
142
|
-
${W}`,{cause:B})}throw B}return Z(J)};return X.force=(Y)=>Z(Y),X.schema=$,X}var e$=a.create({service:"session.compaction"});function e5($){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 Y=$.messages[X];if(Y?.role!=="assistant")continue;let J=Y.content;if(typeof J==="string"&&J.trim())return J.trim();if(Array.isArray(J)){let B=J.filter((W)=>W?.type==="text"&&typeof W?.text==="string").map((W)=>W.text).join(`
|
|
143
|
-
`).trim();if(B)return B}}return null}var $X={Compacted:O2.define("session.compacted",N.object({sessionID:P2.zod}))},r5=2,lW=2000,cW=8000;function uW($){return $.cfg.compaction?.preserve_recent_tokens??Math.min(cW,Math.max(lW,Math.floor(A1($)*0.25)))}function oW($){let Z=[];for(let X=0;X<$.length;X++){let Y=$[X];if(Y.info.role!=="user")continue;if(Y.parts.some((J)=>J.type==="compaction"))continue;Z.push({start:X,end:$.length,id:Y.info.id})}for(let X=0;X<Z.length-1;X++)Z[X].end=Z[X+1].start;return Z}class q8 extends Z2.Service()("@qitqode/SessionCompaction"){}var ZX=_.effect(q8,Q.gen(function*(){let $=yield*p.Service,Z=yield*B2.Service,X=yield*v2,Y=yield*E2.Service,J=yield*H2.Service,B=yield*c0.Service,W=yield*z2.Service,G=Q.fn("SessionCompaction.isOverflow")(function*(D){return M1({cfg:yield*Z.get(),tokens:D.tokens,model:D.model})}),H=5000,V=new Map,K=Q.fn("SessionCompaction.estimate")(function*(D){let U=`${D.model.providerID}\x00${D.model.id}\x00${D.model.api.npm}\x00${D.model.api.id}`,P=0;for(let F of D.messages){let b=`${U}\x00${o.fingerprint(F)}`,O=V.get(b);if(O===void 0){let M=yield*o.toModelMessagesEffect([F],D.model);O=0;for(let I of M)O+=g6.estimate(JSON.stringify(I));if(V.size>=5000)V.delete(V.keys().next().value);V.set(b,O)}else V.delete(b),V.set(b,O);P+=O}return P}),y=Q.fn("SessionCompaction.select")(function*(D){let U=D.cfg.compaction?.tail_turns??r5;if(U<=0)return{head:D.messages,tail_start_id:void 0};let P=uW({cfg:D.cfg,model:D.model}),F=oW(D.messages);if(!F.length)return{head:D.messages,tail_start_id:void 0};let b=F.slice(-U),O=yield*Q.forEach(b,(k)=>K({messages:D.messages.slice(k.start,k.end),model:D.model}),{concurrency:1});if(O.at(-1)>P)return e$.info("tail fallback",{tokenBudget:P,size:O.at(-1)}),{head:D.messages,tail_start_id:void 0};let M=0,I;for(let k=b.length-1;k>=0;k--){let E=O[k];if(M+E>P)break;M+=E,I=b[k]}if(!I||I.start===0)return{head:D.messages,tail_start_id:void 0};return{head:D.messages.slice(0,I.start),tail_start_id:I.id}}),j=Q.fn("SessionCompaction.prune")(function*(D){if(!(yield*Z.get()).compaction?.prune)return;e$.info("pruning",{agentID:D.agentID??"main"});let P=yield*o.filterCompactedEffect(D.sessionID,{agentID:D.agentID}).pipe(Q.catchIf(P8.isInstance,()=>Q.succeed(void 0)));if(!P)return;let{total:F,pruned:b,toPrune:O}=E6(P);if(e$.info("found",{pruned:b,total:F}),b>_1)yield*f6(O,(M)=>X.updatePart(M)),e$.info("pruned",{count:O.length})}),q=Q.fn("SessionCompaction.process")(function*(D){let U=D.messages.findLast((h)=>h.info.id===D.parentID);if(!U||U.info.role!=="user")throw Error(`Compaction parent must be a user message: ${D.parentID}`);let P=U.info,F=U.parts.find((h)=>h.type==="compaction"),b=D.messages,O;if(D.overflow){let h=D.messages.findIndex((v)=>v.info.id===D.parentID);for(let v=h-1;v>=0;v--){let e=D.messages[v];if(e.info.role==="user"&&!e.parts.some((n)=>n.type==="compaction")){O={info:e.info,parts:e.parts},b=D.messages.slice(0,v);break}}if(!(O&&b.some((v)=>v.info.role==="user"&&!v.parts.some((e)=>e.type==="compaction"))))O=void 0,b=D.messages}let M=yield*Y.get("compaction"),I=M.model?yield*W.getModel(M.model.providerID,M.model.modelID):yield*W.getModel(P.model.providerID,P.model.modelID),k=yield*Z.get(),E=F&&b.at(-1)?.info.id===D.parentID?b.slice(0,-1):b,L=yield*y({messages:E,cfg:k,model:I}),S=yield*J.trigger("experimental.session.compacting",{sessionID:D.sessionID},{context:[],prompt:void 0}),T=`When constructing the summary, try to stick to this template:
|
|
144
|
-
---
|
|
145
|
-
## Goal
|
|
146
|
-
|
|
147
|
-
[What goal(s) is the user trying to accomplish?]
|
|
148
|
-
|
|
149
|
-
## Instructions
|
|
150
|
-
|
|
151
|
-
- [What important instructions did the user give you that are relevant]
|
|
152
|
-
- [If there is a plan or spec, include information about it so next agent can continue using it]
|
|
153
|
-
|
|
154
|
-
## Discoveries
|
|
155
|
-
|
|
156
|
-
[What notable things were learned during this conversation that would be useful for the next agent to know when continuing the work]
|
|
157
|
-
|
|
158
|
-
## Accomplished
|
|
159
|
-
|
|
160
|
-
[What work has been completed, what work is still in progress, and what work is left?]
|
|
161
|
-
|
|
162
|
-
## Relevant files / directories
|
|
163
|
-
|
|
164
|
-
[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.]
|
|
165
|
-
---`,w=S.prompt??[T,...S.context].join(`
|
|
166
|
-
|
|
167
|
-
`),A=structuredClone(L.head);yield*J.trigger("experimental.chat.messages.transform",{},{messages:A});let R=yield*o.toModelMessagesEffect(A,I,{stripMedia:!0}),C=yield*d.context,g={id:w2.ascending(),role:"assistant",parentID:D.parentID,sessionID:D.sessionID,agentID:D.agentID??void 0,mode:"compaction",agent:"compaction",variant:P.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,m=yield*Q.promise(()=>Z0.resolveCompressTrajectorySafe({messages:R,tier:"economical",protectFirstSystem:!0,protectFirstUser:!0,protectLastTurns:k.compaction?.tail_turns??r5}).catch((h)=>{let f=Z0.isBackendBillingError(h);return e$.warn(f?"compressTrajectorySafe rejected (qredits/rate limit); using local compaction fallback":"compressTrajectorySafe unavailable; using local compaction fallback",{error:h instanceof Error?h.message:String(h),...f?{billing:!0}:{},sessionID:D.sessionID}),null}));if(m!==null){if(!m.safe)e$.info("compressTrajectorySafe: no safe middle span; falling back to local compaction",{sessionID:D.sessionID,reason:m.reason});else if(l=e5(m),l===null)e$.warn("compressTrajectorySafe: could not extract summary text; using local compaction fallback",{sessionID:D.sessionID})}if(l!==null){let h=Date.now();yield*X.updateMessage(g),yield*X.updatePart({id:Y2.ascending(),messageID:g.id,sessionID:D.sessionID,type:"text",text:l,time:{start:h,end:h}}),yield*X.updateMessage({...g,finish:"done"})}else{yield*X.updateMessage(g);let h=yield*B.create({assistantMessage:g,sessionID:D.sessionID,model:I}),f=yield*h.process({user:P,agent:M,sessionID:D.sessionID,tools:{},system:[],messages:[...R,{role:"user",content:[{type:"text",text:w}]}],model:I});if(f==="overflow")return h.message.error=new o.ContextOverflowError({message:O?"Conversation history too large to compact - exceeds model context limit":"Session too large to compact - context exceeds model limit even after stripping media"}).toObject(),h.message.finish="error",yield*X.updateMessage(h.message),"stop";if(f==="text-repeat")return"stop";if(h.message.error)return"stop"}if(F&&L.tail_start_id&&F.tail_start_id!==L.tail_start_id)yield*X.updatePart({...F,tail_start_id:L.tail_start_id});if(D.auto){if(O){let h=O.info,f=yield*X.updateMessage({id:w2.ascending(),role:"user",sessionID:D.sessionID,agentID:D.agentID??void 0,time:{created:Date.now()},agent:h.agent,model:h.model,format:h.format,tools:h.tools,system:h.system});for(let v of O.parts){if(v.type==="compaction")continue;let e=v.type==="file"&&o.isMedia(v.mime)?{type:"text",text:`[Attached ${v.mime}: ${v.filename??"file"}]`}:v;yield*X.updatePart({...e,id:Y2.ascending(),messageID:f.id,sessionID:D.sessionID})}}if(!O){let h=yield*W.getProvider(P.model.providerID);if((yield*J.trigger("experimental.compaction.autocontinue",{sessionID:D.sessionID,agent:P.agent,model:yield*W.getModel(P.model.providerID,P.model.modelID),provider:{source:h.source,info:h,options:h.options},message:P,overflow:D.overflow===!0},{enabled:!0})).enabled){let f=yield*X.updateMessage({id:w2.ascending(),role:"user",sessionID:D.sessionID,agentID:D.agentID??void 0,time:{created:Date.now()},agent:P.agent,model:P.model}),v=(D.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.
|
|
168
|
-
|
|
169
|
-
`:"")+"Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.";yield*X.updatePart({id:Y2.ascending(),messageID:f.id,sessionID:D.sessionID,type:"text",metadata:{compaction_continue:!0},synthetic:!0,text:v,time:{start:Date.now(),end:Date.now()}})}}}return yield*$.publish($X.Compacted,{sessionID:D.sessionID}),"continue"}),z=Q.fn("SessionCompaction.create")(function*(D){let U=yield*X.updateMessage({id:w2.ascending(),role:"user",model:D.model,sessionID:D.sessionID,agentID:D.agentID??void 0,agent:D.agent,time:{created:Date.now()}});yield*X.updatePart({id:Y2.ascending(),messageID:U.id,sessionID:U.sessionID,type:"compaction",auto:D.auto,overflow:D.overflow})});return q8.of({isOverflow:G,prune:j,process:q,create:z})})),XX=_.suspend(()=>ZX.pipe(_.provide(z2.defaultLayer),_.provide(l0),_.provide(c0.defaultLayer),_.provide(E2.defaultLayer),_.provide(H2.defaultLayer),_.provide(p.layer),_.provide(B2.defaultLayer))),{runPromise:k7}=t5(q8,XX);function pW($){return k7((Z)=>Z.isOverflow($))}function iW($){return k7((Z)=>Z.prune($))}var nW=s5(N.object({sessionID:P2.zod,agent:N.string(),model:N.object({providerID:$1.zod,modelID:t0.zod}),auto:N.boolean(),overflow:N.boolean().optional(),agentID:N.string().optional()}),($)=>k7((Z)=>Z.create($)));var N$={};b2(N$,{resolveThresholds:()=>BX,parseThreshold:()=>JX,layer:()=>WX,defaultThresholdsFor:()=>YX,defaultLayer:()=>ZV,SessionPrune:()=>N$,Service:()=>v6});var e0=a.create({service:"session.prune"}),aW=4096,sW=1536,rW=1536,tW=300000,eW=13000,$V=3;function YX($){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 QX($,Z){if(!$)return!0;let X=$.cacheTTL??tW;if(!Z)return!0;return Date.now()-Z>X}function JX($,Z){let X=$.trim();if(X.endsWith("%")){let W=parseFloat(X.slice(0,-1));if(!Number.isFinite(W)||W<=0||W>100)throw Error(`Invalid checkpoint threshold percentage: "${$}" (must be 0 < n <= 100)`);let G=Math.floor(Z*W/100);if(G<=0)throw Error(`Invalid checkpoint threshold percentage: "${$}" (resolves to zero tokens)`);return G}let Y=X.match(/^(\d+(?:\.\d+)?)([KkMm]?)$/);if(!Y)throw Error(`Invalid checkpoint threshold format: "${$}"`);let J=parseFloat(Y[1]);if(Y[2]==="K"||Y[2]==="k")J*=1000;else if(Y[2]==="M"||Y[2]==="m")J*=1e6;let B=Math.floor(J);if(B<=0)throw Error(`Invalid checkpoint threshold: "${$}" (must be greater than 0)`);return B}function BX($,Z,X){let Y=X??eW,J=Z-Y;if(J<=0)throw Error(`Model window size (${Z}) is too small for checkpoints (need > ${Y} reserved tokens)`);let B=$.map((K)=>({raw:K,value:JX(K,Z)})),W=[],G=!1;for(let K of B){if(K.value<=J){W.push(K.value);continue}if(!G){e0.info(`checkpoint threshold "${K.raw}" (${K.value}) exceeds maxAllowed (${J}) \u2014 clamped to maxAllowed`),W.push(J),G=!0;continue}e0.info(`checkpoint threshold "${K.raw}" (${K.value}) exceeds maxAllowed (${J}) \u2014 dropped (already clamped earlier)`)}let H=W.sort((K,y)=>K-y),V=[];for(let K of H)if(V.length===0||V[V.length-1]!==K)V.push(K);return V}class v6 extends Z2.Service()("@qitqode/SessionPrune"){}var WX=_.effect(v6,Q.gen(function*(){let $=yield*B2.Service,Z=yield*v2,X=yield*P$.Service,Y=yield*_2.Service,J=new Map,B=new Set,W=new Map,G=Q.fn("SessionPrune.stripNonEssential")(function*(j){if(!QX(j.model,j.lastAssistantTime))return;let q=yield*Z.messages({sessionID:j.sessionID,agentID:"main"}).pipe(Q.catchIf(P8.isInstance,()=>Q.succeed(void 0)));if(!q)return;let z=0,D=q.length;for(let P=q.length-1;P>=0;P--){if(q[P].info.role==="user")z++;if(z>3){D=P;break}}let U=0;for(let P=0;P<D;P++){let F=q[P];for(let b of F.parts){if(b.type==="file"&&o.isMedia(b.mime))yield*Z.updatePart({...b,url:"",filename:`[stripped: ${b.filename??b.mime}]`}),U++;if(b.type==="reasoning"&&F.info.role==="assistant")yield*Z.updatePart({...b,text:""}),U++}}if(U>0)e0.info("stripped non-essential content",{count:U})}),H=Q.fn("SessionPrune.fireCheckpoints")(function*(j){if(j.agentID&&(yield*Y.isSystemSpawned(j.sessionID,j.agentID)))return;if((j.agentID?yield*Y.get(j.sessionID,j.agentID):void 0)?.mode==="subagent")return;if(yield*X.isWriterRunning(j.sessionID)){e0.info("checkpoint writer running, skipping new threshold trigger",{sessionID:j.sessionID});return}let z=yield*$.get(),D=A1({cfg:z,model:j.model});if(D===0)return;let U=z.checkpoint?.thresholds??YX(D),P=BX(U,D,z.checkpoint?.reserved);if(P.length===0)return;let F=z.checkpoint?.max_writer_failures??$V,b=j.tokens.total||j.tokens.input+j.tokens.output+j.tokens.cache.read+j.tokens.cache.write,O=J.get(j.sessionID)??new Set,M=P[P.length-1];for(let I of P){if(b<I)break;if(O.has(I))continue;let k;if((yield*X.tryStartCheckpointWriter({sessionID:j.sessionID,model:{providerID:j.model.providerID,modelID:j.model.id},promptOps:j.promptOps,onStarted:(L)=>{k=L}}).pipe(Q.catch(()=>Q.succeed("skipped"))))==="started")yield*Q.gen(function*(){let L=k?yield*T2.await(k):yield*X.waitForWriter(j.sessionID).pipe(Q.map((T)=>T==="success"?{status:"success"}:T==="failure"?{status:"failure",error:"writer failed"}:{status:"cancelled"}));if(L.status==="success"){W.delete(j.sessionID);return}if(L.status!=="failure")return;let S=(W.get(j.sessionID)??0)+1;if(W.set(j.sessionID,S),S<F)J.delete(j.sessionID),B.delete(j.sessionID),e0.info("checkpoint writer failed \u2014 cleared thresholds for retry",{sessionID:j.sessionID,attempt:S,maxAttempts:F});else e0.warn("checkpoint writer gave up after max consecutive failures",{sessionID:j.sessionID,maxAttempts:F})}).pipe(Q.forkDetach);if(O.add(I),e0.info("checkpoint triggered",{threshold:I,currentTokens:b}),I===M)B.add(j.sessionID)}J.set(j.sessionID,O)}),V=Q.fn("SessionPrune.prune")(function*(j){let q=yield*$.get();if(!q.compaction?.prune)return;if(!QX(j.model,j.lastAssistantTime))return;let z=k6({cfg:q,tokens:j.tokens,model:j.model});if(z===0)return;let D=z>=2?2:1;e0.info("pruning",{level:D});let U=yield*Z.messages({sessionID:j.sessionID,agentID:"main"}).pipe(Q.catchIf(P8.isInstance,()=>Q.succeed(void 0)));if(!U)return;let{total:P,pruned:F,toPrune:b}=E6(U);if(e0.info("found",{pruned:F,total:P,level:D}),D===1){for(let O of b)if(O.state.status==="completed"){let M=O.state.output;if(M.length>aW)O.state.output=M.slice(0,sW)+`
|
|
170
|
-
|
|
171
|
-
[... trimmed \u2014 kept first and last 1.5K of `+M.length+` chars ...]
|
|
172
|
-
|
|
173
|
-
`+M.slice(-rW),yield*Z.updatePart(O)}e0.info("soft-trimmed",{count:b.length})}else if(F>_1)yield*f6(b,(O)=>Z.updatePart(O)),e0.info("pruned",{count:b.length});if(D>=2)yield*G({sessionID:j.sessionID,model:j.model,lastAssistantTime:j.lastAssistantTime})}),K=Q.fn("SessionPrune.maxThresholdCrossed")(function*(j){return B.has(j)}),y=Q.fn("SessionPrune.resetThresholds")(function*(j){J.delete(j),B.delete(j)});return v6.of({prune:V,fireCheckpoints:H,maxThresholdCrossed:K,resetThresholds:y})})),ZV=_.suspend(()=>WX.pipe(_.provide(l0),_.provide(B2.defaultLayer),_.provide(P$.defaultLayer),_.provide(_2.defaultLayer)));var $$={};b2($$,{layer:()=>VX,defaultLayer:()=>YV,SessionRevert:()=>$$,Service:()=>d6,RevertInput:()=>QV});var XV=a.create({service:"session.revert"}),QV=N.object({sessionID:P2.zod,messageID:w2.zod,partID:Y2.zod.optional()});class d6 extends Z2.Service()("@qitqode/SessionRevert"){}var VX=_.effect(d6,Q.gen(function*(){let $=yield*v2,Z=yield*q0.Service,X=yield*k$.Service,Y=yield*p.Service,J=yield*P0.Service,B=yield*y0.Service,W=Q.fn("SessionRevert.revert")(function*(V){yield*B.assertNotBusy(V.sessionID);let K=yield*$.messages({sessionID:V.sessionID,agentID:"*"}),y,j=yield*$.get(V.sessionID),q,z=[];for(let F of K){if(F.info.role==="user")y=F.info;let b=[];for(let O of F.parts){if(q){if(O.type==="patch")z.push(O);continue}if(!q){if(F.info.id===V.messageID&&!V.partID||O.id===V.partID){let M=b.some((I)=>["text","tool"].includes(I.type))?V.partID:void 0;q={messageID:!M&&y?y.id:F.info.id,partID:M}}b.push(O)}}}if(!q)return j;let D=q.messageID;if(q.snapshot=j.revert?.snapshot??(yield*Z.track()),j.revert?.snapshot)yield*Z.restore(j.revert.snapshot);if(yield*Z.revert(z),q.snapshot)q.diff=yield*Z.diff(q.snapshot);let U=K.filter((F)=>F.info.id>=D),P=yield*J.computeDiff({messages:U});return yield*X.write(["session_diff",V.sessionID],P).pipe(Q.ignore),yield*Y.publish(A2.Diff,{sessionID:V.sessionID,diff:P}),yield*$.setRevert({sessionID:V.sessionID,revert:q,summary:M6(P)}),yield*$.get(V.sessionID)}),G=Q.fn("SessionRevert.unrevert")(function*(V){XV.info("unreverting",V),yield*B.assertNotBusy(V.sessionID);let K=yield*$.get(V.sessionID);if(!K.revert)return K;if(K.revert.snapshot)yield*Z.restore(K.revert.snapshot);return yield*$.clearRevert(V.sessionID),yield*$.get(V.sessionID)}),H=Q.fn("SessionRevert.cleanup")(function*(V){if(!V.revert)return;let K=V.id,y=yield*$.messages({sessionID:K,agentID:"*"}),j=V.revert.messageID,q=[],z;for(let D of y){if(D.info.id<j)continue;if(D.info.id>j){q.push(D);continue}if(V.revert.partID){z=D;continue}q.push(D)}for(let D of q)R1.run(o.Event.Removed,{sessionID:K,messageID:D.info.id});if(V.revert.partID&&z){let D=V.revert.partID,U=z.parts.findIndex((P)=>P.id===D);if(U>=0){let P=z.parts.slice(U);z.parts=z.parts.slice(0,U);for(let F of P)R1.run(o.Event.PartRemoved,{sessionID:K,messageID:z.info.id,partID:F.id})}}yield*$.clearRevert(K)});return d6.of({revert:W,unrevert:G,cleanup:H})})),YV=_.suspend(()=>VX.pipe(_.provide(y0.defaultLayer),_.provide(l0),_.provide(q0.defaultLayer),_.provide(k$.defaultLayer),_.provide(p.layer),_.provide(P0.defaultLayer)));var c$={};b2(c$,{stepSignature:()=>c8,stableStringify:()=>W8,recallHintLines:()=>l8,layer:()=>bJ,defaultLayer:()=>dH,createStructuredOutputTool:()=>v4,ShellInput:()=>wJ,SessionPrompt:()=>c$,Service:()=>o8,PromptInput:()=>PJ,LoopInput:()=>NJ,CommandInput:()=>xJ});var N0={};b2(N0,{layer:()=>MQ,defaultLayer:()=>S3,ToolsChanged:()=>K9,Status:()=>mK,Service:()=>_4,Resource:()=>vK,MCP:()=>N0,Failed:()=>dK,BrowserOpenFailed:()=>H9,AuthRequired:()=>Z4});var kX=V9(IK(),1);import e6 from"process";import{PassThrough as kK}from"stream";var I1="2025-11-25";var GX=[I1,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],S$="io.modelcontextprotocol/related-task",l6="2.0",J0=HX(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),jX=R2([x(),D2().int()]),OX=x(),dz=a2({ttl:R2([D2(),S7()]).optional(),pollInterval:D2().optional()}),BV=u({ttl:D2().optional()}),WV=u({taskId:x()}),E7=a2({progressToken:jX.optional(),[S$]:WV.optional()}),k0=u({_meta:E7.optional()}),N8=k0.extend({task:BV.optional()}),FX=($)=>N8.safeParse($).success,B0=u({method:x(),params:k0.loose().optional()}),u0=u({_meta:E7.optional()}),o0=u({method:x(),params:u0.loose().optional()}),W0=a2({_meta:E7.optional()}),c6=R2([x(),D2().int()]),zX=u({jsonrpc:i(l6),id:c6,...B0.shape}).strict(),w8=($)=>zX.safeParse($).success,yX=u({jsonrpc:i(l6),...o0.shape}).strict(),DX=($)=>yX.safeParse($).success,f7=u({jsonrpc:i(l6),id:c6,result:W0}).strict(),Z1=($)=>f7.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 v7=u({jsonrpc:i(l6),id:c6.optional(),error:u({code:D2().int(),message:x(),data:u2().optional()})}).strict();var qX=($)=>v7.safeParse($).success;var T$=R2([zX,yX,f7,v7]),mz=R2([f7,v7]),X1=W0.strict(),VV=u0.extend({requestId:c6.optional(),reason:x().optional()}),u6=o0.extend({method:i("notifications/cancelled"),params:VV}),KV=u({src:x(),mimeType:x().optional(),sizes:c(x()).optional(),theme:I0(["light","dark"]).optional()}),x8=u({icons:c(KV).optional()}),C1=u({name:x(),title:x().optional()}),PX=C1.extend({...C1.shape,...x8.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),HV=h7(u({applyDefaults:M2().optional()}),h2(x(),u2())),GV=g7(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},h7(u({form:HV.optional(),url:J0.optional()}),h2(x(),u2()).optional())),jV=a2({list:J0.optional(),cancel:J0.optional(),requests:a2({sampling:a2({createMessage:J0.optional()}).optional(),elicitation:a2({create:J0.optional()}).optional()}).optional()}),OV=a2({list:J0.optional(),cancel:J0.optional(),requests:a2({tools:a2({call:J0.optional()}).optional()}).optional()}),FV=u({experimental:h2(x(),J0).optional(),sampling:u({context:J0.optional(),tools:J0.optional()}).optional(),elicitation:GV.optional(),roots:u({listChanged:M2().optional()}).optional(),tasks:jV.optional()}),zV=k0.extend({protocolVersion:x(),capabilities:FV,clientInfo:PX}),yV=B0.extend({method:i("initialize"),params:zV});var DV=u({experimental:h2(x(),J0).optional(),logging:J0.optional(),completions:J0.optional(),prompts:u({listChanged:M2().optional()}).optional(),resources:u({subscribe:M2().optional(),listChanged:M2().optional()}).optional(),tools:u({listChanged:M2().optional()}).optional(),tasks:OV.optional()}),d7=W0.extend({protocolVersion:x(),capabilities:DV,serverInfo:PX,instructions:x().optional()}),NX=o0.extend({method:i("notifications/initialized"),params:u0.optional()}),wX=($)=>NX.safeParse($).success,o6=B0.extend({method:i("ping"),params:k0.optional()}),qV=u({progress:D2(),total:o2(D2()),message:o2(x())}),PV=u({...u0.shape,...qV.shape,progressToken:jX}),p6=o0.extend({method:i("notifications/progress"),params:PV}),NV=k0.extend({cursor:OX.optional()}),L8=B0.extend({params:NV.optional()}),b8=W0.extend({nextCursor:OX.optional()}),wV=I0(["working","input_required","completed","failed","cancelled"]),U8=u({taskId:x(),status:wV,ttl:R2([D2(),S7()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:o2(D2()),statusMessage:o2(x())}),Q1=W0.extend({task:U8}),xV=u0.merge(U8),A8=o0.extend({method:i("notifications/tasks/status"),params:xV}),i6=B0.extend({method:i("tasks/get"),params:k0.extend({taskId:x()})}),n6=W0.merge(U8),a6=B0.extend({method:i("tasks/result"),params:k0.extend({taskId:x()})}),lz=W0.loose(),s6=L8.extend({method:i("tasks/list")}),r6=b8.extend({tasks:c(U8)}),t6=B0.extend({method:i("tasks/cancel"),params:k0.extend({taskId:x()})}),xX=W0.merge(U8),LX=u({uri:x(),mimeType:o2(x()),_meta:h2(x(),u2()).optional()}),bX=LX.extend({text:x()}),m7=x().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),UX=LX.extend({blob:m7}),M8=I0(["user","assistant"]),k1=u({audience:c(M8).optional(),priority:D2().min(0).max(1).optional(),lastModified:KX.datetime({offset:!0}).optional()}),AX=u({...C1.shape,...x8.shape,uri:x(),description:o2(x()),mimeType:o2(x()),annotations:k1.optional(),_meta:o2(a2({}))}),LV=u({...C1.shape,...x8.shape,uriTemplate:x(),description:o2(x()),mimeType:o2(x()),annotations:k1.optional(),_meta:o2(a2({}))}),bV=L8.extend({method:i("resources/list")}),l7=b8.extend({resources:c(AX)}),UV=L8.extend({method:i("resources/templates/list")}),c7=b8.extend({resourceTemplates:c(LV)}),u7=k0.extend({uri:x()}),AV=u7,MV=B0.extend({method:i("resources/read"),params:AV}),o7=W0.extend({contents:c(R2([bX,UX]))}),p7=o0.extend({method:i("notifications/resources/list_changed"),params:u0.optional()}),_V=u7,RV=B0.extend({method:i("resources/subscribe"),params:_V}),CV=u7,IV=B0.extend({method:i("resources/unsubscribe"),params:CV}),kV=u0.extend({uri:x()}),SV=o0.extend({method:i("notifications/resources/updated"),params:kV}),TV=u({name:x(),description:o2(x()),required:o2(M2())}),hV=u({...C1.shape,...x8.shape,description:o2(x()),arguments:o2(c(TV)),_meta:o2(a2({}))}),gV=L8.extend({method:i("prompts/list")}),i7=b8.extend({prompts:c(hV)}),EV=k0.extend({name:x(),arguments:h2(x(),x()).optional()}),fV=B0.extend({method:i("prompts/get"),params:EV}),n7=u({type:i("text"),text:x(),annotations:k1.optional(),_meta:h2(x(),u2()).optional()}),a7=u({type:i("image"),data:m7,mimeType:x(),annotations:k1.optional(),_meta:h2(x(),u2()).optional()}),s7=u({type:i("audio"),data:m7,mimeType:x(),annotations:k1.optional(),_meta:h2(x(),u2()).optional()}),vV=u({type:i("tool_use"),name:x(),id:x(),input:h2(x(),u2()),_meta:h2(x(),u2()).optional()}),dV=u({type:i("resource"),resource:R2([bX,UX]),annotations:k1.optional(),_meta:h2(x(),u2()).optional()}),mV=AX.extend({type:i("resource_link")}),r7=R2([n7,a7,s7,mV,dV]),lV=u({role:M8,content:r7}),t7=W0.extend({description:x().optional(),messages:c(lV)}),e7=o0.extend({method:i("notifications/prompts/list_changed"),params:u0.optional()}),cV=u({title:x().optional(),readOnlyHint:M2().optional(),destructiveHint:M2().optional(),idempotentHint:M2().optional(),openWorldHint:M2().optional()}),uV=u({taskSupport:I0(["required","optional","forbidden"]).optional()}),MX=u({...C1.shape,...x8.shape,description:x().optional(),inputSchema:u({type:i("object"),properties:h2(x(),J0).optional(),required:c(x()).optional()}).catchall(u2()),outputSchema:u({type:i("object"),properties:h2(x(),J0).optional(),required:c(x()).optional()}).catchall(u2()).optional(),annotations:cV.optional(),execution:uV.optional(),_meta:h2(x(),u2()).optional()}),oV=L8.extend({method:i("tools/list")}),$9=b8.extend({tools:c(MX)}),h$=W0.extend({content:c(r7).default([]),structuredContent:h2(x(),u2()).optional(),isError:M2().optional()}),cz=h$.or(W0.extend({toolResult:u2()})),pV=N8.extend({name:x(),arguments:h2(x(),u2()).optional()}),iV=B0.extend({method:i("tools/call"),params:pV}),_8=o0.extend({method:i("notifications/tools/list_changed"),params:u0.optional()}),_X=u({autoRefresh:M2().default(!0),debounceMs:D2().int().nonnegative().default(300)}),RX=I0(["debug","info","notice","warning","error","critical","alert","emergency"]),nV=k0.extend({level:RX}),aV=B0.extend({method:i("logging/setLevel"),params:nV}),sV=u0.extend({level:RX,logger:x().optional(),data:u2()}),rV=o0.extend({method:i("notifications/message"),params:sV}),tV=u({name:x().optional()}),eV=u({hints:c(tV).optional(),costPriority:D2().min(0).max(1).optional(),speedPriority:D2().min(0).max(1).optional(),intelligencePriority:D2().min(0).max(1).optional()}),$K=u({mode:I0(["auto","required","none"]).optional()}),ZK=u({type:i("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:c(r7).default([]),structuredContent:u({}).loose().optional(),isError:M2().optional(),_meta:h2(x(),u2()).optional()}),XK=T7("type",[n7,a7,s7]),m6=T7("type",[n7,a7,s7,vV,ZK]),QK=u({role:M8,content:R2([m6,c(m6)]),_meta:h2(x(),u2()).optional()}),YK=N8.extend({messages:c(QK),modelPreferences:eV.optional(),systemPrompt:x().optional(),includeContext:I0(["none","thisServer","allServers"]).optional(),temperature:D2().optional(),maxTokens:D2().int(),stopSequences:c(x()).optional(),metadata:J0.optional(),tools:c(MX).optional(),toolChoice:$K.optional()}),Z9=B0.extend({method:i("sampling/createMessage"),params:YK}),X9=W0.extend({model:x(),stopReason:o2(I0(["endTurn","stopSequence","maxTokens"]).or(x())),role:M8,content:XK}),Q9=W0.extend({model:x(),stopReason:o2(I0(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:M8,content:R2([m6,c(m6)])}),JK=u({type:i("boolean"),title:x().optional(),description:x().optional(),default:M2().optional()}),BK=u({type:i("string"),title:x().optional(),description:x().optional(),minLength:D2().optional(),maxLength:D2().optional(),format:I0(["email","uri","date","date-time"]).optional(),default:x().optional()}),WK=u({type:I0(["number","integer"]),title:x().optional(),description:x().optional(),minimum:D2().optional(),maximum:D2().optional(),default:D2().optional()}),VK=u({type:i("string"),title:x().optional(),description:x().optional(),enum:c(x()),default:x().optional()}),KK=u({type:i("string"),title:x().optional(),description:x().optional(),oneOf:c(u({const:x(),title:x()})),default:x().optional()}),HK=u({type:i("string"),title:x().optional(),description:x().optional(),enum:c(x()),enumNames:c(x()).optional(),default:x().optional()}),GK=R2([VK,KK]),jK=u({type:i("array"),title:x().optional(),description:x().optional(),minItems:D2().optional(),maxItems:D2().optional(),items:u({type:i("string"),enum:c(x())}),default:c(x()).optional()}),OK=u({type:i("array"),title:x().optional(),description:x().optional(),minItems:D2().optional(),maxItems:D2().optional(),items:u({anyOf:c(u({const:x(),title:x()}))}),default:c(x()).optional()}),FK=R2([jK,OK]),zK=R2([HK,GK,FK]),yK=R2([zK,JK,BK,WK]),DK=N8.extend({mode:i("form").optional(),message:x(),requestedSchema:u({type:i("object"),properties:h2(x(),yK),required:c(x()).optional()})}),qK=N8.extend({mode:i("url"),message:x(),elicitationId:x(),url:x().url()}),PK=R2([DK,qK]),Y9=B0.extend({method:i("elicitation/create"),params:PK}),NK=u0.extend({elicitationId:x()}),wK=o0.extend({method:i("notifications/elicitation/complete"),params:NK}),J9=W0.extend({action:I0(["accept","decline","cancel"]),content:g7(($)=>$===null?void 0:$,h2(x(),R2([x(),D2(),M2(),c(x())])).optional())}),xK=u({type:i("ref/resource"),uri:x()});var LK=u({type:i("ref/prompt"),name:x()}),bK=k0.extend({ref:R2([LK,xK]),argument:u({name:x(),value:x()}),context:u({arguments:h2(x(),x()).optional()}).optional()}),UK=B0.extend({method:i("completion/complete"),params:bK});var B9=W0.extend({completion:a2({values:c(x()).max(100),total:o2(D2().int()),hasMore:o2(M2())})}),AK=u({uri:x().startsWith("file://"),name:x().optional(),_meta:h2(x(),u2()).optional()}),MK=B0.extend({method:i("roots/list"),params:k0.optional()}),_K=W0.extend({roots:c(AK)}),RK=o0.extend({method:i("notifications/roots/list_changed"),params:u0.optional()}),uz=R2([o6,yV,UK,aV,fV,gV,bV,UV,MV,RV,IV,iV,oV,i6,a6,s6,t6]),oz=R2([u6,p6,NX,RK,A8]),pz=R2([X1,X9,Q9,J9,_K,n6,r6,Q1]),iz=R2([o6,Z9,Y9,MK,i6,a6,s6,t6]),nz=R2([u6,p6,rV,SV,p7,_8,e7,A8,wK]),az=R2([X1,d7,B9,t7,i7,l7,c7,o7,h$,$9,n6,r6,Q1]);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 Y=X;if(Y.elicitations)return new CX(Y.elicitations,Z)}return new r($,Z,X)}}class CX extends r{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super($2.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}class W9{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
174
|
-
`);if($===-1)return null;let Z=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),CK(Z)}clear(){this._buffer=void 0}}function CK($){return T$.parse(JSON.parse($))}function IX($){return JSON.stringify($)+`
|
|
175
|
-
`}var SK=e6.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function TK(){let $={};for(let Z of SK){let X=e6.env[Z];if(X===void 0)continue;if(X.startsWith("()"))continue;$[Z]=X}return $}class R8{constructor($){if(this._readBuffer=new W9,this._stderrStream=null,this._serverParams=$,$.stderr==="pipe"||$.stderr==="overlapped")this._stderrStream=new kK}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=kX.default(this._serverParams.command,this._serverParams.args??[],{env:{...TK(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:e6.platform==="win32"&&hK(),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=IX($);if(this._process.stdin.write(X))Z();else this._process.stdin.once("drain",Z)})}}function hK(){return"type"in e6}var g$={};b2(g$,{layer:()=>hX,defaultLayer:()=>fK,Tokens:()=>SX,Service:()=>$4,McpAuth:()=>g$,Entry:()=>EK,ClientInfo:()=>TX});import gK from"path";var SX=N.object({accessToken:N.string(),refreshToken:N.string().optional(),expiresAt:N.number().optional(),scope:N.string().optional()}),TX=N.object({clientId:N.string(),clientSecret:N.string().optional(),clientIdIssuedAt:N.number().optional(),clientSecretExpiresAt:N.number().optional()}),EK=N.object({tokens:SX.optional(),clientInfo:TX.optional(),codeVerifier:N.string().optional(),oauthState:N.string().optional(),serverUrl:N.string().optional()}),C8=gK.join(w$.Path.data,"mcp-auth.json");class $4 extends Z2.Service()("@qitqode/McpAuth"){}var hX=_.effect($4,Q.gen(function*(){let $=yield*s2.Service,Z=F6.makeUnsafe(1),X=Q.fn("McpAuth.read")(function*(){return yield*$.readJson(C8).pipe(Q.map((F)=>F),Q.catch(()=>Q.succeed({})))}),Y=Q.fn("McpAuth.all")(function*(){let F=yield*X();return Object.fromEntries(Object.entries(F).filter(([b])=>!b.includes("\x00")))}),J=Q.fn("McpAuth.get")(function*(F){return(yield*X())[F]}),B=Q.fn("McpAuth.getForUrl")(function*(F,b){let O=yield*J(F);if(!O)return;if(!O.serverUrl)return;if(O.serverUrl!==b)return;return O}),W=Q.fn("McpAuth.set")(function*(F,b,O){yield*Z.withPermits(1)(Q.gen(function*(){let M=yield*X();if(O)b.serverUrl=O;yield*$.writeJson(C8,{...M,[F]:b},384).pipe(Q.orDie)}))}),G=Q.fn("McpAuth.remove")(function*(F){yield*Z.withPermits(1)(Q.gen(function*(){let b=yield*X();delete b[F],yield*$.writeJson(C8,b,384).pipe(Q.orDie)}))}),H=(F,b)=>Q.fn(`McpAuth.${b}`)(function*(O,M,I){yield*Z.withPermits(1)(Q.gen(function*(){let k=yield*X(),E=k[O]??{};if(E[F]=M,I)E.serverUrl=I;yield*$.writeJson(C8,{...k,[O]:E},384).pipe(Q.orDie)}))}),V=(F,b)=>Q.fn(`McpAuth.${b}`)(function*(O){yield*Z.withPermits(1)(Q.gen(function*(){let M=yield*X(),I=M[O];if(!I)return;delete I[F],yield*$.writeJson(C8,M,384).pipe(Q.orDie)}))}),K=H("tokens","updateTokens"),y=H("clientInfo","updateClientInfo"),j=H("codeVerifier","updateCodeVerifier"),q=H("oauthState","updateOAuthState"),z=V("codeVerifier","clearCodeVerifier"),D=V("oauthState","clearOAuthState"),U=Q.fn("McpAuth.getOAuthState")(function*(F){return(yield*J(F))?.oauthState}),P=Q.fn("McpAuth.isTokenExpired")(function*(F){let b=yield*J(F);if(!b?.tokens)return null;if(!b.tokens.expiresAt)return!1;return b.tokens.expiresAt<Date.now()/1000});return $4.of({all:Y,get:J,getForUrl:B,set:W,remove:G,updateTokens:K,updateClientInfo:y,updateCodeVerifier:j,clearCodeVerifier:z,updateOAuthState:q,getOAuthState:U,clearOAuthState:D,isTokenExpired:P})})),fK=hX.pipe(_.provide(s2.defaultLayer));var vK=F2.object({name:F2.string(),uri:F2.string(),description:F2.string().optional(),mimeType:F2.string().optional(),client:F2.string()}).meta({ref:"McpResource"}),K9=O2.define("mcp.tools.changed",F2.object({server:F2.string()})),H9=O2.define("mcp.browser.open.failed",F2.object({mcpName:F2.string(),url:F2.string()})),Z4=O2.define("mcp.auth.required",F2.object({server:F2.string(),reason:F2.enum(["client_registration","login"])})),dK=x2.create("MCPFailed",F2.object({name:F2.string()})),mK=F2.discriminatedUnion("status",[F2.object({status:F2.literal("connected")}).meta({ref:"MCPStatusConnected"}),F2.object({status:F2.literal("disabled")}).meta({ref:"MCPStatusDisabled"}),F2.object({status:F2.literal("pending")}).meta({ref:"MCPStatusPending"}),F2.object({status:F2.literal("failed"),error:F2.string()}).meta({ref:"MCPStatusFailed"}),F2.object({status:F2.literal("needs_auth")}).meta({ref:"MCPStatusNeedsAuth"}),F2.object({status:F2.literal("needs_client_registration"),error:F2.string()}).meta({ref:"MCPStatusNeedsClientRegistration"})]).meta({ref:"MCPStatus"});var Y4=30000,G9=a.create({service:"mcp.catalog"}),X4=($)=>$.replace(/[^a-zA-Z0-9_-]/g,"_");function I8($){return typeof $==="object"&&$!==null&&"type"in $}function lK($,Z,X){let Y=$.inputSchema,J={...Y,type:"object",properties:Y.properties??{},additionalProperties:!1};return gX({description:$.description??"",inputSchema:K$(J),execute:async(B)=>Z.callTool({name:$.name,arguments:B||{}},h$,{resetTimeoutOnProgress:!0,timeout:X})})}function S1($,Z,X){return Q.tryPromise({try:()=>Q4(Z.listTools(),X??Y4),catch:(Y)=>Y instanceof Error?Y:Error(String(Y))}).pipe(Q.map((Y)=>Y.tools),Q.catch((Y)=>{return G9.error("failed to get tools from client",{key:$,error:Y}),Q.succeed(void 0)}))}function cK($,Z,X,Y){return Q.tryPromise({try:()=>X(Z),catch:(J)=>{return G9.error(`failed to get ${Y}`,{clientName:$,error:J instanceof Error?J.message:String(J)}),J}}).pipe(Q.map((J)=>{let B={},W=X4($);for(let G of J)B[W+":"+X4(G.name)]={...G,client:$};return B}),Q.orElseSucceed(()=>{return}))}function EX($,Z,X){let Y={};for(let[J,B]of Object.entries($.clients)){if($.status[J]?.status!=="connected")continue;let W=$.defs[J];if(!W){G9.warn("missing cached tools for connected server",{clientName:J});continue}let H=(I8(Z[J])?Z[J]:void 0)?.timeout??X;for(let V of W)Y[X4(J)+"_"+X4(V.name)]=lK(V,B,H)}return Y}function j9($,Z,X){return Q.forEach(Object.entries($.clients).filter(([Y])=>$.status[Y]?.status==="connected"),([Y,J])=>cK(Y,J,Z,X).pipe(Q.map((B)=>Object.entries(B??{}))),{concurrency:8}).pipe(Q.map((Y)=>Object.fromEntries(Y.flat())))}function fX($,Z){return $.type==="local"&&Z?.type==="claude"}function T1($){return!!$._zod}function Z$($,Z){if(T1($))return O9($,Z);return $.safeParse(Z)}function J4($){if(!$)return;let Z;if(T1($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function vX($){if(T1($)){let B=$._zod?.def;if(B){if(B.value!==void 0)return B.value;if(Array.isArray(B.values)&&B.values.length>0)return B.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 Y=$.value;if(Y!==void 0)return Y;return}function E$($){return $==="completed"||$==="failed"||$==="cancelled"}function F9($){let X=J4($)?.method;if(!X)throw Error("Schema is missing a method literal");let Y=vX(X);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function z9($,Z){let X=Z$($,Z);if(!X.success)throw X.error;return X.data}var oK=60000;class y9{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(u6,(Z)=>{this._oncancel(Z)}),this.setNotificationHandler(p6,(Z)=>{this._onprogress(Z)}),this.setRequestHandler(o6,(Z)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(i6,async(Z,X)=>{let Y=await this._taskStore.getTask(Z.params.taskId,X.sessionId);if(!Y)throw new r($2.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(a6,async(Z,X)=>{let Y=async()=>{let J=Z.params.taskId;if(this._taskMessageQueue){let W;while(W=await this._taskMessageQueue.dequeue(J,X.sessionId)){if(W.type==="response"||W.type==="error"){let G=W.message,H=G.id,V=this._requestResolvers.get(H);if(V)if(this._requestResolvers.delete(H),W.type==="response")V(G);else{let K=G,y=new r(K.error.code,K.error.message,K.error.data);V(y)}else{let K=W.type==="response"?"Response":"Error";this._onerror(Error(`${K} handler missing for request ${H}`))}continue}await this._transport?.send(W.message,{relatedRequestId:X.requestId})}}let B=await this._taskStore.getTask(J,X.sessionId);if(!B)throw new r($2.InvalidParams,`Task not found: ${J}`);if(!E$(B.status))return await this._waitForTaskUpdate(J,X.signal),await Y();if(E$(B.status)){let W=await this._taskStore.getTaskResult(J,X.sessionId);return this._clearTaskQueue(J),{...W,_meta:{...W._meta,[S$]:{taskId:J}}}}return await Y()};return await Y()}),this.setRequestHandler(s6,async(Z,X)=>{try{let{tasks:Y,nextCursor:J}=await this._taskStore.listTasks(Z.params?.cursor,X.sessionId);return{tasks:Y,nextCursor:J,_meta:{}}}catch(Y){throw new r($2.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(t6,async(Z,X)=>{try{let Y=await this._taskStore.getTask(Z.params.taskId,X.sessionId);if(!Y)throw new r($2.InvalidParams,`Task not found: ${Z.params.taskId}`);if(E$(Y.status))throw new r($2.InvalidParams,`Cannot cancel task in terminal status: ${Y.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(Y){if(Y instanceof r)throw Y;throw new r($2.InvalidRequest,`Failed to cancel task: ${Y instanceof Error?Y.message:String(Y)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,Z,X,Y,J=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Y,Z),startTime:Date.now(),timeout:Z,maxTotalTimeout:X,resetTimeoutOnProgress:J,onTimeout:Y})}_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 Y=this._transport?.onmessage;this._transport.onmessage=(J,B)=>{if(Y?.(J,B),Z1(J)||qX(J))this._onresponse(J);else if(w8(J))this._onrequest(J,B);else if(DX(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,Y=this._transport,J=$.params?._meta?.[S$]?.taskId;if(X===void 0){let V={jsonrpc:"2.0",id:$.id,error:{code:$2.MethodNotFound,message:"Method not found"}};if(J&&this._taskMessageQueue)this._enqueueTaskMessage(J,{type:"error",message:V,timestamp:Date.now()},Y?.sessionId).catch((K)=>this._onerror(Error(`Failed to enqueue error response: ${K}`)));else Y?.send(V).catch((K)=>this._onerror(Error(`Failed to send an error response: ${K}`)));return}let B=new AbortController;this._requestHandlerAbortControllers.set($.id,B);let W=FX($.params)?$.params.task:void 0,G=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,H={signal:B.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(V)=>{if(B.signal.aborted)return;let K={relatedRequestId:$.id};if(J)K.relatedTask={taskId:J};await this.notification(V,K)},sendRequest:async(V,K,y)=>{if(B.signal.aborted)throw new r($2.ConnectionClosed,"Request was cancelled");let j={...y,relatedRequestId:$.id};if(J&&!j.relatedTask)j.relatedTask={taskId:J};let q=j.relatedTask?.taskId??J;if(q&&G)await G.updateTaskStatus(q,"input_required");return await this.request(V,K,j)},authInfo:Z?.authInfo,requestId:$.id,requestInfo:Z?.requestInfo,taskId:J,taskStore:G,taskRequestedTtl:W?.ttl,closeSSEStream:Z?.closeSSEStream,closeStandaloneSSEStream:Z?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(W)this.assertTaskHandlerCapability($.method)}).then(()=>X($,H)).then(async(V)=>{if(B.signal.aborted)return;let K={result:V,jsonrpc:"2.0",id:$.id};if(J&&this._taskMessageQueue)await this._enqueueTaskMessage(J,{type:"response",message:K,timestamp:Date.now()},Y?.sessionId);else await Y?.send(K)},async(V)=>{if(B.signal.aborted)return;let K={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(V.code)?V.code:$2.InternalError,message:V.message??"Internal error",...V.data!==void 0&&{data:V.data}}};if(J&&this._taskMessageQueue)await this._enqueueTaskMessage(J,{type:"error",message:K,timestamp:Date.now()},Y?.sessionId);else await Y?.send(K)}).catch((V)=>this._onerror(Error(`Failed to send response: ${V}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:Z,...X}=$.params,Y=Number(Z),J=this._progressHandlers.get(Y);if(!J){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let B=this._responseHandlers.get(Y),W=this._timeoutInfo.get(Y);if(W&&B&&W.resetTimeoutOnProgress)try{this._resetTimeout(Y)}catch(G){this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),B(G);return}J(X)}_onresponse($){let Z=Number($.id),X=this._requestResolvers.get(Z);if(X){if(this._requestResolvers.delete(Z),Z1($))X($);else{let B=new r($.error.code,$.error.message,$.error.data);X(B)}return}let Y=this._responseHandlers.get(Z);if(Y===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 B=$.result;if(B.task&&typeof B.task==="object"){let W=B.task;if(typeof W.taskId==="string")J=!0,this._taskProgressTokens.set(W.taskId,Z)}}if(!J)this._progressHandlers.delete(Z);if(Z1($))Y($);else{let B=r.fromError($.error.code,$.error.message,$.error.data);Y(B)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,Z,X){let{task:Y}=X??{};if(!Y){try{yield{type:"result",result:await this.request($,Z,X)}}catch(B){yield{type:"error",error:B instanceof r?B:new r($2.InternalError,String(B))}}return}let J;try{let B=await this.request($,Q1,X);if(B.task)J=B.task.taskId,yield{type:"taskCreated",task:B.task};else throw new r($2.InternalError,"Task creation did not return a task");while(!0){let W=await this.getTask({taskId:J},X);if(yield{type:"taskStatus",task:W},E$(W.status)){if(W.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:J},Z,X)};else if(W.status==="failed")yield{type:"error",error:new r($2.InternalError,`Task ${J} failed`)};else if(W.status==="cancelled")yield{type:"error",error:new r($2.InternalError,`Task ${J} was cancelled`)};return}if(W.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:J},Z,X)};return}let G=W.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((H)=>setTimeout(H,G)),X?.signal?.throwIfAborted()}}catch(B){yield{type:"error",error:B instanceof r?B:new r($2.InternalError,String(B))}}}request($,Z,X){let{relatedRequestId:Y,resumptionToken:J,onresumptiontoken:B,task:W,relatedTask:G}=X??{};return new Promise((H,V)=>{let K=(P)=>{V(P)};if(!this._transport){K(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),W)this.assertTaskCapability($.method)}catch(P){K(P);return}X?.signal?.throwIfAborted();let y=this._requestMessageId++,j={...$,jsonrpc:"2.0",id:y};if(X?.onprogress)this._progressHandlers.set(y,X.onprogress),j.params={...$.params,_meta:{...$.params?._meta||{},progressToken:y}};if(W)j.params={...j.params,task:W};if(G)j.params={...j.params,_meta:{...j.params?._meta||{},[S$]:G}};let q=(P)=>{this._responseHandlers.delete(y),this._progressHandlers.delete(y),this._cleanupTimeout(y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(P)}},{relatedRequestId:Y,resumptionToken:J,onresumptiontoken:B}).catch((b)=>this._onerror(Error(`Failed to send cancellation: ${b}`)));let F=P instanceof r?P:new r($2.RequestTimeout,String(P));V(F)};this._responseHandlers.set(y,(P)=>{if(X?.signal?.aborted)return;if(P instanceof Error)return V(P);try{let F=Z$(Z,P.result);if(!F.success)V(F.error);else H(F.data)}catch(F){V(F)}}),X?.signal?.addEventListener("abort",()=>{q(X?.signal?.reason)});let z=X?.timeout??oK,D=()=>q(r.fromError($2.RequestTimeout,"Request timed out",{timeout:z}));this._setupTimeout(y,z,X?.maxTotalTimeout,D,X?.resetTimeoutOnProgress??!1);let U=G?.taskId;if(U){let P=(F)=>{let b=this._responseHandlers.get(y);if(b)b(F);else this._onerror(Error(`Response handler missing for side-channeled request ${y}`))};this._requestResolvers.set(y,P),this._enqueueTaskMessage(U,{type:"request",message:j,timestamp:Date.now()}).catch((F)=>{this._cleanupTimeout(y),V(F)})}else this._transport.send(j,{relatedRequestId:Y,resumptionToken:J,onresumptiontoken:B}).catch((P)=>{this._cleanupTimeout(y),V(P)})})}async getTask($,Z){return this.request({method:"tasks/get",params:$},n6,Z)}async getTaskResult($,Z,X){return this.request({method:"tasks/result",params:$},Z,X)}async listTasks($,Z){return this.request({method:"tasks/list",params:$},r6,Z)}async cancelTask($,Z){return this.request({method:"tasks/cancel",params:$},xX,Z)}async notification($,Z){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let X=Z?.relatedTask?.taskId;if(X){let W={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[S$]:Z.relatedTask}}};await this._enqueueTaskMessage(X,{type:"notification",message:W,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 W={...$,jsonrpc:"2.0"};if(Z?.relatedTask)W={...W,params:{...W.params,_meta:{...W.params?._meta||{},[S$]:Z.relatedTask}}};this._transport?.send(W,Z).catch((G)=>this._onerror(G))});return}let B={...$,jsonrpc:"2.0"};if(Z?.relatedTask)B={...B,params:{...B.params,_meta:{...B.params?._meta||{},[S$]:Z.relatedTask}}};await this._transport.send(B,Z)}setRequestHandler($,Z){let X=F9($);this.assertRequestHandlerCapability(X),this._requestHandlers.set(X,(Y,J)=>{let B=z9($,Y);return Promise.resolve(Z(B,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=F9($);this._notificationHandlers.set(X,(Y)=>{let J=z9($,Y);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 Y=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,Z,X,Y)}async _clearTaskQueue($,Z){if(this._taskMessageQueue){let X=await this._taskMessageQueue.dequeueAll($,Z);for(let Y of X)if(Y.type==="request"&&w8(Y.message)){let J=Y.message.id,B=this._requestResolvers.get(J);if(B)B(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 Y=await this._taskStore?.getTask($);if(Y?.pollInterval)X=Y.pollInterval}catch{}return new Promise((Y,J)=>{if(Z.aborted){J(new r($2.InvalidRequest,"Request cancelled"));return}let B=setTimeout(Y,X);Z.addEventListener("abort",()=>{clearTimeout(B),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(Y)=>{if(!$)throw Error("No request provided");return await X.createTask(Y,$.id,{method:$.method,params:$.params},Z)},getTask:async(Y)=>{let J=await X.getTask(Y,Z);if(!J)throw new r($2.InvalidParams,"Failed to retrieve task: Task not found");return J},storeTaskResult:async(Y,J,B)=>{await X.storeTaskResult(Y,J,B,Z);let W=await X.getTask(Y,Z);if(W){let G=A8.parse({method:"notifications/tasks/status",params:W});if(await this.notification(G),E$(W.status))this._cleanupTaskProgressHandler(Y)}},getTaskResult:(Y)=>{return X.getTaskResult(Y,Z)},updateTaskStatus:async(Y,J,B)=>{let W=await X.getTask(Y,Z);if(!W)throw new r($2.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(E$(W.status))throw new r($2.InvalidParams,`Cannot update task "${Y}" from terminal status "${W.status}" to "${J}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await X.updateTaskStatus(Y,J,B,Z);let G=await X.getTask(Y,Z);if(G){let H=A8.parse({method:"notifications/tasks/status",params:G});if(await this.notification(H),E$(G.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return X.listTasks(Y,Z)}}}}function dX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function mX($,Z){let X={...$};for(let Y in Z){let J=Y,B=Z[J];if(B===void 0)continue;let W=X[J];if(dX(W)&&dX(B))X[J]={...W,...B};else X[J]=B}return X}var lX=V9(pK(),1),cX=V9(iK(),1);function nK(){let $=new lX.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return cX.default($),$}class D9{constructor($){this._ajv=$??nK()}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 q9{constructor($){this._client=$}async*callToolStream($,Z=h$,X){let Y=this._client,J={...X,task:X?.task??(Y.isToolTask($.name)?{}:void 0)},B=Y.requestStream({method:"tools/call",params:$},Z,J),W=Y.getToolOutputValidator($.name);for await(let G of B){if(G.type==="result"&&W){let H=G.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 V=W(H.structuredContent);if(!V.valid){yield{type:"error",error:new r($2.InvalidParams,`Structured content does not match the tool's output schema: ${V.errorMessage}`)};return}}catch(V){if(V instanceof r){yield{type:"error",error:V};return}yield{type:"error",error:new r($2.InvalidParams,`Failed to validate structured content: ${V instanceof Error?V.message:String(V)}`)};return}}yield G}}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 uX($,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 oX($,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 B4($,Z){if(!$||Z===null||typeof Z!=="object")return;if($.type==="object"&&$.properties&&typeof $.properties==="object"){let X=Z,Y=$.properties;for(let J of Object.keys(Y)){let B=Y[J];if(X[J]===void 0&&Object.prototype.hasOwnProperty.call(B,"default"))X[J]=B.default;if(X[J]!==void 0)B4(B,X[J])}}if(Array.isArray($.anyOf)){for(let X of $.anyOf)if(typeof X!=="boolean")B4(X,Z)}if(Array.isArray($.oneOf)){for(let X of $.oneOf)if(typeof X!=="boolean")B4(X,Z)}}function aK($){if(!$)return{supportsFormMode:!1,supportsUrlMode:!1};let Z=$.form!==void 0,X=$.url!==void 0;return{supportsFormMode:Z||!Z&&!X,supportsUrlMode:X}}class k8 extends y9{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 D9,Z?.listChanged)this._pendingListChangedConfig=Z.listChanged}_setupListChangedHandlers($){if($.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",_8,$.tools,async()=>{return(await this.listTools()).tools});if($.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",e7,$.prompts,async()=>{return(await this.listPrompts()).prompts});if($.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",p7,$.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new q9(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=mX(this._capabilities,$)}setRequestHandler($,Z){let Y=J4($)?.method;if(!Y)throw Error("Schema is missing a method literal");let J;if(T1(Y)){let W=Y;J=W._zod?.def?.value??W.value}else{let W=Y;J=W._def?.value??W.value}if(typeof J!=="string")throw Error("Schema method literal must be a string");let B=J;if(B==="elicitation/create"){let W=async(G,H)=>{let V=Z$(Y9,G);if(!V.success){let P=V.error instanceof Error?V.error.message:String(V.error);throw new r($2.InvalidParams,`Invalid elicitation request: ${P}`)}let{params:K}=V.data;K.mode=K.mode??"form";let{supportsFormMode:y,supportsUrlMode:j}=aK(this._capabilities.elicitation);if(K.mode==="form"&&!y)throw new r($2.InvalidParams,"Client does not support form-mode elicitation requests");if(K.mode==="url"&&!j)throw new r($2.InvalidParams,"Client does not support URL-mode elicitation requests");let q=await Promise.resolve(Z(G,H));if(K.task){let P=Z$(Q1,q);if(!P.success){let F=P.error instanceof Error?P.error.message:String(P.error);throw new r($2.InvalidParams,`Invalid task creation result: ${F}`)}return P.data}let z=Z$(J9,q);if(!z.success){let P=z.error instanceof Error?z.error.message:String(z.error);throw new r($2.InvalidParams,`Invalid elicitation result: ${P}`)}let D=z.data,U=K.mode==="form"?K.requestedSchema:void 0;if(K.mode==="form"&&D.action==="accept"&&D.content&&U){if(this._capabilities.elicitation?.form?.applyDefaults)try{B4(U,D.content)}catch{}}return D};return super.setRequestHandler($,W)}if(B==="sampling/createMessage"){let W=async(G,H)=>{let V=Z$(Z9,G);if(!V.success){let D=V.error instanceof Error?V.error.message:String(V.error);throw new r($2.InvalidParams,`Invalid sampling request: ${D}`)}let{params:K}=V.data,y=await Promise.resolve(Z(G,H));if(K.task){let D=Z$(Q1,y);if(!D.success){let U=D.error instanceof Error?D.error.message:String(D.error);throw new r($2.InvalidParams,`Invalid task creation result: ${U}`)}return D.data}let q=K.tools||K.toolChoice?Q9:X9,z=Z$(q,y);if(!z.success){let D=z.error instanceof Error?z.error.message:String(z.error);throw new r($2.InvalidParams,`Invalid sampling result: ${D}`)}return z.data};return super.setRequestHandler($,W)}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:I1,capabilities:this._capabilities,clientInfo:this._clientInfo}},d7,Z);if(X===void 0)throw Error(`Server sent invalid initialize result: ${X}`);if(!GX.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($){uX(this._serverCapabilities?.tasks?.requests,$,"Server")}assertTaskHandlerCapability($){if(!this._capabilities)return;oX(this._capabilities.tasks?.requests,$,"Client")}async ping($){return this.request({method:"ping"},X1,$)}async complete($,Z){return this.request({method:"completion/complete",params:$},B9,Z)}async setLoggingLevel($,Z){return this.request({method:"logging/setLevel",params:{level:$}},X1,Z)}async getPrompt($,Z){return this.request({method:"prompts/get",params:$},t7,Z)}async listPrompts($,Z){return this.request({method:"prompts/list",params:$},i7,Z)}async listResources($,Z){return this.request({method:"resources/list",params:$},l7,Z)}async listResourceTemplates($,Z){return this.request({method:"resources/templates/list",params:$},c7,Z)}async readResource($,Z){return this.request({method:"resources/read",params:$},o7,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=h$,X){if(this.isToolTaskRequired($.name))throw new r($2.InvalidRequest,`Tool "${$.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let Y=await this.request({method:"tools/call",params:$},Z,X),J=this.getToolOutputValidator($.name);if(J){if(!Y.structuredContent&&!Y.isError)throw new r($2.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`);if(Y.structuredContent)try{let B=J(Y.structuredContent);if(!B.valid)throw new r($2.InvalidParams,`Structured content does not match the tool's output schema: ${B.errorMessage}`)}catch(B){if(B instanceof r)throw B;throw new r($2.InvalidParams,`Failed to validate structured content: ${B instanceof Error?B.message:String(B)}`)}}return Y}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 Y=this._jsonSchemaValidator.getValidator(Z.outputSchema);this._cachedToolOutputValidators.set(Z.name,Y)}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:$},$9,Z);return this.cacheToolMetadata(X.tools),X}_setupListChangedHandler($,Z,X,Y){let J=_X.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:B,debounceMs:W}=J.data,{onChanged:G}=X,H=async()=>{if(!B){G(null,null);return}try{let K=await Y();G(null,K)}catch(K){let y=K instanceof Error?K:Error(String(K));G(y,null)}},V=()=>{if(W){let K=this._listChangedDebounceTimers.get($);if(K)clearTimeout(K);let y=setTimeout(H,W);this._listChangedDebounceTimers.set($,y)}else H()};this.setNotificationHandler(Z,V)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}function h1($){if(!$)return{};if($ instanceof Headers)return Object.fromEntries($.entries());if(Array.isArray($))return Object.fromEntries($);return{...$}}function W4($=fetch,Z){if(!Z)return $;return async(X,Y)=>{let J={...Z,...Y,headers:Y?.headers?{...h1(Z.headers),...h1(Y.headers)}:Z.headers};return $(X,J)}}var P9;P9=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(($)=>$.webcrypto);async function sK($){return(await P9).getRandomValues(new Uint8Array($))}async function rK($){let X=Math.pow(2,8)-Math.pow(2,8)%66,Y="";while(Y.length<$){let J=await sK($-Y.length);for(let B of J)if(B<X)Y+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[B%66]}return Y}async function tK($){return await rK($)}async function eK($){let Z=await(await P9).subtle.digest("SHA-256",new TextEncoder().encode($));return btoa(String.fromCharCode(...new Uint8Array(Z))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function N9($){if(!$)$=43;if($<43||$>128)throw`Expected a length between 43 and 128. Received ${$}.`;let Z=await tK($),X=await eK(Z);return{code_verifier:Z,code_challenge:X}}var V0=nX().superRefine(($,Z)=>{if(!URL.canParse($))return Z.addIssue({code:sX.custom,message:"URL must be parseable",fatal:!0}),iX}).refine(($)=>{let Z=new URL($);return Z.protocol!=="javascript:"&&Z.protocol!=="data:"&&Z.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),tX=a2({resource:x().url(),authorization_servers:c(V0).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:M2().optional(),authorization_details_types_supported:c(x()).optional(),dpop_signing_alg_values_supported:c(x()).optional(),dpop_bound_access_tokens_required:M2().optional()}),w9=a2({issuer:x(),authorization_endpoint:V0,token_endpoint:V0,registration_endpoint:V0.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:V0.optional(),revocation_endpoint:V0.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:M2().optional()}),$3=a2({issuer:x(),authorization_endpoint:V0,token_endpoint:V0,userinfo_endpoint:V0.optional(),jwks_uri:V0,registration_endpoint:V0.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:M2().optional(),request_parameter_supported:M2().optional(),request_uri_parameter_supported:M2().optional(),require_request_uri_registration:M2().optional(),op_policy_uri:V0.optional(),op_tos_uri:V0.optional(),client_id_metadata_document_supported:M2().optional()}),eX=u({...$3.shape,...w9.pick({code_challenge_methods_supported:!0}).shape}),$Q=u({access_token:x(),id_token:x().optional(),token_type:x(),expires_in:rX.number().optional(),scope:x().optional(),refresh_token:x().optional()}).strip(),ZQ=u({error:x(),error_description:x().optional(),error_uri:x().optional()}),pX=V0.optional().or(i("").transform(()=>{return})),Z3=u({redirect_uris:c(V0),token_endpoint_auth_method:x().optional(),grant_types:c(x()).optional(),response_types:c(x()).optional(),client_name:x().optional(),client_uri:V0.optional(),logo_uri:pX,scope:x().optional(),contacts:c(x()).optional(),tos_uri:pX,policy_uri:x().optional(),jwks_uri:V0.optional(),jwks:aX().optional(),software_id:x().optional(),software_version:x().optional(),software_statement:x().optional()}).strip(),X3=u({client_id:x(),client_secret:x().optional(),client_id_issued_at:D2().optional(),client_secret_expires_at:D2().optional()}).strip(),XQ=Z3.merge(X3),QD=u({error:x(),error_description:x().optional()}).strip(),YD=u({token:x(),token_type_hint:x().optional()}).strip();function QQ($){let Z=typeof $==="string"?new URL($):new URL($.href);return Z.hash="",Z}function YQ({requestedResource:$,configuredResource:Z}){let X=typeof $==="string"?new URL($):new URL($.href),Y=typeof Z==="string"?new URL(Z):new URL(Z.href);if(X.origin!==Y.origin)return!1;if(X.pathname.length<Y.pathname.length)return!1;let J=X.pathname.endsWith("/")?X.pathname:X.pathname+"/",B=Y.pathname.endsWith("/")?Y.pathname:Y.pathname+"/";return J.startsWith(B)}class p2 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 V4 extends p2{}V4.errorCode="invalid_request";class g1 extends p2{}g1.errorCode="invalid_client";class E1 extends p2{}E1.errorCode="invalid_grant";class f1 extends p2{}f1.errorCode="unauthorized_client";class K4 extends p2{}K4.errorCode="unsupported_grant_type";class H4 extends p2{}H4.errorCode="invalid_scope";class G4 extends p2{}G4.errorCode="access_denied";class f$ extends p2{}f$.errorCode="server_error";class j4 extends p2{}j4.errorCode="temporarily_unavailable";class O4 extends p2{}O4.errorCode="unsupported_response_type";class F4 extends p2{}F4.errorCode="unsupported_token_type";class z4 extends p2{}z4.errorCode="invalid_token";class y4 extends p2{}y4.errorCode="method_not_allowed";class D4 extends p2{}D4.errorCode="too_many_requests";class v1 extends p2{}v1.errorCode="invalid_client_metadata";class q4 extends p2{}q4.errorCode="insufficient_scope";class P4 extends p2{}P4.errorCode="invalid_target";var JQ={[V4.errorCode]:V4,[g1.errorCode]:g1,[E1.errorCode]:E1,[f1.errorCode]:f1,[K4.errorCode]:K4,[H4.errorCode]:H4,[G4.errorCode]:G4,[f$.errorCode]:f$,[j4.errorCode]:j4,[O4.errorCode]:O4,[F4.errorCode]:F4,[z4.errorCode]:z4,[y4.errorCode]:y4,[D4.errorCode]:D4,[v1.errorCode]:v1,[q4.errorCode]:q4,[P4.errorCode]:P4};class X0 extends Error{constructor($){super($??"Unauthorized")}}function Q3($){return["client_secret_basic","client_secret_post","none"].includes($)}var x9="code",L9="S256";function Y3($,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&&Q3($.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 J3($,Z,X,Y){let{client_id:J,client_secret:B}=Z;switch($){case"client_secret_basic":B3(J,B,X);return;case"client_secret_post":W3(J,B,Y);return;case"none":V3(J,Y);return;default:throw Error(`Unsupported client authentication method: ${$}`)}}function B3($,Z,X){if(!Z)throw Error("client_secret_basic authentication requires a client_secret");let Y=btoa(`${$}:${Z}`);X.set("Authorization",`Basic ${Y}`)}function W3($,Z,X){if(X.set("client_id",$),Z)X.set("client_secret",Z)}function V3($,Z){Z.set("client_id",$)}async function WQ($){let Z=$ instanceof Response?$.status:void 0,X=$ instanceof Response?await $.text():$;try{let Y=ZQ.parse(JSON.parse(X)),{error:J,error_description:B,error_uri:W}=Y;return new(JQ[J]||f$)(B||"",W)}catch(Y){let J=`${Z?`HTTP ${Z}: `:""}Invalid OAuth error response: ${Y}. Raw body: ${X}`;return new f$(J)}}async function x$($,Z){try{return await b9($,Z)}catch(X){if(X instanceof g1||X instanceof f1)return await $.invalidateCredentials?.("all"),await b9($,Z);else if(X instanceof E1)return await $.invalidateCredentials?.("tokens"),await b9($,Z);throw X}}async function b9($,{serverUrl:Z,authorizationCode:X,scope:Y,resourceMetadataUrl:J,fetchFn:B}){let W=await $.discoveryState?.(),G,H,V,K=J;if(!K&&W?.resourceMetadataUrl)K=new URL(W.resourceMetadataUrl);if(W?.authorizationServerUrl){if(H=W.authorizationServerUrl,G=W.resourceMetadata,V=W.authorizationServerMetadata??await KQ(H,{fetchFn:B}),!G)try{G=await VQ(Z,{resourceMetadataUrl:K},B)}catch{}if(V!==W.authorizationServerMetadata||G!==W.resourceMetadata)await $.saveDiscoveryState?.({authorizationServerUrl:String(H),resourceMetadataUrl:K?.toString(),resourceMetadata:G,authorizationServerMetadata:V})}else{let F=await z3(Z,{resourceMetadataUrl:K,fetchFn:B});H=F.authorizationServerUrl,V=F.authorizationServerMetadata,G=F.resourceMetadata,await $.saveDiscoveryState?.({authorizationServerUrl:String(H),resourceMetadataUrl:K?.toString(),resourceMetadata:G,authorizationServerMetadata:V})}let y=await H3(Z,$,G),j=await Promise.resolve($.clientInformation());if(!j){if(X!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let F=V?.client_id_metadata_document_supported===!0,b=$.clientMetadataUrl;if(b&&!K3(b))throw new v1(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${b}`);if(F&&b)j={client_id:b},await $.saveClientInformation?.(j);else{if(!$.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let M=await N3(H,{metadata:V,clientMetadata:$.clientMetadata,fetchFn:B});await $.saveClientInformation(M),j=M}}let q=!$.redirectUrl;if(X!==void 0||q){let F=await P3($,H,{metadata:V,resource:y,authorizationCode:X,fetchFn:B});return await $.saveTokens(F),"AUTHORIZED"}let z=await $.tokens();if(z?.refresh_token)try{let F=await q3(H,{metadata:V,clientInformation:j,refreshToken:z.refresh_token,resource:y,addClientAuthentication:$.addClientAuthentication,fetchFn:B});return await $.saveTokens(F),"AUTHORIZED"}catch(F){if(!(F instanceof p2)||F instanceof f$);else throw F}let D=$.state?await $.state():void 0,{authorizationUrl:U,codeVerifier:P}=await y3(H,{metadata:V,clientInformation:j,state:D,redirectUrl:$.redirectUrl,scope:Y||G?.scopes_supported?.join(" ")||$.clientMetadata.scope,resource:y});return await $.saveCodeVerifier(P),await $.redirectToAuthorization(U),"REDIRECT"}function K3($){if(!$)return!1;try{let Z=new URL($);return Z.protocol==="https:"&&Z.pathname!=="/"}catch{return!1}}async function H3($,Z,X){let Y=QQ($);if(Z.validateResourceURL)return await Z.validateResourceURL(Y,X?.resource);if(!X)return;if(!YQ({requestedResource:Y,configuredResource:X.resource}))throw Error(`Protected resource ${X.resource} does not match expected ${Y} (or origin)`);return new URL(X.resource)}function d1($){let Z=$.headers.get("WWW-Authenticate");if(!Z)return{};let[X,Y]=Z.split(" ");if(X.toLowerCase()!=="bearer"||!Y)return{};let J=U9($,"resource_metadata")||void 0,B;if(J)try{B=new URL(J)}catch{}let W=U9($,"scope")||void 0,G=U9($,"error")||void 0;return{resourceMetadataUrl:B,scope:W,error:G}}function U9($,Z){let X=$.headers.get("WWW-Authenticate");if(!X)return null;let Y=new RegExp(`${Z}=(?:"([^"]+)"|([^\\s,]+))`),J=X.match(Y);if(J)return J[1]||J[2];return null}async function VQ($,Z,X=fetch){let Y=await O3($,"oauth-protected-resource",X,{protocolVersion:Z?.protocolVersion,metadataUrl:Z?.resourceMetadataUrl});if(!Y||Y.status===404)throw await Y?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!Y.ok)throw await Y.body?.cancel(),Error(`HTTP ${Y.status} trying to load well-known OAuth protected resource metadata.`);return tX.parse(await Y.json())}async function A9($,Z,X=fetch){try{return await X($,{headers:Z})}catch(Y){if(Y instanceof TypeError)if(Z)return A9($,void 0,X);else return;throw Y}}function G3($,Z="",X={}){if(Z.endsWith("/"))Z=Z.slice(0,-1);return X.prependPathname?`${Z}/.well-known/${$}`:`/.well-known/${$}${Z}`}async function BQ($,Z,X=fetch){return await A9($,{"MCP-Protocol-Version":Z},X)}function j3($,Z){return!$||$.status>=400&&$.status<500&&Z!=="/"}async function O3($,Z,X,Y){let J=new URL($),B=Y?.protocolVersion??I1,W;if(Y?.metadataUrl)W=new URL(Y.metadataUrl);else{let H=G3(Z,J.pathname);W=new URL(H,Y?.metadataServerUrl??J),W.search=J.search}let G=await BQ(W,B,X);if(!Y?.metadataUrl&&j3(G,J.pathname)){let H=new URL(`/.well-known/${Z}`,J);G=await BQ(H,B,X)}return G}function F3($){let Z=typeof $==="string"?new URL($):$,X=Z.pathname!=="/",Y=[];if(!X)return Y.push({url:new URL("/.well-known/oauth-authorization-server",Z.origin),type:"oauth"}),Y.push({url:new URL("/.well-known/openid-configuration",Z.origin),type:"oidc"}),Y;let J=Z.pathname;if(J.endsWith("/"))J=J.slice(0,-1);return Y.push({url:new URL(`/.well-known/oauth-authorization-server${J}`,Z.origin),type:"oauth"}),Y.push({url:new URL(`/.well-known/openid-configuration${J}`,Z.origin),type:"oidc"}),Y.push({url:new URL(`${J}/.well-known/openid-configuration`,Z.origin),type:"oidc"}),Y}async function KQ($,{fetchFn:Z=fetch,protocolVersion:X=I1}={}){let Y={"MCP-Protocol-Version":X,Accept:"application/json"},J=F3($);for(let{url:B,type:W}of J){let G=await A9(B,Y,Z);if(!G)continue;if(!G.ok){if(await G.body?.cancel(),G.status>=400&&G.status<500)continue;throw Error(`HTTP ${G.status} trying to load ${W==="oauth"?"OAuth":"OpenID provider"} metadata from ${B}`)}if(W==="oauth")return w9.parse(await G.json());else return eX.parse(await G.json())}return}async function z3($,Z){let X,Y;try{if(X=await VQ($,{resourceMetadataUrl:Z?.resourceMetadataUrl},Z?.fetchFn),X.authorization_servers&&X.authorization_servers.length>0)Y=X.authorization_servers[0]}catch{}if(!Y)Y=String(new URL("/",$));let J=await KQ(Y,{fetchFn:Z?.fetchFn});return{authorizationServerUrl:Y,authorizationServerMetadata:J,resourceMetadata:X}}async function y3($,{metadata:Z,clientInformation:X,redirectUrl:Y,scope:J,state:B,resource:W}){let G;if(Z){if(G=new URL(Z.authorization_endpoint),!Z.response_types_supported.includes(x9))throw Error(`Incompatible auth server: does not support response type ${x9}`);if(Z.code_challenge_methods_supported&&!Z.code_challenge_methods_supported.includes(L9))throw Error(`Incompatible auth server: does not support code challenge method ${L9}`)}else G=new URL("/authorize",$);let H=await N9(),V=H.code_verifier,K=H.code_challenge;if(G.searchParams.set("response_type",x9),G.searchParams.set("client_id",X.client_id),G.searchParams.set("code_challenge",K),G.searchParams.set("code_challenge_method",L9),G.searchParams.set("redirect_uri",String(Y)),B)G.searchParams.set("state",B);if(J)G.searchParams.set("scope",J);if(J?.includes("offline_access"))G.searchParams.append("prompt","consent");if(W)G.searchParams.set("resource",W.href);return{authorizationUrl:G,codeVerifier:V}}function D3($,Z,X){return new URLSearchParams({grant_type:"authorization_code",code:$,code_verifier:Z,redirect_uri:String(X)})}async function HQ($,{metadata:Z,tokenRequestParams:X,clientInformation:Y,addClientAuthentication:J,resource:B,fetchFn:W}){let G=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(B)X.set("resource",B.href);if(J)await J(H,X,G,Z);else if(Y){let K=Z?.token_endpoint_auth_methods_supported??[],y=Y3(Y,K);J3(y,Y,H,X)}let V=await(W??fetch)(G,{method:"POST",headers:H,body:X});if(!V.ok)throw await WQ(V);return $Q.parse(await V.json())}async function q3($,{metadata:Z,clientInformation:X,refreshToken:Y,resource:J,addClientAuthentication:B,fetchFn:W}){let G=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y}),H=await HQ($,{metadata:Z,tokenRequestParams:G,clientInformation:X,addClientAuthentication:B,resource:J,fetchFn:W});return{refresh_token:Y,...H}}async function P3($,Z,{metadata:X,resource:Y,authorizationCode:J,fetchFn:B}={}){let W=$.clientMetadata.scope,G;if($.prepareTokenRequest)G=await $.prepareTokenRequest(W);if(!G){if(!J)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!$.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");let V=await $.codeVerifier();G=D3(J,V,$.redirectUrl)}let H=await $.clientInformation();return HQ(Z,{metadata:X,tokenRequestParams:G,clientInformation:H??void 0,addClientAuthentication:$.addClientAuthentication,resource:Y,fetchFn:B})}async function N3($,{metadata:Z,clientMetadata:X,fetchFn:Y}){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 B=await(Y??fetch)(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)});if(!B.ok)throw await WQ(B);return XQ.parse(await B.json())}var w3={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Y1 extends Error{constructor($,Z){super(`Streamable HTTP error: ${Z}`);this.code=$}}class S8{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=W4(Z?.fetch,Z?.requestInit),this._sessionId=Z?.sessionId,this._reconnectionOptions=Z?.reconnectionOptions??w3}async _authThenStart(){if(!this._authProvider)throw new X0("No auth provider");let $;try{$=await x$(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 X0;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=h1(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 Y=await(this._fetch??fetch)(this._url,{method:"GET",headers:X,signal:this._abortController?.signal});if(!Y.ok){if(await Y.body?.cancel(),Y.status===401&&this._authProvider)return await this._authThenStart();if(Y.status===405)return;throw new Y1(Y.status,`Failed to open SSE stream: ${Y.statusText}`)}this._handleSseStream(Y.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,Y=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Z*Math.pow(X,$),Y)}_scheduleReconnection($,Z=0){let X=this._reconnectionOptions.maxRetries;if(Z>=X){this.onerror?.(Error(`Maximum reconnection attempts (${X}) exceeded.`));return}let Y=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)})},Y)}_handleSseStream($,Z,X){if(!$)return;let{onresumptiontoken:Y,replayMessageId:J}=Z,B,W=!1,G=!1;(async()=>{try{let V=$.pipeThrough(new TextDecoderStream).pipeThrough(new GQ({onRetry:(j)=>{this._serverRetryMs=j}})).getReader();while(!0){let{value:j,done:q}=await V.read();if(q)break;if(j.id)B=j.id,W=!0,Y?.(j.id);if(!j.data)continue;if(!j.event||j.event==="message")try{let z=T$.parse(JSON.parse(j.data));if(Z1(z)){if(G=!0,J!==void 0)z.id=J}this.onmessage?.(z)}catch(z){this.onerror?.(z)}}if((X||W)&&!G&&this._abortController&&!this._abortController.signal.aborted)this._scheduleReconnection({resumptionToken:B,onresumptiontoken:Y,replayMessageId:J},0)}catch(V){if(this.onerror?.(Error(`SSE stream disconnected: ${V}`)),(X||W)&&!G&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:B,onresumptiontoken:Y,replayMessageId:J},0)}catch(j){this.onerror?.(Error(`Failed to reconnect: ${j instanceof Error?j.message:String(j)}`))}}})()}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 X0("No auth provider");if(await x$(this._authProvider,{serverUrl:this._url,authorizationCode:$,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new X0("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:Y}=Z||{};if(X){this._startOrAuthSse({resumptionToken:X,replayMessageId:w8($)?$.id:void 0}).catch((y)=>this.onerror?.(y));return}let J=await this._commonHeaders();J.set("content-type","application/json"),J.set("accept","application/json, text/event-stream");let B={...this._requestInit,method:"POST",headers:J,body:JSON.stringify($),signal:this._abortController?.signal},W=await(this._fetch??fetch)(this._url,B),G=W.headers.get("mcp-session-id");if(G)this._sessionId=G;if(!W.ok){let y=await W.text().catch(()=>null);if(W.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Y1(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:j,scope:q}=d1(W);if(this._resourceMetadataUrl=j,this._scope=q,await x$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new X0;return this._hasCompletedAuthFlow=!0,this.send($)}if(W.status===403&&this._authProvider){let{resourceMetadataUrl:j,scope:q,error:z}=d1(W);if(z==="insufficient_scope"){let D=W.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===D)throw new Y1(403,"Server returned 403 after trying upscoping");if(q)this._scope=q;if(j)this._resourceMetadataUrl=j;if(this._lastUpscopingHeader=D??void 0,await x$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new X0;return this.send($)}}throw new Y1(W.status,`Error POSTing to endpoint: ${y}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,W.status===202){if(await W.body?.cancel(),wX($))this._startOrAuthSse({resumptionToken:void 0}).catch((y)=>this.onerror?.(y));return}let V=(Array.isArray($)?$:[$]).filter((y)=>("method"in y)&&("id"in y)&&y.id!==void 0).length>0,K=W.headers.get("content-type");if(V)if(K?.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:Y},!1);else if(K?.includes("application/json")){let y=await W.json(),j=Array.isArray(y)?y.map((q)=>T$.parse(q)):[T$.parse(y)];for(let q of j)this.onmessage?.(q)}else throw await W.body?.cancel(),new Y1(-1,`Unexpected content type: ${K}`);else await W.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 Y1(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 T8=a.create({service:"mcp.oauth"}),l1=19876,m1="/mcp/oauth/callback";class h8{mcpName;serverUrl;config;callbacks;auth;authKey;constructor($,Z,X,Y,J,B){this.mcpName=$;this.serverUrl=Z;this.config=X;this.callbacks=Y;this.auth=J;this.authKey=B??$}get redirectUrl(){if(this.config.redirectUri)return this.config.redirectUri;return`http://127.0.0.1:${l1}${m1}`}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 Q.runPromise(this.auth.getForUrl(this.mcpName,this.serverUrl));if($?.clientInfo){if($.clientInfo.clientSecretExpiresAt&&$.clientInfo.clientSecretExpiresAt<Date.now()/1000){T8.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 Q.runPromise(this.auth.updateClientInfo(this.mcpName,{clientId:$.client_id,clientSecret:$.client_secret,clientIdIssuedAt:$.client_id_issued_at,clientSecretExpiresAt:$.client_secret_expires_at},this.serverUrl)),T8.info("saved dynamically registered client",{mcpName:this.mcpName,clientId:$.client_id})}async tokens(){let $=await Q.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 Q.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)),T8.info("saved oauth tokens",{mcpName:this.mcpName})}async redirectToAuthorization($){T8.info("redirecting to authorization",{mcpName:this.mcpName,url:$.toString()}),await this.callbacks.onRedirect($)}async saveCodeVerifier($){await Q.runPromise(this.auth.updateCodeVerifier(this.authKey,$))}async codeVerifier(){let $=await Q.runPromise(this.auth.get(this.authKey));if(!$?.codeVerifier)throw Error(`No code verifier saved for MCP server: ${this.mcpName}`);return $.codeVerifier}async saveState($){await Q.runPromise(this.auth.updateOAuthState(this.authKey,$))}async state(){let $=await Q.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 Q.runPromise(this.auth.updateOAuthState(this.authKey,Z)),Z}async invalidateCredentials($){T8.info("invalidating credentials",{mcpName:this.mcpName,type:$});let Z=await Q.runPromise(this.auth.get(this.mcpName));if(!Z)return;switch($){case"all":await Q.runPromise(this.auth.remove(this.mcpName));break;case"client":delete Z.clientInfo,await Q.runPromise(this.auth.set(this.mcpName,Z));break;case"tokens":delete Z.tokens,await Q.runPromise(this.auth.set(this.mcpName,Z));break}}}function jQ($){if(!$)return{port:l1,path:m1};try{let Z=new URL($),X=Z.port?parseInt(Z.port,10):Z.protocol==="https:"?443:80,Y=Z.pathname||m1;return{port:X,path:Y}}catch{return{port:l1,path:m1}}}var b$={};b2(b$,{waitForCallback:()=>_3,stop:()=>zQ,isRunning:()=>C3,isPortInUse:()=>FQ,ensureRunning:()=>M3,cancelPending:()=>R3,McpOAuthCallback:()=>b$});import{createConnection as x3}from"net";import{createServer as L3}from"http";var J1=a.create({service:"mcp.oauth-callback"}),c1=l1,w4=m1,b3=`<!DOCTYPE html>
|
|
176
|
-
<html>
|
|
177
|
-
<head>
|
|
178
|
-
<title>QitQode - Authorization Successful</title>
|
|
179
|
-
<style>
|
|
180
|
-
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; }
|
|
181
|
-
.container { text-align: center; padding: 2rem; }
|
|
182
|
-
h1 { color: #4ade80; margin-bottom: 1rem; }
|
|
183
|
-
p { color: #aaa; }
|
|
184
|
-
</style>
|
|
185
|
-
</head>
|
|
186
|
-
<body>
|
|
187
|
-
<div class="container">
|
|
188
|
-
<h1>Authorization Successful</h1>
|
|
189
|
-
<p>You can close this window and return to QitQode.</p>
|
|
190
|
-
</div>
|
|
191
|
-
<script>setTimeout(() => window.close(), 2000);</script>
|
|
192
|
-
</body>
|
|
193
|
-
</html>`,N4=($)=>`<!DOCTYPE html>
|
|
194
|
-
<html>
|
|
195
|
-
<head>
|
|
196
|
-
<title>QitQode - Authorization Failed</title>
|
|
197
|
-
<style>
|
|
198
|
-
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; }
|
|
199
|
-
.container { text-align: center; padding: 2rem; }
|
|
200
|
-
h1 { color: #f87171; margin-bottom: 1rem; }
|
|
201
|
-
p { color: #aaa; }
|
|
202
|
-
.error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
|
|
203
|
-
</style>
|
|
204
|
-
</head>
|
|
205
|
-
<body>
|
|
206
|
-
<div class="container">
|
|
207
|
-
<h1>Authorization Failed</h1>
|
|
208
|
-
<p>An error occurred during authorization.</p>
|
|
209
|
-
<div class="error">${$}</div>
|
|
210
|
-
</div>
|
|
211
|
-
</body>
|
|
212
|
-
</html>`,L$,U0=new Map,B1=new Map,U3=300000;function OQ($){for(let[Z,X]of B1)if(X===$){B1.delete(Z);break}}function A3($,Z){let X=new URL($.url||"/",`http://localhost:${c1}`);if(X.pathname!==w4){Z.writeHead(404),Z.end("Not found");return}let Y=X.searchParams.get("code"),J=X.searchParams.get("state"),B=X.searchParams.get("error"),W=X.searchParams.get("error_description");if(J1.info("received oauth callback",{hasCode:!!Y,state:J,error:B}),!J){J1.error("oauth callback missing state parameter",{url:X.toString()}),Z.writeHead(400,{"Content-Type":"text/html"}),Z.end(N4("Missing required state parameter - potential CSRF attack"));return}if(B){let H=W||B;if(U0.has(J)){let V=U0.get(J);clearTimeout(V.timeout),U0.delete(J),OQ(J),V.reject(Error(H))}Z.writeHead(200,{"Content-Type":"text/html"}),Z.end(N4(H));return}if(!Y){Z.writeHead(400,{"Content-Type":"text/html"}),Z.end(N4("No authorization code provided"));return}if(!U0.has(J)){J1.error("oauth callback with invalid state",{state:J,pendingStates:Array.from(U0.keys())}),Z.writeHead(400,{"Content-Type":"text/html"}),Z.end(N4("Invalid or expired state parameter - potential CSRF attack"));return}let G=U0.get(J);clearTimeout(G.timeout),U0.delete(J),OQ(J),G.resolve(Y),Z.writeHead(200,{"Content-Type":"text/html"}),Z.end(b3)}async function M3($){let{port:Z,path:X}=jQ($);if(L$&&(c1!==Z||w4!==X))J1.info("stopping oauth callback server to reconfigure",{oldPort:c1,newPort:Z}),await zQ();if(L$)return;if(await FQ(Z)){J1.info("oauth callback server already running on another instance",{port:Z});return}c1=Z,w4=X,L$=L3(A3),await new Promise((J,B)=>{L$.listen(c1,()=>{J1.info("oauth callback server started",{port:c1,path:w4}),J()}),L$.on("error",B)})}function _3($,Z){if(Z)B1.set(Z,$);return new Promise((X,Y)=>{let J=setTimeout(()=>{if(U0.has($)){if(U0.delete($),Z)B1.delete(Z);Y(Error("OAuth callback timeout - authorization took too long"))}},U3);U0.set($,{resolve:X,reject:Y,timeout:J})})}function R3($){let X=B1.get($)??$,Y=U0.get(X);if(Y)clearTimeout(Y.timeout),U0.delete(X),B1.delete($),Y.reject(Error("Authorization cancelled"))}async function FQ($=l1){return new Promise((Z)=>{let X=x3($,"127.0.0.1");X.on("connect",()=>{X.destroy(),Z(!0)}),X.on("error",()=>{Z(!1)})})}async function zQ(){if(L$)await new Promise(($)=>L$.close(()=>$())),L$=void 0,J1.info("oauth callback server stopped");for(let[$,Z]of U0)clearTimeout(Z.timeout),Z.reject(Error("OAuth callback server stopped"));U0.clear(),B1.clear()}function C3(){return L$!==void 0}var v$=new Map,DQ="\x00",b4=($,Z)=>$+DQ+Z,L4=($)=>Q.tryPromise(()=>$.close()).pipe(Q.ignore),M9=($,Z)=>{let X=v$.get($);if(v$.set($,Z),!X||X===Z)return Q.void;return L4(X)},x4=($,Z)=>Q.gen(function*(){let X=v$.get($);if(!X||Z&&X!==Z)return;v$.delete($),yield*L4(X)}),qQ=($)=>{let Z=$+DQ;return Q.forEach(Array.from(v$.entries()).filter(([X])=>X.startsWith(Z)),([X,Y])=>x4(X,Y),{concurrency:"unbounded",discard:!0})};function PQ($){let Z=Q.fn("MCP.startAuth")(function*(H){let V=yield*$.getConfig(H);if(!V)throw Error(`MCP server ${H} not found or disabled`);if(V.type!=="remote")throw Error(`MCP server ${H} is not a remote server`);if(V.oauth===!1)throw Error(`MCP server ${H} has OAuth explicitly disabled`);let K=yield*$.pendingKey(H);b$.cancelPending(K);let y=typeof V.oauth==="object"?V.oauth:void 0;yield*Q.promise(()=>b$.ensureRunning(y?.redirectUri));let j=Array.from(crypto.getRandomValues(new Uint8Array(32))).map((U)=>U.toString(16).padStart(2,"0")).join("");yield*$.auth.updateOAuthState(K,j);let q,z=new h8(H,V.url,{clientId:y?.clientId,clientSecret:y?.clientSecret,scope:y?.scope,redirectUri:y?.redirectUri},{onRedirect:async(U)=>{q=U}},$.auth,K),D=new S8(new URL(V.url),{authProvider:z});return yield*Q.tryPromise({try:()=>{let U=new k8({name:"qitqode",version:U1});return U.connect(D).then(()=>({authorizationUrl:"",oauthState:j,pendingKey:K,transport:void 0,client:U}))},catch:(U)=>U}).pipe(Q.catch((U)=>{if(U instanceof X0&&q)return M9(K,D).pipe(Q.as({authorizationUrl:q.toString(),oauthState:j,pendingKey:K,transport:D}));return L4(D).pipe(Q.andThen(Q.die(U)))}))}),X=Q.fn("MCP.finishAuth")(function*(H,V){let K=yield*$.pendingKey(H),y=v$.get(K);if(!y)throw Error(`No pending OAuth flow for MCP server: ${H}`);let j=yield*Q.tryPromise({try:()=>y.finishAuth(V).then(()=>!0),catch:(q)=>q}).pipe(Q.option);if(Y0.isNone(j))return yield*x4(K,y),{status:"failed",error:"OAuth completion failed"};if(v$.get(K)===y)v$.delete(K);return yield*Q.gen(function*(){yield*$.auth.clearCodeVerifier(K);let q=yield*$.getConfig(H);if(!q)return{status:"failed",error:"MCP config not found after auth"};return yield*$.createAndStore(H,q)}).pipe(Q.ensuring(L4(y)))}),Y=Q.fn("MCP.authenticate")(function*(H){let V=yield*Z(H);if(!V.authorizationUrl){let y="client"in V?V.client:void 0,j=yield*$.getConfig(H);if(!j)return yield*Q.tryPromise(()=>y?.close()??Promise.resolve()).pipe(Q.ignore),{status:"failed",error:"MCP config not found after auth"};let q=y?yield*S1(H,y,j.timeout):void 0;if(!y||!q)return yield*Q.tryPromise(()=>y?.close()??Promise.resolve()).pipe(Q.ignore),{status:"failed",error:"Failed to get tools"};return yield*$.auth.clearOAuthState(V.pendingKey),yield*$.storeClient(H,y,q,j.timeout)}let K=b$.waitForCallback(V.oauthState,V.pendingKey);return yield*Q.gen(function*(){if(!(yield*Q.promise(()=>yQ(V.authorizationUrl))))yield*$.bus.publish(H9,{mcpName:H,url:V.authorizationUrl}).pipe(Q.ignore);let j=yield*Q.promise(()=>K);if((yield*$.auth.getOAuthState(V.pendingKey))!==V.oauthState)throw yield*$.auth.clearOAuthState(V.pendingKey),Error("OAuth state mismatch - potential CSRF attack");return yield*$.auth.clearOAuthState(V.pendingKey),yield*X(H,j)}).pipe(Q.ensuring(Q.sync(()=>b$.cancelPending(V.pendingKey)).pipe(Q.andThen(x4(V.pendingKey,V.transport)))))}),J=Q.fn("MCP.removeAuth")(function*(H){yield*$.auth.remove(H);let V=yield*$.pendingKey(H);yield*$.auth.clearCodeVerifier(V),yield*$.auth.clearOAuthState(V),b$.cancelPending(V),yield*x4(V)}),B=Q.fn("MCP.supportsOAuth")(function*(H){let V=yield*$.getConfig(H);return!!V&&V.type==="remote"&&V.oauth!==!1}),W=Q.fn("MCP.hasStoredTokens")(function*(H){return!!(yield*$.auth.get(H))?.tokens}),G=Q.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:Y,finishAuth:X,removeAuth:J,supportsOAuth:B,hasStoredTokens:W,getAuthStatus:G}}class _9 extends Event{constructor($,Z){var X,Y;super($),this.code=(X=Z==null?void 0:Z.code)!=null?X:void 0,this.message=(Y=Z==null?void 0:Z.message)!=null?Y:void 0}[Symbol.for("nodejs.util.inspect.custom")]($,Z,X){return X(NQ(this),Z)}[Symbol.for("Deno.customInspect")]($,Z){return $(NQ(this),Z)}}function I3($){let Z=globalThis.DOMException;return typeof Z=="function"?new Z($,"SyntaxError"):SyntaxError($)}function R9($){return $ instanceof Error?"errors"in $&&Array.isArray($.errors)?$.errors.map(R9).join(", "):("cause"in $)&&$.cause instanceof Error?`${$}: ${R9($.cause)}`:$.message:`${$}`}function NQ($){return{type:$.type,message:$.message,code:$.code,defaultPrevented:$.defaultPrevented,cancelable:$.cancelable,timeStamp:$.timeStamp}}var LQ=($)=>{throw TypeError($)},E9=($,Z,X)=>Z.has($)||LQ("Cannot "+X),V2=($,Z,X)=>(E9($,Z,"read from private field"),X?X.call($):Z.get($)),r2=($,Z,X)=>Z.has($)?LQ("Cannot add the same private member more than once"):Z instanceof WeakSet?Z.add($):Z.set($,X),g2=($,Z,X,Y)=>(E9($,Z,"write to private field"),Z.set($,X),X),U$=($,Z,X)=>(E9($,Z,"access private method"),X),A0,W1,u1,U4,A4,f8,i1,v8,d$,o1,n1,p1,g8,X$,C9,I9,k9,wQ,S9,T9,E8,h9,g9;class a1 extends EventTarget{constructor($,Z){var X,Y;super(),r2(this,X$),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,r2(this,A0),r2(this,W1),r2(this,u1),r2(this,U4),r2(this,A4),r2(this,f8),r2(this,i1),r2(this,v8,null),r2(this,d$),r2(this,o1),r2(this,n1,null),r2(this,p1,null),r2(this,g8,null),r2(this,I9,async(J)=>{var B;V2(this,o1).reset();let{body:W,redirected:G,status:H,headers:V}=J;if(H===204){U$(this,X$,E8).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(G?g2(this,u1,new URL(J.url)):g2(this,u1,void 0),H!==200){U$(this,X$,E8).call(this,`Non-200 status code (${H})`,H);return}if(!(V.get("content-type")||"").startsWith("text/event-stream")){U$(this,X$,E8).call(this,'Invalid content type, expected "text/event-stream"',H);return}if(V2(this,A0)===this.CLOSED)return;g2(this,A0,this.OPEN);let K=new Event("open");if((B=V2(this,g8))==null||B.call(this,K),this.dispatchEvent(K),typeof W!="object"||!W||!("getReader"in W)){U$(this,X$,E8).call(this,"Invalid response body, expected a web ReadableStream",H),this.close();return}let y=new TextDecoder,j=W.getReader(),q=!0;do{let{done:z,value:D}=await j.read();D&&V2(this,o1).feed(y.decode(D,{stream:!z})),z&&(q=!1,V2(this,o1).reset(),U$(this,X$,h9).call(this))}while(q)}),r2(this,k9,(J)=>{g2(this,d$,void 0),!(J.name==="AbortError"||J.type==="aborted")&&U$(this,X$,h9).call(this,R9(J))}),r2(this,S9,(J)=>{typeof J.id=="string"&&g2(this,v8,J.id);let B=new MessageEvent(J.event||"message",{data:J.data,origin:V2(this,u1)?V2(this,u1).origin:V2(this,W1).origin,lastEventId:J.id||""});V2(this,p1)&&(!J.event||J.event==="message")&&V2(this,p1).call(this,B),this.dispatchEvent(B)}),r2(this,T9,(J)=>{g2(this,f8,J)}),r2(this,g9,()=>{g2(this,i1,void 0),V2(this,A0)===this.CONNECTING&&U$(this,X$,C9).call(this)});try{if($ instanceof URL)g2(this,W1,$);else if(typeof $=="string")g2(this,W1,new URL($,k3()));else throw Error("Invalid URL")}catch{throw I3("An invalid or illegal string was specified")}g2(this,o1,xQ({onEvent:V2(this,S9),onRetry:V2(this,T9)})),g2(this,A0,this.CONNECTING),g2(this,f8,3000),g2(this,A4,(X=Z==null?void 0:Z.fetch)!=null?X:globalThis.fetch),g2(this,U4,(Y=Z==null?void 0:Z.withCredentials)!=null?Y:!1),U$(this,X$,C9).call(this)}get readyState(){return V2(this,A0)}get url(){return V2(this,W1).href}get withCredentials(){return V2(this,U4)}get onerror(){return V2(this,n1)}set onerror($){g2(this,n1,$)}get onmessage(){return V2(this,p1)}set onmessage($){g2(this,p1,$)}get onopen(){return V2(this,g8)}set onopen($){g2(this,g8,$)}addEventListener($,Z,X){let Y=Z;super.addEventListener($,Y,X)}removeEventListener($,Z,X){let Y=Z;super.removeEventListener($,Y,X)}close(){V2(this,i1)&&clearTimeout(V2(this,i1)),V2(this,A0)!==this.CLOSED&&(V2(this,d$)&&V2(this,d$).abort(),g2(this,A0,this.CLOSED),g2(this,d$,void 0))}}A0=new WeakMap,W1=new WeakMap,u1=new WeakMap,U4=new WeakMap,A4=new WeakMap,f8=new WeakMap,i1=new WeakMap,v8=new WeakMap,d$=new WeakMap,o1=new WeakMap,n1=new WeakMap,p1=new WeakMap,g8=new WeakMap,X$=new WeakSet,C9=function(){g2(this,A0,this.CONNECTING),g2(this,d$,new AbortController),V2(this,A4)(V2(this,W1),U$(this,X$,wQ).call(this)).then(V2(this,I9)).catch(V2(this,k9))},I9=new WeakMap,k9=new WeakMap,wQ=function(){var $;let Z={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...V2(this,v8)?{"Last-Event-ID":V2(this,v8)}:void 0},cache:"no-store",signal:($=V2(this,d$))==null?void 0:$.signal};return"window"in globalThis&&(Z.credentials=this.withCredentials?"include":"same-origin"),Z},S9=new WeakMap,T9=new WeakMap,E8=function($,Z){var X;V2(this,A0)!==this.CLOSED&&g2(this,A0,this.CLOSED);let Y=new _9("error",{code:Z,message:$});(X=V2(this,n1))==null||X.call(this,Y),this.dispatchEvent(Y)},h9=function($,Z){var X;if(V2(this,A0)===this.CLOSED)return;g2(this,A0,this.CONNECTING);let Y=new _9("error",{code:Z,message:$});(X=V2(this,n1))==null||X.call(this,Y),this.dispatchEvent(Y),g2(this,i1,setTimeout(V2(this,g9),V2(this,f8)))},g9=new WeakMap,a1.CONNECTING=0,a1.OPEN=1,a1.CLOSED=2;function k3(){let $="document"in globalThis?globalThis.document:void 0;return $&&typeof $=="object"&&"baseURI"in $&&typeof $.baseURI=="string"?$.baseURI:void 0}class bQ extends Error{constructor($,Z,X){super(`SSE error: ${Z}`);this.code=$,this.event=X}}class f9{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=W4(Z?.fetch,Z?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new X0("No auth provider");let $;try{$=await x$(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 X0;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=h1(this._requestInit?.headers);return new Headers({...$,...Z})}_startOrAuth(){let $=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((Z,X)=>{this._eventSource=new a1(this._url.href,{...this._eventSourceInit,fetch:async(Y,J)=>{let B=await this._commonHeaders();B.set("Accept","text/event-stream");let W=await $(Y,{...J,headers:B});if(W.status===401&&W.headers.has("www-authenticate")){let{resourceMetadataUrl:G,scope:H}=d1(W);this._resourceMetadataUrl=G,this._scope=H}return W}}),this._abortController=new AbortController,this._eventSource.onerror=(Y)=>{if(Y.code===401&&this._authProvider){this._authThenStart().then(Z,X);return}let J=new bQ(Y.code,Y.message,Y);X(J),this.onerror?.(J)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(Y)=>{let J=Y;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(B){X(B),this.onerror?.(B),this.close();return}Z()}),this._eventSource.onmessage=(Y)=>{let J=Y,B;try{B=T$.parse(JSON.parse(J.data))}catch(W){this.onerror?.(W);return}this.onmessage?.(B)}})}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 X0("No auth provider");if(await x$(this._authProvider,{serverUrl:this._url,authorizationCode:$,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new X0("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},Y=await(this._fetch??fetch)(this._endpoint,X);if(!Y.ok){let J=await Y.text().catch(()=>null);if(Y.status===401&&this._authProvider){let{resourceMetadataUrl:B,scope:W}=d1(Y);if(this._resourceMetadataUrl=B,this._scope=W,await x$(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new X0;return this.send($)}throw Error(`Error POSTing to endpoint (HTTP ${Y.status}): ${J}`)}await Y.body?.cancel()}catch(Z){throw this.onerror?.(Z),Z}}setProtocolVersion($){this._protocolVersion=$}}var A$=a.create({service:"mcp.connection"});function UQ($){let Z=(J,B,W)=>Q.acquireUseRelease(Q.succeed(J),(G)=>Q.tryPromise({try:()=>{let H=new k8({name:"qitqode",version:U1});return Q4(H.connect(G),B).then(()=>H)},catch:(H)=>H instanceof Error?H:Error(String(H))}),(G,H)=>{if(!i2.isFailure(H))return Q.void;if(W?.(W2.squash(H.cause)))return Q.void;return Q.tryPromise(()=>G.close()).pipe(Q.ignore)}),X=Q.fn("MCP.connectRemote")(function*(J,B){let W=yield*$.directory(),G=b4(W,J),H=B.oauth===!1,V=typeof B.oauth==="object"?B.oauth:void 0,K;if(!H)K=new h8(J,B.url,{clientId:V?.clientId,clientSecret:V?.clientSecret,scope:V?.scope,redirectUri:V?.redirectUri},{onRedirect:async(P)=>{A$.info("oauth redirect requested",{key:J,url:P.toString()})}},$.auth,G);let y=[{name:"StreamableHTTP",transport:new S8(new URL(B.url),{authProvider:K,requestInit:B.headers?{headers:B.headers}:void 0})},{name:"SSE",transport:new f9(new URL(B.url),{authProvider:K,requestInit:B.headers?{headers:B.headers}:void 0})}],j=B.timeout??Y4,q,z=(P)=>{let F=P instanceof Error?P.message:String(P);return P instanceof X0||!!K&&F.includes("OAuth")},D=(P)=>{let F=P instanceof Error?P.message:String(P);return F.includes("registration")||F.includes("client_id")},U=(P)=>!!K&&z(P)&&!D(P);for(let{name:P,transport:F}of y){let b=yield*Z(F,j,U).pipe(Q.map((O)=>({client:O,transportName:P})),Q.catch((O)=>{let M=O instanceof Error?O:Error(String(O));if(z(O)){if(A$.info("mcp server requires authentication",{key:J,transport:P}),D(O))return q={status:"needs_client_registration",error:"Server does not support dynamic client registration. Please provide clientId in config."},$.publish(Z4,{server:J,reason:"client_registration"}).pipe(Q.ignore,Q.as(void 0));if(!K)return q={status:"failed",error:`MCP server requires authentication, but OAuth is disabled: ${M.message}`},Q.succeed(void 0);return q={status:"needs_auth"},M9(G,F).pipe(Q.andThen($.publish(Z4,{server:J,reason:"login"})),Q.ignore,Q.as(void 0))}return A$.debug("transport connection failed",{key:J,transport:P,url:v9.redactString(B.url),error:M.message}),q={status:"failed",error:M.message},Q.succeed(void 0)}));if(b)return A$.info("connected",{key:J,transport:b.transportName}),{client:b.client,status:{status:"connected"}};if(q?.status==="needs_auth"||q?.status==="needs_client_registration")break}return{client:void 0,status:q??{status:"failed",error:"Unknown error"}}}),Y=Q.fn("MCP.connectLocal")(function*(J,B){let[W,...G]=B.command,H=yield*$.directory(),V=new R8({stderr:"pipe",command:W,args:G,cwd:H,env:{...M4(),...W==="qitqode"||W==="opencode"?{BUN_BE_BUN:"1"}:{},...B.environment}});V.stderr?.on("data",(y)=>{A$.info(`mcp stderr: ${y.toString()}`,{key:J})});let K=B.timeout??Y4;return yield*Z(V,K).pipe(Q.map((y)=>({client:y,status:{status:"connected"}})),Q.catch((y)=>{let j=y instanceof Error?y.message:String(y);return A$.error("local mcp startup failed",{key:J,command:v9.redactCommand(B.command),cwd:H,error:j}),Q.succeed({client:void 0,status:{status:"failed",error:j}})}))});return Q.fn("MCP.create")(function*(J,B){if(B.enabled===!1)return A$.info("mcp server disabled",{key:J}),{status:{status:"disabled"}};A$.info("found",{key:J,type:B.type});let W=B.type==="remote"?yield*X(J,B):yield*Y(J,B);if(!W.client)return{status:W.status};let G=yield*S1(J,W.client,B.timeout);if(!G)return yield*Q.tryPromise(()=>W.client.close()).pipe(Q.ignore),{status:{status:"failed",error:"Failed to get tools"}};return A$.info("create() successfully created client",{key:J,toolCount:G.length}),{client:W.client,status:W.status,defs:G}})}var d8=a.create({service:"mcp"});class _4 extends Z2.Service()("@qitqode/MCP"){}var MQ=_.effect(_4,Q.gen(function*(){let $=yield*s1.ChildProcessSpawner,Z=yield*g$.Service,X=yield*p.Service,Y=UQ({auth:Z,directory:()=>d.directory,publish:(L,S)=>X.publish(L,S)}),J=(L,S)=>Y(L,S).pipe(Q.map((T)=>({mcpClient:T.client,status:T.status,defs:T.defs}))),B=yield*B2.Service,W=Q.fnUntraced(function*(L){if(process.platform==="win32")return[];let S=[],T=[L];while(T.length>0){let w=T.shift(),A=yield*$.spawn(r1.make("pgrep",["-P",String(w)],{stdin:"ignore"})),R=yield*c2.mkString(c2.decodeText(A.stdout));yield*A.exitCode;for(let C of R.split(`
|
|
213
|
-
`)){let g=parseInt(C,10);if(!isNaN(g)&&!S.includes(g))S.push(g),T.push(g)}}return S},Q.scoped,Q.catch(()=>Q.succeed([])));function G(L,S,T,w,A){T.setNotificationHandler(_8,async()=>{if(d8.info("tools list changed notification received",{server:S}),L.clients[S]!==T||L.status[S]?.status!=="connected")return;let R=await w.promise(S1(S,T,A));if(!R)return;if(L.clients[S]!==T||L.status[S]?.status!=="connected")return;L.defs[S]=R,await w.promise(X.publish(K9,{server:S}).pipe(Q.ignore))})}let H=yield*d.make(Q.fn("MCP.state")(function*(){let L=yield*B.get(),S=yield*D0.make(),T=yield*d.directory,w=L.mcp??{},A={status:{},clients:{},defs:{}};return yield*Q.forEach(Object.entries(w),([R,C])=>Q.gen(function*(){if(!I8(C)){d8.error("Ignoring MCP config entry without type",{key:R});return}if(C.enabled===!1){A.status[R]={status:"disabled"};return}if(fX(C,L.mcp_origins?.[R])){A.status[R]={status:"pending"};return}let g=yield*J(R,C).pipe(Q.catch(()=>Q.void));if(!g)return;if(A.status[R]=g.status,g.mcpClient)A.clients[R]=g.mcpClient,A.defs[R]=g.defs,G(A,R,g.mcpClient,S,C.timeout)}),{concurrency:8}),yield*Q.addFinalizer(()=>Q.gen(function*(){yield*Q.forEach(Object.values(A.clients),(R)=>Q.gen(function*(){let C=R.transport instanceof R8?R.transport.pid:null;if(typeof C==="number"){let g=yield*W(C);for(let l of g)try{process.kill(l,"SIGTERM")}catch{}}yield*Q.tryPromise(()=>R.close()).pipe(Q.ignore)}),{concurrency:8}),yield*qQ(T)})),A}));function V(L,S){let T=L.clients[S];if(delete L.defs[S],!T)return Q.void;return Q.tryPromise(()=>T.close()).pipe(Q.ignore)}let K=Q.fnUntraced(function*(L,S,T,w,A){let R=yield*D0.make();return yield*V(L,S),L.status[S]={status:"connected"},L.clients[S]=T,L.defs[S]=w,G(L,S,T,R,A),L.status[S]}),y=Q.fn("MCP.status")(function*(){let L=yield*d.get(H),T=(yield*B.get()).mcp??{},w={};for(let[A,R]of Object.entries(T)){if(!I8(R))continue;w[A]=L.status[A]??{status:"disabled"}}return w}),j=Q.fn("MCP.clients")(function*(){return(yield*d.get(H)).clients}),q=Q.fn("MCP.createAndStore")(function*(L,S){let T=yield*d.get(H),w=yield*J(L,S);if(T.status[L]=w.status,!w.mcpClient)return yield*V(T,L),delete T.clients[L],w.status;return yield*K(T,L,w.mcpClient,w.defs,S.timeout)}),z=Q.fn("MCP.add")(function*(L,S){return yield*q(L,S),{status:(yield*d.get(H)).status}}),D=Q.fn("MCP.connect")(function*(L){let S=yield*k(L);if(!S){d8.error("MCP config not found or invalid",{name:L});return}yield*q(L,{...S,enabled:!0})}),U=Q.fn("MCP.disconnect")(function*(L){let S=yield*d.get(H);yield*V(S,L),delete S.clients[L],S.status[L]={status:"disabled"}}),P=Q.fn("MCP.tools")(function*(){let L=yield*d.get(H),S=yield*B.get();return EX(L,S.mcp??{},S.experimental?.mcp_timeout)}),F=Q.fn("MCP.prompts")(function*(){let L=yield*d.get(H);return yield*j9(L,(S)=>S.listPrompts().then((T)=>T.prompts),"prompts")}),b=Q.fn("MCP.resources")(function*(){let L=yield*d.get(H);return yield*j9(L,(S)=>S.listResources().then((T)=>T.resources),"resources")}),O=Q.fnUntraced(function*(L,S,T,w){let R=(yield*d.get(H)).clients[L];if(!R){d8.warn(`client not found for ${T}`,{clientName:L});return}return yield*Q.tryPromise({try:()=>S(R),catch:(C)=>{return d8.error(`failed to ${T}`,{clientName:L,...w,error:C?.message}),C}}).pipe(Q.orElseSucceed(()=>{return}))}),M=Q.fn("MCP.getPrompt")(function*(L,S,T){return yield*O(L,(w)=>w.getPrompt({name:S,arguments:T}),"getPrompt",{promptName:S})}),I=Q.fn("MCP.readResource")(function*(L,S){return yield*O(L,(T)=>T.readResource({uri:S}),"readResource",{resourceUri:S})}),k=Q.fnUntraced(function*(L){let T=(yield*B.get()).mcp?.[L];if(!T||!I8(T))return;return T}),E=PQ({auth:Z,bus:X,pendingKey:(L)=>Q.map(d.directory,(S)=>b4(S,L)),getConfig:k,storeClient:(L,S,T,w)=>Q.gen(function*(){let A=yield*d.get(H);return yield*K(A,L,S,T,w)}),createAndStore:q});return _4.of({status:y,clients:j,tools:P,prompts:F,resources:b,add:z,connect:D,disconnect:U,getPrompt:M,readResource:I,startAuth:E.startAuth,authenticate:E.authenticate,finishAuth:E.finishAuth,removeAuth:E.removeAuth,supportsOAuth:E.supportsOAuth,hasStoredTokens:E.hasStoredTokens,getAuthStatus:E.getAuthStatus})})),S3=MQ.pipe(_.provide(g$.layer),_.provide(p.layer),_.provide(B2.defaultLayer),_.provide(t1),_.provide(s2.defaultLayer));var G0={};b2(G0,{layer:()=>IQ,hints:()=>R4,defaultLayer:()=>f3,deepResearchTemplate:()=>CQ,Service:()=>C4,Info:()=>E3,Event:()=>g3,Default:()=>S0,Command:()=>G0});var _Q=`Create or update \`AGENTS.md\` for this repository.
|
|
214
|
-
|
|
215
|
-
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.
|
|
216
|
-
|
|
217
|
-
User-provided focus or constraints (honor these):
|
|
218
|
-
$ARGUMENTS
|
|
219
|
-
|
|
220
|
-
## How to investigate
|
|
221
|
-
|
|
222
|
-
Read the highest-value sources first:
|
|
223
|
-
- \`README*\`, root manifests, workspace config, lockfiles
|
|
224
|
-
- build, test, lint, formatter, typecheck, and codegen config
|
|
225
|
-
- CI workflows and pre-commit / task runner config
|
|
226
|
-
- existing instruction files (\`AGENTS.md\`, \`CLAUDE.md\`, \`.cursor/rules/\`, \`.cursorrules\`, \`.github/copilot-instructions.md\`)
|
|
227
|
-
- repo-local QitQode config such as \`qitqode.json\`
|
|
228
|
-
|
|
229
|
-
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.
|
|
230
|
-
|
|
231
|
-
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.
|
|
232
|
-
|
|
233
|
-
## What to extract
|
|
234
|
-
|
|
235
|
-
Look for the highest-signal facts for an agent working in this repo:
|
|
236
|
-
- exact developer commands, especially non-obvious ones
|
|
237
|
-
- how to run a single test, a single package, or a focused verification step
|
|
238
|
-
- required command order when it matters, such as \`lint -> typecheck -> test\`
|
|
239
|
-
- monorepo or multi-package boundaries, ownership of major directories, and the real app/library entrypoints
|
|
240
|
-
- framework or toolchain quirks: generated code, migrations, codegen, build artifacts, special env loading, dev servers, infra deploy flow
|
|
241
|
-
- repo-specific style or workflow conventions that differ from defaults
|
|
242
|
-
- testing quirks: fixtures, integration test prerequisites, snapshot workflows, required services, flaky or expensive suites
|
|
243
|
-
- important constraints from existing instruction files worth preserving
|
|
244
|
-
|
|
245
|
-
Good \`AGENTS.md\` content is usually hard-earned context that took reading multiple files to infer.
|
|
246
|
-
|
|
247
|
-
## Questions
|
|
248
|
-
|
|
249
|
-
Only ask the user questions if the repo cannot answer something important. Use the \`question\` tool for one short batch at most.
|
|
250
|
-
|
|
251
|
-
Good questions:
|
|
252
|
-
- undocumented team conventions
|
|
253
|
-
- branch / PR / release expectations
|
|
254
|
-
- missing setup or test prerequisites that are known but not written down
|
|
255
|
-
|
|
256
|
-
Do not ask about anything the repo already makes clear.
|
|
257
|
-
|
|
258
|
-
## Writing rules
|
|
259
|
-
|
|
260
|
-
Include only high-signal, repo-specific guidance such as:
|
|
261
|
-
- exact commands and shortcuts the agent would otherwise guess wrong
|
|
262
|
-
- architecture notes that are not obvious from filenames
|
|
263
|
-
- conventions that differ from language or framework defaults
|
|
264
|
-
- setup requirements, environment quirks, and operational gotchas
|
|
265
|
-
- references to existing instruction sources that matter
|
|
266
|
-
|
|
267
|
-
Exclude:
|
|
268
|
-
- generic software advice
|
|
269
|
-
- long tutorials or exhaustive file trees
|
|
270
|
-
- obvious language conventions
|
|
271
|
-
- speculative claims or anything you could not verify
|
|
272
|
-
- content better stored in another file referenced via \`qitqode.json\` \`instructions\`
|
|
273
|
-
|
|
274
|
-
When in doubt, omit.
|
|
275
|
-
|
|
276
|
-
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.
|
|
277
|
-
|
|
278
|
-
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.
|
|
279
|
-
`;var RQ=`You are a code reviewer. Your job is to review code changes and provide actionable feedback.
|
|
280
|
-
|
|
281
|
-
---
|
|
282
|
-
|
|
283
|
-
Input: $ARGUMENTS
|
|
284
|
-
|
|
285
|
-
---
|
|
286
|
-
|
|
287
|
-
## Determining What to Review
|
|
288
|
-
|
|
289
|
-
Based on the input provided, determine which type of review to perform:
|
|
290
|
-
|
|
291
|
-
1. **No arguments (default)**: Review all uncommitted changes
|
|
292
|
-
- Run: \`git diff\` for unstaged changes
|
|
293
|
-
- Run: \`git diff --cached\` for staged changes
|
|
294
|
-
- Run: \`git status --short\` to identify untracked (net new) files
|
|
295
|
-
|
|
296
|
-
2. **Commit hash** (40-char SHA or short hash): Review that specific commit
|
|
297
|
-
- Run: \`git show $ARGUMENTS\`
|
|
298
|
-
|
|
299
|
-
3. **Branch name**: Compare current branch to the specified branch
|
|
300
|
-
- Run: \`git diff $ARGUMENTS...HEAD\`
|
|
301
|
-
|
|
302
|
-
4. **PR URL or number** (contains "github.com" or "pull" or looks like a PR number): Review the pull request
|
|
303
|
-
- Run: \`gh pr view $ARGUMENTS\` to get PR context
|
|
304
|
-
- Run: \`gh pr diff $ARGUMENTS\` to get the diff
|
|
305
|
-
|
|
306
|
-
Use best judgement when processing input.
|
|
307
|
-
|
|
308
|
-
---
|
|
309
|
-
|
|
310
|
-
## Gathering Context
|
|
311
|
-
|
|
312
|
-
**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.
|
|
313
|
-
|
|
314
|
-
- Use the diff to identify which files changed
|
|
315
|
-
- Use \`git status --short\` to identify untracked files, then read their full contents
|
|
316
|
-
- Read the full file to understand existing patterns, control flow, and error handling
|
|
317
|
-
- Check for existing style guide or conventions files (CONVENTIONS.md, AGENTS.md, .editorconfig, etc.)
|
|
318
|
-
|
|
319
|
-
---
|
|
320
|
-
|
|
321
|
-
## What to Look For
|
|
322
|
-
|
|
323
|
-
**Bugs** - Your primary focus.
|
|
324
|
-
- Logic errors, off-by-one mistakes, incorrect conditionals
|
|
325
|
-
- If-else guards: missing guards, incorrect branching, unreachable code paths
|
|
326
|
-
- Edge cases: null/empty/undefined inputs, error conditions, race conditions
|
|
327
|
-
- Security issues: injection, auth bypass, data exposure
|
|
328
|
-
- Broken error handling that swallows failures, throws unexpectedly or returns error types that are not caught.
|
|
329
|
-
|
|
330
|
-
**Structure** - Does the code fit the codebase?
|
|
331
|
-
- Does it follow existing patterns and conventions?
|
|
332
|
-
- Are there established abstractions it should use but doesn't?
|
|
333
|
-
- Excessive nesting that could be flattened with early returns or extraction
|
|
334
|
-
|
|
335
|
-
**Performance** - Only flag if obviously problematic.
|
|
336
|
-
- O(n\xB2) on unbounded data, N+1 queries, blocking I/O on hot paths
|
|
337
|
-
|
|
338
|
-
**Behavior Changes** - If a behavioral change is introduced, raise it (especially if it's possibly unintentional).
|
|
339
|
-
|
|
340
|
-
---
|
|
341
|
-
|
|
342
|
-
## Before You Flag Something
|
|
343
|
-
|
|
344
|
-
**Be certain.** If you're going to call something a bug, you need to be confident it actually is one.
|
|
345
|
-
|
|
346
|
-
- Only review the changes - do not review pre-existing code that wasn't modified
|
|
347
|
-
- Don't flag something as a bug if you're unsure - investigate first
|
|
348
|
-
- Don't invent hypothetical problems - if an edge case matters, explain the realistic scenario where it breaks
|
|
349
|
-
- If you need more context to be sure, use the tools below to get it
|
|
350
|
-
|
|
351
|
-
**Don't be a zealot about style.** When checking code against conventions:
|
|
352
|
-
|
|
353
|
-
- Verify the code is *actually* in violation. Don't complain about else statements if early returns are already being used correctly.
|
|
354
|
-
- Some "violations" are acceptable when they're the simplest option. A \`let\` statement is fine if the alternative is convoluted.
|
|
355
|
-
- Excessive nesting is a legitimate concern regardless of other style choices.
|
|
356
|
-
- Don't flag style preferences as issues unless they clearly violate established project conventions.
|
|
357
|
-
|
|
358
|
-
---
|
|
359
|
-
|
|
360
|
-
## Tools
|
|
361
|
-
|
|
362
|
-
Use these to inform your review:
|
|
363
|
-
|
|
364
|
-
- **Explore agent** - Find how existing code handles similar problems. Check patterns, conventions, and prior art before claiming something doesn't fit.
|
|
365
|
-
- **Exa Code Context** - Verify correct usage of libraries/APIs before flagging something as wrong.
|
|
366
|
-
- **Exa Web Search** - Research best practices if you're unsure about a pattern.
|
|
367
|
-
|
|
368
|
-
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.
|
|
369
|
-
|
|
370
|
-
---
|
|
371
|
-
|
|
372
|
-
## Output
|
|
373
|
-
|
|
374
|
-
1. If there is a bug, be direct and clear about why it is a bug.
|
|
375
|
-
2. Clearly communicate severity of issues. Do not overstate severity.
|
|
376
|
-
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.
|
|
377
|
-
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.
|
|
378
|
-
5. Write so the reader can quickly understand the issue without reading too closely.
|
|
379
|
-
6. AVOID flattery, do not give any comments that are not helpful to the reader. Avoid phrasing like "Great job ...", "Thanks for ...".
|
|
380
|
-
`;var d9=_Q,m9=RQ;var g3={Executed:O2.define("command.executed",N.object({name:N.string(),sessionID:P2.zod,arguments:N.string(),messageID:w2.zod}))},E3=N.object({name:N.string(),description:N.string().optional(),agent:N.string().optional(),model:N.string().optional(),source:N.enum(["command","mcp","skill"]).optional(),template:N.promise(N.string()).or(N.string()),subtask:N.boolean().optional(),hints:N.array(N.string())}).meta({ref:"Command"});function R4($){let Z=[],X=$.match(/\$\d+/g);if(X)for(let Y of[...new Set(X)].sort())Z.push(Y);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 CQ(){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(`
|
|
381
|
-
`)}class C4 extends Z2.Service()("@qitqode/Command"){}var IQ=_.effect(C4,Q.gen(function*(){let $=yield*B2.Service,Z=yield*N0.Service,X=yield*z$.Service,Y=Q.fn("Command.state")(function*(G){let H=yield*$.get(),V=yield*D0.make(),K={};if(K[S0.INIT]={name:S0.INIT,description:"guided AGENTS.md setup",source:"command",get template(){return d9.replace("${path}",G.worktree)},hints:R4(d9)},K[S0.REVIEW]={name:S0.REVIEW,description:"review changes [commit|branch|pr], defaults to uncommitted",source:"command",get template(){return m9.replace("${path}",G.worktree)},subtask:!0,hints:R4(m9)},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(`
|
|
382
|
-
`)},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(`
|
|
383
|
-
`)},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 CQ()},hints:["$ARGUMENTS"]};for(let[y,j]of Object.entries(H.command??{}))K[y]={name:y,agent:j.agent,model:j.model,description:j.description,source:"command",get template(){return j.template},subtask:j.subtask,hints:R4(j.template)};for(let[y,j]of Object.entries(yield*Z.prompts()))K[y]={name:y,source:"mcp",description:j.description,get template(){return V.promise(Z.getPrompt(j.client,j.name,j.arguments?Object.fromEntries(j.arguments.map((q,z)=>[q.name,`$${z+1}`])):{}).pipe(Q.map((q)=>q?.messages.map((z)=>z.content.type==="text"?z.content.text:"").join(`
|
|
384
|
-
`)||"")))},hints:j.arguments?.map((q,z)=>`$${z+1}`)??[]};for(let y of yield*X.all()){if(K[y.name])continue;K[y.name]={name:y.name,description:y.description,source:"skill",get template(){return y.content},hints:[]}}return{commands:K}}),J=yield*d.make((G)=>Y(G)),B=Q.fn("Command.get")(function*(G){return(yield*d.get(J)).commands[G]}),W=Q.fn("Command.list")(function*(){let G=yield*d.get(J);return Object.values(G.commands)});return C4.of({get:B,list:W})})),f3=IQ.pipe(_.provide(B2.defaultLayer),_.provide(N0.defaultLayer),_.provide(z$.defaultLayer));var kQ=new WeakMap;function I4($,Z){let X=kQ.get(Z);if(!X)X=new Map,kQ.set(Z,X);let Y=`${$.providerID}\x00${$.api.id}`,J=X.get(Y);if(J)return J;let B=n2.schema($,N.toJSONSchema(Z));return X.set(Y,B),B}var k4=Q.fn("Session.buildLLMRequestPrefix")(function*($){let Z=yield*f2.Service,X=yield*K0.Service,Y=yield*o.toModelMessagesEffect($.msgs,$.model),J=$.msgs.findLast((V)=>V.info.role==="user");if(!J)return yield*Q.die(Error("buildLLMRequestPrefix: no user message in msgs"));let B=J.info,W=yield*Z.buildSystemArray({agent:$.agent,model:$.model,system:$.additions,user:B,sessionID:$.sessionID,agentID:B.agentID}),G=yield*X.tools({modelID:t0.make($.model.api.id),providerID:$.model.providerID,agent:$.agent}),H={};for(let V of G){let K=I4($.model,V.parameters);H[V.id]=t$({description:V.description,inputSchema:K$(K)})}return{system:W,tools:H,inheritedMessages:Y}});var i0={};b2(i0,{layer:()=>oQ,gcInboxRows:()=>uQ,defaultLayer:()=>i3,Service:()=>E4,MAX_DRAIN_PER_TURN:()=>cQ,InboxReceiverNotFound:()=>l9});import S4 from"crypto";var TQ="0123456789ABCDEFGHJKMNPQRSTVWXYZ",T4=32;var v3=16,hQ=10,SQ=281474976710655;var V1;(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"})(V1||(V1={}));class e1 extends Error{constructor($,Z){super(`${Z} (${$})`);this.name="ULIDError",this.code=$}}function d3($){let Z=Math.floor($()*T4)%T4;return TQ.charAt(Z)}function m3($){let Z=l3(),X=Z&&(Z.crypto||Z.msCrypto)||(typeof S4<"u"?S4:null);if(typeof X?.getRandomValues==="function")return()=>{let Y=new Uint8Array(1);return X.getRandomValues(Y),Y[0]/255};else if(typeof X?.randomBytes==="function")return()=>X.randomBytes(1).readUInt8()/255;else if(S4?.randomBytes)return()=>S4.randomBytes(1).readUInt8()/255;throw new e1(V1.PRNGDetectFailure,"Failed to find a reliable PRNG")}function l3(){if(o3())return self;if(typeof window<"u")return window;if(typeof global<"u")return global;if(typeof globalThis<"u")return globalThis;return null}function c3($,Z){let X="";for(;$>0;$--)X=d3(Z)+X;return X}function u3($,Z=hQ){if(isNaN($))throw new e1(V1.EncodeTimeValueMalformed,`Time must be a number: ${$}`);else if($>SQ)throw new e1(V1.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${SQ}: ${$}`);else if($<0)throw new e1(V1.EncodeTimeNegative,`Time must be positive: ${$}`);else if(Number.isInteger($)===!1)throw new e1(V1.EncodeTimeValueMalformed,`Time must be an integer: ${$}`);let X,Y="";for(let J=Z;J>0;J--)X=$%T4,Y=TQ.charAt(X)+Y,$=($-X)/T4;return Y}function o3(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function $8($,Z){let X=Z||m3(),Y=!$||isNaN($)?Date.now():$;return u3(Y,hQ)+c3(v3,X)}var Q$=h4("inbox",{id:Q0().primaryKey(),receiver_session_id:Q0().$type().notNull().references(()=>T0.id,{onDelete:"cascade"}),receiver_actor_id:Q0().notNull(),sender_session_id:Q0().$type(),sender_actor_id:Q0(),type:Q0().notNull().default("text"),content:Q0({mode:"json"}).$type().notNull(),created_at:K1().notNull()},($)=>[Z8("inbox_receiver_idx").on($.receiver_session_id,$.receiver_actor_id,$.id),Z8("inbox_created_idx").on($.created_at)]);function gQ($){if($.type==="actor_notification")return $.content.text??"(no notification body)";let Z=$.content,X=$.sender_session_id?`${$.sender_session_id}:${$.sender_actor_id??"?"}`:"system",Y=new Date($.created_at).toISOString();return`<inbox from="${X}" sent_at="${Y}">
|
|
385
|
-
${Z.text??"(empty)"}
|
|
386
|
-
</inbox>`}function EQ($){let Z=`Background actor "${$.description}" (actor_id: ${$.actorID})`;if($.status==="completed"){let X=`Status: ${$.reportedStatus??"unknown"}`,Y=$.reportedSummary?`
|
|
387
|
-
Summary: ${$.reportedSummary}`:"";return`<actor-notification>
|
|
388
|
-
${Z} completed.
|
|
389
|
-
${X}${Y}
|
|
390
|
-
Result: ${$.result??"(no output)"}
|
|
391
|
-
</actor-notification>`}if($.status==="failed")return`<actor-notification>
|
|
392
|
-
${Z} failed.
|
|
393
|
-
Error: ${$.error??"unknown"}
|
|
394
|
-
</actor-notification>`;return`<actor-notification>
|
|
395
|
-
${Z} was cancelled.
|
|
396
|
-
</actor-notification>`}var fQ=a.create({service:"inbox"}),p3=604800000,cQ=100;function uQ($){return Q.sync(()=>t2.use((Z)=>Z.delete(Q$).where(dQ(Q$.created_at,$)).run()))}class l9 extends p0.TaggedErrorClass()("InboxReceiverNotFound",{receiverSessionID:p0.String,receiverActorID:p0.String}){}class E4 extends Z2.Service()("@qitqode/Inbox"){}var oQ=_.effect(E4,Q.gen(function*(){let $=yield*p.Service,Z=yield*_2.Service,X=yield*J2.Service,Y=yield*l2.Scope;yield*uQ(Date.now()-p3),fQ.info("inbox gc-on-init complete");let J=Q.fn("Inbox.send")(function*(G){if(!(yield*Z.get(G.receiverSessionID,G.receiverActorID)))return yield*Q.fail(new l9({receiverSessionID:G.receiverSessionID,receiverActorID:G.receiverActorID}));let V={id:$8(),receiver_session_id:G.receiverSessionID,receiver_actor_id:G.receiverActorID,sender_session_id:G.senderSessionID??null,sender_actor_id:G.senderActorID??null,type:G.type??"text",content:{text:G.content},created_at:Date.now()};yield*Q.sync(()=>t2.use((y)=>y.insert(Q$).values(V).run())),yield*$.publish(lQ,{receiverSessionID:G.receiverSessionID,receiverActorID:G.receiverActorID,...G.senderSessionID!==void 0?{senderSessionID:G.senderSessionID}:{},...G.senderActorID!==void 0?{senderActorID:G.senderActorID}:{},inboxID:V.id,type:V.type});let K=H1.current;if(K)yield*K.loop({sessionID:G.receiverSessionID,agentID:G.receiverActorID}).pipe(Q.ignore,Q.forkIn(Y));else fQ.warn("inbox.send: sessionPromptRef.current undefined \u2014 wake skipped",{receiverActorID:G.receiverActorID});return{inboxID:V.id}}),B=Q.fn("Inbox.drain")(function*(G,H){let V=yield*Q.sync(()=>t2.use((z)=>z.select().from(Q$).where(vQ(j0(Q$.receiver_session_id,G),j0(Q$.receiver_actor_id,H))).orderBy(Q$.id).limit(cQ).all()));if(V.length===0)return 0;let y=(yield*X.messages({sessionID:G,agentID:H})).findLast((z)=>(z.info.role==="user"||z.info.role==="assistant")&&("model"in z.info)&&z.info.model!==void 0&&z.info.model.providerID!=="system"&&z.info.agent!=="system");if(!y||!("model"in y.info)||!y.info.model||!("agent"in y.info))return 0;let j=w2.ascending(),q=Date.now();yield*X.updateMessage({id:j,role:"user",sessionID:G,agentID:H,time:{created:q},agent:y.info.agent,model:y.info.model});for(let z of V)yield*X.updatePart({id:Y2.ascending(),messageID:j,sessionID:G,type:"text",synthetic:!0,text:gQ(z)});return yield*Q.sync(()=>t2.use((z)=>z.delete(Q$).where(mQ(Q$.id,V.map((D)=>D.id))).run())),V.length}),W=E4.of({send:J,drain:B});return g4.current=W,yield*Q.addFinalizer(()=>Q.sync(()=>{if(g4.current===W)g4.current=void 0})),W})),i3=oQ.pipe(_.provide(p.defaultLayer),_.provide(_2.defaultLayer),_.provide(J2.defaultLayer));function m8($){return $.replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
|
|
397
|
-
`).map((Z)=>Z.trim()).find((Z)=>Z.length>0)}var G1={};b2(G1,{layer:()=>pQ,defaultLayer:()=>n3,TaskGateState:()=>G1,Service:()=>f4});class f4 extends Z2.Service()("@qitqode/TaskGateState"){}var pQ=_.effect(f4,Q.gen(function*(){let $=yield*d.make(Q.fn("TaskGateState.state")(function*(){return{counts:new Map}})),Z=Q.fn("TaskGateState.get")(function*(J){return(yield*d.get($)).counts.get(J)??0}),X=Q.fn("TaskGateState.bump")(function*(J){let B=yield*d.get($),W=(B.counts.get(J)??0)+1;return B.counts.set(J,W),W}),Y=Q.fn("TaskGateState.clear")(function*(J){(yield*d.get($)).counts.delete(J)});return f4.of({get:Z,bump:X,clear:Y})})),n3=pQ;var m$=a.create({service:"session.prompt"}),a3=`Use this tool to return your final response in the requested structured format.
|
|
398
|
-
|
|
399
|
-
IMPORTANT:
|
|
400
|
-
- You MUST call this tool exactly once at the end of your response
|
|
401
|
-
- The input must be valid JSON matching the required schema
|
|
402
|
-
- Complete all necessary research and tool calls BEFORE calling this tool
|
|
403
|
-
- This tool provides your final answer - no further actions are taken after calling it`,sQ="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 s3($){return/\/\.qitqode\/(tools?|skills?|hooks?)\//.test($)}function v4($){let{$schema:Z,...X}=$.schema;return t$({description:a3,inputSchema:K$(X),async execute(Y){return $.onSuccess(Y),{output:"Structured output captured successfully.",title:"Structured Output",metadata:{valid:!0}}},toModelOutput({output:Y}){return{type:"text",value:Y.output}}})}function rQ($){return Q.gen(function*(){let Z=yield*K0.Service,X=yield*N0.Service,Y=yield*j1.Service,J=yield*p.Service,B=yield*y2.Service,W=yield*H2.Service,G=yield*_2.Service;return Q.fn("SessionPrompt.resolveTools")(function*(V){let F=[];try{const K=iQ(F,m$.time("resolveTools"),0);let y={};let j=yield*D0.make();let q=yield*$();let z=Q.fn("SessionPrompt.whitelistFor")(function*(){if(!V.agentID)return;let I=yield*G.get(V.session.id,V.agentID);if(!I||!Array.isArray(I.tools))return;return new Set(I.tools)});let D=yield*z();let U=(I)=>({title:"Tool not permitted",output:`The "${I}" tool is not in this actor's whitelist. Allowed tools: ${D?[...D].join(", "):"(none)"}.`,metadata:{rejected:!0,reason:"tool-whitelist"}});let P=(I,k)=>({sessionID:V.session.id,abort:k.abortSignal,messageID:V.processor.message.id,callID:k.toolCallId,extra:{model:V.model,bypassAgentCheck:V.bypassAgentCheck,promptOps:q},agent:V.agent.name,actorID:V.agentID,taskId:V.task_id,messages:V.messages,metadata:(E)=>V.processor.updateToolCall(k.toolCallId,(L)=>{if(!["running","pending"].includes(L.state.status))return L;return{...L,state:{title:E.title,metadata:E.metadata,status:"running",input:I,time:{start:Date.now()}}}}),ask:(E)=>B.ask({...E,sessionID:V.session.id,tool:{messageID:V.processor.message.id,callID:k.toolCallId},ruleset:y2.merge(V.agent.permission,V.session.permission??[]),interactive:!T6.has(V.agent.name)},k.abortSignal).pipe(Q.orDie)});for(let I of yield*Z.tools({modelID:t0.make(V.model.api.id),providerID:V.model.providerID,agent:V.agent})){let k=I4(V.model,I.parameters);y[I.id]=t$({description:I.description,inputSchema:K$(k),execute(E,L){return j.promise(Q.gen(function*(){let S=Date.now(),T=L?.toolCallId??"?";m$.debug("tool execute start",{tool:I.id,callID:T,sessionID:V.session.id});let w=P(E,L);if(D&&!D.has(I.id)){let g=U(I.id);return m$.debug("tool execute rejected",{tool:I.id,callID:T,durationMs:Date.now()-S}),yield*V.processor.completeToolCall(L.toolCallId,g),g}let A={args:E};if(yield*W.trigger("tool.execute.before",{tool:I.id,sessionID:w.sessionID,callID:w.callID},A),A.cancel){let g={title:"Cancelled",output:A.cancelReason||"Tool call cancelled by hook",metadata:{cancelled:!0}};return yield*J.publish(k2.ToolCall,{sessionID:w.sessionID,tool_name:I.id,input_bytes:k2.jsonByteLength(A.args),output_bytes:0,tool_call_id:L.toolCallId,tool_call_status:"cancelled"}).pipe(Q.ignore),yield*V.processor.completeToolCall(L.toolCallId,g),g}let R=yield*I.execute(A.args,w);m$.debug("tool execute done",{tool:I.id,callID:T,durationMs:Date.now()-S,ok:!0});let C={...R,attachments:R.attachments?.map((g)=>({...g,id:Y2.ascending(),sessionID:w.sessionID,messageID:V.processor.message.id}))};if(yield*W.trigger("tool.execute.after",{tool:I.id,sessionID:w.sessionID,callID:w.callID,args:A.args},C),(I.id==="write"||I.id==="edit")&&A.args?.filePath&&s3(A.args.filePath))yield*Z.reload().pipe(Q.tapError((g)=>Q.sync(()=>m$.warn("extension reload failed",{error:g}))),Q.ignore);if(yield*J.publish(k2.ToolCall,{sessionID:w.sessionID,tool_name:I.id,input_bytes:k2.jsonByteLength(A.args),output_bytes:Buffer.byteLength(C.output??"","utf8"),tool_call_id:L.toolCallId,tool_call_status:"success"}).pipe(Q.ignore),L.abortSignal?.aborted)yield*V.processor.completeToolCall(L.toolCallId,C);return C}))}})}for(let[I,k]of Object.entries(yield*X.tools())){let E=k.execute;if(!E)continue;let L=yield*Q.promise(()=>Promise.resolve(aQ(k.inputSchema).jsonSchema)),S=n2.schema(V.model,L);k.inputSchema=K$(S),k.execute=(T,w)=>j.promise(Q.gen(function*(){let A=Date.now(),R=w?.toolCallId??"?";m$.debug("tool execute start (mcp)",{tool:I,callID:R,sessionID:V.session.id});let C=P(T,w);if(D&&!D.has(I)){let n=U(I),s={title:n.title,metadata:n.metadata,output:n.output,attachments:[],content:[{type:"text",text:n.output}]};return m$.debug("tool execute rejected (mcp)",{tool:I,callID:R,durationMs:Date.now()-A}),yield*V.processor.completeToolCall(w.toolCallId,s),s}let g={args:T};if(yield*W.trigger("tool.execute.before",{tool:I,sessionID:C.sessionID,callID:w.toolCallId},g),g.cancel){let n={content:[{type:"text",text:g.cancelReason||"Tool call cancelled by hook"}]};return yield*J.publish(k2.ToolCall,{sessionID:C.sessionID,tool_name:I,input_bytes:k2.jsonByteLength(g.args),output_bytes:0,tool_call_id:w.toolCallId,tool_call_status:"cancelled"}).pipe(Q.ignore),n}yield*C.ask({permission:I,metadata:{},patterns:["*"],always:["*"]});let l=yield*Q.promise(()=>E(g.args,w));m$.debug("tool execute done (mcp)",{tool:I,callID:R,durationMs:Date.now()-A,ok:!0}),yield*W.trigger("tool.execute.after",{tool:I,sessionID:C.sessionID,callID:w.toolCallId,args:T},l);let m=[];yield*J.publish(k2.ToolCall,{sessionID:C.sessionID,tool_name:I,input_bytes:k2.jsonByteLength(T),output_bytes:k2.jsonByteLength(l.content??""),tool_call_id:w.toolCallId,tool_call_status:"success"}).pipe(Q.ignore);let h=[];for(let n of l.content)if(n.type==="text")m.push(n.text);else if(n.type==="image")h.push({type:"file",mime:n.mimeType,url:`data:${n.mimeType};base64,${n.data}`});else if(n.type==="resource"){let{resource:s}=n;if(s.text)m.push(s.text);if(s.blob)h.push({type:"file",mime:s.mimeType??"application/octet-stream",url:`data:${s.mimeType??"application/octet-stream"};base64,${s.blob}`,filename:s.uri})}let f=yield*Y.output(m.join(`
|
|
404
|
-
|
|
405
|
-
`),{},V.agent),e={title:"",metadata:{...l.metadata,truncated:f.truncated,...f.truncated&&{outputPath:f.outputPath}},output:f.content,attachments:h.map((n)=>({...n,id:Y2.ascending(),sessionID:C.sessionID,messageID:V.processor.message.id})),content:l.content};if(w.abortSignal?.aborted)yield*V.processor.completeToolCall(w.toolCallId,e);return e})),y[I]=k}return y}catch(b){var O=b,M=1}finally{nQ(F,O,M)}})})}function tQ($){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 c9($){return tQ($)}var d4=Q.gen(function*(){return{bus:yield*p.Service,status:yield*z0.Service,sessions:yield*v2,agents:yield*E2.Service,provider:yield*z2.Service,processor:yield*c0.Service,prune:yield*N$.Service,checkpoint:yield*P$.Service,compaction:yield*q$.Service,config:yield*B2.Service,plugin:yield*H2.Service,permission:yield*y2.Service,fsys:yield*s2.Service,registry:yield*K0.Service,scope:yield*l2.Scope,instruction:yield*G$.Service,state:yield*y0.Service,goal:yield*m0.Service,taskGateState:yield*G1.Service,taskRegistry:yield*M0.Service,revert:yield*$$.Service,summary:yield*P0.Service,sys:yield*V$.Service,llm:yield*f2.Service,actorRegistry:yield*_2.Service,inbox:yield*i0.Service}}),u9=Q.fnUntraced(function*($,Z,X,Y){let J=(yield*$.list()).filter((G)=>!G.hidden).map((G)=>G.name),B=J.length?` Available agents: ${J.join(", ")}`:"",W=new x2.Unknown({message:`Agent not found: "${X}".${B}`});return yield*Z.publish(A2.Error,{sessionID:Y,error:W.toObject()}),W}),l$=Q.fnUntraced(function*($,Z,X,Y){let J=yield*$.get(X);if(!J)throw yield*u9($,Z,X,Y);return J}),X8=Q.fnUntraced(function*($,Z,X){if(!Z)return X;let Y=yield*$.resolveModelRef(Z);return{providerID:Y.providerID,modelID:Y.id}});function r3($,Z,X){if(!$.startsWith("data:"))return $;return`[data-url:${Z}${X?`:${X}`:""}]`}function eQ($){return{...$,url:r3($.url,$.mime,$.filename)}}function t3($){if($.status==="completed"&&$.attachments&&$.attachments.length>0)return{...$,attachments:$.attachments.map(eQ)};return $}function e3($){if($.type==="file")return eQ($);if($.type==="tool")return{...$,state:t3($.state)};return $}function m4($){if(!$)return;if(typeof $==="object"&&$!==null&&"message"in $&&typeof $.message==="string")return $.message;return JSON.stringify($)}function $Y($){return $.filter((Z)=>Z.type==="text"&&!Z.synthetic&&!Z.ignored).map((Z)=>Z.text).join(`
|
|
406
|
-
`)}function l4($,Z){if($.structured!==void 0)return JSON.stringify($.structured);return Z.findLast((X)=>X.type==="text"&&!X.synthetic)?.text}function c4($){return $.map((Z)=>({...Z.info,created:Z.info.time.created,parts:Z.parts.map(e3)}))}function ZY($,Z,X){let Y=$.findIndex((J)=>J.info.id===Z.id);if(Y===-1)return[...$,{info:Z,parts:X}];return $.map((J,B)=>B===Y?{info:Z,parts:X}:J)}function o9($,Z,X){return X.pipe(Q.catchDefect((Y)=>{if(!(Y instanceof Z0.BackendAuthRejectedError))return Q.die(Y);return Z.publish(A2.Error,{sessionID:$,error:new x2.Unknown({message:Y.message}).toObject()}).pipe(Q.andThen(Q.die(Y)))}))}var XY=Q.fn("SessionPrompt.prepareStep")(function*($){let X=$.msgs.findLast((B)=>B.info.role==="user")?.parts.some((B)=>B.type==="agent")??!1,Y=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")Y.StructuredOutput=$.createStructuredOutputTool({schema:$.lastUser.format.schema,onSuccess(B){$.structured.value=B}});if($.step===1)yield*$.summary.summarize({sessionID:$.sessionID,messageID:$.lastUser.id}).pipe(Q.ignore,Q.forkIn($.scope));if($.step>1&&$.lastFinished)for(let B of $.msgs){if(B.info.role!=="user"||B.info.id<=$.lastFinished.id)continue;for(let W of B.parts){if(W.type!=="text"||W.ignored||W.synthetic)continue;if(!W.text.trim())continue;W.text=U2({source:"recovery",trust:"runtime-safety",body:["The user sent the following message:",W.text,"","Please address this message and continue with your tasks."].join(`
|
|
407
|
-
`)})}}yield*$.plugin.trigger("experimental.chat.messages.transform",{},{messages:$.msgs});let J=$.msgs.findLast((B)=>B.info.role==="user"&&B.info.id===$.lastUser.id)?.parts??[];return{tools:Y,format:$.lastUser.format??{type:"text"},query:$Y(J)}});function QY($){return{cancelledByPlugin:Q.gen(function*(){let Y={cancel:void 0,cancelReason:void 0};if(yield*$.plugin.trigger("session.userQuery.pre",{sessionID:$.sessionID,agentID:$.agentID,step:$.step,messageID:$.lastUser.id,query:$.query},Y),!Y.cancel)return!1;return $.cancellation.cancelled=!0,$.cancellation.reason=Y.cancelReason,$.handle.message.error=new o.AbortedError({message:Y.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:Y.cancelReason,trajectory:$.trajectoryForStep($.msgs,$.handle.message)},{}),!0}),withUserQueryPost:(Y)=>Y.pipe(Q.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:i2.isFailure(J)?W2.pretty(J.cause):m4($.handle.message.error),finalText:l4($.handle.message,o.parts($.handle.message.id)),trajectory:$.trajectoryForStep($.msgs,$.handle.message)},{}).pipe(Q.ignore)))}}var Q8={};b2(Q8,{toSchemaOnlyTools:()=>JY,runMaxStep:()=>QH,runCandidate:()=>BY,parseJudgeIndex:()=>WY,judge:()=>VY,MaxMode:()=>Q8,MAX_MODE_AGENT:()=>$H,DEFAULT_CANDIDATES:()=>YY});var u4=a.create({service:"session.max-mode"}),YY=5,$H="max";function JY($){let Z={};for(let[X,Y]of Object.entries($)){let{execute:J,...B}=Y;Z[X]=B}return Z}var BY=($,Z)=>Q.gen(function*(){let X=R6(),Y={index:Z,reasoning:"",text:"",toolCalls:[],finishReason:"stop"},J=JY($.tools),B=$.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*p9(B,(W)=>{switch(W.type){case"reasoning-delta":if(Y.reasoning+=W.text,X.append(W.text))return Q.fail(x6());if(W.providerMetadata)Y.reasoningMetadata=W.providerMetadata;break;case"text-delta":if(Y.text+=W.text,X.append(W.text))return Q.fail(x6());if(W.providerMetadata)Y.textMetadata=W.providerMetadata;break;case"tool-call":Y.toolCalls.push({toolCallId:W.toolCallId,toolName:W.toolName,input:W.input??{},providerMetadata:W.providerMetadata});break;case"finish-step":Y.finishReason=W.finishReason??Y.finishReason,Y.usage=W.usage,Y.providerMetadata=W.providerMetadata;break;case"error":return Q.fail(W.error);default:break}return Q.void}),Y}).pipe(Q.catchCauseIf((X)=>!W2.hasInterruptsOnly(X),(X)=>Q.fail(W2.squash(X))),Q.retry({while:f2.isTransientCapacityError,schedule:f2.persistentRetrySchedule}),Q.catchIf(A7,()=>Q.succeed("text-repeat")),Q.catch((X)=>Q.sync(()=>{return u4.warn("candidate failed",{index:Z,error:X instanceof Error?X.message:String(X)}),null})));function ZH($,Z){let X=$.toolCalls.length===0?"(no tool calls \u2014 final answer / text only)":$.toolCalls.map((B)=>` - ${B.toolName}(${JSON.stringify(B.input)})`).join(`
|
|
408
|
-
`),Y=$.reasoning.trim()?$.reasoning.trim():"(no reasoning emitted)",J=$.text.trim()?$.text.trim():"(no text emitted)";return[`### Candidate ${Z}`,`Reasoning:
|
|
409
|
-
${Y}`,`Message:
|
|
410
|
-
${J}`,`Proposed tool calls:
|
|
411
|
-
${X}`].join(`
|
|
412
|
-
`)}var XH=["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(`
|
|
413
|
-
`);function WY($,Z){let X=$.match(/\d+/);if(!X)return 0;let Y=parseInt(X[0],10);if(Number.isNaN(Y)||Y<0||Y>=Z)return 0;return Y}var VY=($,Z)=>Q.gen(function*(){if(Z.length===1)return{pick:0,usage:void 0};let X=Z.map((H,V)=>ZH(H,V)).join(`
|
|
414
|
-
|
|
415
|
-
`),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(`
|
|
416
|
-
`)}],B="",W,G=$.llm.stream({user:$.user,sessionID:$.sessionID,parentSessionID:$.parentSessionID,model:$.model,agent:$.agent,permission:$.permission,system:[XH],messages:J,tools:{},toolChoice:"none",agentID:$.agentID});return yield*p9(G,(H)=>{if(H.type==="text-delta")B+=H.text;else if(H.type==="finish-step")W=H.usage;else if(H.type==="error")return Q.fail(H.error);return Q.void}),{pick:WY(B,Z.length),usage:W}}).pipe(Q.catchCauseIf((X)=>!W2.hasInterruptsOnly(X),(X)=>Q.fail(W2.squash(X))),Q.retry({while:f2.isTransientCapacityError,schedule:f2.persistentRetrySchedule}),Q.catch((X)=>{return u4.warn("judge failed, defaulting to candidate 0",{error:X instanceof Error?X.message:String(X)}),Q.succeed({pick:0,usage:void 0})})),QH=($)=>Q.gen(function*(){let Z=Math.max(1,$.candidates??YY),X=(y)=>$.setStatus?$.setStatus(y):Q.void,Y=Date.now();yield*X(`thinking \u2014 ${Z} candidates`);let J=yield*Q.all(Array.from({length:Z},(y,j)=>BY($,j)),{concurrency:Z});if(J.some((y)=>y==="text-repeat"))return"text-repeat";let B=J.filter((y)=>y!==null&&y!=="text-repeat");if(B.length===0)return u4.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 ${B.length} candidates`);let{pick:W,usage:G}=yield*VY($,B),H=B[W];u4.info("max step",{candidates:Z,survivors:B.length,winner:W,toolCalls:H.toolCalls.length});let K=[...B.filter((y,j)=>j!==W).map((y)=>y.usage),G].reduce((y,j)=>{if(!j)return y;let q=S6({model:$.model,usage:j});return y.cost+=q.cost,y.tokensIn+=q.tokens.input+q.tokens.cache.read+q.tokens.cache.write,y.tokensOut+=q.tokens.output+q.tokens.reasoning,y},{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:W,total:B.length},thinkingMs:Date.now()-Y,overhead:K})});var KY="This model cannot read images and no image-capable fallback tier is available. Choose a vision-capable model or remove the image.",HY="The image analysis returned no useful text. Please try the image again or remove it.";function YH($){if(!$.startsWith("data:"))return;let Z=$.indexOf(",");if(Z<0)return;let X=$.slice(Z+1),Y=X.endsWith("==")?2:X.endsWith("=")?1:0;return Math.max(0,Math.floor(X.length*3/4)-Y)}function JH($){if($.info.role!=="user")return[];return $.parts.flatMap((Z,X)=>{if(Z.type!=="file"||!Z.mime.startsWith("image/"))return[];return[{url:Z.url,mime:Z.mime,filename:Z.filename,index:X}]})}function GY($,Z){let X=JH($);if(X.length===0)return{kind:"none",reason:"no-images"};if(Z.capabilities.input.image)return{kind:"none",reason:"native-vision"};if(X.length>4)return{kind:"error",message:`Vision fallback supports at most 4 images per message; received ${X.length}. Remove some images and try again.`};for(let Y of X){let J=YH(Y.url);if(J!==void 0&&J>4194304)return{kind:"error",message:`Image ${Y.filename?`"${Y.filename}" `:""}is too large for vision fallback (maximum 4 MB). Resize it and try again.`};if(Y.url.startsWith("data:")&&(J===void 0||J===0))return{kind:"error",message:`Image ${Y.filename?`"${Y.filename}" `:""}is empty or corrupted. Provide a valid image and try again.`}}return{kind:"fallback",images:X}}function jY($,Z,X=["default","power","fast","economical","free","orchestrated"]){let Y=[];for(let J of X){let B=Object.values($).flatMap((W)=>Object.values(W.models)).find((W)=>W.id===J);if(B&&(B.providerID!==Z.providerID||B.id!==Z.id)&&B.capabilities.input.image)Y.push(B)}for(let J of Object.values($).sort((B,W)=>B.id.localeCompare(W.id)))for(let B of Object.values(J.models).sort((W,G)=>W.id.localeCompare(G.id)))if(B.providerID!==Z.providerID||B.id!==Z.id){if(B.capabilities.input.image&&!Y.includes(B))Y.push(B)}return Y[0]}function OY($,Z){return[{role:"user",content:[{type:"text",text:`Analyze the attached images for the user's request. Describe only useful, observable details. Do not speculate about hidden metadata.
|
|
417
|
-
|
|
418
|
-
User request:
|
|
419
|
-
`+(Z.trim()||"Describe the images.")},...$.map((X)=>({type:"image",image:X.url,mediaType:X.mime}))]}]}function BH($){if($.type==="image")return!0;return $.type==="file"&&typeof $.mediaType==="string"&&$.mediaType.startsWith("image/")}function WH($){let Z=$.type==="image"?$.image:$.type==="file"?$.data:void 0;if(typeof Z==="string")return Z;if(Z instanceof URL)return Z.toString();return}function VH($,Z){let X=new Set(Z.map((Y)=>Y.url));if(X.size>0){let Y=$.findLastIndex((J)=>J.role==="user"&&Array.isArray(J.content)&&J.content.some((B)=>{let W=WH(B);return W!==void 0&&X.has(W)}));if(Y>=0)return Y}return $.findLastIndex((Y)=>Y.role==="user")}function FY($,Z,X=[]){let Y=VH($,X),J=$.map((W,G)=>{if(G!==Y||W.role!=="user"||!Array.isArray(W.content))return W;return{...W,content:W.content.filter((H)=>!BH(H))}}),B={role:"user",content:`[Vision analysis \u2014 generated context]
|
|
420
|
-
`+Z.trim()};if(Y<0)return[...J,B];return J.splice(Y+1,0,B),J}var yY=Q.fn("SessionPrompt.executeLlmStep")(function*($){let Z=$.lastUser.agentID?yield*$.actorRegistry.get($.sessionID,$.lastUser.agentID).pipe(Q.orElseSucceed(()=>{return})):void 0;if(Z?.contextMode==="full"&&(Z.mode==="subagent"||Z.mode==="peer")){let P=Y$.current?.getForkContext($.lastUser.agentID),F=P?yield*P:void 0;if(!F)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(Q.ignore),{kind:"break",reason:"missing-fork-context"};let b=$.msgs.filter((k)=>k.info.id>F.watermarkMsgID&&k.info.agentID===$.lastUser.agentID),O=yield*o.toModelMessagesEffect(b,$.model),M=[...F.inheritedMessages,...O];if(yield*$.cancelledByPlugin)return{kind:"processed",result:"stop",fork:!0};return{kind:"processed",result:yield*$.withUserQueryPost($.handle.process({user:$.lastUser,agent:$.agent,permission:F.parentPermission??$.session.permission,sessionID:$.sessionID,parentSessionID:$.session.parentID,system:[],prebuiltSystem:F.system,messages:[...M,...$.isLastStep?[{role:"assistant",content:$.maxStepsText}]:[]],tools:$.tools,model:$.model,toolChoice:$.format.type==="json_schema"?"required":void 0,agentID:$.lastUser.agentID})),fork:!0}}let[Y,J,B]=yield*Q.all([$.sys.skills($.agent),Q.sync(()=>$.sys.environment($.model,$.session.time.created)),$.instruction.system().pipe(Q.orDie)]);if(!$.session.parentID&&!$.instructionsNotified.has($.sessionID)){$.instructionsNotified.add($.sessionID);let P=(yield*d.context).worktree,F=Array.from(B.paths,(b)=>G$.display(b,P));if(F.length>0)yield*$.bus.publish(zY,{files:F}).pipe(Q.ignore)}let W=[...J,...Y?[Y]:[],...B.content,...$.format.type==="json_schema"?[sQ]:[]],G=$.msgs.find((P)=>P.info.id===$.lastUser.id),H=G?GY(G,$.model):{kind:"none",reason:"no-images"};if(H.kind==="error")return{kind:"break",reason:"vision-unavailable",message:H.message};let{system:V,inheritedMessages:K}=yield*k4({sessionID:$.sessionID,agent:$.agent,model:$.model,msgs:$.msgs,additions:W}).pipe(Q.provideService(f2.Service,$.llm),Q.provideService(K0.Service,$.registry)),y;if(H.kind==="fallback"){let P=$.visionAnalysis.get($.lastUser.id);if(P===void 0){let F=jY(yield*$.provider.list(),$.model);if(!F)return{kind:"break",reason:"vision-unavailable",message:KY};yield*$.slog.warn("vision fallback routing",{selectedModel:$.model.id,fallbackModel:F.id,imageCount:H.images.length});let b=G?.parts.filter((M)=>M.type==="text"&&!M.ignored).map((M)=>M.text).join(`
|
|
421
|
-
`)??"",O=yield*$.llm.stream({user:$.lastUser,agent:$.agent,model:F,sessionID:$.sessionID,system:[],messages:OY(H.images,b),tools:{},retries:0,toolChoice:"none",agentID:$.lastUser.agentID}).pipe(J8((M)=>M.type==="text-delta"),Y8((M)=>M.text),B8,Q.orDie);if(!O.trim())return{kind:"break",reason:"vision-unavailable",message:HY};P=O,$.visionAnalysis.set($.lastUser.id,P)}y=FY(K,P,H.images)}let j=(yield*$.config.get()).experimental?.maxMode,q=$.agent.name===Q8.MAX_MODE_AGENT&&j!==void 0&&$.format.type!=="json_schema",z={user:$.lastUser,agent:$.agent,permission:$.session.permission,sessionID:$.sessionID,parentSessionID:$.session.parentID,system:W,prebuiltSystem:V,messages:[...y??K,...$.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 D=q?Q8.runMaxStep({...z,handle:$.handle,llm:$.llm,candidates:j?.candidates,setStatus:(P)=>$.status.set($.sessionID,P?{type:"busy",message:P}:{type:"busy"})}):$.handle.process(z);return{kind:"processed",result:yield*$.withUserQueryPost(D),fork:!1}});function DY($){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 o4($,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(Q.ignore)}function qY($,Z){return Q.gen(function*(){yield*$.checkpoint.waitForWriter(Z.sessionID).pipe(Q.ignore);let X=yield*$.checkpoint.lastBoundary(Z.sessionID).pipe(Q.catch(()=>Q.succeed(void 0))),Y=X?Z.msgs.find((J)=>J.info.id===X):void 0;return X?yield*$.checkpoint.insertRebuildBoundary({sessionID:Z.sessionID,boundary:X,lastMessageInfo:DY(Z.msgs.map((J)=>J.info)),agentID:Z.lastUser.agentID,agent:Z.lastUser.agent,model:{providerID:Z.model.providerID,modelID:Z.model.id},boundaryCreatedAt:Y?.info.time.created}).pipe(Q.catch(()=>Q.succeed(!1))):!1})}var PY=Q.fn("SessionPrompt.handlePreStepOverflow")(function*($,Z){if(Z.isBoundedComputation||Z.lastFinished.summary===!0)return!1;let X=yield*$.config.get();if(!(M1({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*o4($,Z,!1),!0;if(yield*$.checkpoint.hasCheckpoint(Z.sessionID).pipe(Q.catch(()=>Q.succeed(!1)))){if(yield*qY($,Z))return yield*$.prune.resetThresholds(Z.sessionID),!0}return yield*o4($,Z,!1),!0}),NY=Q.fn("SessionPrompt.handleProviderOverflow")(function*($,Z){if(!Z.isBoundedComputation&&Z.lastUser.agentID&&Z.lastUser.agentID!=="main")return yield*o4($,Z,!0),!0;if(!Z.isBoundedComputation){let X=yield*$.checkpoint.isWriterRunning(Z.sessionID).pipe(Q.catch(()=>Q.succeed(!1))),Y=yield*$.checkpoint.hasCheckpoint(Z.sessionID).pipe(Q.catch(()=>Q.succeed(!1)));if(X||Y){if(yield*qY($,Z))return yield*$.prune.resetThresholds(Z.sessionID),!0}yield*o4($,Z,!0)}return!0});function wY($){return(Z)=>Q.gen(function*(){let X=yield*o.filterCompactedEffect($.sessionID,{contextFrom:$.session.contextFrom,contextWatermark:$.session.contextWatermark,agentID:$.agentID}).pipe(Q.catch(()=>Q.succeed([]))),Y=X.findLast((K)=>K.info.role==="assistant"),J=Y&&Y.info.role==="assistant"?Y.info:void 0,B=Y?.parts??[],W=i2.isFailure(Z),G=!!J?.error,H=$.cancellation.cancelled?"cancelled":W||G?"error":"completed",V=$.cancellation.cancelled?$.cancellation.reason:W?W2.pretty(Z.cause):J?m4(J.error):void 0;yield*$.plugin.trigger("session.post",{sessionID:$.sessionID,agentID:$.agentID,task_id:$.task_id,outcome:H,error:V,finalText:J?l4(J,B):void 0,assistantMessageID:J?.id,trajectory:c4(X)},{})}).pipe(Q.ignore)}function xY($){let Z={cancelled:!1,reason:void 0},X={tokens_in:0,tokens_out:0,files_changed:0},Y=Q.gen(function*(){let W={cancel:void 0,cancelReason:void 0};if(yield*$.plugin.trigger("session.pre",{sessionID:$.sessionID,agentID:$.agentID,task_id:$.task_id},W),!W.cancel)return;return Z.cancelled=!0,Z.reason=W.cancelReason,yield*Q.fail(new x2.Unknown({message:W.cancelReason??"Session cancelled by plugin"}))});return{cancellation:Z,agentMetrics:X,before:Y,publishAgentRequest:(W,G)=>$.bus.publish(k2.AgentRequest,{sessionID:$.sessionID,phase:W,task_type:G,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(Q.ignore),schedulePrune:(W)=>$.prune.prune({sessionID:$.sessionID,model:W.model,tokens:W.lastFinished.tokens,lastAssistantTime:W.lastFinished.time.completed,promptOps:W.promptOps}).pipe(Q.ignore,Q.forkIn($.scope),Q.asVoid)}}var LY={input:0,output:0,reasoning:0,cache:{read:0,write:0}};function p4($){return{id:w2.ascending(),sessionID:$.sessionID,role:"assistant",parentID:$.parentID,agentID:$.agentID,mode:$.agent,agent:$.agent,variant:$.variant,path:{cwd:$.cwd,root:$.root},cost:0,tokens:{...LY,cache:{...LY.cache}},modelID:$.modelID,providerID:$.providerID,time:{created:$.created??Date.now()}}}var KH=a.create({service:"session.prompt"}),bY=Q.fn("SessionPrompt.getModel")(function*($,Z,X,Y,J){let B=yield*$.getModel(X,Y).pipe(Q.exit);if(i2.isSuccess(B))return B.value;let W=W2.squash(B.cause);if(z2.ModelNotFoundError.isInstance(W)){let G=W.data.suggestions?.length?` Did you mean: ${W.data.suggestions.join(", ")}?`:"";yield*Z.publish(A2.Error,{sessionID:J,error:new x2.Unknown({message:`Model not found: ${W.data.providerID}/${W.data.modelID}.${G}`}).toObject()})}return yield*Q.failCause(B.cause)}),UY=bY,n4=Q.fn("SessionPrompt.getModel")(function*($,Z,X){let Y=yield*z2.Service,J=yield*p.Service;return yield*bY(Y,J,$,Z,X)}),AY=Q.fnUntraced(function*($,Z,X){if(X!==void 0){let B=yield*$.messages({sessionID:Z,agentID:X}),W=B.findLast((G)=>G.info.role==="assistant");if(W)return W;if(B.length>0)return B[B.length-1]}let Y=yield*$.findMessage(Z,(B)=>B.info.role!=="user",{agentID:"*"});if(Y0.isSome(Y))return Y.value;let J=yield*$.messages({sessionID:Z,limit:1,agentID:"*"});if(J.length>0)return J[0];throw Error("Impossible")}),MY=AY,HH=Q.fnUntraced(function*($,Z){let X=yield*v2;return yield*AY(X,$,Z)}),i9=Q.fn("SessionPrompt.handleSubtask")(function*($){let{task:Z,model:X,lastUser:Y,sessionID:J,session:B,msgs:W,getOps:G}=$,H=yield*d.context,V=yield*p.Service,K=yield*K0.Service,y=yield*v2,j=yield*E2.Service,q=yield*H2.Service,z=yield*y2.Service,D=yield*G(),{actor:U}=yield*K.named(),P=Z.model?yield*n4(Z.model.providerID,Z.model.modelID,J):X,F=yield*y.updateMessage(p4({sessionID:J,parentID:Y.id,agentID:Y.agentID,agent:Z.agent,variant:Y.model.variant,cwd:H.directory,root:H.worktree,modelID:P.id,providerID:P.providerID})),b={operation:{action:"run",prompt:Z.prompt,description:Z.description,subagent_type:Z.agent,command:Z.command}},O=yield*y.updatePart({id:Y2.ascending(),messageID:F.id,sessionID:F.sessionID,type:"tool",callID:$8(),tool:i4.id,state:{status:"running",input:b,time:{start:Date.now()}}});yield*q.trigger("tool.execute.before",{tool:i4.id,sessionID:J,callID:O.id},{args:b});let M=yield*l$(j,V,Z.agent,J),I,k=new AbortController,E=yield*U.execute(b,{agent:Z.agent,messageID:F.id,sessionID:J,abort:k.signal,callID:O.callID,extra:{bypassAgentCheck:!0,promptOps:D},messages:W,metadata:(T)=>Q.gen(function*(){O=yield*y.updatePart({...O,type:"tool",state:{...O.state,...T}})}),ask:(T)=>z.ask({...T,sessionID:J,ruleset:y2.merge(M.permission,B.permission??[])}).pipe(Q.orDie)}).pipe(Q.catchCause((T)=>{let w=W2.squash(T);return I=w instanceof Error?w:Error(String(w)),KH.error("subtask execution failed",{error:I,agent:Z.agent,description:Z.description}),Q.void}),Q.onInterrupt(()=>Q.gen(function*(){if(k.abort(),F.finish="tool-calls",F.time.completed=Date.now(),yield*y.updateMessage(F),O.state.status==="running")yield*y.updatePart({...O,state:{status:"error",error:"Cancelled",time:{start:O.state.time.start,end:Date.now()},metadata:O.state.metadata,input:O.state.input}})}))),L=E?.attachments?.map((T)=>({...T,id:Y2.ascending(),sessionID:J,messageID:F.id}));if(yield*q.trigger("tool.execute.after",{tool:i4.id,sessionID:J,callID:O.id,args:b},E),F.finish="tool-calls",F.time.completed=Date.now(),yield*y.updateMessage(F),E&&O.state.status==="running")yield*y.updatePart({...O,state:{status:"completed",input:O.state.input,title:E.title,metadata:E.metadata,output:E.output,attachments:L,time:{...O.state.time,end:Date.now()}}});if(!E)yield*y.updatePart({...O,state:{status:"error",error:I?`Tool execution failed: ${I.message}`:"Tool execution failed",time:{start:O.state.status==="running"?O.state.time.start:Date.now(),end:Date.now()},metadata:O.state.status==="pending"?void 0:O.state.metadata,input:O.state.input}});if(!Z.command)return;let S={id:w2.ascending(),sessionID:J,role:"user",agentID:Y.agentID,time:{created:Date.now()},agent:Y.agent,model:Y.model};yield*y.updateMessage(S),yield*y.updatePart({id:Y2.ascending(),messageID:S.id,sessionID:J,type:"text",text:"Summarize the actor tool output above and continue with your task.",synthetic:!0})});var O1={};b2(O1,{decide:()=>jH,TaskGate:()=>O1,MAX_TASK_GATE_SUBAGENT_REACT:()=>n9,MAX_TASK_GATE_MAIN_REACT:()=>a9});var n9=2,a9=3,GH=($,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:",Y=Z==="subagent"?"Then re-emit your final message starting with the **Status**/**Summary** header.":"Then continue or respond.";return U2({source:"task-gate",trust:"local-policy",body:[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.",Y].join(`
|
|
422
|
-
`)})},jH=Q.fn("TaskGate.decide")(function*($){let Y=(yield*(yield*M0.Service).list({session_id:$.session_id,owner:$.owner,include_terminal:!1}).pipe(Q.orElseSucceed(()=>[]))).filter((J)=>J.status==="open"||J.status==="in_progress");if(Y.length===0)return{needReentry:!1,capExceeded:!1,incompleteTasks:[]};if($.reactCount>=$.maxReact)return{needReentry:!1,capExceeded:!0,incompleteTasks:Y.map((J)=>J.id)};return{needReentry:!0,capExceeded:!1,reentryText:GH(Y,$.mode),incompleteTasks:Y.map((J)=>J.id)}});function _Y($){return Q.fn("SessionPrompt.taskGate")(function*(Z){if(($.agentID??"main")!=="main")return!1;let X=yield*$.agents.get("main").pipe(Q.orElseSucceed(()=>{return}));if(X&&y2.disabled(["task"],X.permission).has("task"))return!1;if(Z.tools?.task===!1)return!1;let Y=yield*$.taskGateState.get($.sessionID),J=yield*O1.decide({session_id:$.sessionID,owner:void 0,reactCount:Y,maxReact:a9,mode:"main"}).pipe(Q.provideService(M0.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 OH=12;function RY($){return Q.fn("SessionPrompt.goalGate")(function*(Z){if(($.agentID??"main")!=="main")return!1;let X=yield*$.goal.get($.sessionID);if(!X)return!1;let Y=yield*o.filterCompactedEffect($.sessionID,{contextFrom:$.session.contextFrom,contextWatermark:$.session.contextWatermark,agentID:"main"}),J=Y.findLast((H)=>H.info.role==="assistant")?.info.id,B=yield*$.goal.evaluate({condition:X.condition,msgs:Y,model:Z.model}).pipe(Q.catchCause((H)=>Q.gen(function*(){if(W2.hasInterruptsOnly(H))return yield*Q.failCause(H);return yield*$.slog.warn("goal judge failed; allowing stop",{error:W2.pretty(H)}),{ok:!0,reason:"judge error",judgeFailed:!0}}))),W=0;switch(yield*$.goal.commitVerdict({sessionID:$.sessionID,expectedGeneration:X.generation,verdict:{...B,judgeFailed:"judgeFailed"in B?!0:void 0},judgedMessageID:J,maxReact:OH,reenter:(H,V)=>Q.gen(function*(){W=V,yield*$.appendSyntheticUserTurn({lastUser:Z,sessionID:$.sessionID,text:U2({source:"goal",trust:"local-policy",body:[`Your goal is not yet satisfied: "${H.condition}".`,"A judge reviewed the transcript and reported what is still missing:",B.reason,"Keep working toward the goal. Do not stop until it is genuinely met or impossible."].join(`
|
|
423
|
-
`)})})})})){case"stale":return yield*$.slog.info("goal changed during judge evaluation; discarding verdict",{sessionID:$.sessionID}),!1;case"satisfied":return yield*$.slog.info("goal satisfied; allowing stop",{sessionID:$.sessionID,impossible:B.impossible===!0}),!1;case"capped":return yield*$.slog.warn("goal hit MAX_GOAL_REACT cap; allowing stop",{sessionID:$.sessionID,condition:X.condition}),!1;case"reentered":return yield*$.slog.info("goal not satisfied; re-entering",{sessionID:$.sessionID,attempt:W,reason:B.reason.slice(0,300)}),!0}})}import FH from"path";var zH=a.create({service:"session.prompt.context"});function IY($){return Q.fn("SessionPrompt.ensureTitle")(function*(Z){if(Z.session.parentID)return;if(!SY(Z.session.title))return;let X=(D)=>D.info.role==="user"&&!D.parts.every((U)=>("synthetic"in U)&&U.synthetic),Y=Z.history.findIndex(X);if(Y===-1||Z.history.filter(X).length!==1)return;let J=Z.history.slice(0,Y+1),B=J[Y];if(!B||B.info.role!=="user")return;let W=B.info,G=B.parts.filter((D)=>D.type==="subtask"),H=G.length>0&&B.parts.every((D)=>D.type==="subtask");if(Z.providerID==="qlex"){let D=H?G.map((U)=>U.prompt).join(`
|
|
424
|
-
`):B.parts.map((U)=>{let P=U;return P.type==="text"&&!P.synthetic?String(P.text??""):""}).filter(Boolean).join(`
|
|
425
|
-
`).slice(0,4000);if(D){let U=yield*Q.promise(()=>Z0.resolveChatCompletion(`Generate a very short title (5 words or fewer) for this conversation. Reply with ONLY the title, no quotes or punctuation:
|
|
426
|
-
|
|
427
|
-
${D}`,{temperature:0.5,timeoutMs:1e4}).catch((P)=>{return zH.warn("chatCompletion title generation failed; falling through to llm.stream path",{error:P instanceof Error?P.message:String(P)}),null}));if(U?.content){let P=m8(U.content);if(P){let F=P.length>100?P.substring(0,97)+"...":P;yield*$.sessions.setTitle({sessionID:Z.session.id,title:F}).pipe(Q.catchCause((b)=>$.elog.error("failed to generate title",{error:W2.squash(b)})));return}}}}let V=yield*$.agents.get("title");if(!V)return;let K=V.modelRef?yield*$.provider.resolveModelRef(V.modelRef,Z.providerID):V.model?yield*$.provider.getModel(V.model.providerID,V.model.modelID):(yield*$.provider.getSmallModel(Z.providerID))??(yield*$.provider.getModel(Z.providerID,Z.modelID)),y=H?[{role:"user",content:G.map((D)=>D.prompt).join(`
|
|
428
|
-
`)}]:yield*o.toModelMessagesEffect(J,K),j=yield*$.llm.stream({agent:V,user:W,system:[],small:!0,tools:{},model:K,sessionID:Z.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
|
|
429
|
-
`},...y]}).pipe(J8((D)=>D.type==="text-delta"),Y8((D)=>D.text),B8,Q.orDie),q=m8(j);if(!q)return;let z=q.length>100?q.substring(0,97)+"...":q;yield*$.sessions.setTitle({sessionID:Z.session.id,title:z}).pipe(Q.catchCause((D)=>$.elog.error("failed to generate title",{error:W2.squash(D)})))})}function kY($){return Q.fn("SessionPrompt.insertReminders")(function*(Z){let X=Z.messages.findLast((H)=>H.info.role==="user");if(!X)return Z.messages;let Y=Z.messages.find((H)=>H.info.role==="user"&&H.info.agent==="compose");if(Y){let H=CY();Y.parts.unshift({id:Y2.ascending(),messageID:Y.info.id,sessionID:Y.info.sessionID,type:"text",text:U2({source:"mode",trust:"local-policy",posture:"workflow-compose",body:$.promptCompose+(H?`
|
|
430
|
-
|
|
431
|
-
`+H:"")}),synthetic:!0})}let J=Z.messages.findLast((H)=>H.info.role==="assistant");if(Z.agent.name!=="plan"&&J?.info.agent==="plan"){let H=s9(Z.session);if(!(yield*$.fsys.existsSafe(H)))return Z.messages;let V={id:Y2.ascending(),messageID:X.info.id,sessionID:X.info.sessionID,type:"text",text:U2({source:"mode",trust:"model-guidance",posture:"read-only-plan",body:`${$.buildSwitch}
|
|
432
|
-
|
|
433
|
-
The assistant previously authored a plan file at ${H}. It is being recalled as context only. Execute it only insofar as it is consistent with the user's newest message.`}),synthetic:!0};return X.parts.push(V),Z.messages}if(Z.agent.name!=="plan"||J?.info.agent==="plan")return Z.messages;let B=s9(Z.session),W=yield*$.fsys.existsSafe(B);if(!W)yield*$.fsys.ensureDir(FH.dirname(B)).pipe(Q.catch(Q.die));let G=yield*$.sessions.updatePart({id:Y2.ascending(),messageID:X.info.id,sessionID:X.info.sessionID,type:"text",text:U2({source:"mode",trust:"local-policy",posture:"read-only-plan",envelope:"system-reminder",body:`
|
|
434
|
-
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.
|
|
435
|
-
|
|
436
|
-
## Plan File Info:
|
|
437
|
-
${W?`A plan file already exists at ${B}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${B} using the write tool.`}
|
|
438
|
-
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.
|
|
439
|
-
|
|
440
|
-
## Plan Workflow
|
|
441
|
-
|
|
442
|
-
### Phase 1: Initial Understanding
|
|
443
|
-
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.
|
|
444
|
-
|
|
445
|
-
1. Focus on understanding the user's request and the code associated with their request
|
|
446
|
-
|
|
447
|
-
2. **Launch up to 3 explore agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
|
|
448
|
-
- 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.
|
|
449
|
-
- Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
|
|
450
|
-
- Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
|
|
451
|
-
- 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
|
|
452
|
-
|
|
453
|
-
3. After exploring the code, use the question tool to clarify ambiguities in the user request up front.
|
|
454
|
-
|
|
455
|
-
### Phase 2: Design
|
|
456
|
-
Goal: Design an implementation approach.
|
|
457
|
-
|
|
458
|
-
Launch general agent(s) to design the implementation based on the user's intent and your exploration results from Phase 1.
|
|
459
|
-
|
|
460
|
-
You can launch up to 1 agent(s) in parallel.
|
|
461
|
-
|
|
462
|
-
**Guidelines:**
|
|
463
|
-
- **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
|
|
464
|
-
- **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
|
|
465
|
-
|
|
466
|
-
Examples of when to use multiple agents:
|
|
467
|
-
- The task touches multiple parts of the codebase
|
|
468
|
-
- It's a large refactor or architectural change
|
|
469
|
-
- There are many edge cases to consider
|
|
470
|
-
- You'd benefit from exploring different approaches
|
|
471
|
-
|
|
472
|
-
Example perspectives by task type:
|
|
473
|
-
- New feature: simplicity vs performance vs maintainability
|
|
474
|
-
- Bug fix: root cause vs workaround vs prevention
|
|
475
|
-
- Refactoring: minimal change vs clean architecture
|
|
476
|
-
|
|
477
|
-
In the agent prompt:
|
|
478
|
-
- Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
|
|
479
|
-
- Describe requirements and constraints
|
|
480
|
-
- Request a detailed implementation plan
|
|
481
|
-
|
|
482
|
-
### Phase 3: Review
|
|
483
|
-
Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
|
|
484
|
-
1. Read the critical files identified by agents to deepen your understanding
|
|
485
|
-
2. Ensure that the plans align with the user's original request
|
|
486
|
-
3. Use question tool to clarify any remaining questions with the user
|
|
487
|
-
|
|
488
|
-
### Phase 4: Final Plan
|
|
489
|
-
Goal: Write your final plan to the plan file (the only file you can edit).
|
|
490
|
-
- Include only your recommended approach, not all alternatives
|
|
491
|
-
- Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
|
|
492
|
-
- Include the paths of critical files to be modified
|
|
493
|
-
- Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
|
|
494
|
-
|
|
495
|
-
### Phase 5: Call plan_exit tool
|
|
496
|
-
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.
|
|
497
|
-
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.
|
|
498
|
-
|
|
499
|
-
**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.
|
|
500
|
-
|
|
501
|
-
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.
|
|
502
|
-
`.trim()}),synthetic:!0});return X.parts.push(G),Z.messages})}var TY=5,a4=3,r9=2;function hY($){return $.trim().toLowerCase().replace(/\s+/g," ").replace(/^(let me |i'll |i will |let's )/i,"").slice(0,200)}function gY($,Z){if(Z<=0||$.length<Z)return!1;let X=$.slice(-Z);return X.every((Y)=>Y===X[0])}var EY=U2({source:"recovery",trust:"runtime-safety",body:`
|
|
503
|
-
LOOP DETECTED: Your last several outputs were identical. You are stuck in a repetitive pattern.
|
|
504
|
-
|
|
505
|
-
STOP what you are doing and take a DIFFERENT approach:
|
|
506
|
-
- If you were about to call a tool, try a different tool or different arguments
|
|
507
|
-
- If you were planning an action, reconsider and pick an alternative strategy
|
|
508
|
-
- If you are blocked, explain what's blocking you and ask the user for help
|
|
509
|
-
|
|
510
|
-
Do NOT repeat the same text or action again.
|
|
511
|
-
`}),fY=U2({source:"recovery",trust:"runtime-safety",body:`
|
|
512
|
-
CRITICAL: You are STILL stuck in a loop after a previous recovery attempt.
|
|
513
|
-
|
|
514
|
-
Your previous approach has failed repeatedly. You MUST:
|
|
515
|
-
1. Abandon your current plan entirely
|
|
516
|
-
2. State what you were trying to do and why it failed
|
|
517
|
-
3. Ask the user for guidance on how to proceed
|
|
518
|
-
|
|
519
|
-
If you repeat the same output again, the session will be terminated.
|
|
520
|
-
`});var t9=($)=>Q.fnUntraced(function*(Z){let X=yield*$.updateMessage({id:w2.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,outputBudgetRecoveryTokens:Z.outputBudgetRecoveryTokens,time:{created:Date.now()}});return yield*$.updatePart({id:Y2.ascending(),messageID:X.id,sessionID:X.sessionID,type:"text",synthetic:!0,text:Z.text}),X});function vY(){return U2({source:"recovery",trust:"runtime-safety",body:["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."].join(`
|
|
521
|
-
`)})}function dY(){return U2({source:"recovery",trust:"runtime-safety",body:["The previous assistant response was cut off by a transient stream failure.","Continue the same task from the exact point where the already-visible response stopped.","Do not restart, recap, or repeat text that is already in the conversation.","Finish the answer directly and keep the continuation concise."].join(`
|
|
522
|
-
`)})}function mY(){return U2({source:"recovery",trust:"runtime-safety",body:["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."].join(`
|
|
523
|
-
`)})}function lY(){return U2({source:"recovery",trust:"runtime-safety",body:["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."].join(`
|
|
524
|
-
`)})}function cY($){return $===0?g5:M7}function uY($){return $===0?EY:fY}var yH=L0.QITQODE_OUTPUT_LENGTH_CONTINUATION_LIMIT,DH=L0.QITQODE_INVALID_OUTPUT_CONTINUATION_LIMIT,qH=1,PH=1;function oY($){let Z=0,X=0,Y=0,J=0,B=0,W=0,G=Q.fnUntraced(function*(P){yield*$.sessions.updateMessage(P),yield*$.bus.publish(A2.Error,{sessionID:P.sessionID,error:P.error})}),H=Q.fnUntraced(function*(P,F){let b=D8.copy().streamCutOff({textKept:!0,continued:!0});if(F.data.message===b)return;P.error={...F,data:{...F.data,message:b}},yield*G(P)}),V=Q.fn("SessionPrompt.autoContinueOutputLength")(function*(P){if(P.assistant.finish!=="length"||P.assistant.error||P.assistant.summary)return!1;if(o.parts(P.assistant.id).some((F)=>F.type==="tool"&&!F.metadata?.providerExecuted))return!1;if(Z>=yH)return P.assistant.error=new o.OutputLengthError({}).toObject(),yield*G(P.assistant),!1;return Z++,yield*$.slog.info("auto-continuing output length",{attempt:Z}),yield*$.appendSyntheticUserTurn({lastUser:P.lastUser,sessionID:P.lastUser.sessionID,text:vY()}),!0}),K=Q.fn("SessionPrompt.autoContinueInvalidOutput")(function*(P){if(P.assistant.error||P.assistant.summary||P.assistant.structured!==void 0)return!1;if(X>=DH)return P.assistant.error=new o.InvalidOutputError({message:P.reason}).toObject(),yield*G(P.assistant),!1;return X++,yield*$.slog.info("auto-continuing invalid output",{attempt:X,reason:P.reason}),yield*$.appendSyntheticUserTurn({lastUser:P.lastUser,sessionID:P.lastUser.sessionID,text:mY()}),!0}),y=Q.fn("SessionPrompt.autoRecoverOutputBudget")(function*(P){let F=P.assistant.error;if(!F||!o.APIError.isInstance(F))return!1;if(F.data.category!=="output_budget_exhausted"&&F.data.category!=="empty_output")return!1;if(!F.data.outputBudgetRecoveryAvailable||!F.data.outputBudgetRecoveryTokens||B>=qH)return!1;return B++,yield*$.slog.info("retrying output-budget-starved turn with headroom",{attempt:B}),yield*$.appendSyntheticUserTurn({lastUser:P.lastUser,sessionID:P.lastUser.sessionID,outputBudgetRecoveryTokens:F.data.outputBudgetRecoveryTokens,text:F.data.category==="empty_output"?"The previous attempt produced no visible answer. Please answer the original request directly with visible text.":"The previous attempt ran out of output room. Please answer the original request directly and concisely."}),!0}),j=Q.fn("SessionPrompt.autoContinueStreamCutoff")(function*(P){let F=P.assistant.error;if(!F||!o.APIError.isInstance(F))return!1;if(F.data.category!=="stream_truncated"&&F.data.category!=="stream_failed")return!1;if(!o.parts(P.assistant.id).some((O)=>O.type==="text"&&!O.synthetic&&!O.ignored&&O.text.trim().length>0))return!1;if(W>=PH)return!1;return W++,yield*$.slog.info("continuing cut-off stream",{attempt:W}),yield*$.appendSyntheticUserTurn({lastUser:P.lastUser,sessionID:P.lastUser.sessionID,text:dY()}),yield*H(P.assistant,F),!0}),q=Q.fn("SessionPrompt.autoRetryStructuredOutput")(function*(P){if(P.assistant.error||P.assistant.summary||P.assistant.structured!==void 0)return!1;let F=P.lastUser.format?.type==="json_schema"?P.lastUser.format.retryCount:0;if(Y>=F)return P.assistant.error=new o.StructuredOutputError({message:"Model did not produce structured output",retries:Y}).toObject(),yield*G(P.assistant),!1;return Y++,yield*$.slog.info("retrying structured output",{attempt:Y}),yield*$.appendSyntheticUserTurn({lastUser:P.lastUser,sessionID:P.lastUser.sessionID,text:lY()}),!0}),z=Q.fn("SessionPrompt.handleTextRepeat")(function*(P){if(J>=b7)return yield*$.slog.info("text n-gram: max recovery exceeded, terminating"),yield*$.bus.publish(A2.Error,{sessionID:$.sessionID,error:new x2.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:P.lastUser,sessionID:$.sessionID,text:cY(J)}),J++,yield*$.slog.info("text n-gram: recovery injected",{attempt:J}),!0}),D=Q.fn("SessionPrompt.writeContentFilterError")(function*(P){if(P.assistant.error)return;P.assistant.error=new o.ContentFilterError({message:"The response was withheld by the model provider's content safety filter."}).toObject(),yield*G(P.assistant)}),U=Q.fn("SessionPrompt.writeModelError")(function*(P){if(P.assistant.error)return;P.assistant.error=new o.ModelError({message:P.reason}).toObject(),yield*G(P.assistant)});return{autoContinueOutputLength:V,autoRecoverOutputBudget:y,autoContinueStreamCutoff:j,autoContinueInvalidOutput:K,autoRetryStructuredOutput:q,handleTextRepeat:z,writeContentFilterError:D,writeModelError:U}}function pY($){let Z=[],X=0;return{check:Q.fnUntraced(function*(J){let B=J.completedParts.filter((K)=>K.type==="text"&&!K.synthetic).map((K)=>K.text).join(" ");if(!B.trim())return"none";let W=J.completedParts.filter((K)=>K.type==="tool").map((K)=>`${K.tool}:${JSON.stringify(K.state&&"input"in K.state?K.state.input:"")}`).join("|"),G=hY(B)+(W?`\x00${W}`:"");if(Z.push(G),Z.length>TY)Z.shift();if(Z.length<a4)return"none";if(!gY(Z,a4))return"none";if(X>=r9)return yield*$.slog.info("text loop: max recovery exceeded, terminating"),yield*$.bus.publish(A2.Error,{sessionID:$.sessionID,error:new x2.Unknown({message:`Text loop detected: model repeated the same output ${a4} times after ${r9} recovery attempts. Session terminated.`}).toObject()}),"terminate";let V=uY(X);return yield*$.appendSyntheticUserTurn({lastUser:J.lastUser,sessionID:$.sessionID,text:V}),X++,Z.length=0,yield*$.slog.info("text loop: recovery injected",{attempt:X}),"recovered"})}}import NH from"path";function l8($){let Z=e9($,"task")==="shell"?"- task list":'- task({ operation: "list" })',X=e9($,"actor")==="shell"?"- actor status <actor_id>":'- actor({ operation: "status", actor_id: "<id>" })';return['- memory({ operation: "search", query: "<keyword>" })',Z,X]}function W8($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return"["+$.map(W8).join(",")+"]";return"{"+Object.keys($).sort().map((X)=>JSON.stringify(X)+":"+W8($[X])).join(",")+"}"}function c8($){let Z=[];for(let X of $)if(X.type==="tool")Z.push("tool:"+X.tool+":"+W8(X.state.input??{}));if(Z.length===0)return;return Z.join(`
|
|
525
|
-
`)}var $Z=3,iY=Q.fnUntraced(function*($){let Z=$.msgs.findLast((B)=>B.info.role==="user");if(!Z)return;if(!(yield*$.checkpoint.hasMemoryOrTasks($.sessionID).pipe(Q.catch(()=>Q.succeed(!1)))))return;if(Z.parts.some((B)=>B.type==="text"&&B.synthetic&&B.text.includes("This session has memory at")))return;let Y=NH.join(w$.Path.data,"memory","sessions",$.sessionID),J=l8((yield*$.config.get()).tool);Z.parts.push({id:Y2.ascending(),messageID:Z.info.id,sessionID:$.sessionID,type:"text",synthetic:!0,text:U2({source:"memory",trust:"model-guidance",body:[`This session has memory at ${Y}/. Recall content`,"not in your context with:",J[0],`- Read(file_path="${Y}/...")`,J[1],J[2],"","Don't ask the user about something memory may already record."].join(`
|
|
526
|
-
`)})})}),nY=Q.fnUntraced(function*($){let{lastFinished:Z,model:X}=$;if(!Z||Z.summary===!0||!X)return;let Y=yield*$.config.get(),J=k6({cfg:Y,tokens:Z.tokens,model:X});if(J<2)return;let B=$.msgs.findLast((W)=>W.info.role==="user");if(!B||B.parts.some((W)=>W.type==="text"&&W.text?.includes("Context is filling up")))return;B.parts.push({id:Y2.ascending(),messageID:B.info.id,sessionID:$.sessionID,type:"text",synthetic:!0,text:U2({source:"memory",trust:"runtime-safety",body:[`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."].join(`
|
|
527
|
-
`)})})});function aY($){if(!$.lastFinished)return;let Z=[];for(let J=$.msgs.length-1;J>=0&&Z.length<$Z;J--){let B=$.msgs[J];if(B.info.role!=="assistant"||!B.info.finish)continue;let W=c8(B.parts);if(W===void 0)break;Z.push(W)}if(!(Z.length===$Z&&Z.every((J)=>J===Z[0])))return;let Y=$.msgs.findLast((J)=>J.info.role==="user");if(!Y||Y.parts.some((J)=>J.type==="text"&&J.text?.includes("repeating the same action")))return;Y.parts.push({id:Y2.ascending(),messageID:Y.info.id,sessionID:$.sessionID,type:"text",synthetic:!0,text:U2({source:"recovery",trust:"runtime-safety",body:[`Your last ${$Z} 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."].join(`
|
|
528
|
-
`)})})}var ZZ=a.create({service:"auto-dream"}),XZ=86400000,wH=7,xH=30,$J=1e4,QZ="Auto Dream",YZ="Auto Distill",sY=0,rY=0,ZJ=["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(`
|
|
529
|
-
`),XJ=["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(`
|
|
530
|
-
`);function QJ($){return Q.gen(function*(){if(!$.enabled)return!1;let Z=$.intervalDays*XZ,X=yield*Q.sync(()=>t2.use((B)=>B.select({time_created:T0.time_created}).from(T0).where(j0(T0.title,$.title)).orderBy(u8(T0.time_created)).limit(1).get())),Y=Date.now(),J=X?Y-X.time_created:1/0;if(!X){let B=yield*Q.sync(()=>t2.use((W)=>W.select({time_created:T0.time_created}).from(T0).where(tY(T0.parent_id)).orderBy(eY(T0.time_created)).limit(1).get()));if(!B||Y-B.time_created<Z)return ZZ.info(`auto-${$.label} skipped \u2014 project too young`,{projectAge:B?Math.round((Y-B.time_created)/XZ)+"d":"empty",interval:$.intervalDays+"d"}),!1}if(J<Z)return ZZ.info(`auto-${$.label} skipped \u2014 last run too recent`,{lastRunAgo:Math.round(J/XZ)+"d",interval:$.intervalDays+"d"}),!1;return ZZ.info(`auto-${$.label} triggering`,{lastRun:X?new Date(X.time_created).toISOString():"never",interval:$.intervalDays+"d"}),!0})}function YJ($){let Z=$.dream?.auto!==!1;if(!Z)return Q.succeed(!1);let X=Date.now();if(X-sY<$J)return Q.succeed(!1);sY=X;let Y=$.dream?.interval_days??wH;return QJ({enabled:Z,intervalDays:Y,title:QZ,label:"dream"})}function JJ($){let Z=$.distill?.auto!==!1;if(!Z)return Q.succeed(!1);let X=Date.now();if(X-rY<$J)return Q.succeed(!1);rY=X;let Y=$.distill?.interval_days??xH;return QJ({enabled:Z,intervalDays:Y,title:YZ,label:"distill"})}var BJ=Q.fnUntraced(function*($){let Z=yield*$.config.get(),X=yield*YJ(Z).pipe(Q.catch(()=>Q.succeed(!1))),Y=yield*JJ(Z).pipe(Q.catch(()=>Q.succeed(!1))),J={providerID:$.lastUser.model.providerID,modelID:$.lastUser.model.modelID};if(!X&&!Y)return;let{AppRuntime:B}=yield*Q.promise(()=>import("./chunk-2517cev8.js"));if(X)B.runPromise(v2.use((W)=>Q.gen(function*(){let G=yield*W.create({title:QZ});yield*(yield*$.promptServiceTag).prompt({sessionID:G.id,agent:"dream",model:J,parts:[{type:"text",text:ZJ}]})}))).catch((W)=>$.log.error("auto-dream prompt failed",{error:String(W)}));if(Y)B.runPromise(v2.use((W)=>Q.gen(function*(){let G=yield*W.create({title:YZ});yield*(yield*$.promptServiceTag).prompt({sessionID:G.id,agent:"distill",model:J,parts:[{type:"text",text:XJ}]})}))).catch((W)=>$.log.error("auto-distill prompt failed",{error:String(W)}))});var bH=($)=>$.pipe(Q.catchDefect((Z)=>Z instanceof Z0.BackendAuthRejectedError?Q.succeed(void 0):Q.die(Z))),JZ=($)=>bH(Q.promise(()=>Z0.resolvePrompt($))).pipe(Q.map((Z)=>Z??"")),WJ=Q.gen(function*(){let $=yield*JZ("session/build-switch"),Z=yield*JZ("session/max-steps"),X=yield*JZ("session/compose");return{buildSwitch:$,maxSteps:Z,promptCompose:X}});var VJ=d0.create({service:"session.prompt"}),UH=a.create({service:"session.prompt"});function KJ($,Z,X,Y){return Q.gen(function*(){let{bus:J,status:B,sessions:W,agents:G,provider:H,processor:V,prune:K,checkpoint:y,compaction:j,config:q,plugin:z,permission:D,fsys:U,registry:P,scope:F,instruction:b,state:O,goal:M,taskGateState:I,taskRegistry:k,revert:E,summary:L,sys:S,llm:T,actorRegistry:w,inbox:A}=yield*d4,R=yield*WJ,C=R.buildSwitch,g=R.maxSteps,l=R.promptCompose,m=(t,N2,j2)=>UY(H,J,t,N2,j2),h=(t,N2)=>MY(W,t,N2),f=t9(W),v=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)=>i9({getOps:$,...t}),s=IY({agents:G,provider:H,llm:T,sessions:W,elog:VJ}),G2=kY({sessions:W,fsys:U,buildSwitch:C,promptCompose:l});return{runLoop:Q.fn("SessionPrompt.run")(function*(t,N2,j2){let g0=yield*d.context,I2=VJ.with({sessionID:t}),Q2,q2=0,L2=yield*W.get(t),e2,w0,E0=new Map,R0=N2??"main",f0=xY({sessionID:t,agentID:R0,task_id:j2,plugin:z,bus:J,prune:K,scope:F}),{cancellation:O$,agentMetrics:a0,publishAgentRequest:s0,schedulePrune:N1}=f0,F$=wY({sessionID:t,agentID:R0,task_id:j2,session:L2,cancellation:O$,plugin:z});return yield*Q.gen(function*(){yield*f0.before;let w1=($0,X2)=>c4(ZY($0,X2,o.parts(X2.id))),R$=!1,v0=pY({sessionID:t,bus:J,appendSyntheticUserTurn:f,slog:I2}),J6=oY({sessionID:t,sessions:W,bus:J,appendSyntheticUserTurn:f,slog:I2}),{autoContinueOutputLength:CZ,autoRecoverOutputBudget:IZ,autoContinueStreamCutoff:kZ,autoContinueInvalidOutput:SZ,autoRetryStructuredOutput:QW,handleTextRepeat:YW,writeContentFilterError:TZ,writeModelError:y7}=J6,hZ=_Y({sessionID:t,agentID:N2,agents:G,taskGateState:I,taskRegistry:k,appendSyntheticUserTurn:f,slog:I2}),gZ=RY({sessionID:t,agentID:N2,session:L2,goal:M,bus:J,appendSyntheticUserTurn:f,slog:I2});while(!0){if(!N2||N2==="main")yield*B.set(t,{type:"busy"});yield*A.drain(t,N2??"main").pipe(Q.ignore),yield*I2.info("loop",{step:q2});let $0=yield*o.filterCompactedEffect(t,{contextFrom:L2.contextFrom,contextWatermark:L2.contextWatermark,agentID:N2??"main"}),X2,fZ,C0,D7,x0,vZ=[];for(let K2=$0.length-1;K2>=0;K2--){let H0=$0[K2];if(!X2&&H0.info.role==="user")X2=H0.info,fZ=H0;if(!C0&&H0.info.role==="assistant")C0=H0.info,D7=H0;if(!x0&&H0.info.role==="assistant"&&H0.info.finish)x0=H0.info;if(X2&&x0)break;if(!x0){let W6=H0.parts.filter((r$)=>r$.type==="subtask");vZ.push(...W6)}}if(!X2)throw Error("No user message found in stream. This should never happen.");yield*iY({sessionID:t,msgs:$0,checkpoint:y,config:q});let WW=D7?.parts.some((K2)=>K2.type==="tool"&&!K2.metadata?.providerExecuted)??!1;if(C0?.finish==="length"&&!WW&&X2.id<C0.id&&(yield*CZ({lastUser:X2,assistant:C0})))continue;if(C0){if(yield*IZ({lastUser:X2,assistant:C0}))continue;if(yield*kZ({lastUser:X2,assistant:C0}))continue;let K2=c9({phase:"existing-assistant",lastUser:X2,assistant:C0,parts:D7?.parts??[]});if(K2.type==="filtered"){yield*TZ({assistant:C0}),yield*I2.info("exiting loop",{classification:K2.type});break}if(K2.type==="failed"){yield*y7({assistant:C0,reason:K2.reason}),yield*I2.info("exiting loop",{classification:K2.type,reason:K2.reason});break}if(K2.type==="think-only"||K2.type==="invalid"){let H0=K2.type==="invalid"?K2.reason:"think-only";if(yield*SZ({lastUser:X2,assistant:C0,reason:H0}))continue;yield*I2.info("exiting loop",{classification:K2.type});break}if(K2.type==="final"&&K2.degraded)yield*I2.warn("degraded final on abnormal finish",{finish:C0.finish});if(K2.type!=="continue"){if(yield*hZ(X2))continue;if(yield*gZ(X2))continue;yield*I2.info("exiting loop",{classification:K2.type});break}}if(q2++,q2===1)yield*s({session:L2,modelID:X2.model.modelID,providerID:X2.model.providerID,history:$0}).pipe(Q.ignore,Q.forkIn(F));if(q2===1&&!L2.parentID)yield*BJ({config:q,lastUser:X2,promptServiceTag:Y,log:UH});let r0=yield*m(X2.model.providerID,X2.model.modelID,t);w0=r0,e2=x0;let dZ=vZ.pop();if(dZ?.type==="subtask"){yield*n({task:dZ,model:r0,lastUser:X2,sessionID:t,session:L2,msgs:$0});continue}let mZ=fZ;if(mZ?.parts.some((K2)=>K2.type==="compaction")){let K2=mZ.parts.find((r$)=>r$.type==="compaction"),H0=yield*W.messages({sessionID:t,agentID:X2.agentID??"main"});if((yield*j.process({parentID:X2.id,messages:H0,sessionID:t,auto:K2?.auto??!1,overflow:K2?.overflow,agentID:X2.agentID}))==="stop")break;continue}yield*nY({sessionID:t,msgs:$0,lastFinished:x0,model:r0,config:q}),aY({sessionID:t,msgs:$0,lastFinished:x0});let C$=yield*G.get(X2.agent),q7=C$?.native===!0&&C$?.hidden===!0;if(!R$&&!q7&&x0&&x0.tokens){let K2=yield*$();yield*K.fireCheckpoints({sessionID:t,model:r0,tokens:x0.tokens,promptOps:K2,agentID:X2.agentID}).pipe(Q.ignore)}if(!R$&&x0&&x0.tokens){if(yield*PY({config:q,checkpoint:y,compaction:j,prune:K},{sessionID:t,lastFinished:x0,lastUser:X2,model:r0,msgs:$0,isBoundedComputation:q7})){R$=!0;continue}}if(R$=!1,!C$)throw yield*u9(G,J,X2.agent,t);let VW=C$.steps??1/0,KW=q2>=VW;$0=yield*G2({messages:$0,agent:C$,session:L2});let lZ=p4({sessionID:t,parentID:X2.id,agentID:X2.agentID,agent:C$.name,variant:X2.model.variant,cwd:g0.directory,root:g0.worktree,modelID:r0.id,providerID:r0.providerID});yield*W.updateMessage(lZ);let m2=yield*V.create({assistantMessage:lZ,sessionID:t,model:r0,agentMetrics:a0}),HW=yield*Q.gen(function*(){let K2={value:Q2},H0=yield*XY({sessionID:t,resolvedAgentID:R0,step:q2,task_id:j2,lastUser:X2,lastFinished:x0,msgs:$0,agent:C$,session:L2,model:r0,handle:m2,structured:K2,resolveTools:Z,createStructuredOutputTool:X,summary:L,scope:F,plugin:z}),{tools:W6,format:r$,query:GW}=H0,{cancelledByPlugin:jW,withUserQueryPost:OW}=QY({sessionID:t,agentID:R0,step:q2,lastUser:X2,msgs:$0,query:GW,handle:m2,plugin:z,sessions:W,cancellation:O$,trajectoryForStep:w1}),FW=Q.fnUntraced(function*(V6){if(V6==="continue"&&(yield*CZ({lastUser:X2,assistant:m2.message})))return"continue";if(V6==="text-repeat"){if(yield*YW({lastUser:X2}))return"continue";return"break"}if(K2.value!==void 0)return Q2=K2.value,m2.message.structured=K2.value,m2.message.finish=m2.message.finish??"stop",yield*W.updateMessage(m2.message),"break";let W$=c9({phase:"after-process",lastUser:X2,assistant:m2.message,parts:o.parts(m2.message.id),processResult:V6});if(W$.type==="filtered")return yield*TZ({assistant:m2.message}),"break";if(W$.type==="failed"){if(yield*IZ({lastUser:X2,assistant:m2.message}))return"continue";if(yield*kZ({lastUser:X2,assistant:m2.message}))return"continue";return yield*y7({assistant:m2.message,reason:W$.reason}),"break"}if(W$.type!=="continue"&&!m2.message.error&&r$.type==="json_schema"){if(yield*QW({lastUser:X2,assistant:m2.message}))return"continue";return"break"}if((W$.type==="think-only"||W$.type==="invalid")&&r$.type!=="json_schema"){let zW=W$.type==="invalid"?W$.reason:"think-only";if(yield*SZ({lastUser:X2,assistant:m2.message,reason:zW}))return"continue";return"break"}if(W$.type==="final"&&W$.degraded)yield*I2.warn("degraded final on abnormal finish",{finish:m2.message.finish});if(V6==="stop")return"break";return}),z8=yield*yY({sessionID:t,lastUser:X2,agent:C$,session:L2,model:r0,msgs:$0,tools:W6,format:r$,handle:m2,isLastStep:KW,task_id:j2,instructionsNotified:e,maxStepsText:g,actorRegistry:w,bus:J,config:q,instruction:b,llm:T,provider:H,registry:P,status:B,sys:S,cancelledByPlugin:jW,withUserQueryPost:OW,slog:I2,visionAnalysis:E0});if(z8.kind==="break"){if(z8.reason==="vision-unavailable")yield*y7({assistant:m2.message,reason:z8.message});return"break"}let uZ=yield*FW(z8.result);if(uZ)return uZ;if(z8.result==="overflow")yield*NY({config:q,checkpoint:y,compaction:j,prune:K},{sessionID:t,lastUser:X2,model:r0,msgs:$0,isBoundedComputation:q7});return"continue"}).pipe(Q.ensuring(b.clear(m2.message.id))),cZ=yield*v0.check({lastUser:X2,completedParts:o.parts(m2.message.id)});if(cZ==="terminate")break;if(cZ==="recovered")continue;if(HW==="break"){if(yield*hZ(X2))continue;if(yield*gZ(X2))continue;break}continue}let JW=yield*$();if(w0&&e2)yield*N1({model:w0,lastFinished:e2,promptOps:JW});let B6=yield*h(t,N2),BW=B6.info.role==="assistant"&&!!B6.info.error,EZ=yield*W.findMessage(t,($0)=>$0.info.role==="user",{agentID:"*"});return yield*s0(BW?"error":"completed",Y0.isSome(EZ)?EZ.value.info.agent:B6.info.agent),B6}).pipe((w1)=>o9(t,J,w1),Q.onExit(F$),Q.orDie)}),lastAssistant:h}})}import HJ from"path";var AH=new TextEncoder,BZ=new TextDecoder,MH=($)=>`
|
|
531
|
-
|
|
532
|
-
[... QitQode truncated ${$} bytes of shell output ...]
|
|
533
|
-
|
|
534
|
-
`;class WZ{head=new Uint8Array(262144);tail=new Uint8Array(786432);headBytes=0;tailBytes=0;tailStart=0;seenBytes=0;append($){let Z=AH.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 Y=Z.subarray(X);if(Y.byteLength>=this.tail.byteLength){this.tail.set(Y.subarray(Y.byteLength-this.tail.byteLength)),this.tailBytes=this.tail.byteLength,this.tailStart=0;return}let J=Math.max(0,this.tailBytes+Y.byteLength-this.tail.byteLength);this.tailStart=(this.tailStart+J)%this.tail.byteLength,this.tailBytes=Math.min(this.tail.byteLength,this.tailBytes+Y.byteLength);let B=(this.tailStart+this.tailBytes-Y.byteLength)%this.tail.byteLength,W=Math.min(Y.byteLength,this.tail.byteLength-B);if(this.tail.set(Y.subarray(0,W),B),W<Y.byteLength)this.tail.set(Y.subarray(W),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 BZ.decode($);let X=BZ.decode($.subarray(0,this.headBytes)),Y=BZ.decode($.subarray(this.headBytes));return X+MH(this.seenBytes-this.retainedBytes)+Y}}var _H=50,RH=32768;function GJ($){return Q.gen(function*(){let Z=yield*v2,X=yield*$$.Service,Y=yield*E2.Service,J=yield*z2.Service,B=yield*p.Service,W=yield*H2.Service,G=yield*s1.ChildProcessSpawner;return Q.fn("SessionPrompt.shellImpl")(function*(H){let V=yield*d.context,K=yield*Z.get(H.sessionID);if(K.revert)yield*X.cleanup(K);let y=yield*l$(Y,B,H.agent,H.sessionID),j=yield*X8(J,H.modelRef,H.model),q=yield*X8(J,y.modelRef,y.model),z=j??q??(yield*$(H.sessionID)),D={id:H.messageID??w2.ascending(),sessionID:H.sessionID,time:{created:Date.now()},role:"user",agent:H.agent,model:{providerID:z.providerID,modelID:z.modelID}};yield*Z.updateMessage(D);let U={type:"text",id:Y2.ascending(),messageID:D.id,sessionID:H.sessionID,text:"The following tool was executed by the user",synthetic:!0};yield*Z.updatePart(U);let P={id:w2.ascending(),sessionID:H.sessionID,parentID:D.id,agentID:D.agentID,mode:H.agent,agent:H.agent,cost:0,path:{cwd:V.directory,root:V.worktree},time:{created:Date.now()},role:"assistant",tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:z.modelID,providerID:z.providerID};yield*Z.updateMessage(P);let F={type:"tool",id:Y2.ascending(),messageID:P.id,sessionID:H.sessionID,tool:"bash",callID:$8(),state:{status:"running",time:{start:Date.now()},input:{command:H.command}}};yield*Z.updatePart(F);let b=new WZ,O=!1,M=0,I=0,k=()=>({output:b.toString(),description:"",truncated:b.truncated,totalBytes:b.totalBytes}),E=Q.uninterruptible(Q.gen(function*(){if(O)b.append(`
|
|
535
|
-
|
|
536
|
-
`+["<metadata>","User aborted the command","</metadata>"].join(`
|
|
537
|
-
`));if(!P.time.completed)P.time.completed=Date.now(),yield*Z.updateMessage(P);if(F.state.status==="running"){let S=k();F.state={status:"completed",time:{...F.state.time,end:Date.now()},input:F.state.input,title:"",metadata:S,output:S.output},yield*Z.updatePart(F)}})),L=yield*Q.gen(function*(){let S=F1.preferred(),T=(process.platform==="win32"?HJ.win32.basename(S,".exe"):HJ.basename(S)).toLowerCase(),w={nu:{args:["-c",H.command]},fish:{args:["-c",H.command]},zsh:{args:["-l","-c",`
|
|
538
|
-
__oc_cwd=$PWD
|
|
539
|
-
[[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
|
|
540
|
-
[[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
|
|
541
|
-
cd "$__oc_cwd"
|
|
542
|
-
eval ${JSON.stringify(H.command)}
|
|
543
|
-
`]},bash:{args:["-l","-c",`
|
|
544
|
-
__oc_cwd=$PWD
|
|
545
|
-
shopt -s expand_aliases
|
|
546
|
-
[[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
|
|
547
|
-
cd "$__oc_cwd"
|
|
548
|
-
eval ${JSON.stringify(H.command)}
|
|
549
|
-
`]},cmd:{args:["/c",H.command]},powershell:{args:["-NoProfile","-Command",H.command]},pwsh:{args:["-NoProfile","-Command",H.command]},"":{args:["-c",H.command]}},A=(w[T]??w[""]).args,R=V.directory,C=yield*W.trigger("shell.env",{cwd:R,sessionID:H.sessionID,callID:F.callID},{env:{}}),g=r1.make(S,A,{cwd:R,extendEnv:!0,env:{...C.env,TERM:"dumb"},stdin:"ignore",forceKillAfter:"3 seconds"}),l=yield*G.spawn(g);yield*c2.runForEach(c2.decodeText(l.all),(m)=>Q.suspend(()=>{if(b.append(m),F.state.status!=="running")return Q.void;let h=Date.now();if(h-M<_H&&b.totalBytes-I<RH)return Q.void;return F.state.metadata=k(),M=h,I=b.totalBytes,Z.updatePart(F).pipe(Q.ignore)})),yield*l.exitCode}).pipe(Q.scoped,Q.onInterrupt(()=>Q.sync(()=>{O=!0})),Q.orDie,Q.ensuring(E),Q.exit);if(i2.isFailure(L)&&!W2.hasInterruptsOnly(L.cause))return yield*Q.failCause(L.cause);return{info:P,parts:[F]}})})}import OJ from"path";import CH from"os";import{pathToFileURL as IH,fileURLToPath as kH}from"url";function jJ($){let Z=$.indexOf(",");if(Z===-1)return"";let X=$.slice(0,Z),Y=$.slice(Z+1);if(X.includes(";base64"))return Buffer.from(Y,"base64").toString("utf8");return decodeURIComponent(Y)}var z1=a.create({service:"session.prompt"}),FJ=d0.create({service:"session.prompt"}),SH=393216;function zJ(){return Q.gen(function*(){let $=yield*v2,Z=yield*E2.Service,X=yield*z2.Service,Y=yield*p.Service,J=yield*H2.Service,B=yield*N0.Service,W=Q.fnUntraced(function*(z){let D=yield*$.findMessage(z,(U)=>U.info.role==="user"&&!!U.info.model,{agentID:"*"});if(Y0.isSome(D)&&D.value.info.role==="user")return D.value.info.model;return yield*X.defaultModel()}),G=yield*J$.Service,H=yield*s2.Service,V=yield*K0.Service,K=yield*G$.Service,y=Q.fn("SessionPrompt.resolvePromptParts")(function*(z){let D=yield*d.context,U=[{type:"text",text:z}],P=s4.files(z),F=new Set;return yield*Q.forEach(P,Q.fnUntraced(function*(b){let O=b[1];if(F.has(O))return;F.add(O);let M=O.startsWith("~/")?OJ.join(CH.homedir(),O.slice(2)):OJ.resolve(D.worktree,O),I=yield*H.stat(M).pipe(Q.option);if(Y0.isNone(I)){let E=yield*Z.get(O);if(E)U.push({type:"agent",name:E.name});return}let k=I.value;U.push({type:"file",url:IH(M).href,filename:O,mime:k.type==="Directory"?"application/x-directory":"text/plain"})}),{concurrency:16,discard:!0}),U}),j=Q.fn("SessionPrompt.createUserMessage")(function*(z){let D=z.agent||(yield*Z.defaultAgent()),U=yield*l$(Z,Y,D,z.sessionID),P=yield*X8(X,z.modelRef,z.model),F=yield*X8(X,U.modelRef,U.model),b=P??F??(yield*W(z.sessionID)),O=F&&b.providerID===F.providerID&&b.modelID===F.modelID,M=!z.variant&&U.variant&&O?yield*X.getModel(b.providerID,b.modelID).pipe(Q.catchDefect(()=>Q.void)):void 0,I=z.variant??(U.variant&&M?.variants?.[U.variant]?U.variant:void 0),k={id:z.messageID??w2.ascending(),role:"user",sessionID:z.sessionID,agentID:z.agentID,time:{created:Date.now()},tools:z.tools,agent:U.name,model:{providerID:b.providerID,modelID:b.modelID,variant:I},system:z.system,format:z.format,provenance:z.provenance};yield*Q.addFinalizer(()=>K.clear(k.id));let E=(w)=>({...w,id:w.id?Y2.make(w.id):Y2.ascending()}),L=Q.fn("SessionPrompt.resolveUserPart")(function*(w){if(w.type==="file"){if(w.source?.type==="resource"){let{clientName:R,uri:C}=w.source;z1.info("mcp resource",{clientName:R,uri:C,mime:w.mime});let g=[{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Reading MCP resource: ${w.filename} (${C})`}],l=yield*B.readResource(R,C).pipe(Q.exit);if(i2.isSuccess(l)){let m=l.value;if(!m)throw Error(`Resource not found: ${R}/${C}`);let h=Array.isArray(m.contents)?m.contents:[m.contents];for(let f of h)if("text"in f&&f.text)g.push({messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:f.text});else if("blob"in f&&f.blob){let v="mimeType"in f?f.mimeType:w.mime;g.push({messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`[Binary content: ${v}]`})}g.push({...w,messageID:k.id,sessionID:z.sessionID})}else{let m=W2.squash(l.cause);z1.error("failed to read MCP resource",{error:m,clientName:R,uri:C});let h=m instanceof Error?m.message:String(m);g.push({messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Failed to read MCP resource ${w.filename}: ${h}`})}return g}let A=new URL(w.url);switch(A.protocol){case"data:":if(w.mime==="text/plain")return[{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:w.filename})}`},{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:jJ(w.url)},{...w,messageID:k.id,sessionID:z.sessionID}];break;case"file:":{z1.info("file",{mime:w.mime});let R=kH(w.url);if(yield*H.isDir(R))w.mime="application/x-directory";let{read:C}=yield*V.named(),g=(m,h)=>{let f=new AbortController;return C.execute(m,{sessionID:z.sessionID,abort:f.signal,agent:z.agent,messageID:k.id,extra:{bypassCwdCheck:!0,...h},messages:[],metadata:()=>Q.void,ask:()=>Q.void}).pipe(Q.onInterrupt(()=>Q.sync(()=>f.abort())))};if(w.mime==="text/plain"){let m,h,f={start:A.searchParams.get("start"),end:A.searchParams.get("end")};if(f.start!=null){let s=w.url.split("?")[0],G2=parseInt(f.start,10),C2=f.end?parseInt(f.end,10):void 0;if(G2===C2){let t=yield*G.documentSymbol(s).pipe(Q.catch(()=>Q.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===G2){G2=j2.start.line,C2=j2?.end?.line??G2;break}}}if(Number.isFinite(G2)&&G2>=1){if(m=Math.max(G2,1),C2!=null&&Number.isFinite(C2)&&C2>=G2)h=C2-(m-1)}}let v={filePath:R,offset:m,limit:h},e=[{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(v)}`}],n=yield*X.getModel(k.model.providerID,k.model.modelID).pipe(Q.flatMap((s)=>g(v,{model:s})),Q.exit);if(i2.isSuccess(n)){let s=n.value;if(e.push({messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:s.output}),s.attachments?.length)e.push(...s.attachments.map((G2)=>({...G2,synthetic:!0,filename:G2.filename??w.filename,messageID:k.id,sessionID:z.sessionID})));else e.push({...w,messageID:k.id,sessionID:z.sessionID})}else{let s=W2.squash(n.cause);z1.error("failed to read file",{error:s});let G2=s instanceof Error?s.message:String(s);yield*Y.publish(A2.Error,{sessionID:z.sessionID,error:new x2.Unknown({message:G2}).toObject()}),e.push({messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${R} with the following error: ${G2}`})}return e}if(w.mime==="application/x-directory"){let m={filePath:R},h=yield*g(m).pipe(Q.exit);if(i2.isFailure(h)){let f=W2.squash(h.cause);z1.error("failed to read directory",{error:f});let v=f instanceof Error?f.message:String(f);return yield*Y.publish(A2.Error,{sessionID:z.sessionID,error:new x2.Unknown({message:v}).toObject()}),[{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${R} with the following error: ${v}`}]}return[{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(m)}`},{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:h.value.output},{...w,messageID:k.id,sessionID:z.sessionID}]}let l=yield*H.stat(R).pipe(Q.option);if(Y0.isNone(l)||Number(l.value.size)>SH)return[{messageID:k.id,sessionID:z.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:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: {"filePath":"${R}"}`},{id:w.id,messageID:k.id,sessionID:z.sessionID,type:"file",url:`data:${w.mime};base64,`+Buffer.from(yield*H.readFile(R).pipe(Q.catch(Q.die))).toString("base64"),mime:w.mime,filename:w.filename,source:w.source}]}}}if(w.type==="agent"){let R=y2.evaluate("task",w.name,U.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return[{...w,messageID:k.id,sessionID:z.sessionID},{messageID:k.id,sessionID:z.sessionID,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the actor tool with subagent: "+w.name+R}]}return[{...w,messageID:k.id,sessionID:z.sessionID}]}),S=yield*Q.forEach(z.parts,L,{concurrency:8}).pipe(Q.map((w)=>w.flat().map(E)));yield*J.trigger("chat.message",{sessionID:z.sessionID,agent:z.agent,model:z.model,messageID:z.messageID,variant:z.variant},{message:k,parts:S});let T=o.Info.safeParse(k);if(!T.success)z1.error("invalid user message before save",{sessionID:z.sessionID,messageID:k.id,agent:k.agent,model:k.model,issues:T.error.issues});S.forEach((w,A)=>{let R=o.Part.safeParse(w);if(R.success)return;z1.error("invalid user part before save",{sessionID:z.sessionID,messageID:k.id,partID:w.id,partType:w.type,index:A,issues:R.error.issues,part:w})}),yield*$.updateMessage(k);for(let w of S)yield*$.updatePart(w);return{info:k,parts:S}},Q.scoped),q=Q.fn("SessionPrompt.sweepOrphanAssistants")(function*(z){let D=yield*$.messages({sessionID:z,agentID:"*"}),U=Date.now(),P=3600000;for(let F of D){if(F.info.role!=="assistant")continue;if(F.info.time?.completed)continue;let b=F.info.time?.created??0;if(U-b<3600000)continue;F.info.time={...F.info.time,completed:U},F.info.error=F.info.error??new o.AbortedError({message:"Abandoned: previous request interrupted before completion"}).toObject(),yield*$.updateMessage(F.info).pipe(Q.catchCause((O)=>FJ.warn("orphan-update-failed",{sessionID:z,messageID:F.info.id,cause:O}))),yield*FJ.info("orphan-assistant-cleared",{sessionID:z,messageID:F.info.id})}});return{resolvePromptParts:y,createUserMessage:j,sweepOrphanAssistants:q,lastModel:W}})}var TH=d0.create({service:"session.prompt"}),hH=/!`([^`]+)`/g,gH=/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi,yJ=/\$(\d+)/g,VZ=/^["']|["']$/g;function qJ($,Z,X){return Q.gen(function*(){let Y=yield*E2.Service,J=yield*G0.Service,B=yield*m0.Service,W=yield*p.Service,G=yield*H2.Service;return Q.fn("SessionPrompt.command")(function*(V){yield*TH.info("command",{sessionID:V.sessionID,command:V.command,agent:V.agent});let K=yield*J.get(V.command);if(!K){let L=(yield*J.list()).map((w)=>w.name),S=L.length?` Available commands: ${L.join(", ")}`:"",T=new x2.Unknown({message:`Command not found: "${V.command}".${S}`});throw yield*W.publish(A2.Error,{sessionID:V.sessionID,error:T.toObject()}),T}let y=K.agent??V.agent??(yield*Y.defaultAgent());if(V.command===G0.Default.GOAL){let L=V.arguments.trim(),S=L===""||L==="clear"||L==="reset",T;if(S)yield*B.clear(V.sessionID),T=[{type:"text",text:"Goal cleared.",synthetic:!0}];else yield*B.set(V.sessionID,L),T=[{type:"text",text:`/${V.command} ${L}`},{type:"text",text:m0.startReminder(L),synthetic:!0},...V.parts??[]];yield*G.trigger("command.execute.before",{command:V.command,sessionID:V.sessionID,arguments:V.arguments},{parts:T});let w=yield*$({sessionID:V.sessionID,messageID:V.messageID,model:S?void 0:V.model?z2.parseModel(V.model):yield*X(V.sessionID),agent:y,parts:T,variant:V.variant,noReply:S?!0:void 0});return yield*W.publish(G0.Event.Executed,{name:V.command,sessionID:V.sessionID,arguments:V.arguments,messageID:w.info.id}),w}let q=(V.arguments.match(gH)??[]).map((L)=>L.replace(VZ,"")),z=yield*Q.promise(async()=>K.template),D;if(K.source==="skill")D=V.arguments;else{let L=z.match(yJ)??[],S=0;for(let A of L){let R=Number(A.slice(1));if(R>S)S=R}let T=z.replaceAll(yJ,(A,R)=>{let C=Number(R),g=C-1;if(g>=q.length)return"";if(C===S)return q.slice(g).join(" ");return q[g]}),w=z.includes("$ARGUMENTS");if(D=T.replaceAll("$ARGUMENTS",V.arguments),L.length===0&&!w&&V.arguments.trim())D=D+`
|
|
550
|
-
|
|
551
|
-
`+V.arguments}let U=s4.shell(D);if(U.length>0){let L=F1.preferred(),S=yield*Q.promise(()=>Promise.all(U.map(async([,w])=>(await DJ.text([w],{shell:L,nothrow:!0})).text))),T=0;D=D.replace(hH,()=>S[T++])}D=D.trim();let P=yield*Q.gen(function*(){if(K.model)return z2.parseModel(K.model);if(K.agent){let L=yield*Y.get(K.agent);if(L?.model)return L.model}if(V.model)return z2.parseModel(V.model);return yield*X(V.sessionID)});yield*n4(P.providerID,P.modelID,V.sessionID);let F=yield*l$(Y,W,y,V.sessionID),b=yield*Z(D),O=F.mode==="subagent"&&K.subtask!==!1||K.subtask===!0,M;if(O){let L=K.source==="skill"?z+(V.arguments.trim()?`
|
|
552
|
-
|
|
553
|
-
`+V.arguments:""):b.find((S)=>S.type==="text")?.text??"";M=[{type:"subtask",agent:F.name,description:K.description??"",command:V.command,model:{providerID:P.providerID,modelID:P.modelID},prompt:L}]}else if(K.source==="skill"){let L=V.arguments.trim()?`/${V.command} ${V.arguments}`:`/${V.command}`,S={type:"text",text:`<skill_content name="${V.command}">
|
|
554
|
-
${z}
|
|
555
|
-
</skill_content>`,synthetic:!0},T=b.filter((w)=>w.type!=="text");M=[{type:"text",text:L},S,...T,...V.parts??[]]}else M=[...b,...V.parts??[]];let I=O?V.agent??(yield*Y.defaultAgent()):y,k=O?V.model?z2.parseModel(V.model):yield*X(V.sessionID):P;yield*G.trigger("command.execute.before",{command:V.command,sessionID:V.sessionID,arguments:V.arguments},{parts:M});let E=yield*$({sessionID:V.sessionID,messageID:V.messageID,model:k,agent:I,parts:M,variant:V.variant});return yield*W.publish(G0.Event.Executed,{name:V.command,sessionID:V.sessionID,arguments:V.arguments,messageID:E.info.id}),E})})}var PJ=N.object({sessionID:P2.zod,messageID:w2.zod.optional(),model:N.object({providerID:$1.zod,modelID:t0.zod}).optional(),modelRef:N.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:N.string().optional(),agentID:N.string().optional(),task_id:N.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:N.enum(["user","spawn","hook"]).optional(),provenance:o.Provenance.optional(),noReply:N.boolean().optional(),tools:N.record(N.string(),N.boolean()).optional().describe("@deprecated tools and permissions have been merged, you can set permissions on the session itself now"),format:o.Format.optional(),system:N.string().optional(),variant:N.string().optional(),parts:N.array(N.discriminatedUnion("type",[o.TextPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"TextPartInput"}),o.FilePart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"FilePartInput"}),o.AgentPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"AgentPartInput"}),o.SubtaskPart.omit({messageID:!0,sessionID:!0}).partial({id:!0}).meta({ref:"SubtaskPartInput"})]))}),NJ=N.object({sessionID:P2.zod,agentID:N.string().optional(),task_id:N.string().optional()}),wJ=N.object({sessionID:P2.zod,messageID:w2.zod.optional(),agent:N.string(),model:N.object({providerID:$1.zod,modelID:t0.zod}).optional(),modelRef:N.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:N.string()}),xJ=N.object({messageID:w2.zod.optional(),sessionID:P2.zod,agent:N.string().optional(),model:N.string().optional(),arguments:N.string(),command:N.string(),variant:N.string().optional(),parts:N.array(N.discriminatedUnion("type",[o.FilePart.omit({messageID:!0,sessionID:!0}).partial({id:!0})])).optional()});var EH="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.",fH="Based on the conversation above, write the user's most likely next message:",RU=a.create({service:"session.prompt"}),vH=d0.create({service:"session.prompt"});class o8 extends Z2.Service()("@qitqode/SessionPrompt"){}var bJ=_.effect(o8,Q.gen(function*(){let{bus:$,status:Z,sessions:X,agents:Y,provider:J,processor:B,prune:W,checkpoint:G,compaction:H,config:V,plugin:K,permission:y,fsys:j,registry:q,scope:z,instruction:D,state:U,goal:P,taskGateState:F,taskRegistry:b,revert:O,summary:M,sys:I,llm:k,actorRegistry:E,inbox:L}=yield*d4,S=yield*G0.Service,T=yield*N0.Service,w=yield*J$.Service,A=yield*j1.Service,R=(Q2)=>Q.gen(function*(){let q2={system:[],tools:{},inheritedMessages:[],parentPermission:[]},L2=yield*Y.get(Q2.agentName).pipe(Q.catch(()=>Q.succeed(void 0)));if(!L2)return q2;let e2=yield*J.getModel(Q2.providerID,Q2.modelID).pipe(Q.catch(()=>Q.succeed(void 0)));if(!e2)return q2;let w0=yield*X.get(Q2.sessionID).pipe(Q.catch(()=>Q.succeed(void 0)));if(!w0)return q2;let[E0,R0,f0]=yield*Q.all([I.skills(L2),Q.sync(()=>I.environment(e2,w0.time.created)),D.system().pipe(Q.orDie)]),O$=[...R0,...E0?[E0]:[],...f0.content];return{...yield*k4({sessionID:Q2.sessionID,agent:L2,model:e2,msgs:Q2.msgs,additions:O$}).pipe(Q.provideService(f2.Service,k),Q.provideService(K0.Service,q),Q.catch(()=>Q.succeed(q2))),parentPermission:L2.permission}});r4.current=R,yield*Q.addFinalizer(()=>Q.sync(()=>{if(r4.current===R)r4.current=void 0}));let C=Q.fn("SessionPrompt.runner")(function*(){return yield*D0.make()}),g=Q.fn("SessionPrompt.ops")(function*(){let Q2=yield*C();return{cancel:(q2)=>Q2.fork(l(q2)),resolvePromptParts:(q2)=>m(q2),prompt:(q2)=>t(q2)}}),l=Q.fn("SessionPrompt.cancel")(function*(Q2){yield*vH.info("cancel",{sessionID:Q2}),yield*U.cancel(Q2)}),{resolvePromptParts:m,createUserMessage:h,sweepOrphanAssistants:f,lastModel:v}=yield*zJ(),e=yield*rQ(g),{runLoop:n,lastAssistant:s}=yield*KJ(g,e,v4,o8),G2=yield*GJ(v),C2=Q.fn("SessionPrompt.predict")(function*(Q2){if((yield*V.get()).experimental?.predict_next_prompt===!1)return"";let L2=yield*X.messages({sessionID:Q2.sessionID,agentID:"main"}),e2=(v0)=>v0.info.role==="user"&&!v0.parts.every((J6)=>("synthetic"in J6)&&J6.synthetic),w0=L2.findLastIndex(e2);if(w0===-1)return"";let E0=L2[w0];if(E0.info.role!=="user")return"";let R0=L2.slice(w0+1).filter((v0)=>v0.info.role==="assistant");if(R0.length===0)return"";if(R0.some((v0)=>v0.info.time.completed===void 0))return"";let f0=R0[R0.length-1],O$=yield*Y.get("title");if(!O$)return"";let a0={...O$,prompt:EH},s0=a0.modelRef?yield*J.resolveModelRef(a0.modelRef,f0.info.providerID):a0.model?yield*J.getModel(a0.model.providerID,a0.model.modelID):(yield*J.getSmallModel(f0.info.providerID))??(yield*J.getModel(f0.info.providerID,f0.info.modelID)),N1=yield*o.toModelMessagesEffect([E0,f0],s0,{stripMedia:!0}),F$=yield*k.stream({agent:a0,user:E0.info,system:[],small:!0,tools:{},model:s0,sessionID:Q2.sessionID,retries:1,messages:[...N1,{role:"user",content:fH}]}).pipe(J8((v0)=>v0.type==="text-delta"),Y8((v0)=>v0.text),B8,Q.orElseSucceed(()=>"")),w1=m8(F$);if(!w1)return"";let R$=w1.replace(VZ,"");return R$.length>120?R$.substring(0,117)+"...":R$}),t=Q.fn("SessionPrompt.prompt")(function*(Q2){let q2=yield*X.get(Q2.sessionID);if(Q2.source!=="spawn"&&Q2.source!=="hook")yield*O.cleanup(q2),yield*f(Q2.sessionID);let L2=yield*h(Q2);yield*X.touch(Q2.sessionID);let e2=[];for(let[w0,E0]of Object.entries(Q2.tools??{}))e2.push({permission:w0,action:E0?"allow":"deny",pattern:"*"});if(e2.length>0)q2.permission=e2,yield*X.setPermission({sessionID:q2.id,permission:e2});if(Q2.noReply===!0)return L2;return yield*N2({sessionID:Q2.sessionID,agentID:Q2.agentID??"main",task_id:Q2.task_id})}),N2=Q.fn("SessionPrompt.loop")(function*(Q2){let q2=Q2.agentID??"main",L2=s(Q2.sessionID,q2),e2=n(Q2.sessionID,q2,Q2.task_id);return yield*U.ensureRunning(Q2.sessionID,q2,L2,e2)}),j2=Q.fn("SessionPrompt.shell")(function*(Q2){let q2=s(Q2.sessionID),L2=G2(Q2);return yield*U.startShell(Q2.sessionID,q2,L2)}),g0=yield*qJ(t,m,v),I2=o8.of({cancel:l,prompt:t,loop:N2,shell:j2,command:g0,resolvePromptParts:m,sweepOrphanAssistants:f,predict:C2});return H1.current={loop:I2.loop},yield*Q.addFinalizer(()=>Q.sync(()=>{if(H1.current?.loop===I2.loop)H1.current=void 0})),I2})),dH=_.suspend(()=>bJ.pipe(_.provide(y0.defaultLayer),_.provide(z0.defaultLayer),_.provide(N$.defaultLayer),_.provide(P$.defaultLayer),_.provide(q$.defaultLayer),_.provide(c0.defaultLayer),_.provide(G0.defaultLayer),_.provide(y2.defaultLayer),_.provide(N0.defaultLayer),_.provide(J$.defaultLayer),_.provide(K0.defaultLayer),_.provide(j1.defaultLayer),_.provide(z2.defaultLayer),_.provide(G$.defaultLayer),_.provide(s2.defaultLayer),_.provide(H2.defaultLayer),_.provide(l0),_.provide($$.defaultLayer),_.provide(_.mergeAll(B2.defaultLayer,P0.defaultLayer,LJ.defaultLayer,_2.defaultLayer,E2.defaultLayer,V$.defaultLayer,f2.defaultLayer,p.layer,t1,i0.defaultLayer,m0.defaultLayer,G1.defaultLayer,M0.defaultLayer))));var y1={};b2(y1,{layer:()=>IJ,defaultLayer:()=>aH,Service:()=>V8,Mode:()=>pH,Info:()=>iH,FileDiff:()=>nH,Event:()=>CJ});import mH from"path";var UJ=a.create({service:"vcs"}),AJ=($)=>{if(!$)return 0;if(!$.endsWith(`
|
|
556
|
-
`))return $.split(`
|
|
557
|
-
`).length;return $.slice(0,-1).split(`
|
|
558
|
-
`).length},lH=Q.fnUntraced(function*($,Z,X){let Y=mH.join(Z,X);if(!(yield*$.exists(Y).pipe(Q.orDie)))return"";let J=yield*$.readFile(Y).pipe(Q.catch(()=>Q.succeed(new Uint8Array)));if(Buffer.from(J).includes(0))return"";return Buffer.from(J).toString("utf8")}),RJ=($)=>new Map($.map((Z)=>[Z.file,{additions:Z.additions,deletions:Z.deletions}])),cH=(...$)=>{let Z=new Map;return $.flat().forEach((X)=>{if(!Z.has(X.file))Z.set(X.file,X)}),[...Z.values()]},KZ=Q.fnUntraced(function*($,Z,X,Y,J,B){let W=Y?yield*Z.prefix(X):"",G=(V,K,y)=>_J(MJ(V,V,K,y,"","",{context:Number.MAX_SAFE_INTEGER}));return(yield*Q.forEach(J,(V)=>Q.gen(function*(){let K=V.status==="added"||!Y?"":yield*Z.show(X,Y,V.file,W),y=V.status==="deleted"?"":yield*lH($,X,V.file),j=B.get(V.file);return{file:V.file,patch:G(V.file,K,y),additions:j?.additions??(V.status==="added"?AJ(y):0),deletions:j?.deletions??(V.status==="deleted"?AJ(K):0),status:V.status}}),{concurrency:8})).toSorted((V,K)=>V.file.localeCompare(K.file))}),uH=Q.fnUntraced(function*($,Z,X,Y){if(!Y)return yield*KZ($,Z,X,Y,yield*Z.status(X),new Map);let[J,B]=yield*Q.all([Z.status(X),Z.stats(X,Y)],{concurrency:2});return yield*KZ($,Z,X,Y,J,RJ(B))}),oH=Q.fnUntraced(function*($,Z,X,Y){let[J,B,W]=yield*Q.all([Z.diff(X,Y),Z.stats(X,Y),Z.status(X)],{concurrency:3});return yield*KZ($,Z,X,Y,cH(J,W.filter((G)=>G.code==="??")),RJ(B))}),pH=N.enum(["git","branch"]),CJ={BranchUpdated:O2.define("vcs.branch.updated",N.object({branch:N.string().optional()}))},iH=N.object({branch:N.string().optional(),default_branch:N.string().optional()}).meta({ref:"VcsInfo"}),nH=N.object({file:N.string(),patch:N.string(),additions:N.number(),deletions:N.number(),status:N.enum(["added","deleted","modified"]).optional()}).meta({ref:"VcsFileDiff"});class V8 extends Z2.Service()("@qitqode/Vcs"){}var IJ=_.effect(V8,Q.gen(function*(){let $=yield*s2.Service,Z=yield*u$.Service,X=yield*p.Service,Y=yield*l2.Scope,J=yield*d.make(Q.fn("Vcs.state")(function*(B){if(B.project.vcs!=="git")return{current:void 0,root:void 0};let W=Q.fnUntraced(function*(){return yield*Z.branch(B.directory)}),[G,H]=yield*Q.all([Z.branch(B.directory),Z.defaultBranch(B.directory)],{concurrency:2}),V={current:G,root:H};return UJ.info("initialized",{branch:V.current,default_branch:V.root?.name}),yield*X.subscribe(o$.Event.Updated).pipe(c2.filter((K)=>K.properties.file.endsWith("HEAD")),c2.runForEach((K)=>Q.gen(function*(){let y=yield*W();if(y!==V.current)UJ.info("branch changed",{from:V.current,to:y}),V.current=y,yield*X.publish(CJ.BranchUpdated,{branch:y})})),Q.forkScoped),V}));return V8.of({init:Q.fn("Vcs.init")(function*(){yield*d.get(J).pipe(Q.forkIn(Y))}),branch:Q.fn("Vcs.branch")(function*(){return yield*d.use(J,(B)=>B.current)}),defaultBranch:Q.fn("Vcs.defaultBranch")(function*(){return yield*d.use(J,(B)=>B.root?.name)}),diff:Q.fn("Vcs.diff")(function*(B){let W=yield*d.get(J),G=yield*d.context;if(G.project.vcs!=="git")return[];if(B==="git")return yield*uH($,Z,G.directory,(yield*Z.hasHead(G.directory))?"HEAD":void 0);if(!W.root)return[];if(W.current&&W.current===W.root.name)return[];let H=yield*Z.mergeBase(G.directory,W.root.ref);if(!H)return[];return yield*oH($,Z,G.directory,H)})})})),aH=IJ.pipe(_.provide(u$.defaultLayer),_.provide(s2.defaultLayer),_.provide(p.layer));var p$={};b2(p$,{layer:()=>eJ,defaultLayer:()=>VG,Worktree:()=>p$,StartCommandFailedError:()=>JG,Service:()=>W7,ResetInput:()=>YG,ResetFailedError:()=>h0,RemoveInput:()=>QG,RemoveFailedError:()=>P1,NotGitError:()=>B7,NameGenerationFailedError:()=>rJ,Info:()=>sJ,Event:()=>J7,CreateInput:()=>XG,CreateFailedError:()=>tJ});var _$={};b2(_$,{layer:()=>gJ,defaultLayer:()=>jZ,Service:()=>H8});var D1=a.create({service:"share-next"}),K8=process.env.QITQODE_DISABLE_SHARE==="true"||process.env.QITQODE_DISABLE_SHARE==="1",sH=p0.Struct({id:p0.String,url:p0.String,secret:p0.String});class H8 extends Z2.Service()("@qitqode/ShareNext"){}var HZ=($)=>Q.sync(()=>t2.use($));function hJ($){return{create:`/api/${$}`,sync:(Z)=>`/api/${$}/${Z}/sync`,remove:(Z)=>`/api/${$}/${Z}`,data:(Z)=>`/api/${$}/${Z}/data`}}var rH=hJ("share"),tH=hJ("shares");function kJ($){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 gJ=_.effect(H8,Q.gen(function*(){let $=yield*p8.Service,Z=yield*p.Service,X=yield*B2.Service,Y=yield*GZ.HttpClient,J=GZ.filterStatusOk(Y),B=yield*z2.Service,W=yield*J2.Service;function G(F,b){return Q.gen(function*(){if(K8)return;if(!(yield*y(F)))return;let M=yield*d.get(H),I=M.queue.get(F);if(I){for(let E of b)I.set(kJ(E),E);return}let k=new Map(b.map((E)=>[kJ(E),E]));M.queue.set(F,k),yield*j(F).pipe(Q.delay(1000),Q.catchCause((E)=>Q.sync(()=>{D1.error("share flush failed",{sessionID:F,cause:E})})),Q.forkIn(M.scope))})}let H=yield*d.make(Q.fn("ShareNext.state")(function*(F){let b={queue:new Map,scope:yield*l2.make(),shared:new Map};if(yield*Q.addFinalizer(()=>l2.close(b.scope,i2.void).pipe(Q.andThen(Q.sync(()=>{b.queue.clear(),b.shared.clear()})))),K8)return b;let O=(M,I)=>Z.subscribe(M).pipe(c2.runForEach((k)=>I(k).pipe(Q.catchCause((E)=>Q.sync(()=>{D1.error("share subscriber failed",{type:M.type,cause:E})})))),Q.forkScoped);return yield*O(J2.Event.Updated,(M)=>Q.gen(function*(){let I=yield*W.get(M.properties.sessionID);yield*G(I.id,[{type:"session",data:I}])})),yield*O(o.Event.Updated,(M)=>Q.gen(function*(){let I=M.properties.info;if(yield*G(I.sessionID,[{type:"message",data:I}]),I.role!=="user")return;let k=yield*B.getModel(I.model.providerID,I.model.modelID);yield*G(I.sessionID,[{type:"model",data:[k]}])})),yield*O(o.Event.PartUpdated,(M)=>M.properties.part.type==="compaction"?Q.void:G(M.properties.part.sessionID,[{type:"part",data:M.properties.part}])),yield*O(J2.Event.Diff,(M)=>G(M.properties.sessionID,[{type:"session_diff",data:M.properties.diff}])),yield*O(J2.Event.Deleted,(M)=>P(M.properties.sessionID)),b})),V=Q.fn("ShareNext.request")(function*(){let F={},b=yield*$.active();if(Y0.isNone(b)||!b.value.active_org_id){let M=(yield*X.get()).enterprise?.url??"https://opncd.ai";return{headers:F,api:rH,baseUrl:M}}let O=yield*$.token(b.value.id);if(Y0.isNone(O))throw Error("No active account token available for sharing");return F.authorization=`Bearer ${O.value}`,F["x-org-id"]=b.value.active_org_id,{headers:F,api:tH,baseUrl:b.value.url}}),K=Q.fnUntraced(function*(F){let b=yield*HZ((O)=>O.select().from(q1).where(j0(q1.session_id,F)).get());if(!b)return;return{id:b.id,secret:b.secret,url:b.url}}),y=Q.fnUntraced(function*(F){let b=yield*d.get(H);if(b.shared.has(F)){let M=b.shared.get(F);return M===null?void 0:M}let O=yield*K(F);return b.shared.set(F,O??null),O}),j=Q.fn("ShareNext.flush")(function*(F){if(K8)return;let b=yield*d.get(H),O=b.queue.get(F);if(!O)return;let M=yield*y(F);if(!M){b.queue.delete(F);return}let I=yield*V(),k=yield*j$.post(`${I.baseUrl}${I.api.sync(M.id)}`).pipe(j$.setHeaders(I.headers),j$.bodyJson({secret:M.secret,data:Array.from(O.values())}),Q.flatMap((E)=>Y.execute(E)));if(k.status>=400){D1.warn("failed to sync share",{sessionID:F,shareID:M.id,status:k.status});return}b.queue.delete(F)}),q=Q.fn("ShareNext.full")(function*(F){D1.info("full sync",{sessionID:F});let b=yield*W.get(F),O=yield*W.diff(F),M=yield*Q.sync(()=>Array.from(o.stream(F,{agentID:"*"}))),I=yield*Q.forEach(Array.from(new Map(M.filter((k)=>k.info.role==="user").map((k)=>k.info.model).map((k)=>[`${k.providerID}/${k.modelID}`,k])).values()),(k)=>B.getModel($1.make(k.providerID),t0.make(k.modelID)),{concurrency:8});yield*G(F,[{type:"session",data:b},...M.map((k)=>({type:"message",data:k.info})),...M.flatMap((k)=>k.parts.filter((E)=>E.type!=="compaction").map((E)=>({type:"part",data:E}))),{type:"session_diff",data:O},{type:"model",data:I}])}),z=Q.fn("ShareNext.init")(function*(){if(K8)return;yield*d.get(H)}),D=Q.fn("ShareNext.url")(function*(){return(yield*V()).baseUrl}),U=Q.fn("ShareNext.create")(function*(F){if(K8)return{id:"",url:"",secret:""};D1.info("creating share",{sessionID:F});let b=yield*V(),O=yield*j$.post(`${b.baseUrl}${b.api.create}`).pipe(j$.setHeaders(b.headers),j$.bodyJson({sessionID:F}),Q.flatMap((I)=>J.execute(I)),Q.flatMap(SJ.schemaBodyJson(sH)));yield*HZ((I)=>I.insert(q1).values({session_id:F,id:O.id,secret:O.secret,url:O.url}).onConflictDoUpdate({target:q1.session_id,set:{id:O.id,secret:O.secret,url:O.url}}).run());let M=yield*d.get(H);return M.shared.set(F,O),yield*q(F).pipe(Q.catchCause((I)=>Q.sync(()=>{D1.error("share full sync failed",{sessionID:F,cause:I})})),Q.forkIn(M.scope)),O}),P=Q.fn("ShareNext.remove")(function*(F){if(K8)return;D1.info("removing share",{sessionID:F});let b=yield*d.get(H),O=yield*y(F);if(!O){b.shared.delete(F),b.queue.delete(F);return}let M=yield*V();yield*j$.delete(`${M.baseUrl}${M.api.remove(O.id)}`).pipe(j$.setHeaders(M.headers),j$.bodyJson({secret:O.secret}),Q.flatMap((I)=>J.execute(I))),yield*HZ((I)=>I.delete(q1).where(j0(q1.session_id,F)).run()),b.shared.delete(F),b.queue.delete(F)});return H8.of({init:z,url:D,request:V,create:U,remove:P})})),jZ=gJ.pipe(_.provide(p.layer),_.provide(p8.defaultLayer),_.provide(B2.defaultLayer),_.provide(TJ.layer),_.provide(z2.defaultLayer),_.provide(J2.defaultLayer));var e4={};b2(e4,{layer:()=>EJ,defaultLayer:()=>eH,Service:()=>t4});class t4 extends Z2.Service()("@qitqode/SessionShare"){}var EJ=_.effect(t4,Q.gen(function*(){let $=yield*B2.Service,Z=yield*J2.Service,X=yield*H8,Y=yield*l2.Scope,J=Q.fn("SessionShare.share")(function*(G){if((yield*$.get()).share==="disabled")throw Error("Sharing is disabled in configuration");let V=yield*X.create(G);return yield*Q.sync(()=>R1.run(J2.Event.Updated,{sessionID:G,info:{share:{url:V.url}}})),V}),B=Q.fn("SessionShare.unshare")(function*(G){yield*X.remove(G),yield*Q.sync(()=>R1.run(J2.Event.Updated,{sessionID:G,info:{share:{url:null}}}))}),W=Q.fn("SessionShare.create")(function*(G){let H=yield*Z.create(G);if(H.parentID)return H;let V=yield*$.get();if(!(L0.QITQODE_AUTO_SHARE||V.share==="auto"))return H;return yield*J(H.id).pipe(Q.ignore,Q.forkIn(Y)),H});return t4.of({create:W,share:J,unshare:B})})),eH=EJ.pipe(_.provide(jZ),_.provide(J2.defaultLayer),_.provide(B2.defaultLayer));var oJ=dJ(function*(){a.Default.info("bootstrapping",{directory:S2.directory}),yield*B2.Service.use(($)=>$.get()),yield*H2.Service.use(($)=>$.init()),yield*fJ([J$.Service,_$.Service,G8.Service,j8.Service,o$.Service,V8,q0.Service,cJ,uJ].map(($)=>FZ($.use((Z)=>Z.init())))).pipe(OZ("InstanceBootstrap.init")),yield*y$.Service.use(($)=>$.reconcile()).pipe(mJ(($)=>vJ(()=>a.Default.warn("memory reconcile failed",{error:String($)}))),FZ),yield*p.Service.use(($)=>$.subscribeCallback(G0.Event.Executed,async(Z)=>{if(Z.properties.name===G0.Default.INIT)lJ(S2.project.id)})),yield*k2.subscribe()}).pipe(OZ("InstanceBootstrap"));var ZG=_.mergeAll(B2.defaultLayer,H2.defaultLayer,_$.defaultLayer,G8.defaultLayer,J$.defaultLayer,j8.defaultLayer,o$.defaultLayer,y1.defaultLayer,q0.defaultLayer,p.defaultLayer,y$.defaultLayer,Q7.defaultLayer).pipe(_.provide(Z7)),pJ=$7.make(ZG,{memoMap:X7});var i8=a.create({service:"worktree"}),J7={Ready:O2.define("worktree.ready",N.object({name:N.string(),branch:N.string()})),Failed:O2.define("worktree.failed",N.object({message:N.string()}))},sJ=N.object({name:N.string(),branch:N.string(),directory:N.string()}).meta({ref:"Worktree"}),XG=N.object({name:N.string().optional(),startCommand:N.string().optional().describe("Additional startup script to run after the project's start command")}).meta({ref:"WorktreeCreateInput"}),QG=N.object({directory:N.string()}).meta({ref:"WorktreeRemoveInput"}),YG=N.object({directory:N.string()}).meta({ref:"WorktreeResetInput"}),B7=x2.create("WorktreeNotGitError",N.object({message:N.string()})),rJ=x2.create("WorktreeNameGenerationFailedError",N.object({message:N.string()})),tJ=x2.create("WorktreeCreateFailedError",N.object({message:N.string()})),JG=x2.create("WorktreeStartCommandFailedError",N.object({message:N.string()})),P1=x2.create("WorktreeRemoveFailedError",N.object({message:N.string()})),h0=x2.create("WorktreeResetFailedError",N.object({message:N.string()}));function BG($){return $.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function WG(...$){return $.filter(Boolean).flatMap((Z)=>Z.split(`
|
|
559
|
-
`).map((X)=>X.trim()).flatMap((X)=>{let Y=X.match(/^warning:\s+failed to remove\s+(.+):\s+/i);if(!Y)return[];let J=Y[1]?.trim().replace(/^['"]|['"]$/g,"");if(!J)return[];return[J]}))}class W7 extends Z2.Service()("@qitqode/Worktree"){}var eJ=_.effect(W7,Q.gen(function*(){let $=yield*l2.Scope,Z=yield*s2.Service,X=yield*iJ.Path,Y=yield*s1.ChildProcessSpawner,J=yield*u$.Service,B=yield*M$.Service,W=Q.fnUntraced(function*(A,R){return yield*aJ(Y,A,R)},Q.catch((A)=>Q.succeed({code:1,text:"",stderr:A instanceof Error?A.message:String(A)}))),G=26,H=Q.fn("Worktree.candidate")(function*(A,R){let C=yield*d.context;for(let g of Array.from({length:26},(l,m)=>m)){let l=R?g===0?R:`${R}-${yZ.create()}`:yZ.create(),m=`qitqode/${l}`,h=X.join(A,l);if(yield*Z.exists(h).pipe(Q.orDie))continue;let f=`refs/heads/${m}`;if((yield*W(["show-ref","--verify","--quiet",f],{cwd:C.worktree})).code===0)continue;return sJ.parse({name:l,branch:m,directory:h})}throw new rJ({message:"Failed to generate a unique worktree name"})}),V=Q.fn("Worktree.makeWorktreeInfo")(function*(A){let R=yield*d.context;if(R.project.vcs!=="git")throw new B7({message:"Worktrees are only supported for git projects"});let C=X.join(w$.Path.data,"worktree",R.project.id);yield*Z.makeDirectory(C,{recursive:!0}).pipe(Q.orDie);let g=A?BG(A):"";return yield*H(C,g||void 0)}),K=Q.fnUntraced(function*(A){let R=yield*d.context,C=yield*W(["worktree","add","--no-checkout","-b",A.branch,A.directory],{cwd:R.worktree});if(C.code!==0)throw new tJ({message:C.stderr||C.text||"Failed to create git worktree"});yield*B.addSandbox(R.project.id,A.directory).pipe(Q.catch(()=>Q.void))}),y=Q.fnUntraced(function*(A,R){let C=yield*d.context,g=yield*d.workspaceID,l=C.project.id,m=R?.trim(),h=yield*W(["reset","--hard"],{cwd:A.directory});if(h.code!==0){let v=h.stderr||h.text||"Failed to populate worktree";i8.error("worktree checkout failed",{directory:A.directory,message:v}),Y7.emit("event",{directory:A.directory,project:C.project.id,workspace:g,payload:{type:J7.Failed.type,properties:{message:v}}});return}if(!(yield*Q.promise(()=>S2.provide({directory:A.directory,init:()=>pJ.runPromise(oJ),fn:()=>{return}}).then(()=>!0).catch((v)=>{let e=D$(v);return i8.error("worktree bootstrap failed",{directory:A.directory,message:e}),Y7.emit("event",{directory:A.directory,project:C.project.id,workspace:g,payload:{type:J7.Failed.type,properties:{message:e}}}),!1}))))return;Y7.emit("event",{directory:A.directory,project:C.project.id,workspace:g,payload:{type:J7.Ready.type,properties:{name:A.name,branch:A.branch}}}),yield*k(A.directory,{projectID:l,extra:m})}),j=Q.fn("Worktree.createFromInfo")(function*(A,R){yield*K(A),yield*y(A,R)}),q=Q.fn("Worktree.create")(function*(A){let R=yield*V(A?.name);return yield*K(R),yield*y(R,A?.startCommand).pipe(Q.catchCause((C)=>Q.sync(()=>i8.error("worktree bootstrap failed",{cause:C}))),Q.forkIn($)),R}),z=Q.fnUntraced(function*(A){let R=X.resolve(A),C=yield*Z.realPath(R).pipe(Q.catch(()=>Q.succeed(R))),g=X.normalize(C);return process.platform==="win32"?g.toLowerCase():g});function D(A){return A.split(`
|
|
560
|
-
`).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 g=R[R.length-1];if(!g)return R;if(C.startsWith("branch "))g.branch=C.slice(7).trim();return R},[])}let U=Q.fnUntraced(function*(A,R){for(let C of A){if(!C.path)continue;if((yield*z(C.path))===R)return C}return});function P(A){return Z.exists(A).pipe(Q.orDie,Q.flatMap((R)=>R?W(["fsmonitor--daemon","stop"],{cwd:A}):Q.void))}function F(A){return Q.promise(()=>import("fs/promises").then((R)=>R.rm(A,{recursive:!0,force:!0,maxRetries:5,retryDelay:100})).catch((R)=>{let C=D$(R);throw new P1({message:C||"Failed to remove git worktree directory"})}))}let b=Q.fn("Worktree.remove")(function*(A){let R=yield*d.context;if(R.project.vcs!=="git")throw new B7({message:"Worktrees are only supported for git projects"});let C=yield*z(A.directory),g=yield*W(["worktree","list","--porcelain"],{cwd:R.worktree});if(g.code!==0)throw new P1({message:g.stderr||g.text||"Failed to read git worktrees"});let l=D(g.text),m=yield*U(l,C);if(!m?.path){if(!(yield*Z.exists(C).pipe(Q.orDie)))return!0;let e=yield*z(X.join(w$.Path.data,"worktree",R.project.id));if(C!==e&&!C.startsWith(`${e}${X.sep}`))throw new P1({message:"Directory is not a registered or managed worktree"});return yield*P(C),yield*F(C),!0}yield*P(m.path);let h=yield*W(["worktree","remove","--force",m.path],{cwd:R.worktree});if(h.code!==0){let v=yield*W(["worktree","list","--porcelain"],{cwd:R.worktree});if(v.code!==0)throw new P1({message:h.stderr||h.text||v.stderr||v.text||"Failed to remove git worktree"});if((yield*U(D(v.text),C))?.path)throw new P1({message:h.stderr||h.text||"Failed to remove git worktree"})}yield*F(m.path);let f=m.branch?.replace(/^refs\/heads\//,"");if(f){let v=yield*W(["branch","-D",f],{cwd:R.worktree});if(v.code!==0)throw new P1({message:v.stderr||v.text||"Failed to delete worktree branch"})}return!0}),O=Q.fnUntraced(function*(A,R,C){let g=yield*W(A,R);if(g.code!==0)throw C(g);return g}),M=Q.fnUntraced(function*(A,R){let[C,g]=process.platform==="win32"?["cmd",["/c",R]]:["bash",["-lc",R]],l=yield*Y.spawn(r1.make(C,g,{cwd:A,extendEnv:!0,stdin:"ignore"})),[,m]=yield*Q.all([c2.runDrain(l.stdout),c2.mkString(c2.decodeText(l.stderr))],{concurrency:2}).pipe(Q.orDie);return{code:yield*l.exitCode,stderr:m}},Q.scoped,Q.catch(()=>Q.succeed({code:1,stderr:""}))),I=Q.fnUntraced(function*(A,R,C){let g=R.trim();if(!g)return!0;let l=yield*M(A,g);if(l.code===0)return!0;return i8.error("worktree start command failed",{kind:C,directory:A,message:l.stderr}),!1}),k=Q.fnUntraced(function*(A,R){let C=yield*Q.sync(()=>t2.use((h)=>h.select().from(zZ).where(j0(zZ.id,R.projectID)).get())),l=(C?M$.fromRow(C):void 0)?.commands?.start?.trim()??"";if(!(yield*I(A,l,"project")))return!1;return yield*I(A,R.extra??"","worktree"),!0}),E=Q.fnUntraced(function*(A,R){let C=yield*z(A);yield*Q.forEach(R,(g)=>Q.gen(function*(){let l=yield*z(X.resolve(A,g));if(l===C)return;if(!l.startsWith(`${C}${X.sep}`))return;yield*Z.remove(l,{recursive:!0}).pipe(Q.ignore)}),{concurrency:8})}),L=Q.fnUntraced(function*(A){let R=yield*W(["clean","-ffdx"],{cwd:A});if(R.code===0)return R;let C=WG(R.stderr,R.text);if(!C.length)return R;return yield*E(A,C),yield*W(["clean","-ffdx"],{cwd:A})}),S=Q.fn("Worktree.reset")(function*(A){let R=yield*d.context;if(R.project.vcs!=="git")throw new B7({message:"Worktrees are only supported for git projects"});let C=yield*z(A.directory),g=yield*z(R.worktree);if(C===g)throw new h0({message:"Cannot reset the primary workspace"});let l=yield*W(["worktree","list","--porcelain"],{cwd:R.worktree});if(l.code!==0)throw new h0({message:l.stderr||l.text||"Failed to read git worktrees"});let m=yield*U(D(l.text),C);if(!m?.path)throw new h0({message:"Worktree not found"});let h=m.path,f=yield*J.defaultBranch(R.worktree);if(!f)throw new h0({message:"Default branch not found"});let v=f.ref.indexOf("/");if(f.ref!==f.name&&v>0){let s=f.ref.slice(0,v),G2=f.ref.slice(v+1);yield*O(["fetch",s,G2],{cwd:R.worktree},(C2)=>new h0({message:C2.stderr||C2.text||`Failed to fetch ${f.ref}`}))}yield*O(["reset","--hard",f.ref],{cwd:h},(s)=>new h0({message:s.stderr||s.text||"Failed to reset worktree to target"}));let e=yield*L(h);if(e.code!==0)throw new h0({message:e.stderr||e.text||"Failed to clean worktree"});yield*O(["submodule","update","--init","--recursive","--force"],{cwd:h},(s)=>new h0({message:s.stderr||s.text||"Failed to update submodules"})),yield*O(["submodule","foreach","--recursive","git","reset","--hard"],{cwd:h},(s)=>new h0({message:s.stderr||s.text||"Failed to reset submodules"})),yield*O(["submodule","foreach","--recursive","git","clean","-fdx"],{cwd:h},(s)=>new h0({message:s.stderr||s.text||"Failed to clean submodules"}));let n=yield*W(["-c","core.fsmonitor=false","status","--porcelain=v1"],{cwd:h});if(n.code!==0)throw new h0({message:n.stderr||n.text||"Failed to read git status"});if(n.text.trim())throw new h0({message:`Worktree reset left local changes:
|
|
561
|
-
${n.text.trim()}`});return yield*k(h,{projectID:R.project.id}).pipe(Q.catchCause((s)=>Q.sync(()=>i8.error("worktree start task failed",{cause:s}))),Q.forkIn($)),!0}),T=Q.fn("Worktree.head")(function*(A){return(yield*W(["rev-parse","HEAD"],{cwd:A})).text.trim()}),w=Q.fn("Worktree.isPristine")(function*(A,R){let C=yield*W(["status","--porcelain"],{cwd:A});if(C.code!==0)return!1;if(C.text.trim()!=="")return!1;let g=yield*W(["rev-parse","HEAD"],{cwd:A});return g.code===0&&g.text.trim()===R});return W7.of({makeWorktreeInfo:V,createFromInfo:j,create:q,remove:b,reset:S,head:T,isPristine:w})})),VG=eJ.pipe(_.provide(u$.defaultLayer),_.provide(t1),_.provide(M$.defaultLayer),_.provide(s2.defaultLayer),_.provide(nJ.layer));var r8={};b2(r8,{layer:()=>JB,defaultLayer:()=>zG,UpdateInput:()=>FG,Service:()=>V7,Pty:()=>r8,Info:()=>qZ,Event:()=>s8,CreateInput:()=>OG});function $B($){let Z,X=!1;return()=>{if(X)return Z;return X=!0,Z=$(),Z}}var KG=p0.String.annotate({[XB]:O8.schema("pty")}).pipe(p0.brand("PtyID")),n8=KG.pipe(ZB(($)=>({ascending:(Z)=>$.make(O8.ascending("pty",Z)),zod:O8.schema("pty").pipe(N.custom())})));var a8=a.create({service:"pty"}),QB=2097152,YB=65536,HG=new TextEncoder,DZ=($)=>$.data&&typeof $.data==="object"?$.data:$,GG=($)=>{let Z=JSON.stringify({cursor:$}),X=HG.encode(Z),Y=new Uint8Array(X.length+1);return Y[0]=0,Y.set(X,1),Y},jG=$B(()=>import("./chunk-jvjq554f.js")),qZ=N.object({id:n8.zod,title:N.string(),command:N.string(),args:N.array(N.string()),cwd:N.string(),status:N.enum(["running","exited"]),pid:N.number()}).meta({ref:"Pty"}),OG=N.object({command:N.string().optional(),args:N.array(N.string()).optional(),cwd:N.string().optional(),title:N.string().optional(),env:N.record(N.string(),N.string()).optional()}),FG=N.object({title:N.string().optional(),size:N.object({rows:N.number(),cols:N.number()}).optional()}),s8={Created:O2.define("pty.created",N.object({info:qZ})),Updated:O2.define("pty.updated",N.object({info:qZ})),Exited:O2.define("pty.exited",N.object({id:n8.zod,exitCode:N.number()})),Deleted:O2.define("pty.deleted",N.object({id:n8.zod}))};class V7 extends Z2.Service()("@qitqode/Pty"){}var JB=_.effect(V7,Q.gen(function*(){let $=yield*p.Service,Z=yield*H2.Service;function X(j){try{j.process.kill()}catch{}for(let[q,z]of j.subscribers.entries())try{if(DZ(z)===q)z.close()}catch{}j.subscribers.clear()}let Y=yield*d.make(Q.fn("Pty.state")(function*(j){let q={dir:j.directory,sessions:new Map};return yield*Q.addFinalizer(()=>Q.sync(()=>{for(let z of q.sessions.values())X(z);q.sessions.clear()})),q})),J=Q.fn("Pty.remove")(function*(j){let q=yield*d.get(Y),z=q.sessions.get(j);if(!z)return;q.sessions.delete(j),a8.info("removing session",{id:j}),X(z),yield*$.publish(s8.Deleted,{id:z.info.id})}),B=Q.fn("Pty.list")(function*(){let j=yield*d.get(Y);return Array.from(j.sessions.values()).map((q)=>q.info)}),W=Q.fn("Pty.get")(function*(j){return(yield*d.get(Y)).sessions.get(j)?.info}),G=Q.fn("Pty.create")(function*(j){let q=yield*d.get(Y),z=yield*D0.make(),D=n8.ascending(),U=j.command||F1.preferred(),P=j.args||[];if(F1.login(U))P.push("-l");let F=j.cwd||q.dir,b=yield*Z.trigger("shell.env",{cwd:F},{env:{}}),O={...M4(),...j.env,...b.env,TERM:"xterm-256color",QITQODE_TERMINAL:"1"};if(process.platform==="win32")O.LC_ALL="C.UTF-8",O.LC_CTYPE="C.UTF-8",O.LANG="C.UTF-8";a8.info("creating session",{id:D,cmd:U,args:P,cwd:F});let{spawn:M}=yield*Q.promise(()=>jG()),I=yield*Q.sync(()=>M(U,P,{name:"xterm-256color",cwd:F,env:O})),k={id:D,title:j.title||`Terminal ${D.slice(-4)}`,command:U,args:P,cwd:F,status:"running",pid:I.pid},E={info:k,process:I,buffer:"",bufferCursor:0,cursor:0,subscribers:new Map};return q.sessions.set(D,E),I.onData(S2.bind((L)=>{E.cursor+=L.length;for(let[T,w]of E.subscribers.entries()){if(w.readyState!==1){E.subscribers.delete(T);continue}if(DZ(w)!==T){E.subscribers.delete(T);continue}try{w.send(L)}catch{E.subscribers.delete(T)}}if(E.buffer+=L,E.buffer.length<=QB)return;let S=E.buffer.length-QB;E.buffer=E.buffer.slice(S),E.bufferCursor+=S})),I.onExit(S2.bind(({exitCode:L})=>{if(E.info.status==="exited")return;a8.info("session exited",{id:D,exitCode:L}),E.info.status="exited",z.fork($.publish(s8.Exited,{id:D,exitCode:L})),z.fork(J(D))})),yield*$.publish(s8.Created,{info:k}),k}),H=Q.fn("Pty.update")(function*(j,q){let D=(yield*d.get(Y)).sessions.get(j);if(!D)return;if(q.title)D.info.title=q.title;if(q.size)D.process.resize(q.size.cols,q.size.rows);return yield*$.publish(s8.Updated,{info:D.info}),D.info}),V=Q.fn("Pty.resize")(function*(j,q,z){let U=(yield*d.get(Y)).sessions.get(j);if(U&&U.info.status==="running")U.process.resize(q,z)}),K=Q.fn("Pty.write")(function*(j,q){let D=(yield*d.get(Y)).sessions.get(j);if(D&&D.info.status==="running")D.process.write(q)}),y=Q.fn("Pty.connect")(function*(j,q,z){let U=(yield*d.get(Y)).sessions.get(j);if(!U){q.close();return}a8.info("client connected to session",{id:j});let P=DZ(q);U.subscribers.delete(P),U.subscribers.set(P,q);let F=()=>{U.subscribers.delete(P)},b=U.bufferCursor,O=U.cursor,M=z===-1?O:typeof z==="number"&&Number.isSafeInteger(z)?Math.max(0,z):0,I=(()=>{if(!U.buffer)return"";if(M>=O)return"";let k=Math.max(0,M-b);if(k>=U.buffer.length)return"";return U.buffer.slice(k)})();if(I)try{for(let k=0;k<I.length;k+=YB)q.send(I.slice(k,k+YB))}catch{F(),q.close();return}try{q.send(GG(O))}catch{F(),q.close();return}return{onMessage:(k)=>{U.process.write(typeof k==="string"?k:new TextDecoder().decode(k))},onClose:()=>{a8.info("client disconnected from session",{id:j}),F()}}});return V7.of({list:B,get:W,create:G,update:H,remove:J,resize:V,write:K,connect:y})})),zG=JB.pipe(_.provide(p.layer),_.provide(H2.defaultLayer));var $6={};b2($6,{layer:()=>KB,defaultLayer:()=>PG,Service:()=>G7,MAX_PRE_REACT:()=>WB,MAX_POST_REACT:()=>VB,Actor:()=>$6});var K7=($,Z,X)=>Q.uninterruptible(Q.gen(function*(){let Y=yield*_2.Service;yield*Y.updateStatus($,Z,{status:"running"}).pipe(Q.ignore);let J=yield*X.pipe(Q.interruptible,Q.exit);if(i2.isSuccess(J))return yield*Y.updateStatus($,Z,{status:"idle",lastOutcome:"success",lastError:void 0}).pipe(Q.ignore),J.value;let B=J.cause,W=W2.hasInterruptsOnly(B);return yield*Y.updateStatus($,Z,{status:"idle",lastOutcome:W?"cancelled":"failure",lastError:W?void 0:yG(B)}).pipe(Q.ignore),yield*Q.failCause(B)}));function yG($){return W2.pretty($)}var H7=a.create({service:"actor.spawn"}),WB=3,VB=3,qG=`
|
|
562
|
-
|
|
563
|
-
---
|
|
564
|
-
|
|
565
|
-
## Return format (required)
|
|
566
|
-
|
|
567
|
-
Your FINAL assistant message \u2014 what the spawning agent will receive \u2014 MUST start with this header block:
|
|
568
|
-
|
|
569
|
-
**Status**: success | partial | failed | blocked
|
|
570
|
-
**Summary**: <one sentence describing what happened>
|
|
571
|
-
|
|
572
|
-
After the header, include the actual deliverable (whatever the task asked for in its prompt).
|
|
573
|
-
|
|
574
|
-
If applicable, also include below the deliverable:
|
|
575
|
-
|
|
576
|
-
**Files touched**: <comma-separated paths or "(none)">
|
|
577
|
-
**Findings worth promoting**: <bullet list of cross-task transferable facts; "(none)" if just routine work>
|
|
578
|
-
|
|
579
|
-
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**:".
|
|
580
|
-
`;class G7 extends Z2.Service()("@qitqode/Actor"){}var KB=_.effect(G7,Q.gen(function*(){let $=yield*J2.Service,Z=yield*_2.Service,X=yield*E2.Service,Y=yield*c$.Service,J=yield*i0.Service,B=yield*y0.Service,W=yield*H2.Service,G=yield*p.Service,H=yield*M0.Service,V=yield*l2.Scope,K=new Map,y=Q.fn("Actor.runAgentLoop")(function*(O){let M=yield*Y.prompt({sessionID:O.sessionID,agent:O.agentType,agentID:O.actorID,source:O.source,provenance:O.provenance,model:O.model,task_id:O.task_id,parts:[{type:"text",text:O.task}],...O.format?{format:O.format}:{}}),I=M?.info,k=I?.role==="assistant"?I.structured:void 0;return{finalText:k!==void 0?void 0:M?.parts.findLast((L)=>L.type==="text")?.text,structured:k}}),j=(O)=>Q.gen(function*(){let M=yield*T2.make(),I=O.description??O.agentType;if(O.task_id)yield*H.start({session_id:O.parentSessionID,id:O.task_id,owner:O.actorID}).pipe(Q.ignoreCause({log:"Warn",message:`auto-start of task ${O.task_id} failed`}));let k=(C,g)=>O.background&&O.agentType!=="checkpoint-writer"?J.send({receiverSessionID:O.parentSessionID,receiverActorID:O.parentActorID??"main",senderSessionID:O.sessionID,senderActorID:O.actorID,type:"actor_notification",content:EQ({actorID:O.actorID,description:I,status:C,...g})}).pipe(Q.ignore):Q.void,E=O.parentSessionID===O.sessionID?"subagent":"peer",L=yield*X.get(O.agentType),S=L?!y2.disabled(["write"],L.permission).has("write"):!0,T=Q.gen(function*(){let C,g,l=0,m;while(!0){let h=l>0?m:void 0,f=yield*K7(O.sessionID,O.actorID,y({...O,task:h?h.reason:O.task,source:h?"hook":"spawn",provenance:h?{hookPhase:"pre",hookIteration:l,pluginNames:h.contributingPluginNames,hookIDs:h.contributingHookIDs}:void 0}));if(C=f.finalText,g=f.structured,l++,l>WB){yield*G.publish(t8.ReActMaxReached,{phase:"pre",actorID:O.actorID,agentType:O.agentType}),H7.warn("actor.preStop hit MAX_PRE_REACT cap; skipping further hook checks",{actorID:O.actorID,totalTurns:l});break}let v=yield*W.triggerActorPreStop({sessionID:O.sessionID,parentSessionID:O.parentSessionID,actorID:O.actorID,parentActorID:O.parentActorID,agentType:O.agentType,mode:E,lifecycle:O.lifecycle,finalText:C,task:O.task,description:O.description,task_id:O.task_id,iteration:l-1});if(!v.continue)break;if(!v.reason)break;yield*G.publish(t8.ReActReentered,{phase:"pre",actorID:O.actorID,agentType:O.agentType,iteration:l,triggeredByPlugins:v.contributingPluginNames,reasonPreview:v.reason.slice(0,200)}),m={reason:v.reason,contributingPluginNames:v.contributingPluginNames,contributingHookIDs:v.contributingHookIDs}}return{finalText:C,structured:g}}).pipe(Q.provideService(_2.Service,Z),Q.matchCauseEffect({onSuccess:({finalText:C,structured:g})=>Q.gen(function*(){let l=C;if(O.gateEligible){let j2=0;while(!0){let g0=yield*O1.decide({session_id:O.parentSessionID,owner:O.actorID,reactCount:j2,maxReact:n9,mode:"subagent"}).pipe(Q.provideService(M0.Service,H));if(!g0.needReentry)break;j2++;let I2=yield*K7(O.sessionID,O.actorID,y({...O,task:g0.reentryText,source:"hook",provenance:{hookPhase:"post",hookIteration:j2,pluginNames:[],hookIDs:[]}})).pipe(Q.catch(()=>Q.gen(function*(){return H7.error("actor.gate runTurn failed",{actorID:O.actorID}),{finalText:void 0,structured:void 0}})),Q.provideService(_2.Service,Z));if(I2.finalText!==void 0)l=I2.finalText;if(I2.structured!==void 0)g=I2.structured}}let m=O.gateEligible?yield*H.list({session_id:O.parentSessionID,owner:O.actorID,include_terminal:!1}).pipe(Q.orElseSucceed(()=>[])):[],f=m.filter((j2)=>j2.status==="open"||j2.status==="in_progress").length>0?"partial":m.length>0?"blocked":void 0,v=BB(l),e=f??v.status,n=m.map((j2)=>j2.id),s=f&&n.length>0?`${l??""}
|
|
581
|
-
|
|
582
|
-
**Incomplete tasks**: ${n.join(", ")}`:l,G2=g!==void 0?JSON.stringify(g):s??"(no output)";yield*k("completed",{result:G2,...e?{reportedStatus:e}:{},...v.summary?{reportedSummary:v.summary}:{}}),yield*T2.succeed(M,{status:"success",...s!==void 0?{finalText:s}:{},...g!==void 0?{structured:g}:{},...e?{reportedStatus:e}:{},...v.summary?{reportedSummary:v.summary}:{},...n.length>0?{incompleteTasks:n}:{}});let C2=0,t=C,N2;while(!0){let j2=yield*W.triggerActorPostStop({sessionID:O.sessionID,parentSessionID:O.parentSessionID,actorID:O.actorID,parentActorID:O.parentActorID,agentType:O.agentType,mode:E,lifecycle:O.lifecycle,finalText:t,task:O.task,description:O.description,task_id:O.task_id,outcome:"success",iteration:C2,canWrite:S});if(!j2.continue)break;if(!j2.reason)break;if(C2>=VB){yield*G.publish(t8.ReActMaxReached,{phase:"post",actorID:O.actorID,agentType:O.agentType}),H7.warn("actor.postStop hit MAX_POST_REACT cap; skipping further hook checks",{actorID:O.actorID,totalTurns:C2+1});break}C2++,yield*G.publish(t8.ReActReentered,{phase:"post",actorID:O.actorID,agentType:O.agentType,iteration:C2,triggeredByPlugins:j2.contributingPluginNames,reasonPreview:j2.reason.slice(0,200)}),N2={reason:j2.reason,contributingPluginNames:j2.contributingPluginNames,contributingHookIDs:j2.contributingHookIDs};let g0=yield*K7(O.sessionID,O.actorID,y({...O,task:N2.reason,source:"hook",provenance:{hookPhase:"post",hookIteration:C2,pluginNames:N2.contributingPluginNames,hookIDs:N2.contributingHookIDs}})).pipe(Q.catch(()=>Q.gen(function*(){return H7.error("actor.postStop runTurn failed",{actorID:O.actorID}),{finalText:void 0,structured:void 0}})),Q.provideService(_2.Service,Z));if(g0.finalText===void 0)break;t=g0.finalText}yield*Q.sync(()=>K.delete(O.actorID))}),onFailure:(C)=>Q.gen(function*(){let g=W2.hasInterruptsOnly(C),l=W2.pretty(C);yield*k(g?"cancelled":"failed",g?{}:{error:l}),yield*T2.succeed(M,g?{status:"cancelled"}:{status:"failure",error:l}),yield*Q.sync(()=>K.delete(O.actorID))})})),w=yield*_0;return{fiber:yield*(w?T.pipe(Q.provideService(_0,w)):T).pipe(Q.forkIn(V)),outcome:M}}),q=Q.fn("Actor.spawnPeer")(function*(O){let M=yield*$.create({parentID:O.sessionID,contextFrom:O.context==="full"?O.sessionID:void 0,title:`${O.agentType}: ${O.task.slice(0,40)}`});if(yield*Z.register({sessionID:M.id,actorID:M.id,mode:"peer",parentActorID:O.parentActorID,agent:O.agentType,description:O.description??O.agentType,contextMode:O.context,contextWatermark:void 0,background:O.background,lifecycle:O.lifecycle??"persistent",tools:O.tools}),O.forkContext)K.set(M.id,O.forkContext);let{fiber:I,outcome:k}=yield*j({sessionID:M.id,parentSessionID:O.sessionID,parentActorID:O.parentActorID,actorID:M.id,agentType:O.agentType,task:O.task,description:O.description,background:O.background,model:O.model,lifecycle:O.lifecycle??"persistent",task_id:O.task_id,format:O.format});if(!O.background)yield*e8.join(I).pipe(Q.ignore);return{actorID:M.id,sessionID:M.id,outcome:k}}),z=Q.fn("Actor.spawnSubagent")(function*(O){let M=yield*Z.allocateActorID(O.sessionID,O.agentType),I=O.context==="full"?yield*$.lastMainMessageID(O.sessionID):void 0;if(yield*Z.register({sessionID:O.sessionID,actorID:M,mode:"subagent",parentActorID:O.parentActorID,agent:O.agentType,description:O.description??O.agentType,contextMode:O.context,contextWatermark:I,background:O.background,lifecycle:O.lifecycle??"ephemeral",tools:O.tools}),O.onActorID)yield*Q.sync(()=>O.onActorID(M)).pipe(Q.ignore);if(O.forkContext)K.set(M,O.forkContext);let k=yield*X.get(O.agentType),E=k?.mode==="subagent"&&!k?.prompt&&O.agentType!=="checkpoint-writer",L=E?O.task+qG:O.task,{fiber:S,outcome:T}=yield*j({sessionID:O.sessionID,parentSessionID:O.parentSessionID??O.sessionID,parentActorID:O.parentActorID,actorID:M,agentType:O.agentType,task:L,description:O.description,background:O.background,model:O.model,lifecycle:O.lifecycle??"ephemeral",task_id:O.task_id,gateEligible:E,format:O.format});if(O.onReady)yield*Q.ignore(O.onReady({actorID:M,sessionID:O.sessionID}));if(!O.background)yield*e8.join(S).pipe(Q.ignore);return{actorID:M,sessionID:O.sessionID,outcome:T}}),D=Q.fn("Actor.spawn")(function*(O){let M=yield*_0,I=O.mode==="peer"?q(O):z(O);return yield*M?I.pipe(Q.provideService(_0,M)):I}),U=Q.fn("Actor.cancel")(function*(O,M,I){let k=yield*Z.listByParent(O,M);yield*Q.forEach(k,(E)=>U(O,E.actorID,I),{concurrency:"unbounded",discard:!0}),yield*B.cancelActor(O,M),yield*Z.updateStatus(O,M,{status:"idle",lastOutcome:"cancelled"}).pipe(Q.ignore),yield*Q.sync(()=>K.delete(M))}),P=Q.fn("Actor.getForkContext")(function*(O){return K.get(O)}),F=G7.of({spawn:D,cancel:U,getForkContext:P}),b=Y$.current;return Y$.current=F,yield*Q.addFinalizer(()=>Q.sync(()=>{if(Y$.current===F)Y$.current=b})),F})),PG=_.suspend(()=>KB.pipe(_.provide(J2.defaultLayer),_.provide(_2.defaultLayer),_.provide(E2.defaultLayer),_.provide(c$.defaultLayer),_.provide(y0.defaultLayer),_.provide(i0.defaultLayer),_.provide(H2.defaultLayer),_.provide(p.layer),_.provide(M0.defaultLayer)));var Q6={};b2(Q6,{layer:()=>iB,defaultLayer:()=>Qj,WorkflowRuntime:()=>Q6,Service:()=>z7});import{createHash as pB}from"crypto";var NG=/export\s+const\s+meta\s*=\s*/;function NZ($){let Z=NG.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 Y=wG($,X);if(Y===-1)return{ok:!1,error:"could not locate a balanced meta object literal"};let J=$.slice(X,Y+1),B=xG(J);if(!B.ok)return{ok:!1,error:`meta is not a valid object literal: ${B.error}`};let W=B.value;if(typeof W!=="object"||W===null||Array.isArray(W))return{ok:!1,error:"meta must be an object"};let G=W;if(typeof G.name!=="string"||!G.name)return{ok:!1,error:"meta.name (non-empty string) is required"};if(typeof G.description!=="string"||!G.description)return{ok:!1,error:"meta.description (non-empty string) is required"};let H=Y+1+($[Y+1]===";"?1:0),V=$.slice(Z.index,H),K=$.slice(0,Z.index)+V.replace(/[^\n]/g," ")+$.slice(H);return{ok:!0,meta:G,body:K}}function wG($,Z){let X=0,Y="";for(let J=Z;J<$.length;J++){let B=$[J];if(Y){if(B==="\\"){J++;continue}if(B===Y)Y="";continue}if(B==="/"&&$[J+1]==="/"){J+=2;while(J<$.length&&$[J]!==`
|
|
583
|
-
`)J++;continue}if(B==="/"&&$[J+1]==="*"){J+=2;while(J<$.length&&!($[J]==="*"&&$[J+1]==="/"))J++;J++;continue}if(B==='"'||B==="'"||B==="`"){Y=B;continue}if(B==="{")X++;else if(B==="}"){if(X--,X===0)return J}}return-1}var HB=100;function xG($){let Z={text:$,pos:0,depth:0};try{n0(Z);let X=wZ(Z);if(n0(Z),Z.pos!==Z.text.length)throw new O0(`unexpected token at offset ${Z.pos}`);return{ok:!0,value:X}}catch(X){if(X instanceof O0)return{ok:!1,error:X.message};throw X}}class O0 extends Error{}function n0($){for(;;){let Z=$.text[$.pos];if(Z===" "||Z==="\t"||Z===`
|
|
584
|
-
`||Z==="\r"||Z==="\f"||Z==="\v"){$.pos++;continue}if(Z==="/"&&$.text[$.pos+1]==="/"){$.pos+=2;while($.pos<$.text.length&&$.text[$.pos]!==`
|
|
585
|
-
`)$.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 O0("unterminated comment");$.pos+=2;continue}return}}function wZ($){let Z=$.text[$.pos];if(Z===void 0)throw new O0("unexpected end of input");if(Z==="{")return LG($);if(Z==="[")return bG($);if(Z==='"'||Z==="'")return GB($);if(Z==="-"||Z>="0"&&Z<="9")return AG($);if(PZ($,"true"))return!0;if(PZ($,"false"))return!1;if(PZ($,"null"))return null;throw new O0(`unexpected token at offset ${$.pos} (only data literals are allowed)`)}function LG($){if(++$.depth>HB)throw new O0("meta nesting too deep");$.pos++;let Z={};if(n0($),$.text[$.pos]==="}")return $.pos++,$.depth--,Z;for(;;){n0($);let X=UG($);if(n0($),$.text[$.pos]!==":")throw new O0(`expected ':' after key '${X}' at offset ${$.pos}`);$.pos++,n0($),Z[X]=wZ($),n0($);let Y=$.text[$.pos];if(Y===","){if($.pos++,n0($),$.text[$.pos]==="}")return $.pos++,$.depth--,Z;continue}if(Y==="}")return $.pos++,$.depth--,Z;throw new O0(`expected ',' or '}' at offset ${$.pos}`)}}function bG($){if(++$.depth>HB)throw new O0("meta nesting too deep");$.pos++;let Z=[];if(n0($),$.text[$.pos]==="]")return $.pos++,$.depth--,Z;for(;;){n0($),Z.push(wZ($)),n0($);let X=$.text[$.pos];if(X===","){if($.pos++,n0($),$.text[$.pos]==="]")return $.pos++,$.depth--,Z;continue}if(X==="]")return $.pos++,$.depth--,Z;throw new O0(`expected ',' or ']' at offset ${$.pos}`)}}function UG($){let Z=$.text[$.pos];if(Z==='"'||Z==="'")return GB($);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 O0(`expected a property name at offset ${$.pos}`)}function GB($){let Z=$.text[$.pos];$.pos++;let X="";for(;;){let Y=$.text[$.pos];if(Y===void 0||Y===`
|
|
586
|
-
`)throw new O0("unterminated string");if(Y==="\\"){let J=$.text[$.pos+1];if($.pos+=2,J==="n")X+=`
|
|
587
|
-
`;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 B=$.text.slice($.pos,$.pos+4);if(!/^[0-9a-fA-F]{4}$/.test(B))throw new O0("invalid \\u escape");X+=String.fromCharCode(parseInt(B,16)),$.pos+=4}else if(J===void 0)throw new O0("unterminated string");else X+=J;continue}if(Y===Z)return $.pos++,X;X+=Y,$.pos++}}function AG($){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),Y=Number(X);if(!Number.isFinite(Y))throw new O0(`invalid number '${X}'`);return Y}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 jB=O2.define("workflow.phase",N.object({sessionID:P2.zod,runID:N.string(),title:N.string()})),OB=O2.define("workflow.log",N.object({sessionID:P2.zod,runID:N.string(),message:N.string()})),FB=O2.define("workflow.started",N.object({sessionID:P2.zod,runID:N.string(),name:N.string()})),j7=O2.define("workflow.finished",N.object({sessionID:P2.zod,runID:N.string(),status:N.enum(["completed","failed","cancelled"]),error:N.string().optional()})),zB=O2.define("workflow.agent_failed",N.object({sessionID:P2.zod,runID:N.string(),actorID:N.string().optional(),agentType:N.string(),label:N.string().optional(),phase:N.string().optional(),reason:N.enum(["over-cap","spawn-reject","timeout","actor-error","no-deliverable"]),errorMessage:N.string().optional()})),yB=O2.define("workflow.child_failed",N.object({sessionID:P2.zod,runID:N.string(),childRunID:N.string(),name:N.string(),status:N.enum(["failed","cancelled"]),error:N.string().optional()}));import LZ from"path";import{createHash as MG}from"crypto";var F0=h4("workflow_run",{id:Q0().primaryKey(),session_id:Q0().$type().notNull().references(()=>T0.id,{onDelete:"cascade"}),name:Q0().notNull(),status:Q0().$type().notNull(),running:K1().notNull().default(0),succeeded:K1().notNull().default(0),failed:K1().notNull().default(0),current_phase:Q0(),parent_actor_id:Q0(),args:Q0({mode:"json"}),script_sha:Q0(),agent_timeout_ms:K1(),error:Q0(),...DB},($)=>[Z8("workflow_run_session_idx").on($.session_id),Z8("workflow_run_status_idx").on($.status)]);function xZ($){if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.map(xZ);return Object.fromEntries(Object.keys($).sort().map((Z)=>[Z,xZ($[Z])]))}function qB($,Z){let X=xZ({prompt:$,agentType:Z.agentType??null,model:Z.model??null,schema:Z.schema??null,phase:Z.phase??null});return MG("sha256").update(JSON.stringify(X)).digest("hex")}var Z6=()=>LZ.join(w$.Path.data,"workflow"),i$=new Map;function PB($,Z){if(Z.length===0)return Promise.resolve();let Y=(i$.get($)??Promise.resolve()).catch(()=>{}).then(async()=>{let J=await import("fs/promises");await J.mkdir(Z6(),{recursive:!0}),await J.appendFile(bZ($),Z.map((B)=>JSON.stringify(B)+`
|
|
588
|
-
`).join(""))});return i$.set($,Y),Y.finally(()=>{if(i$.get($)===Y)i$.delete($)})}var _G=/^wf_[0-9A-Za-z]+$/,NB=($)=>{if(!_G.test($))throw Error(`invalid workflow runID: ${JSON.stringify($)}`);return $},wB=($)=>LZ.join(Z6(),`${NB($)}.js`),bZ=($)=>LZ.join(Z6(),`${NB($)}.jsonl`);function xB($){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 RG=($)=>Q.sync(()=>t2.use((Z)=>Z.insert(F0).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:F0.id,set:{status:"running",running:0,succeeded:0,failed:0,script_sha:$.scriptSha??null,...$.agentTimeoutMs!==void 0?{agent_timeout_ms:$.agentTimeoutMs}:{}}}).run())),CG=($)=>Q.sync(()=>t2.use((Z)=>Z.update(F0).set({current_phase:$.phase}).where(j0(F0.id,$.runID)).run())),IG=($)=>Q.sync(()=>t2.use((Z)=>Z.update(F0).set({running:$.running,succeeded:$.succeeded,failed:$.failed}).where(j0(F0.id,$.runID)).run())),kG=($)=>Q.sync(()=>t2.use((Z)=>Z.update(F0).set({status:$.status,...$.error?{error:$.error}:{}}).where(j0(F0.id,$.runID)).run())),SG=($)=>Q.sync(()=>t2.use((Z)=>{return(($?.sessionID)?Z.select().from(F0).where(j0(F0.session_id,$.sessionID)).orderBy(u8(F0.time_created)).all():Z.select().from(F0).orderBy(u8(F0.time_created)).all()).map(xB)})),TG=($)=>Q.sync(()=>t2.use((Z)=>{let X=Z.select().from(F0).where(j0(F0.id,$)).get();return X?xB(X):void 0})),hG=($,Z)=>Q.promise(async()=>{await(await import("fs/promises")).mkdir(Z6(),{recursive:!0}),await Bun.write(wB($),Z)}),gG=($)=>Q.promise(()=>Bun.file(wB($)).text()),EG=($,Z)=>Q.promise(()=>PB($,[Z])),fG=($,Z)=>Q.promise(()=>PB($,Z)),vG=($)=>Q.promise(async()=>{let Z=Bun.file(bZ($));if(!await Z.exists())return{results:new Map,pass:1};let X=await Z.text(),Y=new Map,J=0;for(let B of X.split(`
|
|
589
|
-
`)){if(!B)continue;let W;try{W=JSON.parse(B)}catch{continue}if(typeof W.pass==="number"&&W.pass>J)J=W.pass;if(W.t==="agent")Y.set(W.key,W.result)}return{results:Y,pass:J+1}}),dG=($)=>Q.promise(async()=>{let X=(i$.get($)??Promise.resolve()).catch(()=>{}).then(async()=>{await(await import("fs/promises")).mkdir(Z6(),{recursive:!0}),await Bun.write(bZ($),"")});i$.set($,X);try{await X}finally{if(i$.get($)===X)i$.delete($)}}),d2={recordStart:RG,recordPhase:CG,flushCounters:IG,recordTerminal:kG,list:SG,load:TG,writeScript:hG,readScript:gG,appendJournal:EG,appendJournalSync:fG,loadJournal:vG,clearJournal:dG};class UZ{#$=new Map;get($){return this.#$.get($)}set($){return this.#$.set($.runID,$),$}values(){return this.#$.values()}clear(){this.#$.clear()}}function LB($){let Z=(B)=>Q.gen(function*(){if(B.status!=="running")return;if(yield*X(B),yield*$.flushNow(B),yield*d2.recordTerminal({runID:B.runID,status:"cancelled"}).pipe(Q.ignore),B.fiber)yield*e8.interrupt(B.fiber);B.status="cancelled",yield*$.bus.publish(j7,{sessionID:B.sessionID,runID:B.runID,status:"cancelled"}),yield*T2.succeed(B.deferred,{status:"cancelled"})}).pipe(Q.provideService(_0,B.instance)),X=(B)=>Q.gen(function*(){let W=Y$.current;if(W)yield*Q.forEach([...B.childActorIDs],(G)=>W.cancel(B.sessionID,G,"graceful").pipe(Q.ignore),{concurrency:"unbounded",discard:!0});yield*Q.forEach([...B.worktrees],(G)=>$.worktree.remove({directory:G}).pipe(Q.ignore),{concurrency:"unbounded",discard:!0}),B.worktrees.clear(),yield*Q.forEach([...B.childRunIDs],(G)=>Q.gen(function*(){let H=$.runs.get(G);if(H&&H.status==="running")yield*Z(H)}).pipe(Q.ignore),{concurrency:"unbounded",discard:!0})}).pipe(Q.provideService(_0,B.instance));return{reclaim:X,cancelEntry:Z,complete:(B)=>Q.gen(function*(){if(B.entry.status="completed",yield*$.flushNow(B.entry),yield*d2.recordTerminal({runID:B.entry.runID,status:"completed"}).pipe(Q.ignore),yield*$.bus.publish(j7,{sessionID:B.sessionID,runID:B.entry.runID,status:"completed"}),B.notifyOnTerminal!==!1)yield*$.inbox.send({receiverSessionID:B.sessionID,receiverActorID:B.parentActorID,senderSessionID:B.sessionID,senderActorID:"workflow",type:"actor_notification",content:`Workflow completed. run_id: ${B.entry.runID}
|
|
590
|
-
`+JSON.stringify(B.result??null).slice(0,4000)}).pipe(Q.ignore);yield*T2.succeed(B.entry.deferred,{status:"completed",result:B.result})}).pipe(Q.provideService(_0,B.entry.instance)),fail:(B)=>Q.gen(function*(){if(yield*X(B.entry),B.entry.status="failed",yield*$.flushNow(B.entry),yield*d2.recordTerminal({runID:B.entry.runID,status:"failed",error:B.error}).pipe(Q.ignore),yield*$.bus.publish(j7,{sessionID:B.sessionID,runID:B.entry.runID,status:"failed",error:B.error}),B.notifyOnTerminal!==!1)yield*$.inbox.send({receiverSessionID:B.sessionID,receiverActorID:B.parentActorID,senderSessionID:B.sessionID,senderActorID:"workflow",type:"actor_notification",content:`Workflow failed. run_id: ${B.entry.runID}
|
|
591
|
-
error: ${B.error}`}).pipe(Q.ignore);yield*T2.succeed(B.entry.deferred,{status:"failed",error:B.error})}).pipe(Q.provideService(_0,B.entry.instance))}}import mG from"os";function AZ($){let Z=0,X=[],Y=()=>{Z--;let J=X.shift();if(J)J()};return{run(J){return new Promise((B,W)=>{let G=()=>{Z++,J().then((H)=>{Y(),B(H)},(H)=>{Y(),W(H)})};if(Z<$)G();else X.push(G)})}}}function bB(){let $=mG.cpus().length;return Math.min(16,2*Math.max(1,$>0?$:4))}function UB($,Z){return Q.gen(function*(){if(Z)yield*d2.clearJournal($).pipe(Q.ignore);let X=yield*d2.loadJournal($);return{results:X.results,pass:X.pass,occurrences:new Map}})}function AB($,Z){let X=$.occurrences.get(Z)??0;return $.occurrences.set(Z,X+1),Z+":"+X}function MB($,Z,X,Y){return d2.appendJournalSync($,[{t:"agent",key:X,result:Y,pass:Z.pass}]).pipe(Q.ignore)}var _B=Symbol("straggler-timeout");function CB($){let Z=(H,V,K,y)=>{let j=V.timeoutMs??$.runAgentTimeoutMs;if(!j||j<=0)return K;return Q.raceFirst(K,Q.sleep(`${j} millis`).pipe(Q.as(_B))).pipe(Q.flatMap((q)=>q===_B?Q.gen(function*(){let z=$.getActor();if(z)yield*z.cancel($.sessionID,H,"graceful").pipe(Q.ignore);return yield*Q.sync(()=>{try{y?.()}catch{}}),null}):Q.succeed(q)))},X=(H,V,K={})=>{try{$.bridge.fork($.bus.publish(zB,{sessionID:$.sessionID,runID:$.runID,actorID:K.actorID,agentType:H.agentType??"general",label:H.label,phase:H.phase??$.entry.currentPhase,reason:V,errorMessage:K.errorMessage}).pipe(Q.ignore))}catch{}},Y=(H)=>H.label?H.phase?`[${H.phase}] ${H.label}`:H.label:H.phase?`[${H.phase}]`:void 0,J=(H,V,K)=>({mode:"subagent",sessionID:$.sessionID,agentType:H.agentType??"general",description:Y(H),task:V,context:"none",tools:H.tools?[...H.tools]:"INHERIT",background:!0,parentActorID:$.parentActorID,model:K,onActorID:(y)=>$.entry.childActorIDs.add(y),...H.schema?{format:{type:"json_schema",schema:H.schema,retryCount:2}}:{}}),B=async(H,V,K,y)=>{$.entry.running++,$.scheduleFlush($.entry);let j="actor-error",q,z,D=await $.bridge.promise(Q.gen(function*(){let U=yield*H.spawn(J(K,V,y));q=U.actorID;let P=yield*Z(U.actorID,K,T2.await(U.outcome).pipe(Q.map((F)=>{if(F.status!=="success")return j="actor-error",z=F.error,null;let b=K.schema?F.structured??null:F.structured??F.finalText??null;if(b===null)j="no-deliverable";return b})),()=>{j="timeout"});return $.entry.childActorIDs.delete(U.actorID),P})).catch((U)=>{return j="spawn-reject",z=U instanceof Error?U.message:String(U),null});if($.entry.running--,D!==null)$.entry.succeeded++;else $.entry.failed++,X(K,j,{actorID:q,errorMessage:z});return $.scheduleFlush($.entry),D},W=async(H,V,K,y)=>{let j="actor-error",q,z,D=await $.bridge.promise(Q.gen(function*(){let L=yield*$.worktree.makeWorktreeInfo();return yield*$.worktree.createFromInfo(L),L})).catch((L)=>{return z=L instanceof Error?L.message:String(L),null});if(!D)return X(K,"spawn-reject",{errorMessage:z}),null;$.entry.worktrees.add(D.directory);let U=await $.bridge.promise($.worktree.head(D.directory)).catch(()=>""),P=await S2.provide({directory:D.directory,fn:()=>Promise.resolve(S2.current)}),F=await $.bridge.promise(RB().pipe(Q.provideService(_0,P)));$.entry.running++,$.scheduleFlush($.entry);let b=await S2.provide({directory:D.directory,fn:()=>F.promise(Q.gen(function*(){let L=yield*H.spawn(J(K,V,y));q=L.actorID;let S=yield*Z(L.actorID,K,T2.await(L.outcome),()=>{j="timeout"});if($.entry.childActorIDs.delete(L.actorID),S===null)return null;if(S.status!=="success")j="actor-error",z=S.error;return{actorID:L.actorID,outcome:S}})).catch((L)=>{return j="spawn-reject",z=L instanceof Error?L.message:String(L),null})}).catch((L)=>{return j="spawn-reject",z=L instanceof Error?L.message:String(L),null}),O=!!b&&b.outcome.status==="success";if($.entry.running--,O)$.entry.succeeded++;else $.entry.failed++,X(K,j,{actorID:q,errorMessage:z});$.scheduleFlush($.entry);let M=b&&b.outcome.status==="success"?K.schema?b.outcome.structured??null:b.outcome.structured??b.outcome.finalText??null:null,I=U!==""&&await $.bridge.promise($.worktree.isPristine(D.directory,U)).catch(()=>!1);if(!(O&&!I))return await $.bridge.promise($.worktree.remove({directory:D.directory})).catch(()=>{return}),$.entry.worktrees.delete(D.directory),O?M:null;let E={branch:D.branch,directory:D.directory,changed:!0};if(M&&typeof M==="object"&&!Array.isArray(M))return{...M,_worktree:E};return{_worktree:E,result:M}},G=async(H,V,K)=>{if($.entry.agentCount>=$.lifecycleCap)return $.warnCapOnce(),X(H,"over-cap"),null;$.entry.agentCount++;let y=$.getActor();if(!y)throw Error("Actor service unavailable");let j=await $.bridge.promise($.resolveAgentModel(H.model,$.defaultModel,$.entry.warnedModelRefs));return K(y,V,H,j)};return(H,V)=>{let K=V??{},y=String(H);if(K.isolation!=="worktree"){let j=qB(y,{agentType:K.agentType,model:K.model,schema:K.schema,phase:K.phase}),q=AB($.journal,j);if($.journal.results.has(q))return $.entry.succeeded++,$.scheduleFlush($.entry),Promise.resolve($.journal.results.get(q));return(async()=>{let z=await $.semaphore.run(async()=>$.globalSemaphore.run(async()=>G(K,y,B)));if(z!==null)await Q.runPromise(MB($.runID,$.journal,q,z));return z})()}return $.semaphore.run(async()=>$.globalSemaphore.run(async()=>G(K,y,W)))}}async function IB($){let Z=MZ(await $),[X,Y,{QuickJSWASMModule:J}]=await Promise.all([Z.importModuleLoader().then(MZ),Z.importFFI(),import("./chunk-gp877cq5.js").then(MZ)]),B=await X();B.type="sync";let W=new Y(B);return new J(B,W)}function MZ($){return $&&"default"in $&&$.default?$.default&&"default"in $.default&&$.default.default?$.default.default:$.default:$}function kB($){let Z=typeof $=="number"?$:$.getTime();return function(){return Date.now()>Z}}var lG={type:"sync",importFFI:()=>import("./chunk-cp39f96a.js").then(($)=>$.QuickJSFFI),importModuleLoader:()=>import("./chunk-hs3vfhar.js").then(($)=>$.default)},SB=lG;var cG=IB(SB),TB=43200000,uG=67108864,oG=2654435769,pG=`
|
|
592
|
-
globalThis.parallel = (thunks) =>
|
|
593
|
-
Promise.all(thunks.map((t) => Promise.resolve().then(t)));
|
|
594
|
-
globalThis.pipeline = (items, ...stages) =>
|
|
595
|
-
Promise.all(items.map((item, index) =>
|
|
596
|
-
stages.reduce((acc, stage) => acc.then((prev) => stage(prev, item, index)), Promise.resolve(item))));
|
|
597
|
-
// Minimal, deterministic URL for dedup/host-extraction in workflow scripts.
|
|
598
|
-
// The bare QuickJS guest has no Web URL. Covers protocol/hostname/pathname/
|
|
599
|
-
// search/hash \u2014 enough for normURL-style dedup \u2014 and THROWS on inputs without
|
|
600
|
-
// a scheme+host, so scripts' try/catch fallbacks behave like the real URL.
|
|
601
|
-
globalThis.URL = class URL {
|
|
602
|
-
constructor(input) {
|
|
603
|
-
const str = String(input);
|
|
604
|
-
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*:)\\/\\/([^/?#]*)([^?#]*)(\\?[^#]*)?(#.*)?$/.exec(str);
|
|
605
|
-
if (!m) throw new TypeError("Invalid URL: " + str);
|
|
606
|
-
this.protocol = m[1].toLowerCase();
|
|
607
|
-
this.hostname = m[2];
|
|
608
|
-
this.pathname = m[3] || "/";
|
|
609
|
-
this.search = m[4] || "";
|
|
610
|
-
this.hash = m[5] || "";
|
|
611
|
-
this.host = m[2];
|
|
612
|
-
}
|
|
613
|
-
toString() { return this.protocol + "//" + this.host + this.pathname + this.search + this.hash; }
|
|
614
|
-
};
|
|
615
|
-
`,O7=($)=>{if(process.env.QQ_WF_TRACE)process.stderr.write(`[sb ${new Date().toISOString()}] ${$}
|
|
616
|
-
`)};async function hB($,Z,X={}){O7("module load begin");let Y=await cG;if(O7("module load end"),X.signal?.aborted)throw Error("workflow script aborted");let J=Y.newRuntime();J.setMemoryLimit(X.memoryLimitBytes??uG),J.setInterruptHandler(kB(Date.now()+(X.deadlineMs??TB)));let B=J.newContext(),W=[],G=[],H=(V)=>{return W.push(V),V};try{iG(B,Z,H,G);let V=(X.seed??oG)>>>0,K=B.evalCode(`
|
|
617
|
-
delete globalThis.Date;
|
|
618
|
-
(function () {
|
|
619
|
-
// mulberry32 \u2014 tiny seeded PRNG; deterministic for a given seed.
|
|
620
|
-
let s = ${V} >>> 0;
|
|
621
|
-
Math.random = function () {
|
|
622
|
-
s = (s + 0x6d2b79f5) >>> 0;
|
|
623
|
-
let t = s;
|
|
624
|
-
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
625
|
-
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
626
|
-
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
627
|
-
};
|
|
628
|
-
})();
|
|
629
|
-
delete globalThis.WeakRef;
|
|
630
|
-
delete globalThis.FinalizationRegistry;
|
|
631
|
-
`);if(K.error)K.error.dispose();else K.value.dispose();let y=B.evalCode(pG);if(y.error){let T=B.dump(y.error);throw y.error.dispose(),Error(`workflow prelude error: ${typeof T==="string"?T:JSON.stringify(T)}`)}y.value.dispose();let j=_Z(B,X.args??null);B.setProp(B.global,"args",j),j.dispose();let q=`(async () => {
|
|
632
|
-
${$}
|
|
633
|
-
})()`,z=B.evalCode(q);if(z.error){let T=B.dump(z.error);throw z.error.dispose(),Error(`workflow script error: ${typeof T==="string"?T:JSON.stringify(T)}`)}let D=H(z.value),U=1,P=50,F=50,b,O=0,M=()=>{if(J.hasPendingJob())J.executePendingJobs(),O=0;else O++;b=setTimeout(M,O<F?U:P)};b=setTimeout(M,U);let I,k=Date.now()+(X.deadlineMs??TB),E=new Promise((T,w)=>{let A=()=>{if(X.signal?.aborted){w(Error("workflow script aborted"));return}if(Date.now()>=k){w(Error("workflow script deadline exceeded"));return}I=setTimeout(A,5)};I=setTimeout(A,5)}),L,S=new Promise((T,w)=>{if(!X.signal)return;if(X.signal.aborted)return w(Error("workflow script aborted"));if(L=()=>w(Error("workflow script aborted")),X.signal.addEventListener("abort",L,{once:!0}),X.signal.aborted)L()});try{O7("resolve begin");let T=await Promise.race([B.resolvePromise(D),E,S]);if(O7("resolve end"),T.error){let A=B.dump(T.error);throw T.error.dispose(),Error(`workflow script rejected: ${typeof A==="string"?A:JSON.stringify(A)}`)}let w=H(T.value);return B.dump(w)}finally{if(clearTimeout(b),clearTimeout(I),L&&X.signal)X.signal.removeEventListener("abort",L)}}finally{for(let V of G)if(V.alive)V.dispose();for(let V of W)if(V.alive)V.dispose();B.dispose(),J.dispose()}}function iG($,Z,X,Y){for(let[J,B]of Object.entries(Z)){let W=$.newFunction(J,(...G)=>{let H=G.map((K)=>$.dump(K)),V=B(...H);if(V instanceof Promise){let K=$.newPromise();return Y.push(K),V.then((y)=>{if(!$.alive)return;let j=_Z($,y);K.resolve(j),j.dispose(),$.runtime.executePendingJobs()},(y)=>{if(!$.alive)return;let j=$.newString(y instanceof Error?y.message:String(y));K.reject(j),j.dispose(),$.runtime.executePendingJobs()}),K.settled.then(()=>{if($.alive)$.runtime.executePendingJobs()}),K.handle}return _Z($,V)});$.setProp($.global,J,X(W))}}function _Z($,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 Y=$.evalCode("JSON.parse"),J=$.unwrapResult(Y),B=$.callFunction(J,$.undefined,X);return J.dispose(),$.unwrapResult(B)}finally{X.dispose()}}import a$ from"path";import{lstat as nG,realpath as aG}from"fs/promises";async function gB($){let Z=$;while(!0)try{await nG(Z);break}catch{let Y=a$.dirname(Z);if(Y===Z)break;Z=Y}let X=await aG(Z);return a$.resolve(X,a$.relative(Z,$))}async function n$($,Z){let X=a$.resolve($,Z),[Y,J]=await Promise.all([gB(a$.resolve($)),gB(X)]);if(!B$.contains($,X)||!B$.contains(Y,J))throw Error(`workspace path escapes the workspace root: ${JSON.stringify(Z)}`);return X}function fB($){return{async readFile(Z){let X=await n$($,String(Z));if(!await B$.exists(X))return null;return B$.readText(X)},async writeFile(Z,X){let Y=await n$($,String(Z));await B$.write(Y,String(X))},async exists(Z){let X=await n$($,String(Z));return B$.exists(X)},async glob(Z){let X=await EB.scan(String(Z),{cwd:$,absolute:!0,include:"all",dot:!0});return(await Promise.all(X.map(async(J)=>{let B=a$.relative($,J);if(B===""||B===".."||B.startsWith(`..${a$.sep}`)||a$.isAbsolute(B))return;try{return await n$($,B),B}catch{return}}))).filter((J)=>J!==void 0).sort()}}}function vB($){let Z=fB($.workspaceRoot),X={...$.hooks,readFile:Z.readFile,writeFile:Z.writeFile,glob:Z.glob,exists:Z.exists};return{hooks:X,evaluate:(Y,J)=>hB(Y,X,{...J,signal:J.signal})}}import{createHash as sG}from"crypto";function mB($){return Q.fn("WorkflowRuntime.resume")(function*(Z){let X=yield*Q.promise(()=>dB.write("workflow-resume:"+Z.runID));return yield*Q.gen(function*(){let Y=$.runs.get(Z.runID);if(Y&&Y.status==="running")return{runID:Z.runID,resumed:!1};let J=yield*d2.load(Z.runID);if(!J)return{runID:Z.runID,resumed:!1};let B=yield*d2.readScript(Z.runID).pipe(Q.exit),W=i2.isSuccess(B)?B.value:"";if(!W)return{runID:Z.runID,resumed:!1};let G=sG("sha256").update(W).digest("hex"),H=J.scriptSha!==G;return yield*$.launch({script:W,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(Q.ensuring(Q.sync(()=>X[Symbol.dispose]())))})}import{createHash as uB}from"crypto";import lB from"path";var rG=/export\s+const\s+meta\s*=/;function X6($){return rG.test($)}var tG=/^[A-Za-z0-9._-]+$/;async function cB($,Z,X){if(!tG.test($))throw Error(`invalid workflow name: ${JSON.stringify($)}`);let Y=[".qitqode/workflows",".claude/workflows"];for(let J of await eG($,Y,Z,X))return B$.readText(J);return null}async function eG($,Z,X,Y){if(!B$.contains(Y,X))return[];let J=[],B=X;for(;;){for(let G of Z){let H=lB.join(B,G,`${$}.js`);if(await B$.exists(H))J.push(H)}if(B===Y)break;let W=lB.dirname(B);if(W===B)break;B=W}return J}function oB($){let Z=(B)=>{let W=String(B);$.entry.currentPhase=W,$.entry.transcript.push({kind:"phase",text:W}),$.bridge.fork(d2.recordPhase({runID:$.runID,phase:W}).pipe(Q.ignore)),$.bridge.fork(d2.appendJournal($.runID,{t:"phase",title:W,pass:$.journal.pass}).pipe(Q.ignore)),$.bridge.fork($.bus.publish(jB,{sessionID:$.sessionID,runID:$.runID,title:W}));return},X=(B)=>{let W=String(B);$.entry.transcript.push({kind:"log",text:W}),$.bridge.fork(d2.appendJournal($.runID,{t:"log",msg:W,pass:$.journal.pass}).pipe(Q.ignore)),$.bridge.fork($.bus.publish(OB,{sessionID:$.sessionID,runID:$.runID,message:W}));return},Y=new Map;return{phase:Z,logHook:X,workflowHook:(B,W,G)=>{let H=String(B),V=G??{},K=uB("sha256").update(JSON.stringify({spec:H,args:W??null})).digest("hex"),y=Y.get(K)??0;Y.set(K,y+1);let j=K+":"+y;if($.journal.results.has("wf:"+j))return $.entry.succeeded++,$.scheduleFlush($.entry),Promise.resolve($.journal.results.get("wf:"+j));let q="wf_"+uB("sha256").update($.runID+j).digest("hex");return $.bridge.promise(Q.gen(function*(){let z=X6(H)?H:yield*Q.promise(()=>cB(H,$.workspaceRoot,S2.worktree));if(z===null)return yield*Q.die(Error(`${$.structuralError}: unknown workflow: ${JSON.stringify(H)}`));let D=X6(H)?"inline:"+K.slice(0,12):H;if($.depth+1>$.maxDepth)return yield*Q.die(Error(`${$.structuralError}: workflow nesting exceeds maxDepth (${$.maxDepth})`));if($.lineage.includes(D))return yield*Q.die(Error(`${$.structuralError}: workflow cycle detected: ${D} is already an ancestor`));$.entry.childRunIDs.add(q),yield*$.launch({script:z,sessionID:$.sessionID,parentActorID:$.parentActorID,args:W,model:$.model,workspace:V.workspace?yield*Q.promise(()=>n$($.workspaceRoot,String(V.workspace))):$.workspaceRoot,maxConcurrentAgents:V.maxConcurrentAgents,scriptDeadlineMs:$.scriptDeadlineMs,lineage:[...$.lineage,D],depth:$.depth+1,maxDepth:$.maxDepth,notifyOnTerminal:!1},q,X6(H)?"inline":H);let U=yield*$.waitFor(q);if(U.status==="failed"&&U.error.includes($.structuralError)){let F=U.error.indexOf($.structuralError);return yield*Q.die(Error(U.error.slice(F)))}if(U.status!=="completed")yield*$.bus.publish(yB,{sessionID:$.sessionID,runID:$.runID,childRunID:q,name:X6(H)?"inline":H,status:U.status,...U.status==="failed"?{error:U.error}:{}}).pipe(Q.ignore);let P=U.status==="completed"?U.result??null:null;if(P!==null)yield*d2.appendJournalSync($.runID,[{t:"agent",key:"wf:"+j,result:P,pass:$.journal.pass}]).pipe(Q.ignore);return P}))}}}var RZ=a.create({service:"workflow.runtime"}),s$=($)=>{if(process.env.QQ_WF_TRACE)process.stderr.write(`[wf ${new Date().toISOString()}] ${$}
|
|
634
|
-
`)},$j=43200000,Zj=1000,Xj="WorkflowStructuralError";class z7 extends Z2.Service()("@qitqode/WorkflowRuntime"){}var iB=_.effect(z7,Q.gen(function*(){let $=yield*p.Service,Z=yield*i0.Service,X=yield*p$.Service,Y=yield*z2.Service,J=yield*B2.Service,B=yield*l2.Scope,W=new UZ,G=(w,A,R)=>w===void 0?Q.succeed(A):Y.resolveModelRef(w).pipe(Q.map((C)=>({providerID:C.providerID,modelID:C.id})),Q.catchCause(()=>Q.sync(()=>{let C=typeof w==="string"?w:`{${Object.keys(w).sort().join(",")}}`;if(!R.has(C))R.add(C),RZ.warn("workflow agent model ref did not resolve \u2014 using run default",{ref:C});return A}))),H,V=0,K,y=Q.fn("WorkflowRuntime.ensureGlobal")(function*(){if(K)return K;return H??=yield*J.get(),V=Math.max(1,H.workflow?.maxConcurrentAgents??bB()),K??=AZ(V),K}),j=new Map,q=(w)=>{let A=j.get(w.runID);if(A)clearTimeout(A),j.delete(w.runID);return d2.flushCounters({runID:w.runID,running:w.running,succeeded:w.succeeded,failed:w.failed}).pipe(Q.ignore)},z=(w)=>{if(j.has(w.runID))return;j.set(w.runID,setTimeout(()=>{j.delete(w.runID),Q.runFork(d2.flushCounters({runID:w.runID,running:w.running,succeeded:w.succeeded,failed:w.failed}).pipe(Q.ignore))},250))},D=LB({runs:W,bus:$,inbox:Z,worktree:X,flushNow:q}),U=(w)=>Q.gen(function*(){let A=W.get(w);if(!A)return{status:"failed",error:"child run missing"};return yield*T2.await(A.deferred)}),P=Q.fn("WorkflowRuntime.launch")(function*(w,A,R){let C=NZ(w.script),g=C.ok?C.body:w.script,l=w.workspace?yield*Q.promise(()=>n$(S2.worktree,w.workspace)):S2.worktree,m=S2.current,h=yield*T2.make(),f={runID:A,sessionID:w.sessionID,instance:m,status:"running",deferred:h,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:[]};W.set(f);let v=pB("sha256").update(w.script).digest("hex");s$(`launch begin ${A}`),yield*d2.recordStart({runID:A,sessionID:w.sessionID,name:R,parentActorID:w.parentActorID,args:w.args,scriptSha:v,agentTimeoutMs:w.agentTimeoutMs}).pipe(Q.ignore),yield*d2.writeScript(A,w.script).pipe(Q.ignore);let e=yield*UB(A,w.freshJournal??!1),n=yield*D0.make(),s=yield*y(),G2=w.lineage??[],C2=w.depth??0,t=w.maxDepth??H?.workflow?.maxDepth??8,N2=w.maxConcurrentAgents??V,j2=Math.max(1,Math.min(N2,V)),g0=AZ(j2),I2=w.maxLifecycleAgents??H?.workflow?.maxLifecycleAgents??Zj,Q2=()=>{if(f.capWarned)return;f.capWarned=!0,RZ.warn("workflow lifecycle agent cap reached \u2014 over-cap agents return null",{runID:A,cap:I2})},q2=w.agentTimeoutMs,L2=CB({runID:A,sessionID:w.sessionID,parentActorID:w.parentActorID,defaultModel:w.model,runAgentTimeoutMs:q2,lifecycleCap:I2,entry:f,bridge:n,bus:$,worktree:X,getActor:()=>Y$.current,resolveAgentModel:G,journal:e,semaphore:g0,globalSemaphore:s,scheduleFlush:z,warnCapOnce:Q2});yield*$.publish(FB,{sessionID:w.sessionID,runID:A,name:R});let e2=oB({runID:A,sessionID:w.sessionID,parentActorID:w.parentActorID,model:w.model,scriptDeadlineMs:w.scriptDeadlineMs,workspaceRoot:l,lineage:G2,depth:C2,maxDepth:t,entry:f,bridge:n,bus:$,journal:e,scheduleFlush:z,launch:P,waitFor:U,structuralError:Xj}),{phase:w0,logHook:E0,workflowHook:R0}=e2,f0=vB({workspaceRoot:l,hooks:{agent:L2,phase:w0,log:E0,workflow:R0}}),O$=Q.gen(function*(){let a0=pB("sha1").update(A).digest().readUInt32BE(0);s$(`eval begin ${A}`);let s0=yield*Q.tryPromise({try:(F$)=>f0.evaluate(g,{deadlineMs:w.scriptDeadlineMs??$j,args:w.args,seed:a0,signal:F$}),catch:(F$)=>F$ instanceof Error?F$:Error(String(F$))}).pipe(Q.result);if(s$(`eval end ${A} ${s0._tag}`),s0._tag==="Success"){yield*D.complete({entry:f,sessionID:w.sessionID,parentActorID:w.parentActorID,result:s0.success,notifyOnTerminal:w.notifyOnTerminal}),s$(`flushed ${A}`),s$(`terminal-recorded ${A}`),s$(`published ${A}`),s$(`deferred-succeeded ${A}`);return}let N1=s0.failure instanceof Error?s0.failure.message:String(s0.failure);RZ.warn("workflow run failed",{runID:A,error:N1}),yield*D.fail({entry:f,sessionID:w.sessionID,parentActorID:w.parentActorID,error:N1,notifyOnTerminal:w.notifyOnTerminal})});return f.fiber=yield*O$.pipe(Q.provideService(_0,m),Q.forkIn(B)),s$(`launched ${A}`),{runID:A}}),F=Q.fn("WorkflowRuntime.start")(function*(w){let A=NZ(w.script);if(!A.ok)return yield*Q.die(A.error);let R=O8.descending("workflow");return yield*P(w,R,A.meta.name)}),b=Q.fn("WorkflowRuntime.status")(function*(w){let A=W.get(w.runID);if(!A)return{status:"unknown",agentCount:0};return{status:A.status,agentCount:A.agentCount,...A.currentPhase!==void 0?{currentPhase:A.currentPhase}:{}}}),O=Q.fn("WorkflowRuntime.transcript")(function*(w){let A=W.get(w.runID);return A?A.transcript.slice():[]}),M=Q.fn("WorkflowRuntime.wait")(function*(w){let A=W.get(w.runID);if(!A)return{status:"failed",error:`unknown runID ${w.runID}`};if(w.timeoutMs===void 0)return yield*T2.await(A.deferred);let R=yield*T2.await(A.deferred).pipe(Q.timeout(w.timeoutMs),Q.catchTag("TimeoutError",()=>Q.succeed(null)));if(R===null)return{status:"failed",error:"workflow wait timed out"};return R}),I=Q.fn("WorkflowRuntime.cancel")(function*(w){let A=W.get(w.runID);if(!A)return;yield*D.cancelEntry(A)}),k=Q.fn("WorkflowRuntime.list")(function*(w){return yield*d2.list(w)}),E=mB({runs:W,launch:P}),L=z7.of({start:F,status:b,wait:M,transcript:O,cancel:I,list:k,resume:E}),S=!1,T=Q.gen(function*(){if(S)return;S=!0,yield*Q.forEach([...W.values()],(w)=>(w.status==="running"?D.cancelEntry(w):Q.void).pipe(Q.ignore),{concurrency:1,discard:!0});for(let w of j.values())clearTimeout(w);j.clear(),W.clear()});return F7.current=L,yield*Q.addFinalizer(()=>T),yield*Q.addFinalizer(()=>Q.sync(()=>{if(F7.current===L)F7.current=void 0})),L})),Qj=iB.pipe(_.provide(p.defaultLayer),_.provide(i0.defaultLayer),_.provide(p$.defaultLayer),_.provide(z2.defaultLayer),_.provide(B2.defaultLayer));var Yj=_.suspend(()=>_.mergeAll(aB.defaultLayer,s2.defaultLayer,p.defaultLayer,I$.defaultLayer,p8.defaultLayer,B2.defaultLayer,u$.defaultLayer,sB.defaultLayer,j8.defaultLayer,o$.defaultLayer,k$.defaultLayer,q0.defaultLayer,H2.defaultLayer,z2.defaultLayer,XW.defaultLayer,E2.defaultLayer,z$.defaultLayer,rB.defaultLayer,C6.defaultLayer,y2.defaultLayer,$W.defaultLayer,J2.defaultLayer,z0.defaultLayer,y0.defaultLayer,m0.defaultLayer,c0.defaultLayer,q$.defaultLayer,N$.defaultLayer,$$.defaultLayer,P0.defaultLayer,c$.defaultLayer,P$.defaultLayer,G$.defaultLayer,f2.defaultLayer,J$.defaultLayer,N0.defaultLayer,g$.defaultLayer,G0.defaultLayer,j1.defaultLayer,K0.defaultLayer,G8.defaultLayer,M$.defaultLayer,y1.defaultLayer,p$.defaultLayer,r8.defaultLayer,ZW.defaultLayer,_$.defaultLayer,e4.defaultLayer,_2.defaultLayer,eB.defaultLayer,$6.defaultLayer,M0.defaultLayer,Q6.defaultLayer,y$.defaultLayer,Q7.defaultLayer).pipe(_.provideMerge(Z7),_.provideMerge(tB))),F8=$7.make(Yj,{memoMap:X7}),Y6=($)=>nB($),EC={runSync($){return F8.runSync(Y6($))},runPromise($,Z){return F8.runPromise(Y6($),Z)},runPromiseExit($,Z){return F8.runPromiseExit(Y6($),Z)},runFork($){return F8.runFork(Y6($))},runCallback($){return F8.runCallback(Y6($))},dispose:()=>F8.dispose()};
|
|
635
|
-
export{y1 as Cg,g$ as Dg,k8 as Eg,X0 as Fg,S8 as Gg,h8 as Hg,b4 as Ig,N0 as Jg,G0 as Kg,_$ as Lg,e4 as Mg,oJ as Ng,p$ as Og,s5 as Pg,z0 as Qg,y0 as Rg,P0 as Sg,$$ as Tg,q$ as Ug,c$ as Vg,n8 as Wg,r8 as Xg,Yj as Yg,EC as Zg};
|