@bkm016/basalt 0.1.21 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{chunk-51a0843g.js → chunk-09tdbx7b.js} +1 -1
- package/{chunk-225dyk1y.js → chunk-0rsyawz5.js} +1 -1
- package/{chunk-y8mf9tcj.js → chunk-1td9hjn9.js} +8 -8
- package/{chunk-g6cc7ac1.js → chunk-1xjkzzyh.js} +2 -2
- package/{chunk-43qf44t8.js → chunk-38932kzp.js} +2 -2
- package/{chunk-gdx1j9c5.js → chunk-5415fcz7.js} +2 -2
- package/{chunk-3phf8eg6.js → chunk-5kezbmgw.js} +2 -2
- package/{chunk-qz6ybxjg.js → chunk-5ph58x6w.js} +8 -8
- package/{chunk-kgnd32hn.js → chunk-6jdqe7sz.js} +1 -1
- package/{chunk-2m2sa0bp.js → chunk-6ztgzx9s.js} +1 -1
- package/{chunk-3r38vbt5.js → chunk-7dzcdpdt.js} +1 -1
- package/{chunk-kka12j10.js → chunk-82djd5fk.js} +1 -1
- package/{chunk-x1y4s01x.js → chunk-86vhsd3y.js} +11 -11
- package/{chunk-jhwb962k.js → chunk-8rfv9mm1.js} +9 -9
- package/{chunk-m9386732.js → chunk-8tvz5ht1.js} +2 -2
- package/{chunk-ve1b6vg6.js → chunk-9pjmwz01.js} +1 -1
- package/{chunk-ewaskman.js → chunk-9wjd9bxm.js} +1 -1
- package/chunk-b49005n2.js +471 -0
- package/{chunk-feyt85gg.js → chunk-bdz2561d.js} +1 -1
- package/{chunk-3t8wz9w8.js → chunk-bkvhwgeb.js} +1 -1
- package/{chunk-kypdthjg.js → chunk-bp9tfav3.js} +1 -1
- package/{chunk-ak95r8mq.js → chunk-cc9htxzx.js} +216 -215
- package/chunk-chfzk1fx.js +3 -0
- package/{chunk-syhhzr1j.js → chunk-cv5kdnsw.js} +2 -2
- package/{chunk-sq5ppnr3.js → chunk-d79s1s4t.js} +3 -3
- package/{chunk-qn70tm91.js → chunk-ec6bzt7w.js} +3 -3
- package/{chunk-h00wjps7.js → chunk-eq54cmsa.js} +1 -1
- package/{chunk-03b5jh31.js → chunk-g54nd4fd.js} +1 -1
- package/{chunk-2fymxwe7.js → chunk-g8p5c4vx.js} +5 -5
- package/{chunk-tmq8ktys.js → chunk-g9bemxpt.js} +1 -1
- package/{chunk-35y6nf6k.js → chunk-hk5p2eee.js} +4 -4
- package/{chunk-9t3v8c3m.js → chunk-jerp4pj5.js} +1 -1
- package/{chunk-0x0459qp.js → chunk-jsvqp20s.js} +1 -1
- package/{chunk-85sjfyjd.js → chunk-kb526065.js} +1 -1
- package/{chunk-cjh5h31t.js → chunk-kpw1qa2n.js} +3 -3
- package/{chunk-97ntcrm7.js → chunk-mbvy2t23.js} +1 -1
- package/{chunk-ttv805sb.js → chunk-mmnsdje8.js} +5 -5
- package/{chunk-9x28stv0.js → chunk-nffwakxq.js} +1 -1
- package/{chunk-wxzk086k.js → chunk-nfj8sj53.js} +1 -1
- package/{chunk-ak9rkrf3.js → chunk-pzwaz2ew.js} +2 -2
- package/{chunk-jy07y4pv.js → chunk-qtrd33pp.js} +5 -5
- package/{chunk-hhxtc9jn.js → chunk-rbk6jxcr.js} +1 -1
- package/{chunk-c5ydt3vq.js → chunk-rx812nrp.js} +2 -2
- package/{chunk-h1fwdz4h.js → chunk-sfgw0vmt.js} +1 -1
- package/chunk-tmefdwxy.js +2 -0
- package/chunk-tvg54x0x.js +2 -0
- package/chunk-v89f2k9b.js +2 -0
- package/{chunk-z4g2q36h.js → chunk-vhe16b65.js} +2 -2
- package/{chunk-np123myw.js → chunk-w4kasz4j.js} +4 -4
- package/{chunk-4fj91gt1.js → chunk-w4zkgn1c.js} +2 -2
- package/chunk-we5emq6f.js +2 -0
- package/{chunk-jpwr1sd2.js → chunk-x0dcabw6.js} +2 -2
- package/{chunk-ntntwtxn.js → chunk-xtj7b70y.js} +2 -2
- package/{chunk-bn1aaewd.js → chunk-xwew53k7.js} +4 -4
- package/{chunk-e8xywvv4.js → chunk-xyhr89y5.js} +1 -1
- package/{chunk-hrn2ss1a.js → chunk-yce46csn.js} +1 -1
- package/{chunk-ftg4b5pa.js → chunk-yetcb1z9.js} +2 -2
- package/chunk-ypmpf75h.js +2 -0
- package/chunk-zz48zvk5.js +2 -0
- package/compiled.js +5 -5
- package/package.json +1 -1
- package/ui-test-worker.js +1 -1
- package/web/chunk-04c54f1s.js +1 -0
- package/web/chunk-04c54f1s.js.br +2 -0
- package/web/chunk-04c54f1s.js.gz +0 -0
- package/web/chunk-04m1cb8w.js +1 -0
- package/web/chunk-04m1cb8w.js.br +0 -0
- package/web/chunk-04m1cb8w.js.gz +0 -0
- package/web/{chunk-j2y3wkxc.js → chunk-08z6mkgz.js} +1 -1
- package/web/chunk-08z6mkgz.js.br +0 -0
- package/web/chunk-08z6mkgz.js.gz +0 -0
- package/web/{chunk-yw5wyz1q.js → chunk-0g9m3rpw.js} +1 -1
- package/web/chunk-0g9m3rpw.js.br +0 -0
- package/web/chunk-0g9m3rpw.js.gz +0 -0
- package/web/{chunk-5vc1wkwb.js → chunk-0jccrdw3.js} +1 -1
- package/web/chunk-0jccrdw3.js.br +0 -0
- package/web/chunk-0jccrdw3.js.gz +0 -0
- package/web/{chunk-yarsp7h7.js → chunk-0vweazdh.js} +1 -1
- package/web/chunk-0vweazdh.js.br +0 -0
- package/web/chunk-0vweazdh.js.gz +0 -0
- package/web/chunk-1vtf555r.js +1 -0
- package/web/chunk-1vtf555r.js.br +0 -0
- package/web/chunk-1vtf555r.js.gz +0 -0
- package/web/{chunk-2h2w244w.js → chunk-29z0ft67.js} +1 -1
- package/web/chunk-29z0ft67.js.br +0 -0
- package/web/chunk-29z0ft67.js.gz +0 -0
- package/web/{chunk-v7ck87jf.js → chunk-2q3m4btb.js} +1 -1
- package/web/chunk-2q3m4btb.js.br +0 -0
- package/web/chunk-2q3m4btb.js.gz +0 -0
- package/web/{chunk-b83bzjcx.js → chunk-2s6fhjjc.js} +90 -90
- package/web/chunk-2s6fhjjc.js.br +0 -0
- package/web/chunk-2s6fhjjc.js.gz +0 -0
- package/web/{chunk-rsc5k5he.js → chunk-2vdx4ykn.js} +1 -1
- package/web/chunk-2vdx4ykn.js.br +0 -0
- package/web/chunk-2vdx4ykn.js.gz +0 -0
- package/web/{chunk-0w6ta3ps.js → chunk-2zgqe8r7.js} +1 -1
- package/web/chunk-2zgqe8r7.js.br +0 -0
- package/web/chunk-2zgqe8r7.js.gz +0 -0
- package/web/{chunk-07dd0jed.js → chunk-3kqpmg83.js} +1 -1
- package/web/chunk-3kqpmg83.js.br +0 -0
- package/web/chunk-3kqpmg83.js.gz +0 -0
- package/web/chunk-3rmqxna0.js +1 -0
- package/web/chunk-3rmqxna0.js.br +0 -0
- package/web/chunk-3rmqxna0.js.gz +0 -0
- package/web/{chunk-vvk9nche.js → chunk-3xmv2349.js} +2 -2
- package/web/chunk-3xmv2349.js.br +0 -0
- package/web/chunk-3xmv2349.js.gz +0 -0
- package/web/{chunk-wh0vt2vd.js → chunk-46cdys11.js} +1 -1
- package/web/chunk-46cdys11.js.br +0 -0
- package/web/{chunk-wh0vt2vd.js.gz → chunk-46cdys11.js.gz} +0 -0
- package/web/chunk-46mw23f0.js +8 -0
- package/web/chunk-46mw23f0.js.br +0 -0
- package/web/chunk-46mw23f0.js.gz +0 -0
- package/web/{chunk-n00se8nk.js → chunk-4r0dvjrr.js} +1 -1
- package/web/chunk-4r0dvjrr.js.br +0 -0
- package/web/chunk-4r0dvjrr.js.gz +0 -0
- package/web/{chunk-16b5anw4.js → chunk-4v6m84pg.js} +1 -1
- package/web/chunk-4v6m84pg.js.br +0 -0
- package/web/chunk-4v6m84pg.js.gz +0 -0
- package/web/{chunk-c69t0ysj.js → chunk-4ye31s2w.js} +1 -1
- package/web/chunk-4ye31s2w.js.br +4 -0
- package/web/chunk-4ye31s2w.js.gz +0 -0
- package/web/{chunk-kr7shpnb.js → chunk-5kavsn22.js} +1 -1
- package/web/chunk-5kavsn22.js.br +0 -0
- package/web/{chunk-kr7shpnb.js.gz → chunk-5kavsn22.js.gz} +0 -0
- package/web/{chunk-m7kypzvp.js → chunk-5q2h4tg8.js} +1 -1
- package/web/chunk-5q2h4tg8.js.br +4 -0
- package/web/chunk-5q2h4tg8.js.gz +0 -0
- package/web/{chunk-gt4dzb4b.js → chunk-5tbk6dx6.js} +1 -1
- package/web/chunk-5tbk6dx6.js.br +0 -0
- package/web/chunk-5tbk6dx6.js.gz +0 -0
- package/web/{chunk-ffwyfdg4.js → chunk-5yb0sm1r.js} +1 -1
- package/web/chunk-5yb0sm1r.js.br +0 -0
- package/web/chunk-5yb0sm1r.js.gz +0 -0
- package/web/chunk-5yz46tjw.js +2 -0
- package/web/chunk-5yz46tjw.js.br +0 -0
- package/web/chunk-5yz46tjw.js.gz +0 -0
- package/web/{chunk-hw4f79k8.js → chunk-619a8t38.js} +1 -1
- package/web/chunk-619a8t38.js.br +0 -0
- package/web/chunk-619a8t38.js.gz +0 -0
- package/web/{chunk-7remkcff.js → chunk-6areryyn.js} +1 -1
- package/web/chunk-6areryyn.js.br +0 -0
- package/web/chunk-6areryyn.js.gz +0 -0
- package/web/{chunk-5wgdprjp.js → chunk-6ms78sx5.js} +1 -1
- package/web/chunk-6ms78sx5.js.br +0 -0
- package/web/chunk-6ms78sx5.js.gz +0 -0
- package/web/{chunk-50wrjr22.js → chunk-6ts9mtye.js} +1 -1
- package/web/chunk-6ts9mtye.js.br +0 -0
- package/web/chunk-6ts9mtye.js.gz +0 -0
- package/web/{chunk-abahqsws.js → chunk-79whhay2.js} +1 -1
- package/web/chunk-79whhay2.js.br +0 -0
- package/web/chunk-79whhay2.js.gz +0 -0
- package/web/{chunk-jge5e8c4.js → chunk-7n1abr86.js} +1 -1
- package/web/chunk-7n1abr86.js.br +0 -0
- package/web/chunk-7n1abr86.js.gz +0 -0
- package/web/chunk-7qxfx983.js +1 -0
- package/web/chunk-7qxfx983.js.br +0 -0
- package/web/chunk-7qxfx983.js.gz +0 -0
- package/web/chunk-91k30q92.js +1 -0
- package/web/chunk-91k30q92.js.br +0 -0
- package/web/chunk-91k30q92.js.gz +0 -0
- package/web/{chunk-78t5dqea.js → chunk-91nyvkrb.js} +1 -1
- package/web/chunk-91nyvkrb.js.br +0 -0
- package/web/chunk-91nyvkrb.js.gz +0 -0
- package/web/{chunk-0q5drhbk.js → chunk-9mbr6znb.js} +1 -1
- package/web/chunk-9mbr6znb.js.br +0 -0
- package/web/chunk-9mbr6znb.js.gz +0 -0
- package/web/{chunk-h4g8j133.js → chunk-9mvw6a5v.js} +1 -1
- package/web/chunk-9mvw6a5v.js.br +0 -0
- package/web/chunk-9mvw6a5v.js.gz +0 -0
- package/web/{chunk-2hd51wb6.js → chunk-a6hdn8tb.js} +1 -1
- package/web/chunk-a6hdn8tb.js.br +0 -0
- package/web/chunk-a6hdn8tb.js.gz +0 -0
- package/web/{chunk-e6r1sb5r.js → chunk-ar6m9fza.js} +1 -1
- package/web/chunk-ar6m9fza.js.br +0 -0
- package/web/chunk-ar6m9fza.js.gz +0 -0
- package/web/{chunk-d4kjy2qn.js → chunk-ayqakyyq.js} +1 -1
- package/web/chunk-ayqakyyq.js.br +0 -0
- package/web/chunk-ayqakyyq.js.gz +0 -0
- package/web/{chunk-4zftsyq2.js → chunk-cc6hn5xv.js} +1 -1
- package/web/chunk-cc6hn5xv.js.br +0 -0
- package/web/chunk-cc6hn5xv.js.gz +0 -0
- package/web/{chunk-0hvyq55w.js → chunk-ccymg1hp.js} +1 -1
- package/web/chunk-ccymg1hp.js.br +0 -0
- package/web/chunk-ccymg1hp.js.gz +0 -0
- package/web/{chunk-55kw8p9r.js → chunk-cg9fe42b.js} +1 -1
- package/web/chunk-cg9fe42b.js.br +0 -0
- package/web/chunk-cg9fe42b.js.gz +0 -0
- package/web/chunk-cmcgmf94.js +1 -0
- package/web/chunk-cmcgmf94.js.br +0 -0
- package/web/chunk-cmcgmf94.js.gz +0 -0
- package/web/chunk-cnbbvd6n.js +1 -0
- package/web/chunk-cnbbvd6n.js.br +0 -0
- package/web/chunk-cnbbvd6n.js.gz +0 -0
- package/web/{chunk-8c6h952g.js → chunk-cxp2nbtc.js} +1 -1
- package/web/chunk-cxp2nbtc.js.br +0 -0
- package/web/chunk-cxp2nbtc.js.gz +0 -0
- package/web/{chunk-j7sfcfxr.js → chunk-dj2b64aj.js} +1 -1
- package/web/chunk-dj2b64aj.js.br +0 -0
- package/web/chunk-dj2b64aj.js.gz +0 -0
- package/web/{chunk-2w4rdnhj.js → chunk-dsga6rp3.js} +1 -1
- package/web/chunk-dsga6rp3.js.br +0 -0
- package/web/chunk-dsga6rp3.js.gz +0 -0
- package/web/chunk-ek6q6a08.js +1 -0
- package/web/chunk-ek6q6a08.js.br +2 -0
- package/web/chunk-ek6q6a08.js.gz +0 -0
- package/web/{chunk-21d8pzcm.js → chunk-et1nm6h1.js} +2 -2
- package/web/chunk-et1nm6h1.js.br +0 -0
- package/web/chunk-et1nm6h1.js.gz +0 -0
- package/web/chunk-f1016wh6.js +1 -0
- package/web/chunk-f1016wh6.js.br +0 -0
- package/web/chunk-f1016wh6.js.gz +0 -0
- package/web/{chunk-z7adzvfz.js → chunk-f42mwg61.js} +1 -1
- package/web/chunk-f42mwg61.js.br +0 -0
- package/web/chunk-f42mwg61.js.gz +0 -0
- package/web/{chunk-pvhz0gqy.js → chunk-fk35d3bz.js} +1 -1
- package/web/chunk-fk35d3bz.js.br +0 -0
- package/web/chunk-fk35d3bz.js.gz +0 -0
- package/web/{chunk-keway722.js → chunk-fpwztdhn.js} +1 -1
- package/web/chunk-fpwztdhn.js.br +0 -0
- package/web/chunk-fpwztdhn.js.gz +0 -0
- package/web/{chunk-qcgs1mft.js → chunk-g30nqfka.js} +1 -1
- package/web/chunk-g30nqfka.js.br +0 -0
- package/web/chunk-g30nqfka.js.gz +0 -0
- package/web/chunk-gbwy4pfg.css +1 -0
- package/web/chunk-gbwy4pfg.css.br +0 -0
- package/web/chunk-gbwy4pfg.css.gz +0 -0
- package/web/{chunk-31vxes2p.js → chunk-gepgx19m.js} +1 -1
- package/web/chunk-gepgx19m.js.br +0 -0
- package/web/chunk-gepgx19m.js.gz +0 -0
- package/web/{chunk-62z94rt2.js → chunk-grz69q28.js} +1 -1
- package/web/chunk-grz69q28.js.br +0 -0
- package/web/chunk-grz69q28.js.gz +0 -0
- package/web/{chunk-acv6gk2b.js → chunk-gt62acsh.js} +1 -1
- package/web/chunk-gt62acsh.js.br +0 -0
- package/web/chunk-gt62acsh.js.gz +0 -0
- package/web/{chunk-w5c2r59n.js → chunk-h28xrvmg.js} +1 -1
- package/web/chunk-h28xrvmg.js.br +0 -0
- package/web/chunk-h28xrvmg.js.gz +0 -0
- package/web/{chunk-56tqa12m.js → chunk-h80ypke7.js} +1 -1
- package/web/chunk-h80ypke7.js.br +0 -0
- package/web/chunk-h80ypke7.js.gz +0 -0
- package/web/chunk-k1cd6e24.js +1 -0
- package/web/chunk-k1cd6e24.js.br +0 -0
- package/web/chunk-k1cd6e24.js.gz +0 -0
- package/web/chunk-k9248573.js +1 -0
- package/web/chunk-k9248573.js.br +0 -0
- package/web/chunk-k9248573.js.gz +0 -0
- package/web/{chunk-cbtpaf3e.js → chunk-kqgn9dsa.js} +1 -1
- package/web/chunk-kqgn9dsa.js.br +0 -0
- package/web/chunk-kqgn9dsa.js.gz +0 -0
- package/web/chunk-kqngpw5m.js +1 -0
- package/web/chunk-kqngpw5m.js.br +0 -0
- package/web/chunk-kqngpw5m.js.gz +0 -0
- package/web/{chunk-d1gga18f.js → chunk-kzj105r1.js} +1 -1
- package/web/chunk-kzj105r1.js.br +0 -0
- package/web/chunk-kzj105r1.js.gz +0 -0
- package/web/chunk-m14v2en1.js +1 -0
- package/web/chunk-m14v2en1.js.br +0 -0
- package/web/chunk-m14v2en1.js.gz +0 -0
- package/web/{chunk-2dykyq1n.js → chunk-m34et8g4.js} +1 -1
- package/web/chunk-m34et8g4.js.br +0 -0
- package/web/chunk-m34et8g4.js.gz +0 -0
- package/web/{chunk-60fbfw70.js → chunk-md1f6gmk.js} +1 -1
- package/web/chunk-md1f6gmk.js.br +0 -0
- package/web/chunk-md1f6gmk.js.gz +0 -0
- package/web/{chunk-fbzhgaak.js → chunk-n05xf20n.js} +1 -1
- package/web/chunk-n05xf20n.js.br +0 -0
- package/web/chunk-n05xf20n.js.gz +0 -0
- package/web/{chunk-zb01zmms.js → chunk-n2k1gd6n.js} +1 -1
- package/web/chunk-n2k1gd6n.js.br +0 -0
- package/web/chunk-n2k1gd6n.js.gz +0 -0
- package/web/{chunk-s7a2f62f.js → chunk-nm8yza3v.js} +1 -1
- package/web/chunk-nm8yza3v.js.br +0 -0
- package/web/chunk-nm8yza3v.js.gz +0 -0
- package/web/chunk-pbg9rdwv.js +1 -0
- package/web/chunk-pbg9rdwv.js.br +2 -0
- package/web/chunk-pbg9rdwv.js.gz +0 -0
- package/web/{chunk-8wgev3hd.js → chunk-qj9nd038.js} +1 -1
- package/web/chunk-qj9nd038.js.br +0 -0
- package/web/chunk-qj9nd038.js.gz +0 -0
- package/web/chunk-qjaex9c0.js +1 -0
- package/web/chunk-qjaex9c0.js.br +2 -0
- package/web/chunk-qjaex9c0.js.gz +0 -0
- package/web/{chunk-2c4affp1.js → chunk-qq79vsm8.js} +1 -1
- package/web/chunk-qq79vsm8.js.br +0 -0
- package/web/chunk-qq79vsm8.js.gz +0 -0
- package/web/{chunk-t0xjx21h.js → chunk-qs5wnwd6.js} +1 -1
- package/web/chunk-qs5wnwd6.js.br +0 -0
- package/web/chunk-qs5wnwd6.js.gz +0 -0
- package/web/{chunk-595tqsv5.js → chunk-r381n550.js} +1 -1
- package/web/chunk-r381n550.js.br +0 -0
- package/web/chunk-r381n550.js.gz +0 -0
- package/web/{chunk-2tc6krye.js → chunk-r48vazdm.js} +1 -1
- package/web/chunk-r48vazdm.js.br +0 -0
- package/web/chunk-r48vazdm.js.gz +0 -0
- package/web/{chunk-ngdj0r7w.js → chunk-r55seq42.js} +1 -1
- package/web/chunk-r55seq42.js.br +0 -0
- package/web/chunk-r55seq42.js.gz +0 -0
- package/web/{chunk-gs41j1vb.js → chunk-r79zekav.js} +1 -1
- package/web/chunk-r79zekav.js.br +0 -0
- package/web/chunk-r79zekav.js.gz +0 -0
- package/web/{chunk-fztzcy7c.js → chunk-r8qyvcks.js} +1 -1
- package/web/chunk-r8qyvcks.js.br +0 -0
- package/web/chunk-r8qyvcks.js.gz +0 -0
- package/web/chunk-r9dt0730.js +1 -0
- package/web/chunk-r9dt0730.js.br +0 -0
- package/web/chunk-r9dt0730.js.gz +0 -0
- package/web/{chunk-82zwwy0b.js → chunk-rpjzwknn.js} +1 -1
- package/web/chunk-rpjzwknn.js.br +0 -0
- package/web/{chunk-82zwwy0b.js.gz → chunk-rpjzwknn.js.gz} +0 -0
- package/web/{chunk-c37hhmtd.js → chunk-sk3065js.js} +1 -1
- package/web/chunk-sk3065js.js.br +0 -0
- package/web/chunk-sk3065js.js.gz +0 -0
- package/web/{chunk-qh24q7c0.js → chunk-smywa1zw.js} +1 -1
- package/web/chunk-smywa1zw.js.br +0 -0
- package/web/chunk-smywa1zw.js.gz +0 -0
- package/web/{chunk-kx2k462h.js → chunk-trssyq9a.js} +1 -1
- package/web/chunk-trssyq9a.js.br +0 -0
- package/web/chunk-trssyq9a.js.gz +0 -0
- package/web/{chunk-sac6fn9n.js → chunk-v329f8df.js} +1 -1
- package/web/chunk-v329f8df.js.br +0 -0
- package/web/chunk-v329f8df.js.gz +0 -0
- package/web/{chunk-p6ma361e.js → chunk-vb2feptd.js} +1 -1
- package/web/chunk-vb2feptd.js.br +0 -0
- package/web/chunk-vb2feptd.js.gz +0 -0
- package/web/chunk-vff33vj3.js +1 -0
- package/web/chunk-vff33vj3.js.br +2 -0
- package/web/chunk-vff33vj3.js.gz +0 -0
- package/web/{chunk-5nbmnchg.js → chunk-w9adyaze.js} +1 -1
- package/web/chunk-w9adyaze.js.br +0 -0
- package/web/chunk-w9adyaze.js.gz +0 -0
- package/web/{chunk-c1zhat04.js → chunk-wgc8z5jv.js} +1 -1
- package/web/chunk-wgc8z5jv.js.br +0 -0
- package/web/chunk-wgc8z5jv.js.gz +0 -0
- package/web/{chunk-m5b7hny2.js → chunk-wvdk3w03.js} +1 -1
- package/web/chunk-wvdk3w03.js.br +0 -0
- package/web/chunk-wvdk3w03.js.gz +0 -0
- package/web/{chunk-ajpzsx51.js → chunk-wxmaw4ht.js} +1 -1
- package/web/chunk-wxmaw4ht.js.br +0 -0
- package/web/chunk-wxmaw4ht.js.gz +0 -0
- package/web/{chunk-2w27acew.js → chunk-x19jdqnt.js} +1 -1
- package/web/chunk-x19jdqnt.js.br +0 -0
- package/web/chunk-x19jdqnt.js.gz +0 -0
- package/web/{chunk-3d3y4tep.js → chunk-x4153gx3.js} +1 -1
- package/web/chunk-x4153gx3.js.br +0 -0
- package/web/chunk-x4153gx3.js.gz +0 -0
- package/web/{chunk-39kaz6fa.js → chunk-x7wmb5d3.js} +1 -1
- package/web/chunk-x7wmb5d3.js.br +0 -0
- package/web/chunk-x7wmb5d3.js.gz +0 -0
- package/web/{chunk-dbv8qpen.js → chunk-xp2zpmpp.js} +2 -2
- package/web/chunk-xp2zpmpp.js.br +0 -0
- package/web/chunk-xp2zpmpp.js.gz +0 -0
- package/web/chunk-y09v3sz7.js +1 -0
- package/web/chunk-y09v3sz7.js.br +0 -0
- package/web/chunk-y09v3sz7.js.gz +0 -0
- package/web/{chunk-780qvh05.js → chunk-ywmsxe5z.js} +1 -1
- package/web/chunk-ywmsxe5z.js.br +0 -0
- package/web/{chunk-780qvh05.js.gz → chunk-ywmsxe5z.js.gz} +0 -0
- package/web/{chunk-fsz1msjr.js → chunk-yzyxa823.js} +1 -1
- package/web/chunk-yzyxa823.js.br +0 -0
- package/web/chunk-yzyxa823.js.gz +0 -0
- package/web/{chunk-ex66t805.js → chunk-zwx48gb8.js} +1 -1
- package/web/chunk-zwx48gb8.js.br +0 -0
- package/web/chunk-zwx48gb8.js.gz +0 -0
- package/web/index.html +1 -1
- package/web/index.html.br +0 -0
- package/web/index.html.gz +0 -0
- package/worker.js +1 -1
- package/chunk-49hsqsht.js +0 -2
- package/chunk-5h59tby8.js +0 -470
- package/chunk-b516bp7n.js +0 -3
- package/chunk-kb5h9rmb.js +0 -2
- package/chunk-r36b12zb.js +0 -2
- package/chunk-re8n2te5.js +0 -2
- package/chunk-rqrjzz73.js +0 -2
- package/chunk-w3n8wm44.js +0 -2
- package/web/chunk-07dd0jed.js.br +0 -0
- package/web/chunk-07dd0jed.js.gz +0 -0
- package/web/chunk-0hvyq55w.js.br +0 -0
- package/web/chunk-0hvyq55w.js.gz +0 -0
- package/web/chunk-0q5drhbk.js.br +0 -0
- package/web/chunk-0q5drhbk.js.gz +0 -0
- package/web/chunk-0w6ta3ps.js.br +0 -0
- package/web/chunk-0w6ta3ps.js.gz +0 -0
- package/web/chunk-16b5anw4.js.br +0 -0
- package/web/chunk-16b5anw4.js.gz +0 -0
- package/web/chunk-21d8pzcm.js.br +0 -0
- package/web/chunk-21d8pzcm.js.gz +0 -0
- package/web/chunk-2c4affp1.js.br +0 -0
- package/web/chunk-2c4affp1.js.gz +0 -0
- package/web/chunk-2dykyq1n.js.br +0 -0
- package/web/chunk-2dykyq1n.js.gz +0 -0
- package/web/chunk-2h2w244w.js.br +0 -0
- package/web/chunk-2h2w244w.js.gz +0 -0
- package/web/chunk-2hd51wb6.js.br +0 -0
- package/web/chunk-2hd51wb6.js.gz +0 -0
- package/web/chunk-2tc6krye.js.br +0 -0
- package/web/chunk-2tc6krye.js.gz +0 -0
- package/web/chunk-2w27acew.js.br +0 -0
- package/web/chunk-2w27acew.js.gz +0 -0
- package/web/chunk-2w4rdnhj.js.br +0 -0
- package/web/chunk-2w4rdnhj.js.gz +0 -0
- package/web/chunk-31vxes2p.js.br +0 -0
- package/web/chunk-31vxes2p.js.gz +0 -0
- package/web/chunk-32qd2y5h.js +0 -1
- package/web/chunk-32qd2y5h.js.br +0 -0
- package/web/chunk-32qd2y5h.js.gz +0 -0
- package/web/chunk-39kaz6fa.js.br +0 -0
- package/web/chunk-39kaz6fa.js.gz +0 -0
- package/web/chunk-3d3y4tep.js.br +0 -0
- package/web/chunk-3d3y4tep.js.gz +0 -0
- package/web/chunk-4makcmpw.js +0 -1
- package/web/chunk-4makcmpw.js.br +0 -0
- package/web/chunk-4makcmpw.js.gz +0 -0
- package/web/chunk-4zftsyq2.js.br +0 -0
- package/web/chunk-4zftsyq2.js.gz +0 -0
- package/web/chunk-50wrjr22.js.br +0 -0
- package/web/chunk-50wrjr22.js.gz +0 -0
- package/web/chunk-55kw8p9r.js.br +0 -0
- package/web/chunk-55kw8p9r.js.gz +0 -0
- package/web/chunk-56tqa12m.js.br +0 -0
- package/web/chunk-56tqa12m.js.gz +0 -0
- package/web/chunk-595tqsv5.js.br +0 -0
- package/web/chunk-595tqsv5.js.gz +0 -0
- package/web/chunk-5h193k2c.js +0 -1
- package/web/chunk-5h193k2c.js.br +0 -0
- package/web/chunk-5h193k2c.js.gz +0 -0
- package/web/chunk-5nbmnchg.js.br +0 -0
- package/web/chunk-5nbmnchg.js.gz +0 -0
- package/web/chunk-5vc1wkwb.js.br +0 -0
- package/web/chunk-5vc1wkwb.js.gz +0 -0
- package/web/chunk-5wgdprjp.js.br +0 -0
- package/web/chunk-5wgdprjp.js.gz +0 -0
- package/web/chunk-60fbfw70.js.br +0 -0
- package/web/chunk-60fbfw70.js.gz +0 -0
- package/web/chunk-62z94rt2.js.br +0 -0
- package/web/chunk-62z94rt2.js.gz +0 -0
- package/web/chunk-67khfy00.css +0 -1
- package/web/chunk-67khfy00.css.br +0 -0
- package/web/chunk-67khfy00.css.gz +0 -0
- package/web/chunk-6bt2t0xt.js +0 -8
- package/web/chunk-6bt2t0xt.js.br +0 -0
- package/web/chunk-6bt2t0xt.js.gz +0 -0
- package/web/chunk-780qvh05.js.br +0 -0
- package/web/chunk-78t5dqea.js.br +0 -0
- package/web/chunk-78t5dqea.js.gz +0 -0
- package/web/chunk-7edmyret.js +0 -1
- package/web/chunk-7edmyret.js.br +0 -0
- package/web/chunk-7edmyret.js.gz +0 -0
- package/web/chunk-7remkcff.js.br +0 -0
- package/web/chunk-7remkcff.js.gz +0 -0
- package/web/chunk-7s062q01.js +0 -1
- package/web/chunk-7s062q01.js.br +0 -0
- package/web/chunk-7s062q01.js.gz +0 -0
- package/web/chunk-82zwwy0b.js.br +0 -0
- package/web/chunk-8c6h952g.js.br +0 -0
- package/web/chunk-8c6h952g.js.gz +0 -0
- package/web/chunk-8wgev3hd.js.br +0 -0
- package/web/chunk-8wgev3hd.js.gz +0 -0
- package/web/chunk-9vcbnf1m.js +0 -1
- package/web/chunk-9vcbnf1m.js.br +0 -0
- package/web/chunk-9vcbnf1m.js.gz +0 -0
- package/web/chunk-abahqsws.js.br +0 -0
- package/web/chunk-abahqsws.js.gz +0 -0
- package/web/chunk-acv6gk2b.js.br +0 -0
- package/web/chunk-acv6gk2b.js.gz +0 -0
- package/web/chunk-ajpzsx51.js.br +0 -0
- package/web/chunk-ajpzsx51.js.gz +0 -0
- package/web/chunk-b1b9txvk.js +0 -1
- package/web/chunk-b1b9txvk.js.br +0 -0
- package/web/chunk-b1b9txvk.js.gz +0 -0
- package/web/chunk-b83bzjcx.js.br +0 -0
- package/web/chunk-b83bzjcx.js.gz +0 -0
- package/web/chunk-c1zhat04.js.br +0 -0
- package/web/chunk-c1zhat04.js.gz +0 -0
- package/web/chunk-c37hhmtd.js.br +0 -0
- package/web/chunk-c37hhmtd.js.gz +0 -0
- package/web/chunk-c69t0ysj.js.br +0 -0
- package/web/chunk-c69t0ysj.js.gz +0 -0
- package/web/chunk-caz85hz4.js +0 -1
- package/web/chunk-caz85hz4.js.br +0 -0
- package/web/chunk-caz85hz4.js.gz +0 -0
- package/web/chunk-cbtpaf3e.js.br +0 -0
- package/web/chunk-cbtpaf3e.js.gz +0 -0
- package/web/chunk-d1gga18f.js.br +0 -0
- package/web/chunk-d1gga18f.js.gz +0 -0
- package/web/chunk-d4kjy2qn.js.br +0 -0
- package/web/chunk-d4kjy2qn.js.gz +0 -0
- package/web/chunk-dbv8qpen.js.br +0 -0
- package/web/chunk-dbv8qpen.js.gz +0 -0
- package/web/chunk-e6r1sb5r.js.br +0 -0
- package/web/chunk-e6r1sb5r.js.gz +0 -0
- package/web/chunk-ep5qff8m.js +0 -1
- package/web/chunk-ep5qff8m.js.br +0 -0
- package/web/chunk-ep5qff8m.js.gz +0 -0
- package/web/chunk-ex66t805.js.br +0 -0
- package/web/chunk-ex66t805.js.gz +0 -0
- package/web/chunk-fb8qtyqg.js +0 -1
- package/web/chunk-fb8qtyqg.js.br +0 -0
- package/web/chunk-fb8qtyqg.js.gz +0 -0
- package/web/chunk-fbzhgaak.js.br +0 -0
- package/web/chunk-fbzhgaak.js.gz +0 -0
- package/web/chunk-ffwyfdg4.js.br +0 -0
- package/web/chunk-ffwyfdg4.js.gz +0 -0
- package/web/chunk-fsz1msjr.js.br +0 -0
- package/web/chunk-fsz1msjr.js.gz +0 -0
- package/web/chunk-fztzcy7c.js.br +0 -0
- package/web/chunk-fztzcy7c.js.gz +0 -0
- package/web/chunk-g4st8a4e.js +0 -1
- package/web/chunk-g4st8a4e.js.br +0 -0
- package/web/chunk-g4st8a4e.js.gz +0 -0
- package/web/chunk-gs41j1vb.js.br +0 -0
- package/web/chunk-gs41j1vb.js.gz +0 -0
- package/web/chunk-gt4dzb4b.js.br +0 -0
- package/web/chunk-gt4dzb4b.js.gz +0 -0
- package/web/chunk-h4g8j133.js.br +0 -0
- package/web/chunk-h4g8j133.js.gz +0 -0
- package/web/chunk-ht3cek8b.js +0 -1
- package/web/chunk-ht3cek8b.js.br +0 -2
- package/web/chunk-ht3cek8b.js.gz +0 -0
- package/web/chunk-hw4f79k8.js.br +0 -0
- package/web/chunk-hw4f79k8.js.gz +0 -0
- package/web/chunk-j2y3wkxc.js.br +0 -0
- package/web/chunk-j2y3wkxc.js.gz +0 -0
- package/web/chunk-j7sfcfxr.js.br +0 -0
- package/web/chunk-j7sfcfxr.js.gz +0 -0
- package/web/chunk-jge5e8c4.js.br +0 -0
- package/web/chunk-jge5e8c4.js.gz +0 -0
- package/web/chunk-jyjgvcac.js +0 -2
- package/web/chunk-jyjgvcac.js.br +0 -0
- package/web/chunk-jyjgvcac.js.gz +0 -0
- package/web/chunk-k9bzz441.js +0 -1
- package/web/chunk-k9bzz441.js.br +0 -0
- package/web/chunk-k9bzz441.js.gz +0 -0
- package/web/chunk-keway722.js.br +0 -0
- package/web/chunk-keway722.js.gz +0 -0
- package/web/chunk-kr7shpnb.js.br +0 -0
- package/web/chunk-kv5swske.js +0 -1
- package/web/chunk-kv5swske.js.br +0 -0
- package/web/chunk-kv5swske.js.gz +0 -0
- package/web/chunk-kx2k462h.js.br +0 -0
- package/web/chunk-kx2k462h.js.gz +0 -0
- package/web/chunk-m5b7hny2.js.br +0 -0
- package/web/chunk-m5b7hny2.js.gz +0 -0
- package/web/chunk-m7kypzvp.js.br +0 -0
- package/web/chunk-m7kypzvp.js.gz +0 -0
- package/web/chunk-n00se8nk.js.br +0 -0
- package/web/chunk-n00se8nk.js.gz +0 -0
- package/web/chunk-ngdj0r7w.js.br +0 -0
- package/web/chunk-ngdj0r7w.js.gz +0 -0
- package/web/chunk-p6ma361e.js.br +0 -0
- package/web/chunk-p6ma361e.js.gz +0 -0
- package/web/chunk-pvhz0gqy.js.br +0 -0
- package/web/chunk-pvhz0gqy.js.gz +0 -0
- package/web/chunk-q96eky9v.js +0 -1
- package/web/chunk-q96eky9v.js.br +0 -0
- package/web/chunk-q96eky9v.js.gz +0 -0
- package/web/chunk-qcgs1mft.js.br +0 -0
- package/web/chunk-qcgs1mft.js.gz +0 -0
- package/web/chunk-qh24q7c0.js.br +0 -0
- package/web/chunk-qh24q7c0.js.gz +0 -0
- package/web/chunk-r1xksxab.js +0 -1
- package/web/chunk-r1xksxab.js.br +0 -0
- package/web/chunk-r1xksxab.js.gz +0 -0
- package/web/chunk-rsc5k5he.js.br +0 -0
- package/web/chunk-rsc5k5he.js.gz +0 -0
- package/web/chunk-s7a2f62f.js.br +0 -0
- package/web/chunk-s7a2f62f.js.gz +0 -0
- package/web/chunk-sac6fn9n.js.br +0 -0
- package/web/chunk-sac6fn9n.js.gz +0 -0
- package/web/chunk-t0xjx21h.js.br +0 -0
- package/web/chunk-t0xjx21h.js.gz +0 -0
- package/web/chunk-v7ck87jf.js.br +0 -0
- package/web/chunk-v7ck87jf.js.gz +0 -0
- package/web/chunk-vvk9nche.js.br +0 -0
- package/web/chunk-vvk9nche.js.gz +0 -0
- package/web/chunk-vxtfen72.js +0 -1
- package/web/chunk-vxtfen72.js.br +0 -0
- package/web/chunk-vxtfen72.js.gz +0 -0
- package/web/chunk-w5c2r59n.js.br +0 -0
- package/web/chunk-w5c2r59n.js.gz +0 -0
- package/web/chunk-wh0vt2vd.js.br +0 -0
- package/web/chunk-xe7fj72r.js +0 -1
- package/web/chunk-xe7fj72r.js.br +0 -0
- package/web/chunk-xe7fj72r.js.gz +0 -0
- package/web/chunk-yarsp7h7.js.br +0 -0
- package/web/chunk-yarsp7h7.js.gz +0 -0
- package/web/chunk-yw5wyz1q.js.br +0 -0
- package/web/chunk-yw5wyz1q.js.gz +0 -0
- package/web/chunk-z3ea4vhk.js +0 -1
- package/web/chunk-z3ea4vhk.js.br +0 -0
- package/web/chunk-z3ea4vhk.js.gz +0 -0
- package/web/chunk-z7adzvfz.js.br +0 -0
- package/web/chunk-z7adzvfz.js.gz +0 -0
- package/web/chunk-zb01zmms.js.br +0 -0
- package/web/chunk-zb01zmms.js.gz +0 -0
package/chunk-5h59tby8.js
DELETED
|
@@ -1,470 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{si,vn,z}from"./chunk-ak9rkrf3.js";import{cs,Xe,Et,us,go,ds,ms,hs,Dt,bs,$e,bo,it}from"./chunk-sq5ppnr3.js";import{xt,yn,oo,Yt,Wi,io}from"./chunk-cjh5h31t.js";import{Zo,Hi,so,bn,qi,t,m,vt,Vi,Ki,Qi,Cr,ti,Ji,wn,ni,ns,ii,ao,os,is,Ne}from"./chunk-2fymxwe7.js";import{lo,Es,xn}from"./chunk-3phf8eg6.js";import{b,ue}from"./chunk-t3mq64c8.js";import{co,W,_n,De,ie,ai,uo,ut,as,er,Ie,U,po,_t,Ue,Ir,q,Be,mo,At,fe,tr,ce,An,li,Fe,ae,pt,ho,ci,_e,Ts,ls,Ae,fo,d,Ps,ee,En,K,ks}from"./chunk-35y6nf6k.js";import{r,Ze}from"./chunk-zkjnt298.js";var qg=r(function(kK,Ng){var Rv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Vl=/[\n\r\u2028\u2029]/,kv=/[\s#!"$&'():;<=>@\\^`|~]/g;Ng.exports=function(o){var a=!1;return o.map(function(u){if(a&&typeof u==="string"&&Vl.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Vl.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(kv,"\\$&")}if("op"in u&&typeof u.op==="string"){if(Rv.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(Vl.test(u.comment))throw TypeError("`comment` must not contain line terminators");return a=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var Hg=r(function(AK,Kg){var Bg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Dg=new RegExp("^"+Bg+"$"),Fg="|&;()<> \\t",Av="'([^']*?)'",Gg="(?:\\\\[\\s\\S]|[^\\\\'])*?",jg="\\$'"+Gg+"'",rm=new RegExp("\\$'"+Gg+"(?:(')|\\\\?$)","g"),Pv="abeEfnrtv",$v=`\x07\b\x1B\x1B\f
|
|
3
|
-
\r \v`,Cv=/^#$/,Jl="'",Ug='"',vu="$",ra="",vv=4294967296;for(tm=0;tm<4;tm++)ra+=(vv*Math.random()).toString(16);var tm,Mv=new RegExp("^"+ra);function Ov(e,o){var a=o.lastIndex,u=[],p;while(p=o.exec(e))if(u[u.length]=p,o.lastIndex===p.index)o.lastIndex+=1;return o.lastIndex=a,u}function _v(e,o,a){var u=typeof e==="function"?e(a):e[a];if(typeof u>"u"&&a!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+ra+JSON.stringify(u)+ra;return o+u}var Lv=/\\([0-7]{1,3}|x[\dA-Fa-f]{1,2}|u[\dA-Fa-f]{1,4}|U[\dA-Fa-f]{1,8}|c(?:\\\\|[\s\S])|[abeEfnrtv\\'"?])/g;function Nv(e,o){var a=o.charAt(0);if(a==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(a==="x"||a==="u"||a==="U"){var p=parseInt(o.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(a>="0"&&a<="7")return String.fromCharCode(parseInt(o,8)&255);var f=Pv.indexOf(o);return f<0?o:$v.charAt(f)}function qv(e){return e.replace(Lv,Nv).split("\x00")[0]}function Dv(e,o){return rm.lastIndex=o,!!rm.exec(e)[1]}function Fv(e,o,a){if(!a)a={};var u=a.escape||"\\",p=a.splitUnquoted===!0?`
|
|
4
|
-
`:typeof a.splitUnquoted==="string"?a.splitUnquoted:"",f="(\\"+u+`['"$\\`+u+Fg+"]|\\$\\$|\\$(?!"+jg.slice(2)+`)|[^\\s'"$`+Fg+"])+",h='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',g=new RegExp(["("+Bg+")","("+jg+"|"+f+"|"+h+"|"+Av+")+"].join("|"),"g"),I=Ov(e,g);if(I.length===0)return[];if(!o)o={};var E=!1;return I.map(function(S){var k=S[0];if(!k||E)return;if(Dg.test(k))return{op:k};var A=!1,P=!1,v="",M=[],J=!1,O=null,V=!1,j;function te(){j+=1;var Y,xe,Ve=k.charAt(j);if(Ve==="{"){if(j+=1,k.charAt(j)==="}")throw Error("Bad substitution: "+k.slice(j-2,j+1));var He=1;Y=j;while(He>0&&Y<k.length){if(k.charAt(Y)==="{"&&k.charAt(Y-1)==="$")He+=1;else if(k.charAt(Y)==="}")He-=1;Y+=1}if(He!==0)throw Error("Bad substitution: "+k.slice(j));Y-=1,xe=k.slice(j,Y),j=Y}else if(/[*@#?$!-]/.test(Ve))xe=Ve;else{var ar=k.slice(j);if(Y=ar.match(/[^\w\d_]/),!Y)xe=ar,j=k.length;else xe=ar.slice(0,Y.index),j+=Y.index-1}return _v(o,"",xe)}function se(){if(O===null)return;if(O===0){if(v!=="")M[M.length]=v,v=""}else{M[M.length]=v,v="";for(var Y=1;Y<O;Y+=1)M[M.length]=""}O=null}for(j=0;j<k.length;j++){var L=k.charAt(j);if(p&&L!==vu)se();if(V=V||!A&&(L==="*"||L==="?"),P)v+=L,P=!1;else if(A)if(L===A)A=!1;else if(A==Jl)v+=L;else if(L===u)if(j+=1,L=k.charAt(j),L===Ug||L===u||L===vu)v+=L;else v+=u+L;else if(L===vu)v+=te();else v+=L;else if(L===Ug||L===Jl)A=L,J=!0;else if(Dg.test(L))return{op:k};else if(Cv.test(L)){E=!0;var re={comment:e.slice(S.index+j+1)};if(v.length)return[v,re];return[re]}else if(L===u)P=!0;else if(L===vu&&k.charAt(j+1)===Jl&&Dv(k,j))se(),J=!0,v+=qv(k.slice(j+2,rm.lastIndex-1)),j=rm.lastIndex-1;else if(L===vu){var he=te();if(!p)v+=he;else for(var we=0;we<he.length;we+=1){var We=he.charAt(we);if(p.indexOf(We)<0)se(),v+=We;else if(O===null)O=We===" "||We==="\t"||We===`
|
|
5
|
-
`?0:1;else if(We!==" "&&We!=="\t"&&We!==`
|
|
6
|
-
`)O+=1}}else v+=L}if(V)return{op:"glob",pattern:v};if(p){if(O!==null&&O>0){M[M.length]=v,v="";for(var X=1;X<O;X+=1)M[M.length]=""}if(v!==""||J&&M.length===0)M[M.length]=v;return M}return v}).reduce(function(S,k){if(typeof k>"u")return S;return[].concat(k).forEach(function(A){S[S.length]=A}),S},[])}Kg.exports=function(o,a,u){var p=Fv(o,a,u);if(typeof a!=="function")return p;return p.reduce(function(f,h){if(typeof h==="object")return f[f.length]=h,f;var g=h.split(RegExp("("+ra+".*?"+ra+")","g"));if(g.length===1)return f[f.length]=g[0],f;return g.filter(Boolean).forEach(function(I){f[f.length]=Mv.test(I)?JSON.parse(I.split(ra)[1]):I}),f},[])}});var Qo={};Ze(Qo,{AssistantMessageEventStream:()=>W,AssistantMessageFrameEncoder:()=>oR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>aR,EventStream:()=>co,InMemoryCredentialStore:()=>uo,InMemoryModelsStore:()=>po,ModelsError:()=>U,StringEnum:()=>ED,Type:()=>Oe,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>ee,clampThinkingLevel:()=>K,cleanupSessionResources:()=>Es,collapseSystemMessages:()=>Fe,contentText:()=>Ir,createAssistantMessageDiagnostic:()=>er,createAssistantMessageEventStream:()=>_n,createFauxCore:()=>Wi,createInitialSystemMessage:()=>mo,createModels:()=>fo,createProvider:()=>d,declarationsEqual:()=>ho,defaultProviderAuthContext:()=>ai,envApiKeyAuth:()=>b,extractDiagnosticError:()=>as,fauxAssistantMessage:()=>Yt,fauxProvider:()=>io,fauxText:()=>xt,fauxThinking:()=>yn,fauxToolCall:()=>oo,formatThrownValue:()=>ut,getCurrentSystemMessage:()=>An,getCurrentSystemPrompt:()=>li,getCurrentTools:()=>ce,getDeclaredTools:()=>_e,getInitialSystemMessage:()=>fe,getModelType:()=>_t,getOverflowPatterns:()=>hD,getSupportedThinkingLevels:()=>En,getSystemMessageText:()=>q,getToolStateChanges:()=>ci,hasApi:()=>Ps,hasNonAdditiveToolChanges:()=>ls,hasToolRedefinitions:()=>Ts,isContextOverflow:()=>Ta,isModelType:()=>Ue,isRecoverableLength:()=>fD,isRetryableAssistantError:()=>cR,lazyApi:()=>ie,lazyOAuth:()=>ue,lazyStream:()=>De,modelsAreEqual:()=>ks,normalizeContext:()=>At,parseJsonWithRepair:()=>vn,parseStreamingJson:()=>z,reduceAssistantMessageFrames:()=>pD,registerSessionResourceCleanup:()=>lo,renderSystemMessageUpdate:()=>Be,repairJson:()=>si,resolveTranscript:()=>ae,resolveTranscriptTools:()=>Ae,retryAssistantCall:()=>ID,retryDelayMs:()=>uR,toToolDeclaration:()=>pt,uuidv7:()=>xn,validateToolArguments:()=>yu,validateToolCall:()=>sU,withoutInitialSystemMessage:()=>tr});var _={};Ze(_,{Counted:()=>td,Entries:()=>pn,EntriesRegExp:()=>rd,Every:()=>on,EveryAll:()=>Dn,GraphemeCount:()=>lM,HasPropertyKey:()=>me,IsArray:()=>Le,IsBigInt:()=>Kr,IsBoolean:()=>cn,IsClassInstance:()=>uy,IsConstructor:()=>Zl,IsDeepEqual:()=>Da,IsEqual:()=>C,IsFunction:()=>_s,IsGreaterEqualThan:()=>Na,IsGreaterThan:()=>sa,IsInteger:()=>im,IsLessEqualThan:()=>Ls,IsLessThan:()=>Mu,IsMaxLength:()=>cy,IsMinLength:()=>my,IsMultipleOf:()=>ay,IsNull:()=>Mo,IsNumber:()=>Ut,IsObject:()=>lt,IsObjectNotArray:()=>rs,IsString:()=>gt,IsSymbol:()=>ed,IsUndefined:()=>rr,IsUnsafePropertyKey:()=>Ou,IsValueLike:()=>ia,Keys:()=>Ee,ShiftLeft:()=>It,Some:()=>qa,SomeAll:()=>py,Symbols:()=>ly,Values:()=>nd});var da={};Ze(da,{Hash:()=>md,HashCode:()=>Wy});var Bt={};Ze(Bt,{ExtendsFalse:()=>et,ExtendsTrue:()=>be,ExtendsUnion:()=>Md,IsExtendsFalse:()=>Ld,IsExtendsTrue:()=>_d,IsExtendsTrueLike:()=>To,IsExtendsUnion:()=>Od,Match:()=>wr});var Oe={};Ze(Oe,{Any:()=>Ba,Array:()=>H,BigInt:()=>Fu,Boolean:()=>D,Call:()=>sw,Capitalize:()=>lw,Codec:()=>gm,Conditional:()=>Ew,Constructor:()=>qs,ConstructorParameters:()=>Sw,Cyclic:()=>js,Decode:()=>Qy,DecodeBuilder:()=>hm,Dependent:()=>la,Encode:()=>Xy,EncodeBuilder:()=>fm,Enum:()=>Ny,Evaluate:()=>qn,Exclude:()=>Tw,Extends:()=>Nn,ExtendsResult:()=>Bt,Extract:()=>kw,Function:()=>Ds,Generic:()=>Ai,Identifier:()=>ju,Immutable:()=>Yy,Index:()=>Cw,Infer:()=>Du,InstanceType:()=>tT,Instantiate:()=>Go,Integer:()=>x,Interface:()=>jS,Intersect:()=>jn,IsAny:()=>Fr,IsArray:()=>Tt,IsBigInt:()=>Po,IsBoolean:()=>yo,IsCall:()=>eu,IsCodec:()=>Qn,IsConstructor:()=>Yr,IsCyclic:()=>cr,IsDependent:()=>Hr,IsEnum:()=>rn,IsEnumValue:()=>Ly,IsFunction:()=>Zr,IsGeneric:()=>Ua,IsIdentifier:()=>rx,IsImmutable:()=>fa,IsInfer:()=>tn,IsInteger:()=>In,IsIntersect:()=>ze,IsKind:()=>Se,IsLiteral:()=>yt,IsNever:()=>Ao,IsNull:()=>Bs,IsNumber:()=>Lr,IsObject:()=>Je,IsOptional:()=>an,IsParameter:()=>ix,IsReadonly:()=>ga,IsRecord:()=>nr,IsRef:()=>zt,IsRefine:()=>ym,IsRest:()=>_i,IsSchema:()=>Dr,IsString:()=>nn,IsSymbol:()=>Gs,IsTemplateLiteral:()=>lr,IsThis:()=>vm,IsTuple:()=>ft,IsUndefined:()=>ys,IsUnion:()=>ye,IsUnknown:()=>en,IsUnsafe:()=>dm,IsVoid:()=>$o,KeyOf:()=>nT,Literal:()=>i,Lowercase:()=>dw,Mapped:()=>pT,Module:()=>ZT,Never:()=>sr,NonNullable:()=>hT,Null:()=>Un,Number:()=>ne,Object:()=>l,Omit:()=>yT,Optional:()=>n,Parameter:()=>ya,Parameters:()=>ET,Partial:()=>ST,Pick:()=>$T,Readonly:()=>Zy,ReadonlyObject:()=>pf,ReadonlyType:()=>MT,Record:()=>Qe,RecordKey:()=>Oi,RecordPattern:()=>Sn,RecordValue:()=>hr,Ref:()=>sn,Refine:()=>ex,Required:()=>zT,Rest:()=>Ia,ReturnType:()=>JT,Script:()=>nR,String:()=>s,Symbol:()=>Ha,TemplateLiteral:()=>aS,This:()=>Cm,Tuple:()=>zr,Uncapitalize:()=>fw,Undefined:()=>Va,Union:()=>y,Unknown:()=>Q,Unsafe:()=>vr,Uppercase:()=>hw,Void:()=>Mm,With:()=>gp});var fu={};Ze(fu,{Clear:()=>Rk,Entries:()=>AF,Get:()=>CF,Has:()=>$F,IsDate:()=>pu,IsDateTime:()=>Sp,IsDuration:()=>wp,IsEmail:()=>Tp,IsHostname:()=>Mp,IsIPv4:()=>Lp,IsIPv6:()=>Np,IsIdnEmail:()=>Op,IsIdnHostname:()=>_p,IsIri:()=>Dp,IsIriReference:()=>qp,IsJsonPointer:()=>jp,IsJsonPointerUriFragment:()=>Fp,IsRegex:()=>Up,IsRelativeJsonPointer:()=>Bp,IsTime:()=>lu,IsUri:()=>Hp,IsUriReference:()=>Gp,IsUriTemplate:()=>Kp,IsUrl:()=>Wp,IsUuid:()=>zp,Reset:()=>Ak,Set:()=>PF,Test:()=>kk});var Ke=10,Sv=15000000;function ct(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&ao.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=Sv}function Hl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as Ag,existsSync as Pg,fchmodSync as wv,fsyncSync as $g,mkdirSync as Cg,openSync as vg,readFileSync as Mg,renameSync as Og,writeFileSync as _g}from"fs";import{dirname as Wl,join as Lg}from"path";class Fi{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=Lg(e,"auth.json"),this.deviceIdPath=Lg(e,"device-id")}load(){if(!Pg(this.path))return;let e;try{e=JSON.parse(Mg(this.path,"utf8"))}catch{this.quarantine();return}let o=zl(e);if(o?.version!==1){this.quarantine();return}let a=zl(o.providers);if(!a){this.quarantine();return}for(let[u,p]of Object.entries(a)){if(!Tv(p))continue;this.providers[u]=p}}deviceId(){if(Pg(this.deviceIdPath)){let o=Mg(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return Cg(Wl(this.deviceIdPath),{recursive:!0}),_g(this.deviceIdPath,`${e}
|
|
7
|
-
`),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[vt]??=e,delete o.openai;try{this.persist(o)}catch(a){throw Error("\u8F6C\u79FB ChatGPT \u8BA2\u9605\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u65B0\u542F\u52A8",{cause:a})}this.providers=o,this.dirty=!1}async read(e,o){return o?.signal?.throwIfAborted(),this.flush(),this.providers[e]?structuredClone(this.providers[e]):void 0}async list(e){return e?.signal?.throwIfAborted(),this.flush(),Object.entries(this.providers).map(([o,a])=>({providerId:o,type:a.type}))}modify(e,o,a){return this.enqueue(e,()=>this.applyModify(e,o),a)}delete(e,o){return this.enqueue(e,()=>{if(!(e in this.providers)){this.flush();return}let a={...this.providers};delete a[e],this.persist(a),this.providers=a,this.dirty=!1},o)}async close(){this.closed=!0;try{while(this.chains.size)await Promise.all(this.chains.values());this.flush()}catch(e){throw this.closed=!1,e}}enqueue(e,o,a){if(this.closed)return Promise.reject(Error("\u51ED\u636E\u5B58\u50A8\u6B63\u5728\u5173\u95ED"));let u=a?.signal;if(u?.aborted)return Promise.reject(u.reason);let p=this.chains.get(e)??Promise.resolve(),f,h=p.then(()=>{if(u?.throwIfAborted(),f)u?.removeEventListener("abort",f);return o()}),g=h.then(()=>{return},()=>{return});if(this.chains.set(e,g),g.then(()=>{if(this.chains.get(e)===g)this.chains.delete(e)}),!u)return h;return new Promise((I,E)=>{let S=()=>E(u.reason);if(f=S,u.addEventListener("abort",S,{once:!0}),h.then((k)=>{u.removeEventListener("abort",S),I(k)},(k)=>{u.removeEventListener("abort",S),E(k)}),u.aborted)S()})}async applyModify(e,o){this.flush();let a=this.providers[e]?structuredClone(this.providers[e]):void 0,u=await o(a);if(u===void 0)return a?structuredClone(a):void 0;return this.providers[e]=structuredClone(u),this.dirty=!0,this.flush(),structuredClone(u)}flush(){if(!this.dirty)return;this.persist(this.providers),this.dirty=!1}persist(e){Cg(Wl(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,a=vg(o,"w",384);try{wv(a,384),_g(a,`${JSON.stringify({version:1,providers:e},null,2)}
|
|
8
|
-
`),$g(a)}finally{Ag(a)}if(Og(o,this.path),process.platform==="win32")return;let u=vg(Wl(this.path),"r");try{$g(u)}catch(p){if(!(p instanceof Error&&("code"in p)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(p.code))))throw p}finally{Ag(u)}}quarantine(){try{Og(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function zl(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function Tv(e){let o=zl(e);if(!o)return!1;if(o.type==="api_key")return o.key===void 0||typeof o.key==="string";if(o.type!=="oauth")return!1;return typeof o.refresh==="string"&&typeof o.access==="string"&&typeof o.expires==="number"}var jv=qg(),Ql=Hg();import{AsyncLocalStorage as Uv}from"async_hooks";var N=new Uv;var Bv=3,Wg=160,Gv=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),Kv=new Set(["if","then","else","elif","while","until","do","coproc","select","!","{","}"]),Jg=/^[A-Za-z_][A-Za-z0-9_]*=/,Hv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),Wv=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),zv=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,Vv=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),Jv=new Set(["command","builtin","nohup","time","setsid"]),Qv=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir"]],["nice",["-n","--adjustment"]],["exec",["-a"]],["timeout",["-s","-k","--signal","--kill-after"]],["stdbuf",["-i","-o","-e","--input","--output","--error"]],["watch",["-n","--interval"]],["xargs",["-I","-n","-P","-L","-s","-d","-E","-a","--arg-file","--delimiter","--max-args","--max-procs"]]]),Xv=new Map([["timeout",1]]),Yv=/^-(workingdirectory|verb|windowstyle|redirectstandardoutput|redirectstandarderror|redirectstandardinput|credential)$/i;function La(e){return{out:e.out,depth:e.depth+1}}function zg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.(exe|cmd|bat|ps1)$/,"")}function nm(e,o,a,u){let p=e.length,f=0,h=o;while(h<p){let g=e.charAt(h);if(g==="\\"){h+=2;continue}if(g==="'"||g==='"'||g==="`"){let I=h+1;while(I<p){let E=e.charAt(I);if(E==="\\"){I+=2;continue}if(E===g)break;I++}h=I+1;continue}if(g===a)f++;else if(g===u){if(f--,f===0)return h+1}h++}return p}function Zv(e){let o={text:"",subs:[],heredocs:[]},a=[],u=[],p=e.length,f=0,h=0,g=null,I=(E)=>{if(e.charAt(E)==="`"){let P=E+1;while(P<p){let v=e.charAt(P);if(v==="\\"){P+=2;continue}if(v==="`")break;P++}return o.subs.push(e.slice(E+1,P)),P<p?P+1:p}if(e.charAt(E+1)==="("){let P=nm(e,E+1,"(",")");if(e.charAt(E+2)==="(")return a.push(e.slice(E,P)),P;return o.subs.push(e.slice(E+2,P-1)),P}let k=nm(e,E+1,"{","}"),A=e.slice(E+2,k-1);for(let P=0;P<A.length;P++){let v=A.charAt(P);if(v==="\\"){P++;continue}if(v==="`"){let M=A.indexOf("`",P+1);o.subs.push(M<0?A.slice(P+1):A.slice(P+1,M)),P=M<0?A.length:M;continue}if(v==="$"&&A.charAt(P+1)==="("){let M=nm(A,P+1,"(",")");o.subs.push(A.slice(P+2,M-1)),P=M-1}}return k};while(f<p){let E=e.charAt(f);if(g==="'"){if(E==="'")g=null;a.push(E),f++;continue}if(g==='"'){if(E==="\\"){if(!'$`"\\\n'.includes(e.charAt(f+1)))a.push("\\");a.push(E,e.charAt(f+1)),f+=2;continue}if(E==='"'){g=null,a.push(E),f++;continue}if(E==="`"||E==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=I(f);continue}a.push(E),f++;continue}if(E==="'"||E==='"'){g=E,a.push(E),f++;continue}if(E==="\\"){if(e.charAt(f+1)===`
|
|
9
|
-
`){f+=2;continue}if(e.charAt(f+1)==="\r"&&e.charAt(f+2)===`
|
|
10
|
-
`){f+=3;continue}a.push(E,e.charAt(f+1)),f+=2;continue}if(E==="`"||E==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=I(f);continue}if((E==="<"||E===">")&&e.charAt(f+1)==="("){let S=nm(e,f+1,"(",")");o.subs.push(e.slice(f+2,S-1)),a.push("_"),f=S;continue}if(E==="#"){let S=a.at(-1);if(S===void 0||`
|
|
11
|
-
;&|()`.includes(S)){while(f<p&&e.charAt(f)!==`
|
|
12
|
-
`)f++;continue}a.push("\\#"),f++;continue}if(E==="<"&&e.charAt(f+1)==="<"&&e.charAt(f+2)!=="<"){let S=f+2;if(e.charAt(S)==="-")S++;a.push(e.slice(f,S));let k=S;while(k<p&&(e.charAt(k)===" "||e.charAt(k)==="\t"))k++;let A="";while(k<p){let P=e.charAt(k);if(P==="'"||P==='"'){let v=e.indexOf(P,k+1);if(v<0)break;A+=e.slice(k+1,v),k=v+1;continue}if(P==="\\"){A+=e.charAt(k+1),k+=2;continue}if(` \r
|
|
13
|
-
;&|()<>`.includes(P))break;A+=P,k++}if(A)u.push(A);f=S;continue}if(E===`
|
|
14
|
-
`){if(u.length>0){let S=zv.test(a.slice(h).join(""));f++;for(let k of u.splice(0)){let A=f,P=p;while(f<p){let v=e.indexOf(`
|
|
15
|
-
`,f),M=v<0?p:v;if(e.slice(f,M).trim()===k){P=f,f=v<0?p:v+1;break}f=v<0?p:v+1}if(S&&P>A)o.heredocs.push(e.slice(A,P))}}else f++;a.push(";",`
|
|
16
|
-
`),h=a.length;continue}a.push(E),f++}return o.text=a.join(""),o}function na(e,o,a){if(o.depth>Bv)return;let u=e;if(a!=="bash")u=u.replaceAll("\\","\\\\");if(a==="powershell")u=u.replace(/`([\s\S])/g,"\\$1");if(a==="cmd")u=u.replace(/\^([\s\S])/g,"\\$1");let p=Zv(u),f;try{f=Ql(p.text)}catch{for(let h of p.text.split(/&&|\|\||[;|&\n]/))om(h.split(/\s+/).filter(Boolean).map((g)=>g.replace(/["']/g,"")),o)}if(f){let h=[];for(let g of f){if(typeof g==="string"){h.push({kind:"word",text:g});continue}if("pattern"in g){h.push({kind:"word",text:g.pattern});continue}if("op"in g)h.push({kind:"op",text:g.op})}eM(h,o)}for(let h of p.subs)na(h,La(o),"bash");for(let h of p.heredocs)na(h,La(o),"bash")}function eM(e,o){let a=[],u=()=>{if(a.length>0)om(a,o);a=[]};for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;if(f.kind==="op"){if(Hv.has(f.text)){u();continue}if(Wv.has(f.text)){if(/^\d+$/.test(a.at(-1)??""))a.pop();p++}continue}a.push(f.text)}u()}function om(e,o){let a=0;for(;;){let h=e[a];if(h===void 0)return;if(Kv.has(h)||Jg.test(h)){a++;continue}if(h==="function"){a+=2;continue}let g=nM(zg(h),e,a);if(g===a)break;a=g}let u=e[a];if(u===void 0)return;let p=zg(u),f=e.slice(a+1);if(p==="git"){sM(u,f,o);return}if(Gv.has(p)){rM(f,o);return}if(p==="eval"){na(f.join(" "),La(o),"bash");return}if(p==="iex"||p==="invoke-expression"){na(f.filter((h)=>!/^-command$/i.test(h)).join(" "),La(o),"powershell");return}if(p==="find"){for(let h=0;h<f.length;h++){if(!/^-(exec|execdir|ok|okdir)$/.test(f[h]??""))continue;let g=f.findIndex((I,E)=>E>h&&(I===";"||I==="+"));om(f.slice(h+1,g<0?void 0:g),o),h=g<0?f.length:g}return}if(p==="start-process"||p==="saps"){tM(f,o);return}if(p==="powershell"||p==="pwsh")Vg(f,/^-(command|c)$/i,o,"powershell");if(p==="cmd")Vg(f,/^\/[ck]$/i,o,"cmd")}function Vg(e,o,a,u){for(let p=0;p<e.length;p++)if(o.test(e[p]??"")){let f=e.slice(p+1).join(" ");if(f.trim())na(f,La(a),u);return}}function tM(e,o){let a=[],u,p=[];for(let f=0;f<e.length;f++){let h=e[f]??"";if(/^-(filepath|path)$/i.test(h)){u=e[++f];continue}if(/^-(argumentlist|args)$/i.test(h)){p.push(e[++f]??"");continue}if(Yv.test(h)){f++;continue}if(h.startsWith("-"))continue;a.push(h)}if(u??=a.shift(),p.length===0)p.push(...a);if(!u)return;om([u,...p.flatMap((f)=>f.split(/[\s,]+/)).filter(Boolean)],o)}function rM(e,o){for(let a=0;a<e.length;a++){let u=e[a]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){a++;continue}if(u.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(u);if(p){let f=p[1]||e[a+1];if(f)na(f,La(o),"bash");return}if(u.startsWith("-")||u==="")continue;return}}function nM(e,o,a){if(Jv.has(e)){let f=a+1;while(o[f]?.startsWith("-"))f++;return f}let u=Qv.get(e);if(!u)return a;let p=a+1;for(;;){let f=o[p];if(f===void 0)return p;let h=e==="env"?/^(?:-S|--split-string=?)([\s\S]*)$/.exec(f):null;if(h){let g=h[1]||o[p+1]||"";o.splice(p,h[1]?1:2,...g.split(/\s+/).filter(Boolean));continue}if(u.includes(f)){p+=2;continue}if(Jg.test(f)||f.startsWith("-")){p++;continue}return p+(Xv.get(e)??0)}}function Eo(e,o){return e.some((a)=>a.length>1&&a.startsWith("-")&&!a.startsWith("--")&&a.slice(1).includes(o))}function Mn(e,o){return e.some((a)=>a===`--${o}`||a.startsWith(`--${o}=`))}var oM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Eo(e,"f")||Eo(e,"i")||Mn(e,"force")||Mn(e,"interactive"))&&!(Eo(e,"n")||Mn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Eo(e,"f")||Mn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Eo(e,"f")||Mn(e,"force")||Mn(e,"discard-changes")||Eo(e,"C")||Mn(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>Eo(e,"f")||Eo(e,"d")||Mn(e,"force")||Mn(e,"force-with-lease")||Mn(e,"force-if-includes")||Mn(e,"delete")||Mn(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>Mn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Eo(e,"D")||Eo(e,"M")||Eo(e,"C")||Eo(e,"f")||Mn(e,"force")?"branch -D/-M/-f \u5F3A\u5236\u5220\u9664\u3001\u8986\u76D6\u6216\u79FB\u52A8\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>Mn(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,prune:(e)=>Eo(e,"n")||Mn(e,"dry-run")?void 0:"prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84","filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>Eo(e,"f")||Mn(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(Eo(e,"f")||Mn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function sM(e,o,a){let u=0;for(;;){let I=o[u];if(I===void 0)break;if(Vv.has(I)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(I)||/^-[Cc].+/.test(I)||I.startsWith("-")){u++;continue}break}let p=o[u]?.toLowerCase();if(!p)return;let f=oM[p];if(!f)return;let h=f(o.slice(u+1));if(!h)return;let g=[e,...o.slice(u)].join(" ");a.out.push({rule:p,fragment:g.length>Wg?`${g.slice(0,Wg)}\u2026`:g,reason:h})}function Vo(e,o="bash"){let a={out:[],depth:0};return na(e,a,o),a.out}function Qg(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),a=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${a}`}var Xl=new Map;function iM(e,o,a,u,p){let f=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((h)=>{let g=(E)=>{if(!Xl.delete(f))return;p?.removeEventListener("abort",I),h(E)},I=()=>{Xg(e,f),g("aborted")};if(Xl.set(f,{session:e,finish:g}),e.appendExtension({namespace:bn,kind:"requested",schemaVersion:1,payload:{id:f,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:E,reason:S})=>({fragment:E,reason:S})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${a}`}}),p?.aborted)I();else p?.addEventListener("abort",I,{once:!0})})}function Xg(e,o){try{e.appendExtension({namespace:bn,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Jn(e,o,a){let u=Xl.get(o);if(!u||u.session!==e){if(!aM(e,o))return"unknown";return Xg(e,o),"expired"}return e.appendExtension({namespace:bn,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:a,resolvedAt:Date.now()},display:{text:a?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(a?"approved":"denied"),"answered"}function aM(e,o){let a=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==bn)continue;let p=u.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==o)continue;if(u.kind==="requested")a=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return a}function Ko(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${Qg(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function qe(e,o,a="bash"){let u=Vo(e,a);if(!u.at(0))return;let f=Qg(u),h=N.getStore();if(h?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${f}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${Ko(u)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let g=await iM(h,e,f,u,o);if(g==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${f} \u672A\u6267\u884C\uFF1A${g==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}var Os={assign:0,create:0,clone:0,discard:0,update:0};function oa(e,o,a){return e>=o&&e<=a}function ey(e){return e===8205}function uM(e){return oa(e,55296,56319)}function Yg(e){return oa(e,127462,127487)}function ty(e){return oa(e,65024,65039)}function ry(e){return oa(e,768,879)||oa(e,6832,6911)||oa(e,7616,7679)||oa(e,65056,65071)}function sm(e){return e>65535?2:1}function Zg(e,o){while(o<e.length){let a=e.codePointAt(o);if(ry(a)||ty(a))o+=sm(a);else break}return o}function Yl(e,o){let a=e.codePointAt(o),u=o+sm(a);u=Zg(e,u);while(u<e.length-1&&ey(e.codePointAt(u))){let p=e.codePointAt(u+1);u+=1+sm(p),u=Zg(e,u)}if(Yg(a)&&u<e.length&&Yg(e.codePointAt(u)))u+=sm(e.codePointAt(u));return u}function ny(e){return e>=768&&(uM(e)||ry(e)||ty(e)||ey(e))}function oy(e){let o=0,a=0;while(a<e.length)a=Yl(e,a),o++;return o}function cM(e,o){let a=0,u=0;while(u<e.length)if(u=Yl(e,u),++a>=o)return!0;return!1}function mM(e,o){let a=0,u=0;while(u<e.length)if(u=Yl(e,u),++a>o)return!1;return!0}function sy(e,o){if(o===0)return!0;if(e.length<o)return!1;let a=0;while(!0){if(ny(e.charCodeAt(a)))return cM(e,o);if(++a>=o)return!0}}function iy(e,o){if(e.length<=o)return!0;let a=0;while(!0){if(ny(e.charCodeAt(a)))return mM(e,o);if(++a>o)return!1}}function Le(e){return Array.isArray(e)}function Kr(e){return C(typeof e,"bigint")}function cn(e){return C(typeof e,"boolean")}function Zl(e){if(rr(e)||!_s(e))return!1;let o=Function.prototype.toString.call(e);if(/^class\s/.test(o))return!0;if(/\[native code\]/.test(o))return!0;return!1}function _s(e){return C(typeof e,"function")}function im(e){return Number.isInteger(e)}function Mo(e){return C(e,null)}function Ut(e){return Number.isFinite(e)}function rs(e){return lt(e)&&!Le(e)}function lt(e){return C(typeof e,"object")&&!Mo(e)}function gt(e){return C(typeof e,"string")}function ed(e){return C(typeof e,"symbol")}function rr(e){return C(e,void 0)}function C(e,o){return e===o}function sa(e,o){return e>o}function Mu(e,o){return e<o}function Ls(e,o){return e<=o}function Na(e,o){return e>=o}function ay(e,o){if(Kr(e)||Kr(o))return BigInt(e)%BigInt(o)===0n;let a=0.0000000001;if(!Ut(e))return!0;if(im(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<a}function uy(e){if(!lt(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(Mo(o))return!1;return C(typeof o.constructor,"function")&&!(C(o.constructor,globalThis.Object)||C(o.constructor.name,"Object"))}function ia(e){return Kr(e)||cn(e)||Mo(e)||Ut(e)||gt(e)||rr(e)}function lM(e){return oy(e)}function cy(e,o){return iy(e,o)}function my(e,o){return sy(e,o)}function on(e,o,a){return e.every((u,p)=>p<o||a(u,p))}function Dn(e,o,a){let u=!0;return e.forEach((p,f)=>{if(f>=o&&!a(p,f))u=!1}),u}function qa(e,o){return e.some((a,u)=>o(a,u))}function py(e,o){let a=!1;return e.forEach((u,p)=>{if(o(u,p))a=!0}),a}function td(e,o){return e.reduce((a,u,p)=>o(u,p)?++a:a,0)}function It(e,o,a){return C(e.length,0)?a():o(e[0],e.slice(1))}function Ou(e){return C(e,"__proto__")||C(e,"constructor")||C(e,"prototype")}function me(e,o){return Ou(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function rd(e){return Ee(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function pn(e){return Object.entries(e)}function Ee(e){return Object.getOwnPropertyNames(e)}function ly(e){return Object.getOwnPropertySymbols(e)}function nd(e){return Object.values(e)}function dM(e,o){if(!lt(o))return!1;let a=Ee(e);return C(a.length,Ee(o).length)&&a.every((u)=>Da(e[u],o[u]))}function fM(e,o){return Le(o)&&C(e.length,o.length)&&e.every((a,u)=>Da(e[u],o[u]))}function Da(e,o){return Le(e)?fM(e,o):lt(e)?dM(e,o):C(e,o)}var hM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function gM(e){return hM.test(e)}function On(e,o){return`(${e} && ${o})`}function br(e,o){return`(${e} || ${o})`}function zn(e){return`!(${e})`}function am(e){return`Array.isArray(${e})`}function dy(e){return`typeof ${e} === "bigint"`}function yM(e){return`typeof ${e} === "boolean"`}function xM(e){return`Number.isInteger(${e})`}function IM(e){return`${e} === null`}function fy(e){return`Number.isFinite(${e})`}function hy(e){return On(gy(e),zn(am(e)))}function gy(e){return`typeof ${e} === "object" && ${e} !== null`}function yy(e){return`typeof ${e} === "string"`}function EM(e){return`typeof ${e} === "symbol"`}function od(e){return`${e} === undefined`}function bM(e){return`typeof ${e} === "function"`}function SM(e){return`Guard.IsConstructor(${e})`}function ko(e,o){return`${e} === ${o}`}function xy(e,o){return`${e} > ${o}`}function sd(e,o){return`${e} < ${o}`}function aa(e,o){return`${e} <= ${o}`}function _u(e,o){return`${e} >= ${o}`}function wM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function TM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function Ns(e,o,a,u){return C(o,"0")?`${e}.every((${a[0]}, ${a[1]}) => (${u}))`:`${e}.every((${a[0]}, ${a[1]}) => (${a[1]} < ${o}) || (${u}))`}function RM(e,o,a){return`${e}.some((${o[0]}, ${o[1]}) => ${a})`}function kM(e,o,a){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${a}) result = true }); return result })(${e})`}function um(e,o,a){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${a}) ? ++result : result, 0)`}function Iy(e){return`Object.entries(${e})`}function ua(e){return`Object.getOwnPropertyNames(${e})`}function ca(e,o){return C(o,'"__proto__"')||C(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function Ey(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function AM(e){return`[${e.join(", ")}]`}function Ti(e,o){return`((${e.join(", ")}) => ${o})`}function Sr(e,o){return`${e}(${o.join(", ")})`}function id(e,o){return`new ${e}(${o.join(", ")})`}function bt(e,o){return`${e}${gM(o)?`.${o}`:`[${Re(o)}]`}`}function Re(e){if(!ia(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function PM(e,o,a){return`(${e} ? ${o} : ${a})`}function cm(e){return`{ ${e.join("; ")}; }`}function ei(e,o){return`const ${e} = ${o}`}function by(e,o){return`if(${e}) { ${o} }`}function mm(e){return`return ${e}`}function Fn(e){return C(e.length,0)?"true":e.reduce((o,a)=>On(o,a))}function ad(e){return C(e.length,0)?"false":e.reduce((o,a)=>br(o,a))}function $M(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function CM(e){return e instanceof Boolean}function vM(e){return e instanceof Number}function MM(e){return e instanceof String}function Sy(e){return globalThis.ArrayBuffer.isView(e)}function wy(e){return e instanceof globalThis.RegExp}function OM(e){return e instanceof globalThis.Date}function _M(e){return e instanceof globalThis.Set}function LM(e){return e instanceof globalThis.Map}var qM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function ss(){return qM}function Ri(e){return ss().immutableTypes?Object.freeze(e):e}function ln(e,o){return Os.assign+=1,Ri({...e,...o})}function DM(e){return e}function FM(e){return me(e,"~kind")||me(e,"~unsafe")}function jM(e){let o={};for(let a of Ee(e)){if(Ou(a))continue;let u=Object.getOwnPropertyDescriptor(e,a);if(u.value=ma(u.value),C(u.enumerable,!0))o[a]=u.value;else Object.defineProperty(o,a,u)}return o}function UM(e){let o={};for(let a of Ee(e)){if(Ou(a))continue;o[a]=ma(e[a])}for(let a of ly(e))o[a]=ma(e[a]);return o}function BM(e){return uy(e)?DM(e):FM(e)?jM(e):UM(e)}function GM(e){return e.map((o)=>ma(o))}function KM(e){return e.slice()}function HM(e){return new RegExp(e.source,e.flags)}function WM(e){return new Map(ma([...e.entries()]))}function zM(e){return new Set(ma([...e.values()]))}function ma(e){return Sy(e)?KM(e):wy(e)?HM(e):LM(e)?WM(e):_M(e)?zM(e):Le(e)?GM(e):lt(e)?BM(e):e}function Fa(e){return Os.clone+=1,ma(e)}function VM(e,o){for(let a of Object.keys(o))Object.defineProperty(e,a,{configurable:!0,writable:!0,enumerable:!1,value:o[a]});return e}function Ty(e,o){return{...e,...o}}function Ct(e,o,a={}){Os.create+=1;let u=Ty(o,a),p=ss().enumerableKind?Ty(u,e):VM(u,e);return Ri(p)}function ps(e,o){Os.discard+=1;let a={};for(let u of Ee(e)){if(o.includes(u))continue;let p=Object.getOwnPropertyDescriptor(e,u);p.value=Fa(p.value),Object.defineProperty(a,u,p)}return Ri(a)}function St(e,o,a){Os.update+=1;let u=ss(),p=Fa(e);for(let f of Object.keys(o))Object.defineProperty(p,f,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[f]});for(let f of Object.keys(a))Object.defineProperty(p,f,{configurable:!0,enumerable:!0,writable:!0,value:a[f]});return Ri(p)}function Se(e,o){return lt(e)&&me(e,"~kind")&&C(e["~kind"],o)}function Dr(e){return lt(e)}function Te(e,o,a){return Ct({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:a},{})}function ki(e){return Se(e,"Deferred")}function JM(e){return St(e,{"~readonly":!0},{})}function Nu(e,o){return St(JM(e),{},o)}function Ry(e,o,a,u){let p=pe(e,o,a);return Nu(p,u)}function QM(e){return St(e,{"~optional":!0},{})}function qu(e,o){return St(QM(e),{},o)}function ky(e,o,a,u){let p=pe(e,o,a);return qu(p,u)}function H(e,o){return Ct({"~kind":"Array"},{type:"array",items:e},o)}function Tt(e){return Se(e,"Array")}function ja(e){return ps(e,["~kind","type","items"])}function qs(e,o,a={}){return Ct({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},a)}function Yr(e){return Se(e,"Constructor")}function Ay(e){return ps(e,["~kind","type","parameters","instanceType"])}function Ds(e,o,a={}){return Ct({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},a)}function Zr(e){return Se(e,"Function")}function Py(e){return ps(e,["~kind","type","parameters","returnType"])}function sn(e,o){return Ct({["~kind"]:"Ref"},{$ref:e},o)}function zt(e){return Se(e,"Ref")}function Ai(e,o){return Ct({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Ua(e){return Se(e,"Generic")}function Ba(e){return Ct({["~kind"]:"Any"},{},e)}function Fr(e){return Se(e,"Any")}var $y="(?!)";function sr(e){return Ct({"~kind":"Never"},{not:{}},e)}function Ao(e){return Se(e,"Never")}function Fs(e,o={}){return Te("AddOptional",[e],o)}function pa(e,o={}){return qu(e,o)}function n(e){return pa(e)}function an(e){return Dr(e)&&me(e,"~optional")}function Cy(e){return Ee(e).filter((o)=>!an(e[o]))}function pm(e){return Ee(e)}function lm(e){return nd(e)}function l(e,o={}){let a=Cy(e),u=a.length>0?{required:a}:{};return Ct({"~kind":"Object"},{type:"object",...u,properties:e},o)}function Je(e){return Se(e,"Object")}function vy(e){return ps(e,["~kind","type","properties","required"])}function Q(e){return Ct({["~kind"]:"Unknown"},{},e)}function en(e){return Se(e,"Unknown")}function js(e,o,a){let u=Ee(e).reduce((p,f)=>({...p,[f]:St(e[f],{},{$id:f})}),{});return Ct({["~kind"]:"Cyclic"},{$defs:u,$ref:o},a)}function cr(e){return Se(e,"Cyclic")}function vr(e){return St(e,{["~unsafe"]:null},{})}function dm(e){return rs(e)&&me(e,"~unsafe")&&Mo(e["~unsafe"])}function Ln(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Du(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p,p],1:(u)=>[u,Q(),Q()]});return Ct({["~kind"]:"Infer"},{type:"infer",name:o,extends:a},{})}function tn(e){return Se(e,"Infer")}function la(e,o,a,u={}){return Ct({"~kind":"Dependent"},{if:e,then:o,else:a},u)}function Hr(e){return Se(e,"Dependent")}function My(e){return ps(e,["~kind","if","then","else"])}function Oy(e){return rs(e)}function _y(e){return Ee(e).filter((a)=>isNaN(a)).reduce((a,u)=>[...a,e[u]],[])}function Ly(e){return gt(e)||Ut(e)}function Ny(e,o){let a=Oy(e)?_y(e):e;return Ct({"~kind":"Enum"},{enum:a},o)}function rn(e){return Se(e,"Enum")}function jn(e,o={}){return Ct({"~kind":"Intersect"},{allOf:e},o)}function ze(e){return Se(e,"Intersect")}function qy(e){return ps(e,["~kind","allOf"])}var ud=void 0;function XM(){try{return Fy("null")(),!0}catch{return!1}}function Dy(){if(rr(ud))ud=XM();return ud&&ss().useAcceleration}function Fy(...e){return new globalThis.Function(...e)}function Wr(){throw Error("Unreachable")}function YM(e){let o=new Set,a=e;while(a&&a!==Object.prototype){for(let u of Reflect.ownKeys(a))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);a=Object.getPrototypeOf(a)}return[...o]}function ZM(e){return typeof e==="number"}var Vn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Vn||(Vn={}));var Ga=BigInt("14695981039346656037"),[eO,tO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],rO=Array.from({length:256}).map((e,o)=>BigInt(o)),Gy=new Float64Array(1),Ky=new DataView(Gy.buffer),Hy=new Uint8Array(Gy.buffer);function Pn(e){Ga=Ga^rO[e],Ga=Ga*eO%tO}function nO(e){Pn(Vn.Array);for(let o of e)Pi(o)}function oO(e){Pn(Vn.BigInt),Ky.setBigInt64(0,e);for(let o of Hy)Pn(o)}function Uy(e){Pn(Vn.Boolean),Pn(e?1:0)}function sO(e){Pn(Vn.Constructor),Pi(e.toString())}function iO(e){Pn(Vn.Date),Pi(e.getTime())}function aO(e){Pn(Vn.Function),Pi(e.toString())}function uO(e){Pn(Vn.Null)}function By(e){Pn(Vn.Number),Ky.setFloat64(0,e,!0);for(let o of Hy)Pn(o)}function cO(e){Pn(Vn.Object);for(let o of YM(e).sort())Pi(o),Pi(e[o])}function mO(e){Pn(Vn.RegExp),cd(e.toString())}var pO=new TextEncoder;function cd(e){Pn(Vn.String);for(let o of pO.encode(e))Pn(o)}function lO(e){Pn(Vn.Symbol),Pi(e.toString())}function dO(e){Pn(Vn.TypeArray);let o=new Uint8Array(e.buffer);for(let a=0;a<o.length;a++)Pn(o[a])}function fO(e){return Pn(Vn.Undefined)}function Pi(e){return Sy(e)?dO(e):OM(e)?iO(e):wy(e)?mO(e):CM(e)?Uy(e.valueOf()):MM(e)?cd(e.valueOf()):vM(e)?By(e.valueOf()):ZM(e)?By(e):Le(e)?nO(e):cn(e)?Uy(e):Kr(e)?oO(e):Zl(e)?sO(e):Mo(e)?uO(e):lt(e)?cO(e):gt(e)?cd(e):ed(e)?lO(e):rr(e)?fO(e):_s(e)?aO(e):Wr()}function Wy(e){return Ga=BigInt("14695981039346656037"),Pi(e),Ga}function md(e){return Wy(e).toString(16).padStart(16,"0")}function zy(e){switch(e.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"dependentRequired":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"exclusiveMinimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"format":return`must match format "${e.params.format}"`;case"if":return`must match "${e.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${e.params.limit} items`;case"maxLength":return`must not have more than ${e.params.limit} characters`;case"maxProperties":return`must not have more than ${e.params.limit} properties`;case"maximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"minItems":return`must not have fewer than ${e.params.limit} items`;case"minLength":return`must not have fewer than ${e.params.limit} characters`;case"minProperties":return`must not have fewer than ${e.params.limit} properties`;case"minimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"multipleOf":return`must be multiple of ${e.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${e.params.pattern}"`;case"propertyNames":return`property names ${e.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${e.params.requiredProperties.join(", ")}`;case"type":return typeof e.params.type==="string"?`must be ${e.params.type}`:`must be either ${e.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return e.params.message;default:return"an unknown validation error occurred"}}var hO=zy;function Vy(){return hO}class fm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,a=Qn(o)?(f)=>this.decode(o["~codec"].decode(f)):this.decode,u=Qn(o)?(f)=>o["~codec"].encode(e(f)):e,p={decode:a,encode:u};return St(this.type,{"~codec":p},{})}}class hm{constructor(e){this.type=e}Decode(e){return new fm(this.type,e)}}function gm(e){return new hm(e)}function Qy(e,o){return gm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function Xy(e,o){return gm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Qn(e){return Dr(e)&&me(e,"~codec")&<(e["~codec"])&&me(e["~codec"],"encode")&&me(e["~codec"],"decode")}function Yy(e){return Ka(e)}function fa(e){return Dr(e)&&me(e,"~immutable")}function Us(e,o={}){return Te("AddReadonly",[e],o)}function ha(e,o={}){return Nu(e,o)}function Zy(e){return ha(e)}function ga(e){return Dr(e)&&me(e,"~readonly")}function yO(e,o){let a=ym(e)?[...e["~refine"],o]:[o];return St(e,{"~refine":a},{})}function ex(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[p,f,()=>"Refine Error"]});return yO(o,{check:a,error:u})}function xO(e){return rs(e)&&me(e,"check")&&me(e,"error")&&_s(e.check)&&_s(e.error)}function ym(e){return Dr(e)&&me(e,"~refine")&&Le(e["~refine"])&&on(e["~refine"],0,(o)=>xO(o))}var tx="-?(?:0|[1-9][0-9]*)n";function Fu(e){return Ct({"~kind":"BigInt"},{type:"bigint"},e)}function Po(e){return Se(e,"BigInt")}function D(e){return Ct({"~kind":"Boolean"},{type:"boolean"},e)}function yo(e){return Se(e,"Boolean")}function ju(e){return Ct({"~kind":"Identifier"},{name:e})}function rx(e){return Se(e,"Identifier")}var xm="-?(?:0|[1-9][0-9]*)";function x(e){return Ct({"~kind":"Integer"},{type:"integer"},e)}function In(e){return Se(e,"Integer")}class nx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function IO(e){return Kr(e)?"bigint":cn(e)?"boolean":Ut(e)?"number":gt(e)?"string":(()=>{throw new nx(e)})()}function i(e,o){return Ct({"~kind":"Literal"},{type:IO(e),const:e},o)}function Im(e){return Kr(e)||cn(e)||Ut(e)||gt(e)}function ox(e){return yt(e)&&Kr(e.const)}function sx(e){return yt(e)&&cn(e.const)}function Em(e){return yt(e)&&Ut(e.const)}function bm(e){return yt(e)&>(e.const)}function yt(e){return Se(e,"Literal")}function Un(e){return Ct({"~kind":"Null"},{type:"null"},e)}function Bs(e){return Se(e,"Null")}var Sm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function ne(e){return Ct({"~kind":"Number"},{type:"number"},e)}function Lr(e){return Se(e,"Number")}function Ha(e){return Ct({"~kind":"Symbol"},{type:"symbol"},e)}function Gs(e){return Se(e,"Symbol")}function ya(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[p,f,f],1:(p)=>[p,Q(),Q()]});return Ct({"~kind":"Parameter"},{name:o,extends:a,equals:u},{})}function ix(e){return Se(e,"Parameter")}var wm=".*";function s(e){return Ct({"~kind":"String"},{type:"string"},e)}function nn(e){return Se(e,"String")}function y(e,o={}){return Ct({"~kind":"Union"},{anyOf:e},o)}function ye(e){return Se(e,"Union")}function ax(e){return ps(e,["~kind","anyOf"])}function Uu(e){let o=ux(e);return C(o.length,2)?o[0]:[]}function EO(e){return!0}function cx(e){return It(e,(o,a)=>bO(o)?cx(a):!1,()=>!0)}function mx(e){return C(e.length,0)?!1:cx(e)}function bO(e){return ye(e)?mx(e.anyOf):yt(e)?EO(e.const):!1}function Tm(e){return mx(e)}function Rm(e){return Ct({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function px(e,o,a=[]){return It(e,(u,p)=>px(p,o,[...a,`${u}${o}`]),()=>a)}function SO(e,o){return C(e.length,0)?[`${o}`]:px(e,o)}function lx(e,o,a=[]){return It(o,(u,p)=>lx(e,p,[...a,...dx(e,u)]),()=>a)}function dx(e,o){return ye(o)?lx(e,o.anyOf):yt(o)?SO(e,o.const):Wr()}function fx(e,o){return It(o,(a,u)=>fx(dx(e,a),u),()=>e)}function wO(e){return e.map((o)=>i(o))}function TO(e){let o=fx([],e),a=wO(o);return y(a)}function RO(e){return C(e.length,0)?Wr():C(e.length,1)&&yt(e[0])?e[0]:TO(e)}function pd(e){let o=Uu(e);return C(o.length,0)?s():Tm(o)?RO(o):Rm(e)}function Bu(e){let o=pd(e);return lr(o)?s():o}function So(e,o){let u={[e]:o};return Ct({["~kind"]:"Record"},{type:"object",patternProperties:u})}function hx(e){return So(fs,e)}function gx(e){return l({true:e,false:e})}function zr(e,o={}){let[a,u,p]=[e,e.length,!1];return Ct({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:a,minItems:u},o)}function ft(e){return Se(e,"Tuple")}function yx(e){return ps(e,["~kind","type","items","minItems","additionalItems"])}function kO(e){return ps(e,["~readonly"])}function ld(e,o){return St(kO(e),{},o)}function xx(e,o,a,u){let p=pe(e,o,a);return ld(p,u)}function Ix(e,o={}){return Te("RemoveReadonly",[e],o)}function Ex(e,o={}){return ld(e,o)}function AO(e){return ps(e,["~optional"])}function dd(e,o){return St(AO(e),{},o)}function bx(e,o,a,u){let p=pe(e,o,a);return dd(p,u)}function Sx(e,o={}){return Te("RemoveOptional",[e],o)}function km(e,o={}){return dd(e,o)}function fd(e){return e.reduceRight((a,u,p)=>({[p]:u,...a}),{})}function wx(e){let o=fd(e.items);return l(o)}function hd(e){return Je(e)||ft(e)}function PO(e,o){return ga(e)?ga(o)?!0:!1:!1}function $O(e,o){return an(e)?an(o)?!0:!1:!1}function CO(e,o){let a=PO(e,o),u=$O(e,o),p=Nr([e,o]),f=Ex(km(p));return a&&u?ha(pa(f)):a&&!u?ha(f):!a&&u?pa(f):f}function vO(e,o,a){return a in e?a in o?CO(e[a],o[a]):e[a]:(a in o)?o[a]:sr()}function MO(e,o){return[...new Set([...Ee(e),...Ee(o)])].reduce((p,f)=>({...p,[f]:vO(e,o,f)}),{})}function Tx(e){return Je(e)?e.properties:ft(e)?fd(e.items):{}}function Rx(e,o){let a=Tx(e),u=Tx(o),p=MO(a,u);return l(p)}function OO(e,o){let a=Wa(e,o);return C(a,Ku)?e:C(a,Hu)?o:C(a,Gu)?o:sr()}function _O(e,o){let a=hd(e),u=hd(o);return a&&u?Rx(e,o):a&&!u?e:!a&&u?o:OO(e,o)}function kx(e,o){return Ao(e)?e:Fr(e)?e:en(e)?o:Ao(o)?o:Fr(o)?o:en(o)?e:_O(e,o)}function LO(e,o){return ye(e)||ye(o)}function NO(e,o){let a=Bo(e),u=Bo(o);return LO(a,u)?Nr([a,u]):kx(a,u)}function Ax(e,o,a=[]){return It(o,(u,p)=>Ax(e,p,[...a,NO(u,e)]),()=>C(a.length,0)?[e]:a)}function Px(e,o,a=[]){return It(e,(u,p)=>Px(p,o,[...a,...Wu([u],o)]),()=>a)}function Wu(e,o=[]){return It(e,(a,u)=>ye(a)?Wu(u,Px(a.anyOf,o)):Wu(u,Ax(a,o)),()=>o)}function qO(e,o){let a=Nn({},e,o);return To(a)?[]:[e]}function $x(e,o,a=[]){return It(e,(u,p)=>$x(p,o,[...a,...qO(u,o)]),()=>a)}function Am(e,o){let a=Bo(e),u=ye(a)?a.anyOf:[a],p=$x(u,o);return wo(p)}function gs(e,o,a){let u=Nr([e,o]),p=Am(a,e);return wo([u,p])}function xo(e,o=[]){return It(e,(a,u)=>xo(u,[...o,i(a)]),()=>wo(o))}function Nr(e){let o=Wu(e),a=gd(o);return wo(a)}function Bn(e){let o=Bu(e);return Bo(o)}function wo(e){let o=gd(e);return Ci(o)}function Bo(e){return Hr(e)?gs(e.if,e.then,e.else):rn(e)?xo(e.enum):ze(e)?Nr(e.allOf):lr(e)?Bn(e.pattern):ye(e)?wo(e.anyOf):e}function Ci(e){return C(e.length,1)?e[0]:C(e.length,0)?sr():y(e)}function Cx(e,o){let a=xo(e);return vi(a,o)}function vx(e,o){return So(Mi,o)}function Mx(e,o){let a=Nr(e);return vi(a,o)}function Ox(e,o){return gt(e)||Ut(e)?l({[e]:o}):C(e,!1)?l({false:o}):C(e,!0)?l({true:o}):l({})}function _x(e,o){return So(za,o)}function Lx(e,o){return me(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?So(e.pattern.toString(),o):So(fs,o)}function Nx(e,o){let a=Uu(e);return Tm(a)?vi(Bn(e),o):So(e,o)}function DO(e){return ye(e)?xa(e.anyOf):[e]}function xa(e,o=[]){return It(e,(a,u)=>xa(u,[...o,...DO(a)]),()=>o)}function FO(e){return e.some((o)=>nn(o)||Lr(o)||In(o))}function jO(e,o){return C(FO(e),!0)?So(fs,o):void 0}function UO(e,o){return e.reduce((a,u)=>yt(u)&&(gt(u.const)||Ut(u.const))?{...a,[u.const]:o}:a,{})}function BO(e,o){let a=UO(e,o);return l(a)}function qx(e,o){let a=xa(e),u=jO(a,o);return Dr(u)?u:BO(a,o)}function vi(e,o){return Fr(e)?hx(o):yo(e)?gx(o):rn(e)?Cx(e.enum,o):In(e)?vx(e,o):ze(e)?Mx(e.allOf,o):yt(e)?Ox(e.const,o):Lr(e)?_x(e,o):ye(e)?qx(e.anyOf,o):nn(e)?Lx(e,o):lr(e)?Nx(e.pattern,o):l({})}function yd(e,o,a){return dt([e])?St(vi(e,o),{},a):Pm(e,o,a)}function Dx(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return yd(f,h,p)}var Mi=`^${xm}$`,za=`^${Sm}$`,fs=`^${wm}$`;function Pm(e,o,a={}){return Te("Record",[e,o],a)}function Qe(e,o,a={}){return yd(e,o,a)}function Fx(e,o){return So(e,o)}function $m(e){return C(e,fs)?s():C(e,Mi)?x():C(e,za)?ne():pd(e)}function Sn(e){return Ee(e.patternProperties)[0]}function Oi(e){let o=Sn(e);return $m(o)}function hr(e){return e.patternProperties[Sn(e)]}function nr(e){return Se(e,"Record")}function Ia(e){return Ct({"~kind":"Rest"},{type:"rest",items:e},{})}function _i(e){return Se(e,"Rest")}function Cm(e){return Ct({["~kind"]:"This"},{$ref:"#"},e)}function vm(e){return Se(e,"This")}function Va(e){return Ct({"~kind":"Undefined"},{type:"undefined"},e)}function ys(e){return Se(e,"Undefined")}function Mm(e){return Ct({"~kind":"Void"},{type:"void"},e)}function $o(e){return Se(e,"Void")}function KO(e,o){return C(e,"Array")?H(o[0]):C(e,"Capitalize")?_m(o[0]):C(e,"ConstructorParameters")?Fm(o[0]):C(e,"Evaluate")?rb(o[0]):C(e,"Exclude")?jm(o[0],o[1]):C(e,"Extract")?Um(o[0],o[1]):C(e,"Index")?Qu(o[0],o[1]):C(e,"InstanceType")?Bm(o[0]):C(e,"Lowercase")?Lm(o[0]):C(e,"NonNullable")?Gm(o[0]):C(e,"Omit")?Km(o[0],o[1]):C(e,"Parameters")?Hm(o[0]):C(e,"Partial")?Wm(o[0]):C(e,"Pick")?zm(o[0],o[1]):C(e,"Readonly")?Vm(o[0]):C(e,"KeyOf")?Xu(o[0]):C(e,"Record")?Pm(o[0],o[1]):C(e,"Required")?Jm(o[0]):C(e,"ReturnType")?Qm(o[0]):C(e,"Uncapitalize")?Nm(o[0]):C(e,"Uppercase")?qm(o[0]):Ju(sn(e),o)}function Ea(){throw Error("Unreachable")}function Kx(e,o=[]){return It(e,(a,u)=>Kx(u,[...o,a[1]]),()=>o)}function ri(e){return C(e.length,3)?[e[0],...Kx(e[1])]:[]}function Hx(e){return ya(e[0],e[2],e[4])}function Wx(e){return ya(e[0],e[2],e[2])}function zx(e){return ya(e[0],Q(),e[2])}function Vx(e){return ya(e,Q(),Q())}function Jx(e){return e}function Qx(e){return ri(e)}function Xx(e){return e[1]}function Yx(e){return ri(e)}function Zx(e){return e[1]}function eI(e){return KO(e[0],e[1])}function tI(e){return null}function rI(e){return s()}function nI(e){return ne()}function oI(e){return D()}function sI(e){return Va()}function iI(e){return Un()}function aI(e){return x()}function uI(e){return Fu()}function cI(e){return Q()}function mI(e){return Ba()}function pI(e){return l({})}function lI(e){return sr()}function dI(e){return Ha()}function fI(e){return Mm()}function hI(e){return Cm()}function gI(e){return i(BigInt(e))}function yI(e){return i(C(e,"true"))}function xI(e){return i(parseFloat(e))}function II(e){return i(e)}function EI(e){return e[1]}function bI(e){return i(e)}function SI(e){return C(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function wI(e){return e[1]}function TI(e){return Om(e)}function RI(e){return C(e.length,6)?la(e[1],e[3],e[5]):la(e[1],e[3],Q())}function kI(e){return e.length>0}function AI(e){return e.reduce((o,a)=>C(a.length,3)?[...o,[a[1]]]:[...o,[]],[])}function PI(e){return C(e.length,6)?[e[1],e[3],e[5]]:[]}function $I(e){return Le(e)&&C(e.length,3)?e[1]:e}function CI(e){return C(e.length,2)?e[1]:[]}function jx(e,o){return o.reduce((a,u)=>{let p=u;return C(p.length,1)?Qu(a,p[0]):C(p.length,0)?H(a):Ea()},e)}function Ux(e,o){return C(o.length,3)?Dm(e,o[0],o[1],o[2]):e}function HO(e,o){return Le(o)&&C(o.length,0)?e:Xm(e,o)}function vI(e){let[o,a,u,p,f]=e;return HO(o?Ux(Xu(jx(a,u)),p):Ux(jx(a,u),p),f)}function xd(e,o){return C(o.length,3)?(()=>{let[a,u,p]=o,f=xd(u,p);if(C(a,"&"))return ze(f)?jn([e,...f.allOf]):jn([e,f]);if(C(a,"|"))return ye(f)?y([e,...f.anyOf]):y([e,f]);Ea()})():e}function MI(e){return e}function OI(e){let[o,a]=e;return xd(o,a)}function _I(e){return e}function LI(e){let[o,a]=e;return xd(o,a)}function NI(e){return tb(e[1])}function qI(e){return e[1]}function DI(e){return Ai(e[0],e[2])}function FI(e){return C(e.length,4)?Du(e[1],e[3]):C(e.length,2)?Du(e[1],Q()):Ea()}function jI(e){return e}function UI(e){return`${e}`}function BI(e){return e}function GI(e){return e}function KI(e){return In(e[3])?Mi:Lr(e[3])?za:Gs(e[3])?fs:nn(e[3])?fs:Ea()}function HI(e){return e}function WI(e){return e.length>0}function zI(e){return e.length>0}function VI(e){let[o,a,u,p,f]=e;return{[a]:o&&u?Us(Fs(f)):o&&!u?Us(f):!o&&u?Fs(f):f}}function JI(e){return e}function QI(e){return ri(e)}function XI(e){return e.reduce((o,a)=>me(a,Mi)||me(a,za)||me(a,fs)?[o[0],ln(o[1],a)]:[ln(o[0],a),o[1]],[{},{}])}function YI(e){return XI(e[1])}function ZI(e){let[o,a]=e,u=C(Ee(a).length,0)?{}:{patternProperties:a};return l(o,u)}function eE(e){return C(e.length,5)?Us(Fs(e[4])):C(e.length,3)?e[2]:C(e.length,4)?C(e[2],"readonly")?Us(e[3]):Fs(e[3]):Ea()}function tE(e){if(!Le(e)||!C(e.length,3))return e;let[o,a,u]=e;return o&&u?Us(Fs(a)):o&&!u?Us(a):!o&&u?Fs(a):a}function rE(e){return C(e.length,2)?Ia(e[1]):C(e.length,1)?e[0]:Ea()}function nE(e){return ri(e)}function oE(e){return zr(e[1])}function sE(e){return Us(Fs(e[4]))}function iE(e){return Us(e[3])}function aE(e){return Fs(e[3])}function uE(e){return e[2]}function cE(e){return e}function mE(e){return C(e.length,2)?Ia(e[1]):C(e.length,1)?e[0]:Ea()}function pE(e){return ri(e)}function lE(e){return Ds(e[1],e[4])}function dE(e){return qs(e[2],e[5])}function Bx(e,o){return C(e,"remove")?Ix(o):C(e,"add")?Us(o):o}function fE(e){return C(e.length,2)&&C(e[0],"-")?"remove":C(e.length,2)&&C(e[0],"+")?"add":C(e.length,1)?"add":"none"}function Gx(e,o){return C(e,"remove")?Sx(o):C(e,"add")?Fs(o):o}function hE(e){return C(e.length,2)&&C(e[0],"-")?"remove":C(e.length,2)&&C(e[0],"+")?"add":C(e.length,1)?"add":"none"}function gE(e){return C(e.length,2)?[e[1]]:[]}function yE(e){return Le(e[6])&&C(e[6].length,1)?zu(ju(e[3]),e[5],e[6][0],Bx(e[1],Gx(e[8],e[10]))):zu(ju(e[3]),e[5],sn(e[3]),Bx(e[1],Gx(e[8],e[10])))}function xE(e){return sn(e)}function IE(e){return BigInt(e)}function EE(e){return parseFloat(e)}function bE(e){return C(e,"true")}function SE(e){return e}function wE(e){return null}function TE(e){return}function RE(e){return{[e[0]]:e[2]}}function kE(e){return ri(e)}function WO(e){return e.reduce((o,a)=>ln(o,a),{})}function AE(e){return WO(e[1])}function PE(e){return ri(e)}function $E(e){return e[1]}function CE(e){return e}function vE(e){return Fu()}function ME(e){return s()}function OE(e){return ne()}function _E(e){return x()}function LE(e){return sr()}function NE(e){return i(e)}function qE(e){return e}function DE(e){return y(e[1])}function FE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function jE(e){return[e[0],...e[1]]}function UE(e){return e}function BE(e){return e[1]}function GE(e){return ri(e)}function KE(e){return C(e.length,2)?e[1]:[]}function HE(e){let o=e[2],a=e[3],[u,p]=e[4],f=C(Ee(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Ai(o,Vu(a,u,f))}}function WE(e){let o=e[2],[a,u]=e[3],p=C(Ee(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Vu(o,a,p)}}function zE(e){return{[e[1]]:Ai(e[2],e[4])}}function VE(e){return{[e[1]]:e[3]}}function JE(e){return null}function QE(e){return e}function XE(e){return ri(e)}function YE(e){return e[1]}function ZE(e){let[o,a]=[e[0],e[1]];return nb(ln(o,XI(a)[0]))}function eb(e){return e}function Yu(e){return C(e.length,2)}function Rt(e,o,a){return Yu(e)?o(e[0],e[1]):a()}function JO(e,o){return C(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Ur(e,o){for(let a=0;a<e.length;a++){let u=JO(e[a],o);if(Yu(u))return u}return[]}function Id(e,o){return Array.from({length:o-e+1},(a,u)=>String.fromCharCode(e+u))}var ob=[...Id(97,122),...Id(65,90)],Ed="0",bd=Id(49,57),Ja=[Ed,...bd],sb=" ",Qa=`
|
|
17
|
-
`;var Li="_",Ym=".",ib="$",Zm="-";var ab="//",ub="/*",XO="*/";function cb(e){let o=e.indexOf(XO);return C(o,-1)?"":e.slice(o+2)}function mb(e){let o=e.indexOf(Qa);return C(o,-1)?"":e.slice(o)}function YO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function ep(e){let o=YO(e);return o.startsWith(ub)?ep(cb(o.slice(2))):o.startsWith(ab)?ep(mb(o.slice(2))):o}function $n(e){let o=e.trimStart();return o.startsWith(ub)?$n(cb(o.slice(2))):o.startsWith(ab)?$n(mb(o.slice(2))):o}function tp(e,o){return Rt(Ur([e],o),(a,u)=>[a,u],()=>["",o])}function ZO(e,o){return e.includes(o)}function Xa(e,o,a,u=""){return Rt(Ur(e,a),(p,f)=>ZO(o,p)?Xa(e,o,f,u):Xa(e,o,f,`${u}${p}`),()=>[u,a])}function e_(e){return Ur(bd,e)}var t_=[...Ja,Li];function r_(e){return Xa(t_,[Li],e)}function n_(e){return Rt(Ur([Ed],e),(o,a)=>[o,a],()=>Rt(e_(e),(o,a)=>Rt(r_(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[]))}function rp(e){return n_($n(e))}function o_(e){return tp(Zm,e)}function s_(e){return Rt(o_(e),(o,a)=>Rt(rp(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function pb(e){return s_($n(e))}function i_(e){return Rt(pb(e),(o,a)=>Rt(Ur(["n"],a),(u,p)=>[`${o}`,p],()=>[]),()=>[])}function Sd(e){return i_(e)}function wd(e,o){return Ur([e],o)}function B(e,o){return C(e,"")?["",o]:e.startsWith(Qa)?wd(e,ep(o)):e.startsWith(sb)?wd(e,o):wd(e,$n(o))}var lb=[...ob,Li,ib];function a_(e){return Ur(lb,e)}var u_=[...lb,...Ja];function db(e,o=""){return Rt(Ur(u_,e),(a,u)=>db(u,`${o}${a}`),()=>[o,e])}function c_(e){return Rt(a_(e),(o,a)=>Rt(db(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Vr(e){return c_($n(e))}var m_=[...Ja,Li];function p_(e){return Yu(Ur([Ym],e))}function fb(e){return Rt(Xa(m_,[Li],e),(o,a)=>C(o,"")?[]:[o,a],()=>[])}function l_(e){return Rt(Ur([Ym],e),(o,a)=>Rt(fb(a),(u,p)=>[`0${o}${u}`,p],()=>[]),()=>[])}function d_(e){return Rt(rp(e),(o,a)=>Rt(Ur([Ym],a),(u,p)=>Rt(fb(p),(f,h)=>[`${o}${u}${f}`,h],()=>[`${o}`,p]),()=>[`${o}`,a]),()=>[])}function f_(e){return p_(e)?l_(e):d_(e)}function hb(e){return f_($n(e))}function h_(e){return tp(Zm,e)}function g_(e){return Rt(h_(e),(o,a)=>Rt(hb(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function np(e){return g_($n(e))}function y_(e){return C(e,"")?[]:[e.slice(0,1),e.slice(1)]}function gb(e,o){return It(e,(a,u)=>o.startsWith(a)?!0:gb(u,o),()=>!1)}function Ni(e,o,a=""){return Rt(y_(o),(u,p)=>gb(e,o)?[a,o]:Ni(e,p,`${a}${u}`),()=>[])}function x_(e,o,a){return Rt(Ur([e],a),(u,p)=>Rt(Ni([o],p),(f,h)=>Rt(Ur([o],h),(g,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function I_(e,o,a){return Rt(Ur([e],a),(u,p)=>Rt(Ni([Qa,o],p),(f,h)=>Rt(Ur([o],h),(g,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function yb(e,o,a,u){return a?x_(e,o,$n(u)):I_(e,o,$n(u))}function E_(e,o){return Ur(e,o)}function b_(e,o){return yb(e,e,!1,o)}function S_(e,o){return Rt(E_(e,o),(a,u)=>b_(a,`${a}${u}`),()=>[])}function op(e,o){return S_(e,$n(o))}function xb(e,o){return Rt(Ni(e,o),(a,u)=>C(a,"")?[]:[a,u],()=>[])}var w=(e,o,a=()=>[])=>e.length===2?o(e):a(),T_=(e)=>w(w(Vr(e),([o,a])=>w(B("extends",a),([u,p])=>w(qt(p),([f,h])=>w(B("=",h),([g,I])=>w(qt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[Hx(o),a]),R_=(e)=>w(w(Vr(e),([o,a])=>w(B("extends",a),([u,p])=>w(qt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Wx(o),a]),k_=(e)=>w(w(Vr(e),([o,a])=>w(B("=",a),([u,p])=>w(qt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[zx(o),a]),A_=(e)=>w(Vr(e),([o,a])=>[Vx(o),a]),bb=(e)=>w(w(T_(e),([o,a])=>[o,a],()=>w(R_(e),([o,a])=>[o,a],()=>w(k_(e),([o,a])=>[o,a],()=>w(A_(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Jx(o),a]),Sb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(bb(u),([p,f])=>[[a,p],f])),([a,u])=>Sb(u,[...o,a]),()=>[o,e]),P_=(e)=>w(w(w(bb(e),([o,a])=>w(Sb(a),([u,p])=>w(w(B(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Qx(o),a]),kd=(e)=>w(w(B("<",e),([o,a])=>w(P_(a),([u,p])=>w(B(">",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Xx(o),a]),wb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(qt(u),([p,f])=>[[a,p],f])),([a,u])=>wb(u,[...o,a]),()=>[o,e]),$_=(e)=>w(w(w(qt(e),([o,a])=>w(wb(a),([u,p])=>w(w(B(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Yx(o),a]),C_=(e)=>w(w(B("<",e),([o,a])=>w($_(a),([u,p])=>w(B(">",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Zx(o),a]),v_=(e)=>w(w(Vr(e),([o,a])=>w(C_(a),([u,p])=>[[o,u],p])),([o,a])=>[eI(o),a]),Tb=(e)=>w(w(w(B(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[tI(o),a]),Rb=(e)=>w(B("string",e),([o,a])=>[rI(o),a]),kb=(e)=>w(B("number",e),([o,a])=>[nI(o),a]),M_=(e)=>w(B("boolean",e),([o,a])=>[oI(o),a]),O_=(e)=>w(B("undefined",e),([o,a])=>[sI(o),a]),__=(e)=>w(B("null",e),([o,a])=>[iI(o),a]),Ab=(e)=>w(B("integer",e),([o,a])=>[aI(o),a]),L_=(e)=>w(B("bigint",e),([o,a])=>[uI(o),a]),N_=(e)=>w(B("unknown",e),([o,a])=>[cI(o),a]),q_=(e)=>w(B("any",e),([o,a])=>[mI(o),a]),D_=(e)=>w(B("object",e),([o,a])=>[pI(o),a]),F_=(e)=>w(B("never",e),([o,a])=>[lI(o),a]),Pb=(e)=>w(B("symbol",e),([o,a])=>[dI(o),a]),j_=(e)=>w(B("void",e),([o,a])=>[fI(o),a]),U_=(e)=>w(B("this",e),([o,a])=>[hI(o),a]),B_=(e)=>w(w(B("${",e),([o,a])=>w(qt(a),([u,p])=>w(B("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[EI(o),a]),Td=(e)=>w(Ni(["${","`"],e),([o,a])=>[bI(o),a]),$b=(e)=>w(w(w(Td(e),([o,a])=>w(B_(a),([u,p])=>w($b(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(w(Td(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(Td(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[SI(o),a]),Ad=(e)=>w(w(B("`",e),([o,a])=>w($b(a),([u,p])=>w(B("`",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[wI(o),a]),G_=(e)=>w(Ad(e),([o,a])=>[TI(o),a]),K_=(e)=>w(w(w(B("if",e),([o,a])=>w(qt(a),([u,p])=>w(B("then",p),([f,h])=>w(qt(h),([g,I])=>w(B("else",I),([E,S])=>w(qt(S),([k,A])=>[[o,u,f,g,E,k],A])))))),([o,a])=>[o,a],()=>w(w(B("if",e),([o,a])=>w(qt(a),([u,p])=>w(B("then",p),([f,h])=>w(qt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>[])),([o,a])=>[RI(o),a]),H_=(e)=>w(Sd(e),([o,a])=>[gI(o),a]),W_=(e)=>w(w(B("true",e),([o,a])=>[o,a],()=>w(B("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[yI(o),a]),z_=(e)=>w(np(e),([o,a])=>[xI(o),a]),V_=(e)=>w(op(["'",'"'],e),([o,a])=>[II(o),a]),J_=(e)=>w(w(w(B("keyof",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kI(o),a]),Cb=(e,o=[])=>w(w(w(B("[",e),([a,u])=>w(qt(u),([p,f])=>w(B("]",f),([h,g])=>[[a,p,h],g]))),([a,u])=>[a,u],()=>w(w(B("[",e),([a,u])=>w(B("]",u),([p,f])=>[[a,p],f])),([a,u])=>[a,u],()=>[])),([a,u])=>Cb(u,[...o,a]),()=>[o,e]),Q_=(e)=>w(Cb(e),([o,a])=>[AI(o),a]),X_=(e)=>w(w(w(B("extends",e),([o,a])=>w(qt(a),([u,p])=>w(B("?",p),([f,h])=>w(qt(h),([g,I])=>w(B(":",I),([E,S])=>w(qt(S),([k,A])=>[[o,u,f,g,E,k],A])))))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[PI(o),a]),Y_=(e)=>w(w(w(B("(",e),([o,a])=>w(qt(a),([u,p])=>w(B(")",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(Rb(e),([o,a])=>[o,a],()=>w(kb(e),([o,a])=>[o,a],()=>w(M_(e),([o,a])=>[o,a],()=>w(O_(e),([o,a])=>[o,a],()=>w(__(e),([o,a])=>[o,a],()=>w(Ab(e),([o,a])=>[o,a],()=>w(L_(e),([o,a])=>[o,a],()=>w(N_(e),([o,a])=>[o,a],()=>w(q_(e),([o,a])=>[o,a],()=>w(D_(e),([o,a])=>[o,a],()=>w(F_(e),([o,a])=>[o,a],()=>w(Pb(e),([o,a])=>[o,a],()=>w(j_(e),([o,a])=>[o,a],()=>w(U_(e),([o,a])=>[o,a],()=>w(H_(e),([o,a])=>[o,a],()=>w(W_(e),([o,a])=>[o,a],()=>w(z_(e),([o,a])=>[o,a],()=>w(V_(e),([o,a])=>[o,a],()=>w(G_(e),([o,a])=>[o,a],()=>w(K_(e),([o,a])=>[o,a],()=>w(cL(e),([o,a])=>[o,a],()=>w(lL(e),([o,a])=>[o,a],()=>w(xL(e),([o,a])=>[o,a],()=>w(yL(e),([o,a])=>[o,a],()=>w(SL(e),([o,a])=>[o,a],()=>w(v_(e),([o,a])=>[o,a],()=>w(wL(e),([o,a])=>[o,a],()=>[])))))))))))))))))))))))))))),([o,a])=>[$I(o),a]),Z_=(e)=>w(w(w(B("with",e),([o,a])=>w(zb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[CI(o),a]),vb=(e)=>w(w(J_(e),([o,a])=>w(Y_(a),([u,p])=>w(Q_(p),([f,h])=>w(X_(h),([g,I])=>w(Z_(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[vI(o),a]),Mb=(e)=>w(w(w(B("&",e),([o,a])=>w(vb(a),([u,p])=>w(Mb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[MI(o),a]),Ob=(e)=>w(w(vb(e),([o,a])=>w(Mb(a),([u,p])=>[[o,u],p])),([o,a])=>[OI(o),a]),_b=(e)=>w(w(w(B("|",e),([o,a])=>w(Ob(a),([u,p])=>w(_b(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[_I(o),a]),sp=(e)=>w(w(Ob(e),([o,a])=>w(_b(a),([u,p])=>[[o,u],p])),([o,a])=>[LI(o),a]),eL=(e)=>w(w(B("readonly",e),([o,a])=>w(sp(a),([u,p])=>[[o,u],p])),([o,a])=>[NI(o),a]),tL=(e)=>w(w(B("|",e),([o,a])=>w(sp(a),([u,p])=>[[o,u],p])),([o,a])=>[qI(o),a]),rL=(e)=>w(w(kd(e),([o,a])=>w(B("=",a),([u,p])=>w(qt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[DI(o),a]),nL=(e)=>w(w(w(B("infer",e),([o,a])=>w(Vr(a),([u,p])=>w(B("extends",p),([f,h])=>w(sp(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>w(w(B("infer",e),([o,a])=>w(Vr(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>[])),([o,a])=>[FI(o),a]),qt=(e)=>w(w(nL(e),([o,a])=>[o,a],()=>w(tL(e),([o,a])=>[o,a],()=>w(eL(e),([o,a])=>[o,a],()=>w(sp(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[jI(o),a]),oL=(e)=>w(np(e),([o,a])=>[UI(o),a]),sL=(e)=>w(Vr(e),([o,a])=>[BI(o),a]),iL=(e)=>w(op(["'",'"'],e),([o,a])=>[GI(o),a]),aL=(e)=>w(w(B("[",e),([o,a])=>w(Vr(a),([u,p])=>w(B(":",p),([f,h])=>w(w(Ab(h),([g,I])=>[g,I],()=>w(kb(h),([g,I])=>[g,I],()=>w(Rb(h),([g,I])=>[g,I],()=>w(Pb(h),([g,I])=>[g,I],()=>[])))),([g,I])=>w(B("]",I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[KI(o),a]),Lb=(e)=>w(w(oL(e),([o,a])=>[o,a],()=>w(sL(e),([o,a])=>[o,a],()=>w(iL(e),([o,a])=>[o,a],()=>w(aL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[HI(o),a]),Nb=(e)=>w(w(w(B("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[WI(o),a]),qb=(e)=>w(w(w(B("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[zI(o),a]),Db=(e)=>w(w(Nb(e),([o,a])=>w(Lb(a),([u,p])=>w(qb(p),([f,h])=>w(B(":",h),([g,I])=>w(qt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[VI(o),a]),ip=(e)=>w(w(w(B(",",e),([o,a])=>w(B(`
|
|
18
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B(";",e),([o,a])=>w(B(`
|
|
19
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B(",",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(B(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(B(`
|
|
20
|
-
`,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))))),([o,a])=>[JI(o),a]),Fb=(e,o=[])=>w(w(ip(e),([a,u])=>w(Db(u),([p,f])=>[[a,p],f])),([a,u])=>Fb(u,[...o,a]),()=>[o,e]),uL=(e)=>w(w(w(Db(e),([o,a])=>w(Fb(a),([u,p])=>w(w(ip(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[QI(o),a]),Pd=(e)=>w(w(B("{",e),([o,a])=>w(uL(a),([u,p])=>w(B("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[YI(o),a]),cL=(e)=>w(Pd(e),([o,a])=>[ZI(o),a]),mL=(e)=>w(w(w(Vr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(B("readonly",h),([g,I])=>w(qt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[o,a],()=>w(w(Vr(e),([o,a])=>w(B(":",a),([u,p])=>w(B("readonly",p),([f,h])=>w(qt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>w(w(Vr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(qt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>w(w(Vr(e),([o,a])=>w(B(":",a),([u,p])=>w(qt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>[])))),([o,a])=>[eE(o),a]),Ib=(e)=>w(w(mL(e),([o,a])=>[o,a],()=>w(w(Nb(e),([o,a])=>w(qt(a),([u,p])=>w(qb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>[])),([o,a])=>[tE(o),a]),jb=(e)=>w(w(w(B("...",e),([o,a])=>w(Ib(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(Ib(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[rE(o),a]),Ub=(e,o=[])=>w(w(B(",",e),([a,u])=>w(jb(u),([p,f])=>[[a,p],f])),([a,u])=>Ub(u,[...o,a]),()=>[o,e]),pL=(e)=>w(w(w(jb(e),([o,a])=>w(Ub(a),([u,p])=>w(w(B(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[nE(o),a]),lL=(e)=>w(w(B("[",e),([o,a])=>w(pL(a),([u,p])=>w(B("]",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[oE(o),a]),dL=(e)=>w(w(Vr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(B("readonly",h),([g,I])=>w(qt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[sE(o),a]),fL=(e)=>w(w(Vr(e),([o,a])=>w(B(":",a),([u,p])=>w(B("readonly",p),([f,h])=>w(qt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[iE(o),a]),hL=(e)=>w(w(Vr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(qt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[aE(o),a]),gL=(e)=>w(w(Vr(e),([o,a])=>w(B(":",a),([u,p])=>w(qt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[uE(o),a]),Eb=(e)=>w(w(dL(e),([o,a])=>[o,a],()=>w(fL(e),([o,a])=>[o,a],()=>w(hL(e),([o,a])=>[o,a],()=>w(gL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[cE(o),a]),Bb=(e)=>w(w(w(B("...",e),([o,a])=>w(Eb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(Eb(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[mE(o),a]),Gb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(Bb(u),([p,f])=>[[a,p],f])),([a,u])=>Gb(u,[...o,a]),()=>[o,e]),Kb=(e)=>w(w(w(Bb(e),([o,a])=>w(Gb(a),([u,p])=>w(w(B(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[pE(o),a]),yL=(e)=>w(w(B("(",e),([o,a])=>w(Kb(a),([u,p])=>w(B(")",p),([f,h])=>w(B("=>",h),([g,I])=>w(qt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[lE(o),a]),xL=(e)=>w(w(B("new",e),([o,a])=>w(B("(",a),([u,p])=>w(Kb(p),([f,h])=>w(B(")",h),([g,I])=>w(B("=>",I),([E,S])=>w(qt(S),([k,A])=>[[o,u,f,g,E,k],A])))))),([o,a])=>[dE(o),a]),IL=(e)=>w(w(w(B("+",e),([o,a])=>w(B("readonly",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B("-",e),([o,a])=>w(B("readonly",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[fE(o),a]),EL=(e)=>w(w(w(B("+",e),([o,a])=>w(B("?",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B("-",e),([o,a])=>w(B("?",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[hE(o),a]),bL=(e)=>w(w(w(B("as",e),([o,a])=>w(qt(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[gE(o),a]),SL=(e)=>w(w(B("{",e),([o,a])=>w(IL(a),([u,p])=>w(B("[",p),([f,h])=>w(Vr(h),([g,I])=>w(B("in",I),([E,S])=>w(qt(S),([k,A])=>w(bL(A),([P,v])=>w(B("]",v),([M,J])=>w(EL(J),([O,V])=>w(B(":",V),([j,te])=>w(qt(te),([se,L])=>w(Tb(L),([re,he])=>w(B("}",he),([we,We])=>[[o,u,f,g,E,k,P,M,O,j,se,re,we],We]))))))))))))),([o,a])=>[yE(o),a]),wL=(e)=>w(Vr(e),([o,a])=>[xE(o),a]),TL=(e)=>w(Sd(e),([o,a])=>[IE(o),a]),RL=(e)=>w(np(e),([o,a])=>[EE(o),a]),kL=(e)=>w(w(B("true",e),([o,a])=>[o,a],()=>w(B("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[bE(o),a]),AL=(e)=>w(op(['"',"'"],e),([o,a])=>[SE(o),a]),PL=(e)=>w(B("null",e),([o,a])=>[wE(o),a]),$L=(e)=>w(B("undefined",e),([o,a])=>[TE(o),a]),Hb=(e)=>w(w(Lb(e),([o,a])=>w(B(":",a),([u,p])=>w($d(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[RE(o),a]),Wb=(e,o=[])=>w(w(ip(e),([a,u])=>w(Hb(u),([p,f])=>[[a,p],f])),([a,u])=>Wb(u,[...o,a]),()=>[o,e]),CL=(e)=>w(w(w(Hb(e),([o,a])=>w(Wb(a),([u,p])=>w(w(ip(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kE(o),a]),zb=(e)=>w(w(B("{",e),([o,a])=>w(CL(a),([u,p])=>w(B("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[AE(o),a]),Vb=(e,o=[])=>w(w(B(",",e),([a,u])=>w($d(u),([p,f])=>[[a,p],f])),([a,u])=>Vb(u,[...o,a]),()=>[o,e]),vL=(e)=>w(w(w($d(e),([o,a])=>w(Vb(a),([u,p])=>w(w(B(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[PE(o),a]),ML=(e)=>w(w(B("[",e),([o,a])=>w(vL(a),([u,p])=>w(B("]",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[$E(o),a]),$d=(e)=>w(w(TL(e),([o,a])=>[o,a],()=>w(RL(e),([o,a])=>[o,a],()=>w(kL(e),([o,a])=>[o,a],()=>w(AL(e),([o,a])=>[o,a],()=>w(PL(e),([o,a])=>[o,a],()=>w($L(e),([o,a])=>[o,a],()=>w(zb(e),([o,a])=>[o,a],()=>w(ML(e),([o,a])=>[o,a],()=>[])))))))),([o,a])=>[CE(o),a]),OL=(e)=>w(B("-?(?:0|[1-9][0-9]*)n",e),([o,a])=>[vE(o),a]),_L=(e)=>w(B(".*",e),([o,a])=>[ME(o),a]),LL=(e)=>w(B("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,a])=>[OE(o),a]),NL=(e)=>w(B("-?(?:0|[1-9][0-9]*)",e),([o,a])=>[_E(o),a]),qL=(e)=>w(B("(?!)",e),([o,a])=>[LE(o),a]),DL=(e)=>w(xb(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,a])=>[NE(o),a]),FL=(e)=>w(w(OL(e),([o,a])=>[o,a],()=>w(_L(e),([o,a])=>[o,a],()=>w(LL(e),([o,a])=>[o,a],()=>w(NL(e),([o,a])=>[o,a],()=>w(qL(e),([o,a])=>[o,a],()=>w(jL(e),([o,a])=>[o,a],()=>w(DL(e),([o,a])=>[o,a],()=>[]))))))),([o,a])=>[qE(o),a]),jL=(e)=>w(w(B("(",e),([o,a])=>w(Cd(a),([u,p])=>w(B(")",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[DE(o),a]),Jb=(e)=>w(w(w(Rd(e),([o,a])=>w(B("|",a),([u,p])=>w(Jb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(w(Rd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[]))),([o,a])=>[FE(o),a]),Rd=(e)=>w(w(FL(e),([o,a])=>w(Cd(a),([u,p])=>[[o,u],p])),([o,a])=>[jE(o),a]),Cd=(e)=>w(w(Jb(e),([o,a])=>[o,a],()=>w(Rd(e),([o,a])=>[o,a],()=>[])),([o,a])=>[UE(o),a]),ux=(e)=>w(w(B("^",e),([o,a])=>w(Cd(a),([u,p])=>w(B("$",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[BE(o),a]),Qb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(qt(u),([p,f])=>[[a,p],f])),([a,u])=>Qb(u,[...o,a]),()=>[o,e]),UL=(e)=>w(w(w(qt(e),([o,a])=>w(Qb(a),([u,p])=>w(w(B(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[GE(o),a]),Xb=(e)=>w(w(w(B("extends",e),([o,a])=>w(UL(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[KE(o),a]),BL=(e)=>w(w(B("interface",e),([o,a])=>w(Vr(a),([u,p])=>w(kd(p),([f,h])=>w(Xb(h),([g,I])=>w(Pd(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[HE(o),a]),GL=(e)=>w(w(B("interface",e),([o,a])=>w(Vr(a),([u,p])=>w(Xb(p),([f,h])=>w(Pd(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[WE(o),a]),KL=(e)=>w(w(B("type",e),([o,a])=>w(Vr(a),([u,p])=>w(kd(p),([f,h])=>w(B("=",h),([g,I])=>w(qt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[zE(o),a]),HL=(e)=>w(w(B("type",e),([o,a])=>w(Vr(a),([u,p])=>w(B("=",p),([f,h])=>w(qt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[VE(o),a]),WL=(e)=>w(w(w(B("export",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[JE(o),a]),Yb=(e)=>w(w(w(B(";",e),([o,a])=>w(B(`
|
|
21
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(B(`
|
|
22
|
-
`,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[QE(o),a]),Zb=(e,o=[])=>w(w(Yb(e),([a,u])=>w(vd(u),([p,f])=>[[a,p],f])),([a,u])=>Zb(u,[...o,a]),()=>[o,e]),zL=(e)=>w(w(w(vd(e),([o,a])=>w(Zb(a),([u,p])=>w(w(Yb(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[XE(o),a]),vd=(e)=>w(w(WL(e),([o,a])=>w(w(BL(a),([u,p])=>[u,p],()=>w(GL(a),([u,p])=>[u,p],()=>w(KL(a),([u,p])=>[u,p],()=>w(HL(a),([u,p])=>[u,p],()=>[])))),([u,p])=>w(Tb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[YE(o),a]),VL=(e)=>w(w(vd(e),([o,a])=>w(zL(a),([u,p])=>[[o,u],p])),([o,a])=>[ZE(o),a]),eS=(e)=>w(w(VL(e),([o,a])=>[o,a],()=>w(rL(e),([o,a])=>[o,a],()=>w(qt(e),([o,a])=>[o,a],()=>[]))),([o,a])=>[eb(o),a]);function tS(e){let o=Ad(`\`${e}\``);return C(o.length,2)?o[0]:Wr()}function QL(e){return e.join("|")}function XL(e){return e.slice(1,e.length-1)}function YL(e,o,a){return Di(o,`${a}${e}`)}function ZL(e,o){return Di(e,`${o}${tx}`)}function eN(e,o){return Di(e,`${o}${xm}`)}function tN(e,o){return Di(e,`${o}${Sm}`)}function rN(e,o){return Zu(y([i("false"),i("true")]),e,o)}function nN(e,o){return Di(e,`${o}${wm}`)}function oN(e,o,a){return Di(o,`${a}${XL(e)}`)}function sN(e,o,a){let u=ec(e,{});return Zu(u,o,a)}function iN(e,o,a){let u=xo(e);return Zu(u,o,a)}function rS(e,o,a,u=[]){return It(e,(p,f)=>rS(f,o,a,[...u,Zu(p,[],"")]),()=>Di(o,`${a}(${QL(u)})`))}function Zu(e,o,a){return rn(e)?iN(e.enum,o,a):In(e)?eN(o,a):yt(e)?YL(e.const,o,a):Po(e)?ZL(o,a):yo(e)?rN(o,a):Lr(e)?tN(o,a):nn(e)?nN(o,a):lr(e)?oN(e.pattern,o,a):oS(e)?sN(e.parameters[0],o,a):ye(e)?rS(e.anyOf,o,a):$y}function Di(e,o){return It(e,(a,u)=>Zu(a,u,o),()=>o)}function aN(e){return`^${Di(e,"")}$`}function nS(e){let o=aN(e);return Rm(o)}function ec(e,o){return dt(e)?St(nS(e),{},o):Om(e,o)}function sS(e,o,a,u){let p=_o(e,o,a);return ec(p,u)}function Om(e,o={}){return Te("TemplateLiteral",[e],o)}function oS(e){return Dr(e)&&me(e,"action")&&C(e.action,"TemplateLiteral")}function iS(e){return ec(e,{})}function uN(e){let o=tS(e);return iS(o)}function aS(e,o={}){let a=gt(e)?uN(e):iS(e);return St(a,{},o)}function lr(e){return Se(e,"TemplateLiteral")}function Md(e){return Ct({["~kind"]:"ExtendsUnion"},{inferred:e})}function Od(e){return lt(e)&&me(e,"~kind")&&me(e,"inferred")&&C(e["~kind"],"ExtendsUnion")&<(e.inferred)}function be(e){return Ct({["~kind"]:"ExtendsTrue"},{inferred:e})}function _d(e){return lt(e)&&me(e,"~kind")&&me(e,"inferred")&&C(e["~kind"],"ExtendsTrue")&<(e.inferred)}function et(){return Ct({["~kind"]:"ExtendsFalse"},{})}function Ld(e){return lt(e)&&me(e,"~kind")&&C(e["~kind"],"ExtendsFalse")}function To(e){return Od(e)||_d(e)}function wr(e,o,a){return To(e)?o(e.inferred):a()}function cN(e,o,a,u){return wr(kt(e,a,u),(p)=>be(ln(ln(e,p),{[o]:a})),()=>et())}function mN(e,o){return be(e)}function pN(e,o,a,u,p){return wr(kt(e,o,a),(f)=>wr(kt(f,o,u),(h)=>be(h),()=>et()),()=>wr(kt(e,o,p),(f)=>be(f),()=>et()))}function lN(e,o,a){let u=xo(a);return kt(e,o,u)}function uS(e,o,a){return It(a,(u,p)=>wr(kt(e,o,u),(f)=>uS(f,o,p),()=>et()),()=>be(e))}function dN(e,o,a){let u=Bn(a);return kt(e,o,u)}function cS(e,o,a){return It(a,(u,p)=>wr(kt(e,o,u),(f)=>be(f),()=>cS(e,o,p)),()=>et())}function Ht(e,o,a){return Fr(a)?mN(e,o):Hr(a)?pN(e,o,a.if,a.then,a.else):rn(a)?lN(e,o,a.enum):tn(a)?cN(e,a.name,o,a.extends):ze(a)?uS(e,o,a.allOf):lr(a)?dN(e,o,a.pattern):ye(a)?cS(e,o,a.anyOf):en(a)?be(e):et()}function mS(e,o,a){return tn(a)?Ht(e,o,a):Fr(a)?be(e):en(a)?be(e):Md(e)}function fN(e,o){let a=fa(e),u=fa(o);return a&&u?!0:!a&&u?!0:a&&!u?!1:!0}function pS(e,o,a,u){return Tt(u)?fN(o,u)?kt(e,a,u.items):et():Ht(e,o,u)}function lS(e,o,a){return Po(a)?be(e):Ht(e,o,a)}function dS(e,o,a){return yo(a)?be(e):Ht(e,o,a)}function hN(e,o,a,u,p){let f=tn(u)?o:u,h=tn(u)?u:o,g=an(o),I=an(u);return!g&&I?et():wr(kt(e,f,h),(E)=>tc(E,a,p),()=>et())}function gN(e,o,a,u){return It(u,(p,f)=>hN(e,o,a,p,f),()=>an(o)?be(e):et())}function yN(e,o,a){return It(o,(u,p)=>gN(e,u,p,a),()=>be(e))}function tc(e,o,a){return yN(e,o,a)}function ap(e,o,a){return $o(a)?be(e):kt(e,o,a)}function fS(e,o,a,u){return Fr(u)?be(e):en(u)?be(e):Yr(u)?wr(tc(e,o,u.parameters),(p)=>ap(p,a,u.instanceType),()=>et()):et()}function hS(e,o,a,u,p){return wr(kt(e,o,p),()=>kt(e,a,p),()=>kt(e,u,p))}function gS(e,o,a){let u=xo(o);return kt(e,u,a)}function yS(e,o,a,u){return Fr(u)?be(e):en(u)?be(e):Zr(u)?wr(tc(e,o,u.parameters),(p)=>ap(p,a,u.returnType),()=>et()):et()}function xS(e,o,a){return In(a)?be(e):Lr(a)?be(e):Ht(e,o,a)}function IS(e,o,a){let u=Nr(o);return kt(e,u,a)}function up(e,o,a){return o===a?be(e):et()}function xN(e,o,a){return yt(a)?up(e,o,a.const):Po(a)?be(e):Ht(e,i(o),a)}function IN(e,o,a){return yt(a)?up(e,o,a.const):yo(a)?be(e):Ht(e,i(o),a)}function EN(e,o,a){return yt(a)?up(e,o,a.const):Lr(a)?be(e):Ht(e,i(o),a)}function bN(e,o,a){return yt(a)?up(e,o,a.const):nn(a)?be(e):Ht(e,i(o),a)}function ES(e,o,a){return Kr(o.const)?xN(e,o.const,a):cn(o.const)?IN(e,o.const,a):Ut(o.const)?EN(e,o.const,a):gt(o.const)?bN(e,o.const,a):Wr()}function bS(e,o,a){return tn(a)?Ht(e,o,a):be(e)}function SS(e,o,a){return Bs(a)?be(e):Ht(e,o,a)}function wS(e,o,a){return Lr(a)?be(e):Ht(e,o,a)}function SN(e,o,a){return an(o)?an(a)?be(e):et():be(e)}function wN(e,o,a){return tn(a)&&Ao(a.extends)?et():wr(kt(e,o,a),(u)=>SN(u,o,a),()=>et())}function TN(e,o){return e.reduce((a,u)=>(u in o)?To(o[u])?{...a,...o[u].inferred}:Wr():Wr(),{})}function RN(e,o,a){let u={};for(let h of Ee(a))u[h]=h in o?wN({},o[h],a[h]):an(a[h])?tn(a[h])?be(ln(e,{[a[h].name]:a[h].extends})):be(e):et();let p=nd(u).every((h)=>To(h)),f=p?TN(Ee(u),u):{};return p?be(f):et()}function kN(e,o,a){let u=RN(e,o,a);return To(u)?be(ln(e,u.inferred)):et()}function AN(e,o,a){return kN(e,o,a)}function PN(e,o){return Ee(o).reduce((a,u)=>({...a,[u]:me(e,u)?ye(a[u])?y([...a[u].anyOf,o[u]]):y([e[u],o[u]]):o[u]}),e)}function TS(e,o,a,u){return It(o,(p,f)=>wr(kt({},e[p],a),(h)=>TS(e,f,a,PN(u,h)),()=>et()),()=>be(u))}function $N(e,o,a,u){let p=Ee(o);return TS(o,p,u,e)}function RS(e,o,a){return nr(a)?$N(e,o,Sn(a),hr(a)):Je(a)?AN(e,o,a.properties):Ht(e,l(o),a)}function CN(e,o){return C(Ee(o).length,0)?be(e):et()}function vN(e,o,a,u,p){return kt(e,a,p)}function kS(e,o,a,u){return nr(u)?vN(e,$m(o),a,$m(Sn(u)),hr(u)):Je(u)?CN(e,u.properties):Fr(u)?be(e):en(u)?be(e):et()}function AS(e,o,a){return nn(a)?be(e):Ht(e,o,a)}function PS(e,o,a){return Gs(a)?be(e):Ht(e,o,a)}function $S(e,o,a){let u=Bn(o);return kt(e,u,a)}function Nd(e,o){return Ct({"~kind":"Inferrable"},{name:e,type:o},{})}function rc(e){return lt(e)&&me(e,"~kind")&&me(e,"name")&&me(e,"type")&&C(e["~kind"],"Inferrable")&>(e.name)&<(e.type)}function qd(e){return _i(e)?tn(e.items)?Tt(e.items.extends)?Nd(e.items.name,e.items.extends.items):en(e.items.extends)?Nd(e.items.name,e.items.extends):void 0:Wr():void 0}function cp(e){return tn(e)?Nd(e.name,e.extends):void 0}function Dd(e,o,a=[]){return It(e,(u,p)=>wr(kt({},u,o),()=>Dd(p,o,[...a,u]),()=>{return}),()=>a)}function CS(e,o,a,u){let p=Dd(a,u);return Le(p)?be(ln(e,{[o]:zr(p)})):et()}function mp(e,o,a,u){let p=Dd(a,u);return Le(p)?be(ln(e,{[o]:y(p)})):et()}function MN(e){return[...e].reverse()}function Fd(e,o){return o?MN(e):e}function ON(e){let o=e.length>0?e[0]:void 0,a=Dr(o)?qd(o):void 0;return Dr(a)}function _N(e,o,a,u,p,f){return wr(kt(e,a,p),(h)=>vS(h,o,u,f),()=>et())}function LN(e,o,a,u,p){let f=qd(u);return rc(f)?CS(e,f.name,Fd(a,o),f.type):It(a,(h,g)=>_N(e,o,h,g,u,p),()=>et())}function NN(e,o,a,u){return It(u,(p,f)=>LN(e,o,a,p,f),()=>C(a.length,0)?be(e):et())}function vS(e,o,a,u){return NN(e,o,a,u)}function qN(e,o,a){let u=ji(e,gr([],[]),a),p=ON(u);return vS(e,p,Fd(o,p),Fd(u,p))}function MS(e,o,a){let u=cp(a);return rc(u)?mp(e,u.name,o,u.type):It(o,(p,f)=>wr(kt(e,p,a),(h)=>MS(h,f,a),()=>et()),()=>be(e))}function OS(e,o,a){let u=ji(e,gr([],[]),o);return ft(a)?qN(e,u,a.items):Tt(a)?MS(e,u,a.items):Ht(e,zr(u),a)}function _S(e,o,a){return $o(a)?be(e):ys(a)?be(e):Ht(e,o,a)}function LS(e,o,a){return It(a,(u,p)=>wr(kt(e,o,u),(f)=>be(f),()=>LS(e,o,p)),()=>et())}function jd(e,o,a){return It(o,(u,p)=>wr(LS(e,u,a),(f)=>jd(f,p,a),()=>et()),()=>be(e))}function NS(e,o,a){let u=cp(a);return rc(u)?mp(e,u.name,o,u.type):ye(a)?jd(e,o,a.anyOf):jd(e,o,[a])}function qS(e,o,a){return tn(a)?Ht(e,o,a):Fr(a)?be(e):en(a)?be(e):et()}function DS(e,o,a){return $o(a)?be(e):Ht(e,o,a)}function kt(e,o,a){return Fr(o)?mS(e,o,a):Tt(o)?pS(e,o,o.items,a):Po(o)?lS(e,o,a):yo(o)?dS(e,o,a):Yr(o)?fS(e,o.parameters,o.instanceType,a):Hr(o)?hS(e,o.if,o.then,o.else,a):rn(o)?gS(e,o.enum,a):Zr(o)?yS(e,o.parameters,o.returnType,a):In(o)?xS(e,o,a):ze(o)?IS(e,o.allOf,a):yt(o)?ES(e,o,a):Ao(o)?bS(e,o,a):Bs(o)?SS(e,o,a):Lr(o)?wS(e,o,a):Je(o)?RS(e,o.properties,a):nr(o)?kS(e,Sn(o),hr(o),a):nn(o)?AS(e,o,a):Gs(o)?PS(e,o,a):lr(o)?$S(e,o.pattern,a):ft(o)?OS(e,o.items,a):ys(o)?_S(e,o,a):ye(o)?NS(e,o.anyOf,a):en(o)?qS(e,o,a):$o(o)?DS(e,o,a):et()}function DN(e,o){return Nr([...e,l(o)])}function Ud(e,o,a){return dt(e)?St(DN(e,o),{},a):Vu(e,o,a)}function FS(e,o,a,u,p){let f=_o(e,o,a),h=nc(e,o,u);return Ud(f,h,p)}function Vu(e,o,a={}){return Te("Interface",[e,o],a)}function Ya(e){return Dr(e)&&me(e,"action")&&C(e.action,"Interface")}function jS(e,o,a={}){return Ud(e,o,a)}function FN(e,o,a){return e.includes(a)?!0:oc([...e,a],o,o[a])}function US(e,o,a){let u=lm(a);return ba(e,o,u)}function ba(e,o,a){return It(a,(u,p)=>oc(e,o,u)?!0:ba(e,o,p),()=>!1)}function oc(e,o,a){return zt(a)?FN(e,o,a.$ref):Tt(a)?oc(e,o,a.items):Yr(a)?ba(e,o,[...a.parameters,a.instanceType]):Zr(a)?ba(e,o,[...a.parameters,a.returnType]):Ya(a)?US(e,o,a.parameters[1]):ze(a)?ba(e,o,a.allOf):Je(a)?US(e,o,a.properties):ye(a)?ba(e,o,a.anyOf):ft(a)?ba(e,o,a.items):nr(a)?oc(e,o,hr(a)):!1}function BS(e,o,a){return oc(e,o,a)}function jN(e,o){return o.reduce((a,u)=>BS([u],e,e[u])?[...a,u]:a,[])}function GS(e){let o=pm(e);return jN(e,o)}function UN(e,o,a){return a.includes(o)?a:(o in e)?sc(e,e[o],[...a,o]):Wr()}function KS(e,o,a){let u=lm(o);return Za(e,u,a)}function Za(e,o,a){return o.reduce((u,p)=>sc(e,p,u),a)}function sc(e,o,a){return zt(o)?UN(e,o.$ref,a):Tt(o)?sc(e,o.items,a):Yr(o)?Za(e,[...o.parameters,o.instanceType],a):Zr(o)?Za(e,[...o.parameters,o.returnType],a):Ya(o)?KS(e,o.parameters[1],a):ze(o)?Za(e,o.allOf,a):Je(o)?KS(e,o.properties,a):ye(o)?Za(e,o.anyOf,a):ft(o)?Za(e,o.items,a):nr(o)?sc(e,hr(o),a):a}function HS(e,o,a){return sc(e,a,[o])}function BN(e){return Ba()}function GN(e){return Ee(e).reduce((o,a)=>({...o,[a]:Sa(e[a])}),{})}function ic(e){return e.reduce((o,a)=>[...o,Sa(a)],[])}function Sa(e){return zt(e)?BN(e.$ref):Tt(e)?H(Sa(e.items),ja(e)):Yr(e)?qs(ic(e.parameters),Sa(e.instanceType)):Zr(e)?Ds(ic(e.parameters),Sa(e.returnType)):ze(e)?jn(ic(e.allOf)):Je(e)?l(GN(e.properties)):nr(e)?Qe(Oi(e),Sa(hr(e))):ye(e)?y(ic(e.anyOf)):ft(e)?zr(ic(e.items)):e}function KN(e,o){return o in e?Sa(e[o]):Q()}function WS(e){return KN(e.$defs,e.$ref)}function HN(e,o,a){let u=_o(e,gr([],[]),o),p=nc({},gr([],[]),a);return Nr([...u,l(p)])}function WN(e,o){return Ee(e).filter((u)=>o.includes(u)).reduce((u,p)=>{let f=e[p],h=Ya(f)?HN(e,f.parameters[0],f.parameters[1]):f;return{...u,[p]:h}},{})}function zS(e,o,a){let u=HS(e,o,a),p=WN(e,u);return js(p,o)}function VS(e,o){return o in e?zt(e[o])?VS(e,e[o].$ref):e[o]:sr()}function Ks(e,o){return VS(e,o)}function JS(e){return cr(e)?WS(e):dm(e)?Q():e}function Nn(e,o,a){let u=JS(o),p=JS(a);return kt(e,u,p)}var Gu=0,ac=1,Ku=2,Hu=3;function Wa(e,o){let a=[Nn({},e,o),Nn({},o,e)];return To(a[0])&&To(a[1])?Gu:To(a[0])&&Ld(a[1])?Ku:Ld(a[0])&&To(a[1])?Hu:ac}function Bd(e,o,a=[],u=o){return It(o,(p,f)=>{let h=Wa(e,p);return C(h,Ku)||C(h,Gu)?u:C(h,ac)?Bd(e,f,[...a,p],u):Bd(e,f,a,u)},()=>[...a,e])}function zN(e,o,a){let u=Bo(e);return Fr(u)?[u]:en(u)?[u]:Ao(u)?pp(o,a):Je(u)?pp(o,[...a,u]):pp(o,Bd(u,a))}function pp(e,o=[]){return It(e,(a,u)=>zN(a,u,o),()=>o)}function gd(e){let o=pp(e);return xa(o)}function Gd(e,o){return St(Bo(e),{},o)}function QS(e,o,a,u){let p=pe(e,o,a);return Gd(p,u)}function uc(e,o=[]){return ki(e)&&C(e.action,"Conditional")?zt(e.parameters[0])?uc(e.parameters[2],uc(e.parameters[3],[...o,e.parameters[0].$ref])):uc(e.parameters[2],uc(e.parameters[3],o)):ki(e)&&C(e.action,"Mapped")?ki(e.parameters[1])&&C(e.parameters[1].action,"KeyOf")&&zt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function VN(e,o){return e.reduce((a,u)=>[...a,o.includes(u.name)],[])}function ZS(e,o,a=[]){return It(e,(u,p)=>It(o,(f,h)=>ZS(p,h,[...a,[f,u]]),()=>a),()=>a)}function JN(e){return lr(e)?Bn(e.pattern):rn(e)?xo(e.enum):e}function QN(e){let o=JN(e);return ye(o)?[...o.anyOf]:[o]}function XN(e,o){return e.reduce((a,u)=>[...a,[...u,o]],[])}function XS(e,o){return o.reduce((a,u)=>[...a,...XN(e,u)],[])}function YS(e){return e.reduce((o,a)=>C(a[0],!0)?XS(o,QN(a[1])):XS(o,[a[1]]),[[]])}function ew(e,o,a){let u=uc(a),p=VN(e,u),f=ZS(o,p);return ki(a)&&C(a.action,"Conditional")?YS(f):ki(a)&&C(a.action,"Mapped")?YS(f):[o]}function YN(){return["(not-resolvable)",sr()]}function ZN(){return["(not-generic)",sr()]}function eq(e,o,a){return[e,Ai(o,a)]}function tq(e,o,a){return o in e?tw(e,o,e[o],a):YN()}function tw(e,o,a,u){return Ua(a)?eq(o,a.parameters,a.expression):zt(a)?tq(e,a.$ref,u):ZN()}function rw(e,o,a){return tw(e,"(anonymous)",o,a)}function rq(e,o,a){if(tn(o)||eu(o)||To(Nn({},o,a)))return;let u={parameter:e,expect:a,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function nw(e,o,a,u,p){let f=pe(e,o,p);return rq(a,f,u),ln(e,{[a]:f})}function nq(e,o,a,u,p){let f=pe(e,o,a.extends),h=pe(e,o,a.equals);return It(p,(g,I)=>Kd(nw(e,o,a.name,f,g),o,u,I),()=>Kd(nw(e,o,a.name,f,h),o,u,[]))}function Kd(e,o,a,u){return It(a,(p,f)=>nq(e,o,p,f,u),()=>e)}function ow(e,o,a,u){return Kd(e,o,a,u)}var Hd=0,Wd=0;function oq(){if(Mu(Wd,ss().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function sq(){oq(),Wd++,Hd++}function iq(){if(Hd--,C(Hd,0))Wd=0}function aq(e){return sa(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function uq(e,o){return C(aq(e),o)}function cq(e,o,a,u,p,f){sq();try{let h=ow(e,o,u,f),g=pe(h,gr([...o.callstack,a.$ref],o.visited),p);return pe(h,gr([],[]),g)}finally{iq()}}function mq(e,o,a,u,p,f){return f.reduce((h,g)=>{let I=cq(e,o,a,u,p,g);return[...h,I]},[])}function pq(e,o,a,u,p,f){let h=ew(u,f,p),g=mq(e,o,a,u,p,h);return C(g.length,1)?g[0]:wo(g)}function lp(e,o,a,u){let p=_o(e,o,u),f=rw(e,a,u),h=f[0],g=f[1];return Ua(g)?uq(o,h)?Ju(sn(h),p):pq(e,o,sn(h),g.parameters,g.expression,p):Ju(a,p)}function Ju(e,o){return Ct({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function sw(e,o){return lp({},gr([],[]),e,o)}function eu(e){return Se(e,"Call")}function lq(e){return ps(e,["~immutable"])}function iw(e,o){return St(lq(e),{},o)}function aw(e,o,a,u){let p=pe(e,o,a);return iw(p,u)}function uw(e,o){return e(o)}function cw(e,o){return gt(o)?i(uw(e,o)):i(o)}function mw(e,o){let a=Bn(o);return oi(e,a)}function pw(e,o){let a=o.map((u)=>oi(e,u));return y(a)}function oi(e,o){return yt(o)?cw(e,o.const):lr(o)?mw(e,o.pattern):ye(o)?pw(e,o.anyOf):o}function _m(e,o={}){return Te("Capitalize",[e],o)}function lw(e,o={}){return zd(e,o)}function Lm(e,o={}){return Te("Lowercase",[e],o)}function dw(e,o={}){return Vd(e,o)}function Nm(e,o={}){return Te("Uncapitalize",[e],o)}function fw(e,o={}){return Jd(e,o)}function qm(e,o={}){return Te("Uppercase",[e],o)}function hw(e,o={}){return Qd(e,o)}var dq=(e)=>e[0].toUpperCase()+e.slice(1),fq=(e)=>e.toLowerCase(),hq=(e)=>e[0].toLowerCase()+e.slice(1),gq=(e)=>e.toUpperCase();function zd(e,o){return dt([e])?St(oi(dq,e),{},o):_m(e,o)}function Vd(e,o){return dt([e])?St(oi(fq,e),{},o):Lm(e,o)}function Jd(e,o){return dt([e])?St(oi(hq,e),{},o):Nm(e,o)}function Qd(e,o){return dt([e])?St(oi(gq,e),{},o):qm(e,o)}function gw(e,o,a,u){let p=pe(e,o,a);return zd(p,u)}function yw(e,o,a,u){let p=pe(e,o,a);return Vd(p,u)}function xw(e,o,a,u){let p=pe(e,o,a);return Jd(p,u)}function Iw(e,o,a,u){let p=pe(e,o,a);return Qd(p,u)}function Dm(e,o,a,u,p={}){return Te("Conditional",[e,o,a,u],p)}function Ew(e,o,a,u,p={}){return Xd({},gr([],[]),e,o,a,u,p)}function yq(e,o,a,u,p,f){let h=Nn(e,a,u);return Od(h)?y([pe(h.inferred,o,p),pe(e,o,f)]):_d(h)?pe(h.inferred,o,p):pe(e,o,f)}function Xd(e,o,a,u,p,f,h){return dt([a,u])?St(yq(e,o,a,u,p,f),{},h):Dm(a,u,p,f,h)}function bw(e,o,a,u,p,f,h){let g=pe(e,o,a),I=pe(e,o,u);return Xd(e,o,g,I,p,f,h)}function Fm(e,o={}){return Te("ConstructorParameters",[e],o)}function Sw(e,o={}){return Yd(e,o)}function xq(e){let o=Yr(e)?e.parameters:[],a=ji({},gr([],[]),o);return zr(a)}function Yd(e,o){return dt([e])?St(xq(e),{},o):Fm(e,o)}function ww(e,o,a,u){let p=pe(e,o,a);return Yd(p,u)}function jm(e,o,a={}){return Te("Exclude",[e,o],a)}function Tw(e,o,a={}){return cc(e,o,a)}function cc(e,o,a){return dt([e,o])?St(Am(e,o),{},a):jm(e,o,a)}function Rw(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return cc(f,h,p)}function Um(e,o,a={}){return Te("Extract",[e,o],a)}function kw(e,o,a={}){return Zd(e,o,a)}function Iq(e,o){let a=Nn({},e,o);return To(a)?[e]:[]}function Aw(e,o,a=[]){return It(e,(u,p)=>Aw(p,o,[...a,...Iq(u,o)]),()=>a)}function Pw(e,o){let a=Bo(e),u=ye(a)?a.anyOf:[a],p=Aw(u,o);return wo(p)}function Zd(e,o,a){return dt([e,o])?St(Pw(e,o),{},a):Um(e,o,a)}function $w(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return Zd(f,h,p)}function Eq(e){return e.reduce((o,a)=>Im(a)?[...o,i(a)]:o,[])}function tu(e){let o=Eq(e);return y(o)}function Qu(e,o,a={}){return Te("Index",[e,o],a)}function Cw(e,o,a={}){let u=Le(o)?tu(o):o;return ef(e,u,a)}function vw(e,o){let a=Ks(e,o);return Lo(a)}function Mw(e,o,a){let u=gs(e,o,a);return Lo(u)}function bq(e,o){let a=Ee(e).filter((S)=>!me(o,S)),u=Ee(o).filter((S)=>!me(e,S)),p=Ee(e).filter((S)=>me(o,S)),f=a.reduce((S,k)=>({...S,[k]:e[k]}),{}),h=u.reduce((S,k)=>({...S,[k]:o[k]}),{}),g=p.reduce((S,k)=>({...S,[k]:Nr([e[k],o[k]])}),{}),I=ln(f,h);return ln(I,g)}function Ow(e){return e.reduce((o,a)=>bq(o,Lo(a)),{})}function _w(e){return e}function Lw(e){let o=wx(zr(e));return Lo(o)}function Sq(e,o){return Ee(e).filter((p)=>(p in o)).reduce((p,f)=>({...p,[f]:wo([e[f],o[f]])}),{})}function Nw(e,o){return It(e,(a,u)=>Nw(u,Sq(o,Lo(a))),()=>o)}function qw(e){return It(e,(o,a)=>Nw(a,Lo(o)),()=>Wr())}function Lo(e){return cr(e)?vw(e.$defs,e.$ref):Hr(e)?Mw(e.if,e.then,e.else):ze(e)?Ow(e.allOf):ye(e)?qw(e.anyOf):ft(e)?Lw(e.items):Je(e)?_w(e.properties):{}}function ru(e){let o=Lo(e);return l(o)}var wq=new RegExp("^(?:0|[1-9][0-9]*)$");function nu(e){let o=`${e}`;return wq.test(o)?parseInt(o):e}function Tq(e){return i(nu(e))}function Dw(e){return e.map((o)=>Fw(o))}function Fw(e){return ze(e)?jn(Dw(e.allOf)):ye(e)?y(Dw(e.anyOf)):yt(e)?Tq(e.const):e}function jw(e,o){let a=Fw(o),u=Nn({},a,ne());return To(u)?e:yt(o)&&C(o.const,"length")?ne():sr()}function Uw(e,o){let a=Ks(e,o);return Co(a)}function Bw(e,o,a){let u=gs(e,o,a);return Co(u)}function Gw(e){let o=xo(e);return Co(o)}function Kw(e){let o=Nr(e);return Co(o)}function Hw(e){return[`${e}`]}function Ww(e){let o=Bn(e);return Co(o)}function zw(e){return e.reduce((o,a)=>[...o,...Co(a)],[])}function Co(e){return cr(e)?Uw(e.$defs,e.$ref):Hr(e)?Bw(e.if,e.then,e.else):rn(e)?Gw(e.enum):ze(e)?Kw(e.allOf):yt(e)?Hw(e.const):lr(e)?Ww(e.pattern):ye(e)?zw(e.anyOf):[]}function ou(e){return Co(e)}function mc(e,o){return o.map((a)=>pc(e,a))}function pc(e,o){return Tt(o)?H(pc(e,o.items)):Yr(o)?qs(mc(e,o.parameters),pc(e,o.instanceType)):Zr(o)?Ds(mc(e,o.parameters),pc(e,o.returnType)):ft(o)?zr(mc(e,o.items)):ye(o)?y(mc(e,o.anyOf)):ze(o)?jn(mc(e,o.allOf)):vm(o)?l(e):o}function Vw(e,o){return pc(e,o)}function Rq(e,o){let a=o in e?e[o]:sr();return Vw(e,a)}function Jw(e,o){return o.reduce((a,u)=>[...a,Rq(e,u)],[])}function kq(e,o){let a=ou(o),u=Jw(e,a);return wo(u)}var Aq=new RegExp(Mi);function Pq(e){return e.filter((a)=>Aq.test(a))}function $q(e){let o=pm(e),a=Pq(o),u=Jw(e,a);return wo(u)}function Qw(e,o){return Lr(o)?$q(e):kq(e,o)}function Cq(e){return i(nu(e))}function Xw(e){return e.map((o)=>tf(o))}function tf(e){return ze(e)?jn(Xw(e.allOf)):ye(e)?y(Xw(e.anyOf)):yt(e)?Cq(e.const):e}function vq(e,o){return e.reduceRight((a,u,p)=>{let f=Nn({},i(p),o);return To(f)?[u,...a]:a},[])}function Mq(e,o){let a=tf(o),u=vq(e,a);return Ci(u)}function Oq(e){return Ci(e)}function Yw(e,o){return yt(o)&&C(o.const,"length")?i(e.length):Lr(o)||In(o)?Oq(e):Mq(e,o)}function Zw(e,o){return Tt(e)?jw(e.items,o):Je(e)?Qw(e.properties,o):ft(e)?Yw(e.items,o):sr()}function _q(e){return cr(e)||Hr(e)||ze(e)||ye(e)?ru(e):e}function ef(e,o,a){return dt([e,o])?St(Zw(_q(e),o),{},a):Qu(e,o,a)}function eT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return ef(f,h,p)}function Bm(e,o={}){return Te("InstanceType",[e],o)}function tT(e,o={}){return rf(e,o)}function Lq(e){return Yr(e)?e.instanceType:sr()}function rf(e,o){return dt([e])?St(Lq(e),{},o):Bm(e,o)}function rT(e,o,a,u={}){let p=pe(e,o,a);return rf(p,u)}function Xu(e,o={}){return Te("KeyOf",[e],o)}function nT(e,o={}){return nf(e,o)}function oT(){return y([ne(),s(),Ha()])}function sT(e){return ne()}function Nq(e){return e.reduce((a,u)=>Im(u)?[...a,i(nu(u))]:Wr(),[])}function iT(e){let o=Ee(e),a=Nq(o);return Ci(a)}function aT(e){return Oi(e)}function uT(e){let o=e.map((a,u)=>i(u));return Ci(o)}function cT(e){return Fr(e)?oT():Tt(e)?sT(e.items):Je(e)?iT(e.properties):nr(e)?aT(e):ft(e)?uT(e.items):sr()}function qq(e){return cr(e)||Hr(e)||ze(e)||ye(e)?ru(e):e}function nf(e,o){return dt([e])?St(cT(qq(e)),{},o):Xu(e,o)}function mT(e,o,a,u){let p=pe(e,o,a);return nf(p,u)}function zu(e,o,a,u,p={}){return Te("Mapped",[e,o,a,u],p)}function pT(e,o,a,u,p={}){return of({},gr([],[]),e,o,a,u,p)}function Dq(e){let o=Bn(e);return dp(o)}function Fq(e){return e.reduce((o,a)=>[...o,...dp(a)],[])}function jq(e){let o=xo(e);return dp(o)}function Uq(e){return Ut(e)?[i(`${e}`)]:[i(e)]}function dp(e){return rn(e)?jq(e.enum):yt(e)?Uq(e.const):lr(e)?Dq(e.pattern):ye(e)?Fq(e.anyOf):[e]}function lT(e){return dp(e)}function Bq(e){return lr(e)?Bn(e.pattern):e}function Gq(e,o,a,u,p,f){let h=ln(e,{[a.name]:u}),g=pe(h,o,p),I=Bq(g),E=pe(h,o,f);return Em(I)||bm(I)?{[I.const]:E}:{}}function Kq(e,o,a,u,p,f){return u.reduce((h,g)=>[...h,Gq(e,o,a,g,p,f)],[])}function Hq(e){return e.reduce((o,a)=>[...o,l(a)],[])}function dT(e,o,a,u,p,f){let h=lT(u),g=Kq(e,o,a,h,p,f),I=Hq(g);return Nr(I)}function of(e,o,a,u,p,f,h){return dt([u])?St(dT(e,o,a,u,p,f),{},h):zu(a,u,p,f,h)}function fT(e,o,a,u,p,f,h){let g=pe(e,o,u);return of(e,o,a,g,p,f,h)}function Wq(e,o,a){let u=ln(e,o);return Ee(o).filter((f)=>a.includes(f)).reduce((f,h)=>({...f,[h]:zS(u,h,o[h])}),{})}function zq(e,o,a){let u=ln(e,o);return Ee(o).filter((f)=>!a.includes(f)).reduce((f,h)=>({...f,[h]:pe(u,gr([],[]),o[h])}),{})}function Vq(e,o,a){let u=GS(o),p=Wq(e,o,u),f=zq(e,o,u),h={...p,...f};return St(h,{},a)}function fp(e,o,a,u){return Vq(e,a,u)}function Gm(e,o={}){return Te("NonNullable",[e],o)}function hT(e,o={}){return sf(e,o)}function Jq(e){let o=y([Un(),Va()]);return cc(e,o,{})}function sf(e,o){return dt([e])?St(Jq(e),{},o):Gm(e,o)}function gT(e,o,a,u){let p=pe(e,o,a);return sf(p,u)}function Km(e,o,a={}){return Te("Omit",[e,o],a)}function yT(e,o,a={}){let u=Le(o)?tu(o):o;return af(e,u,a)}function hp(e){let o=ru(e);return Je(o)?o.properties:Wr()}function Qq(e,o){return Ee(e).reduce((u,p)=>o.includes(p)?u:{...u,[p]:e[p]},{})}function xT(e,o){let a=hp(e),u=ou(o),p=Qq(a,u);return l(p)}function af(e,o,a){return dt([e,o])?St(xT(e,o),{},a):Km(e,o,a)}function IT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return af(f,h,p)}function Hm(e,o={}){return Te("Parameters",[e],o)}function ET(e,o={}){return uf(e,o)}function Xq(e){let o=Zr(e)?e.parameters:[],a=ji({},gr([],[]),o);return zr(a)}function uf(e,o){return dt([e])?St(Xq(e),{},o):Hm(e,o)}function bT(e,o,a,u){let p=pe(e,o,a);return uf(p,u)}function Wm(e,o={}){return Te("Partial",[e],o)}function ST(e,o={}){return cf(e,o)}function wT(e,o){let a=Ks(e,o),u=Hs(a);return js(ln(e,{[o]:u}),o)}function TT(e,o,a){let u=gs(e,o,a);return Hs(u)}function RT(e){let o=Nr(e);return Hs(o)}function kT(e){let o=e.map((a)=>Hs(a));return y(o)}function AT(e){let o=Ee(e).reduce((u,p)=>({...u,[p]:pa(e[p])}),{});return l(o)}function Hs(e){return cr(e)?wT(e.$defs,e.$ref):Hr(e)?TT(e.if,e.then,e.else):ze(e)?RT(e.allOf):ye(e)?kT(e.anyOf):Je(e)?AT(e.properties):l({})}function cf(e,o){return dt([e])?St(Hs(e),{},o):Wm(e,o)}function PT(e,o,a,u){let p=pe(e,o,a);return cf(p,u)}function zm(e,o,a={}){return Te("Pick",[e,o],a)}function $T(e,o,a={}){let u=Le(o)?tu(o):o;return mf(e,u,a)}function Yq(e,o){return Ee(e).reduce((u,p)=>o.includes(p)?ln(u,{[p]:e[p]}):u,{})}function CT(e,o){let a=hp(e),u=ou(o),p=Yq(a,u);return l(p)}function mf(e,o,a){return dt([e,o])?St(CT(e,o),{},a):zm(e,o,a)}function vT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return mf(f,h,p)}function Vm(e,o={}){return Te("ReadonlyObject",[e],o)}function pf(e,o={}){return lf(e,o)}var MT=pf;function OT(e){return Ka(H(e))}function _T(e,o){let a=Ks(e,o),u=Ws(a);return js(ln(e,{[o]:u}),o)}function LT(e,o,a){let u=gs(e,o,a);return Ws(u)}function NT(e){let o=Nr(e);return Ws(o)}function qT(e){let o=Ee(e).reduce((u,p)=>({...u,[p]:ha(e[p])}),{});return l(o)}function DT(e){return Ka(zr(e))}function FT(e){let o=e.map((a)=>Ws(a));return y(o)}function Ws(e){return Tt(e)?OT(e.items):cr(e)?_T(e.$defs,e.$ref):Hr(e)?LT(e.if,e.then,e.else):ze(e)?NT(e.allOf):Je(e)?qT(e.properties):ft(e)?DT(e.items):ye(e)?FT(e.anyOf):e}function lf(e,o){return dt([e])?St(Ws(e),{},o):Vm(e)}function jT(e,o,a,u){let p=pe(e,o,a);return lf(p,u)}function UT(e,o,a,u){return o.visited.includes(u)?a:(u in e)?pe(e,gr(o.callstack,[...o.visited,u]),e[u]):a}function BT(e,o){let a=Ks(e,o),u=zs(a);return js(ln(e,{[o]:u}),o)}function GT(e,o,a){let u=gs(e,o,a);return zs(u)}function KT(e){let o=Nr(e);return zs(o)}function HT(e){let o=e.map((a)=>zs(a));return y(o)}function WT(e){let o=Ee(e).reduce((u,p)=>({...u,[p]:km(e[p])}),{});return l(o)}function zs(e){return cr(e)?BT(e.$defs,e.$ref):Hr(e)?GT(e.if,e.then,e.else):ze(e)?KT(e.allOf):ye(e)?HT(e.anyOf):Je(e)?WT(e.properties):l({})}function Jm(e,o={}){return Te("Required",[e],o)}function zT(e,o={}){return df(e,o)}function df(e,o){return dt([e])?St(zs(e),{},o):Jm(e,o)}function VT(e,o,a,u){let p=pe(e,o,a);return df(p,u)}function Qm(e,o={}){return Te("ReturnType",[e],o)}function JT(e,o={}){return ff(e,o)}function Zq(e){return Zr(e)?e.returnType:sr()}function ff(e,o){return dt([e])?St(Zq(e),{},o):Qm(e,o)}function QT(e,o,a,u={}){let p=pe(e,o,a);return ff(p,u)}function Xm(e,o){return Te("With",[e,o],{})}function gp(e,o){return hf(e,o)}function hf(e,o){return dt([e])?St(e,{},o):Xm(e,o)}function XT(e,o,a,u){let p=pe(e,o,a);return hf(p,u)}function eD(e){return _i(e)?ft(e.items)?gf(e.items.items):tn(e.items)?[e]:zt(e.items)?[e]:[sr()]:[e]}function gf(e){return e.reduce((a,u)=>[...a,...eD(u)],[])}function gr(e,o){return{callstack:e,visited:o}}function dt(e){return It(e,(o,a)=>zt(o)?!1:dt(a),()=>!0)}function nc(e,o,a){return Ee(a).reduce((u,p)=>({...u,[p]:pe(e,o,a[p])}),{})}function ji(e,o,a){let u=_o(e,o,a);return gf(u)}function _o(e,o,a){return a.map((u)=>pe(e,o,u))}function tD(e,o){let a=an(e)?qu(o,{}):o,u=ga(e)?Nu(a,{}):a;return fa(e)?lc(u,{}):u}function rD(e,o,a,u,p){return C(a,"AddImmutable")?YT(e,o,u[0],p):C(a,"RemoveImmutable")?aw(e,o,u[0],p):C(a,"AddReadonly")?Ry(e,o,u[0],p):C(a,"RemoveReadonly")?xx(e,o,u[0],p):C(a,"AddOptional")?ky(e,o,u[0],p):C(a,"RemoveOptional")?bx(e,o,u[0],p):C(a,"Capitalize")?gw(e,o,u[0],p):C(a,"Conditional")?bw(e,o,u[0],u[1],u[2],u[3],p):C(a,"ConstructorParameters")?ww(e,o,u[0],p):C(a,"Evaluate")?QS(e,o,u[0],p):C(a,"Exclude")?Rw(e,o,u[0],u[1],p):C(a,"Extract")?$w(e,o,u[0],u[1],p):C(a,"Index")?eT(e,o,u[0],u[1],p):C(a,"InstanceType")?rT(e,o,u[0],p):C(a,"Interface")?FS(e,o,u[0],u[1],p):C(a,"KeyOf")?mT(e,o,u[0],p):C(a,"Lowercase")?yw(e,o,u[0],p):C(a,"Mapped")?fT(e,o,u[0],u[1],u[2],u[3],p):C(a,"Module")?fp(e,o,u[0],p):C(a,"NonNullable")?gT(e,o,u[0],p):C(a,"Pick")?vT(e,o,u[0],u[1],p):C(a,"Parameters")?bT(e,o,u[0],p):C(a,"Partial")?PT(e,o,u[0],p):C(a,"Omit")?IT(e,o,u[0],u[1],p):C(a,"ReadonlyObject")?jT(e,o,u[0],p):C(a,"Record")?Dx(e,o,u[0],u[1],p):C(a,"Required")?VT(e,o,u[0],p):C(a,"ReturnType")?QT(e,o,u[0],p):C(a,"TemplateLiteral")?sS(e,o,u[0],p):C(a,"Uncapitalize")?xw(e,o,u[0],p):C(a,"Uppercase")?Iw(e,o,u[0],p):C(a,"With")?XT(e,o,u[0],u[1]):Te(a,u,p)}function nD(e,o,a){let u=zt(a)?UT(e,o,a,a.$ref):Tt(a)?H(pe(e,o,a.items),ja(a)):eu(a)?lp(e,o,a.target,a.arguments):Yr(a)?qs(_o(e,o,a.parameters),pe(e,o,a.instanceType),Ay(a)):Zr(a)?Ds(_o(e,o,a.parameters),pe(e,o,a.returnType),Py(a)):Hr(a)?la(pe(e,o,a.if),pe(e,o,a.then),pe(e,o,a.else),My(a)):ze(a)?jn(_o(e,o,a.allOf),qy(a)):Je(a)?l(nc(e,o,a.properties),vy(a)):nr(a)?Fx(Sn(a),pe(e,o,hr(a))):_i(a)?Ia(pe(e,o,a.items)):ft(a)?zr(ji(e,o,a.items),yx(a)):ye(a)?y(_o(e,o,a.anyOf),ax(a)):a;return tD(a,u)}function pe(e,o,a){return ki(a)?rD(e,o,a.action,a.parameters,a.options):nD(e,o,a)}function Go(e,o){return pe(e,gr([],[]),o)}function oD(e){return St(e,{"~immutable":!0},{})}function lc(e,o){return St(oD(e),{},o)}function YT(e,o,a,u){let p=pe(e,o,a);return lc(p,u)}function tb(e,o={}){return Te("AddImmutable",[e],o)}function Ka(e,o={}){return lc(e,o)}function rb(e,o={}){return Te("Evaluate",[e],o)}function qn(e,o={}){return Gd(e,o)}function nb(e,o={}){return Te("Module",[e],o)}function ZT(e,o={}){return fp({},gr([],[]),e,o)}function sD(e,o){let a=Wa(e,o);return C(a,Hu)?1:C(a,ac)?1:0}function eR(e,o,a=[]){return It(o,(u,p)=>C(sD(e,u),1)?eR(e,p,[...a,u]):[...a,e,...o],()=>[...a,e])}function tR(e,o=[]){return It(e,(a,u)=>tR(u,eR(a,o)),()=>o)}function rR(e){return tR(e)}function nR(...e){let[o,a,u]=Ln(e,{2:(h,g)=>gt(h)?[{},h,g]:[h,g,{}],3:(h,g,I)=>[h,g,I],1:(h)=>[{},h,{}]}),p=eS(a),f=Le(p)&&C(p.length,2)?pe(o,gr([],[]),p[0]):sr();return St(f,{},u)}function iD(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function aD(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function uD(e){return{type:"toolCall",id:e.id,name:e.name,arguments:structuredClone(e.arguments),...e.thoughtSignature===void 0?{}:{thoughtSignature:e.thoughtSignature},...e.namespace===void 0?{}:{namespace:e.namespace}}}function cD(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function dc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function su(e){dc(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function xf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var mD=xf(z(""));function If(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,p)=>If(u,o[p]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let a=o;return Object.entries(e).every(([u,p])=>Object.hasOwn(a,u)&&If(p,a[u]))}class oR{started=!1;terminal=!1;blocks=new Map;encode(e){if(this.terminal)throw Error(`Assistant message event ${e.type} follows a terminal event`);switch(e.type){case"start":if(this.started)throw Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:cD(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=su(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:iD(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=su(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=su(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:aD(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=su(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=su(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let a=xf(o.arguments),u=a===mD;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":a}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:uD(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let a=z(o.catchupJson);if(xf(a)!==o.snapshotArguments){let p=z(o.snapshotArguments);if(!If(p,a))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=su(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(dc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){dc(e);let a=this.blocks.get(e);if(a===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(a.kind!==o)throw Error(`Assistant message block ${e} is ${a.kind}, not ${o}`);return a}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,a){let u=this.block(e,a);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let p=u.deltaChars;u.deltaChars+=o.length;let f=Math.max(0,u.coveredChars-p);if(f>=o.length)return;let h=f===0?o:o.slice(f);return a==="text"?{type:"text_delta",contentIndex:e,delta:h}:{type:"thinking_delta",contentIndex:e,delta:h}}}function yf(e,o,a,u,p){if(dc(a),a!==e.content.length){let f=a<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${a}: ${f}`)}e.content.push(structuredClone(u)),o.set(a,p)}function wa(e,o,a,u,p){dc(a);let f=o.get(a),h=e.content[a];if(!f||!h)throw Error(`${p} frame has no started block at index ${a}`);if(f.kind!==u||h.type!==u)throw Error(`${p} frame expected ${u} block at index ${a}, found ${h.type}`);if(f.ended)throw Error(`${p} frame follows the end of block at index ${a}`);return{block:h,state:f}}function pD(e){let o,a,u=new Map;for(let p of e){if(p.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(a!==void 0)throw Error(`${a} frame appears before the start frame`);o=structuredClone(p.partial);continue}if(!o){a??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);yf(o,u,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:f}=wa(o,u,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");f.text+=p.delta;break}case"text_end":{let{block:f,state:h}=wa(o,u,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");if(f.text=p.content,delete f.textSignature,p.textSignature!==void 0)f.textSignature=p.textSignature;h.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);yf(o,u,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:f}=wa(o,u,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");f.thinking+=p.delta;break}case"thinking_end":{let{block:f,state:h}=wa(o,u,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");if(f.thinking=p.content,delete f.thinkingSignature,delete f.redacted,p.thinkingSignature!==void 0)f.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)f.redacted=p.redacted;h.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);yf(o,u,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:f,state:h}=wa(o,u,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||h.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");h.json=p.json,f.arguments=z(p.json);break}case"toolcall_delta":{let{block:f,state:h}=wa(o,u,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||h.kind!=="toolCall")throw Error("Unreachable tool-call frame state");h.json+=p.delta;break}case"toolcall_end":{let{block:f,state:h}=wa(o,u,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(f.id=p.id,f.name=p.name,f.arguments=structuredClone(p.arguments),delete f.thoughtSignature,delete f.namespace,p.thoughtSignature!==void 0)f.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)f.namespace=p.namespace;h.ended=!0;break}}}if(!o)return;for(let[p,f]of u){if(f.kind!=="toolCall"||f.ended||f.json.length===0)continue;let h=o.content[p];if(h?.type!=="toolCall")throw Error("Unreachable tool-call frame state");h.arguments=z(f.json)}return o}var sR=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],lD=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,dD=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Ta(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!dD.some((u)=>u.test(e.errorMessage))){if(sR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&lD.test(e.errorMessage))return!0}}if(o&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>o)return!0}if(o&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=o*0.99)return!0}return!1}function fD(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function hD(){return[...sR]}function iR(e){return new RegExp(e.join("|"),"i")}var gD=iR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),yD=iR(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),aR=60000;function uR(e,o){let a=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??aR)}class yp extends Error{constructor(){super("Aborted")}}function xD(e,o){return new Promise((a,u)=>{if(o?.aborted){u(new yp);return}let p=setTimeout(a,e);o?.addEventListener("abort",()=>{clearTimeout(p),u(new yp)},{once:!0})})}async function ID(e,o,a,u){let p=o?.enabled?o.maxRetries:0,f=0,h;for(;;){let g=await e();if(g.stopReason==="aborted"){if(h)await u?.onRetryFinished?.(!1,h.attempt);return g}if(g.stopReason!=="error"){if(h)await u?.onRetryFinished?.(!0,h.attempt);return g}if(f>=p||!cR(g)){if(h)await u?.onRetryFinished?.(!1,h.attempt,g.errorMessage);return g}f++,h={attempt:f,errorMessage:g.errorMessage||"Unknown error"};let I=uR(o,f);await u?.onRetryScheduled?.(f,p,I,h.errorMessage);try{await xD(I,a)}catch(E){if(await u?.onRetryFinished?.(!1,f,h.errorMessage),E instanceof yp){let{errorMessage:S,...k}=g;return{...k,stopReason:"aborted"}}throw E}await u?.onRetryAttemptStart?.()}}function cR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(gD.test(o))return!1;return yD.test(o)}function ED(e,o){return vr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function fc(e){return me(e,"~refine")&&Le(e["~refine"])&&on(e["~refine"],0,(o)=>lt(o)&&me(o,"check")&&me(o,"error")&&_s(o.check)&&_s(o.error))}function Tn(e){return lt(e)&&!Le(e)}function ui(e){return cn(e)}function Ye(e){return Tn(e)||ui(e)}function iu(e){return me(e,"additionalItems")&&Ye(e.additionalItems)}function Ho(e){return me(e,"additionalProperties")&&Ye(e.additionalProperties)}function hc(e){return me(e,"allOf")&&Le(e.allOf)&&e.allOf.every((o)=>Ye(o))}function gc(e){return me(e,"$anchor")&>(e.$anchor)}function yc(e){return me(e,"anyOf")&&Le(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function xp(e){return me(e,"const")}function Vs(e){return me(e,"contains")&&Ye(e.contains)}function No(e){return me(e,"default")}function xc(e){return me(e,"dependencies")&<(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||Le(o)&&o.every((a)=>gt(a)))}function Ic(e){return me(e,"dependentRequired")&<(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Le(o)&&o.every((a)=>gt(a)))}function au(e){return me(e,"dependentSchemas")&<(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function mi(e){return me(e,"$dynamicAnchor")&>(e.$dynamicAnchor)}function Ec(e){return me(e,"$dynamicRef")&>(e.$dynamicRef)}function bc(e){return me(e,"else")&&Ye(e.else)}function Ip(e){return me(e,"enum")&&Le(e.enum)}function Sc(e){return me(e,"exclusiveMaximum")&&(Ut(e.exclusiveMaximum)||Kr(e.exclusiveMaximum))}function xs(e){return me(e,"exclusiveMinimum")&&(Ut(e.exclusiveMinimum)||Kr(e.exclusiveMinimum))}function Ra(e){return me(e,"format")&>(e.format)}function qo(e){return me(e,"$id")&>(e.$id)}function wc(e){return me(e,"if")&&Ye(e.if)}function pi(e){return me(e,"items")&&(Ye(e.items)||Le(e.items)&&e.items.every((o)=>Ye(o)))}function Tc(e){return pi(e)&&Le(e.items)}function Rc(e){return me(e,"maximum")&&(Ut(e.maximum)||Kr(e.maximum))}function kc(e){return me(e,"maxContains")&&Ut(e.maxContains)}function uu(e){return me(e,"maxItems")&&Ut(e.maxItems)}function Ac(e){return me(e,"maxLength")&&Ut(e.maxLength)}function Pc(e){return me(e,"maxProperties")&&Ut(e.maxProperties)}function Is(e){return me(e,"minimum")&&(Ut(e.minimum)||Kr(e.minimum))}function di(e){return me(e,"minContains")&&Ut(e.minContains)}function Ui(e){return me(e,"minItems")&&Ut(e.minItems)}function ka(e){return me(e,"minLength")&&Ut(e.minLength)}function Aa(e){return me(e,"minProperties")&&Ut(e.minProperties)}function $c(e){return me(e,"multipleOf")&&(Ut(e.multipleOf)||Kr(e.multipleOf))}function Cc(e){return me(e,"not")&&Ye(e.not)}function vc(e){return me(e,"oneOf")&&Le(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function Pa(e){return me(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function fi(e){return me(e,"patternProperties")&<(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function Ss(e){return me(e,"prefixItems")&&Le(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function hi(e){return me(e,"properties")&<(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function cu(e){return me(e,"propertyNames")&&(lt(e.propertyNames)||Ye(e.propertyNames))}function bD(e){return me(e,"$recursiveAnchor")&&cn(e.$recursiveAnchor)}function Mc(e){return bD(e)&&C(e.$recursiveAnchor,!0)}function Oc(e){return me(e,"$recursiveRef")&>(e.$recursiveRef)}function _c(e){return me(e,"$ref")&>(e.$ref)}function ws(e){return me(e,"required")&&Le(e.required)&&e.required.every((o)=>gt(o))}function Lc(e){return me(e,"then")&&Ye(e.then)}function Nc(e){return me(e,"type")&&(gt(e.type)||Le(e.type)&&e.type.every((o)=>gt(o)))}function Bi(e){return me(e,"uniqueItems")&&cn(e.uniqueItems)}function Gi(e){return me(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function zi(e){return me(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function SD(e){return Gi(e)||zi(e)||qa(Ee(e),(o)=>Ep(e[o]))}function wD(e){return qa(e,(o)=>Ep(o))}function Ep(e){return Le(e)?wD(e):lt(e)?SD(e):!1}function mR(e,o){return Ep(o)||qa(Ee(e),(a)=>Ep(e[a]))}class Ef{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Sr(bt("context","Push"),[])}Pop(){return Sr(bt("context","Pop"),[])}AddIndex(e){return Sr(bt("context","AddIndex"),[e])}AddKey(e){return Sr(bt("context","AddKey"),[e])}Merge(e){return Sr(bt("context","Merge"),[e])}}class Kn{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((a)=>this.GetIndices().add(a)),o.GetKeys().forEach((a)=>this.GetKeys().add(a));return!0}}class Hn extends Kn{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=ss().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var bp={identifier:"External",variables:[]};function Wo(e){let o=`External[${bp.variables.length}]`;return bp.variables.push(e),o}function pR(){bp.variables=[]}function lR(){return{...bp}}function dR(e,o,a,u){let p=Wo(a["~refine"].map((f)=>f));return Ns(p,Re(0),["refinement","_"],Sr(bt("refinement","check"),[u]))}function fR(e,o,a,u){return on(a["~refine"],0,(p,f)=>p.check(u))}function hR(e,o,a,u,p,f){return Dn(p["~refine"],0,(h,g)=>h.check(f)||o.AddError({keyword:"~refine",schemaPath:a,instancePath:u,params:{index:g,message:h.error(f)}}))}var TD=0;function ir(){return`var_${TD++}`}function bf(e){return pi(e)&&Le(e.items)}function RD(e,o,a,u){let[p,f]=[ir(),ir()],h=Io(e,o,a.additionalItems,p),g=sd(f,Re(a.items.length)),I=o.AddIndex(f);return Ns(u,Re(0),[p,f],br(g,On(h,I)))}function kD(e,o,a,u){let[p,f]=[ir(),ir()],h=Io(e,o,a.additionalItems,p),g=sd(f,Re(a.items.length));return Ns(u,Re(0),[p,f],br(g,h))}function gR(e,o,a,u){if(!bf(a))return Re(!0);return o.UseUnevaluated()?RD(e,o,a,u):kD(e,o,a,u)}function yR(e,o,a,u){if(!bf(a))return!0;return on(u,0,(f,h)=>Mu(h,a.items.length)||Do(e,o,a.additionalItems,f)&&o.AddIndex(h))}function xR(e,o,a,u,p,f){if(!bf(p))return!0;return on(f,0,(g,I)=>{let E=`${a}/additionalItems`,S=`${u}/${I}`;return Mu(I,p.items.length)||Fo(e,o,E,S,p.additionalItems,g)&&o.AddIndex(I)})}function Rs(e){return new RegExp(e,"u")}function AD(e,o){return!e.UseUnevaluated()&&(C(o,!0)||lt(o)&&C(Ee(o).length,0))}function PD(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Sf(e){let o=[];if(fi(e))o.push(...Ee(e.patternProperties));if(hi(e))o.push(...Ee(e.properties).map(PD));return C(o.length,0)?"(?!)":`(${o.join("|")})`}function $D(e,o,a){return ws(o)&&hi(o)&&!fi(o)&&C(o.additionalProperties,!1)&&C(Ee(o.properties).length,o.required.length)}function CD(e,o,a){return ko(bt(Sr(bt("Object","getOwnPropertyNames"),[a]),"length"),Re(o.required.length))}function vD(e,o,a,u){let[p,f]=[ir(),ir()],h=Wo(Rs(Sf(a))),g=Io(e,o,a.additionalProperties,`${u}[${p}]`),I=Sr(bt(h,"test"),[p]),E=o.AddKey(p),S=o.UseUnevaluated()?br(I,On(g,E)):br(I,g);return Ns(ua(u),Re(0),[p,f],S)}function IR(e,o,a,u){if(AD(o,a.additionalProperties))return Re(!0);return $D(o,a,u)?CD(o,a,u):vD(e,o,a,u)}function ER(e,o,a,u){let p=Rs(Sf(a));return on(Ee(u),0,(h,g)=>p.test(h)||Do(e,o,a.additionalProperties,u[h])&&o.AddKey(h))}function bR(e,o,a,u,p,f){let h=Rs(Sf(p)),g=[];return Dn(Ee(f),0,(E,S)=>{let k=`${a}/additionalProperties`,A=`${u}/${E}`,P=h.test(E)||Fo(e,o,k,A,p.additionalProperties,f[E])&&o.AddKey(E);if(!P)g.push(E);return P})||o.AddError({keyword:"additionalProperties",schemaPath:a,instancePath:u,params:{additionalProperties:g}})}function Xi(e,o,a,u,p){let f=ei("results","[]"),h=a.map((S,k)=>ei(`context_${k}`,id("CheckContext",[]))),g=a.map((S,k)=>ei(`condition_${k}`,Sr(Ti(["context"],Gt(e,o,S,u)),[`context_${k}`]))),I=a.map((S,k)=>by(`condition_${k}`,Sr(bt("results","push"),[`context_${k}`]))),E=mm(On(p,o.Merge("results")));return Sr(Ti([],cm([f,...h,...g,...I,E])),[])}function MD(e,o,a,u){return Xi(e,o,a.allOf,u,ko(bt("results","length"),Re(a.allOf.length)))}function OD(e,o,a,u){return Fn(a.allOf.map((p)=>Gt(e,o,p,u)))}function SR(e,o,a,u){return o.UseUnevaluated()?MD(e,o,a,u):OD(e,o,a,u)}function wR(e,o,a,u){let p=a.allOf.reduce((f,h)=>{let g=new Kn;return Pt(e,g,h,u)?[...f,g]:f},[]);return C(p.length,a.allOf.length)&&o.Merge(p)}function TR(e,o,a,u,p,f){let h=[],g=p.allOf.reduce((E,S,k)=>{let A=`${a}/allOf/${k}`,P=new Hn,v=dr(e,P,A,u,S,f);if(!v)h.push(P);return v?[...E,P]:E},[]),I=C(g.length,p.allOf.length)&&o.Merge(g);if(!I)h.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I}function _D(e,o,a,u){return Xi(e,o,a.anyOf,u,xy(bt("results","length"),Re(0)))}function LD(e,o,a,u){return ad(a.anyOf.map((p)=>Gt(e,o,p,u)))}function RR(e,o,a,u){return o.UseUnevaluated()?_D(e,o,a,u):LD(e,o,a,u)}function kR(e,o,a,u){let p=a.anyOf.reduce((f,h)=>{let g=new Kn;return Pt(e,g,h,u)?[...f,g]:f},[]);return sa(p.length,0)&&o.Merge(p)}function AR(e,o,a,u,p,f){let h=[],g=p.anyOf.reduce((E,S,k)=>{let A=new Hn,P=`${a}/anyOf/${k}`,v=dr(e,A,P,u,S,f);if(!v)h.push(A);return v?[...E,A]:E},[]),I=sa(g.length,0)&&o.Merge(g);if(!I)h.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I||o.AddError({keyword:"anyOf",schemaPath:a,instancePath:u,params:{}})}function PR(e,o,a,u){return a?Re(!0):Re(!1)}function wf(e,o,a,u){return a}function $R(e,o,a,u,p,f){return wf(e,o,p,f)||o.AddError({keyword:"boolean",schemaPath:a,instancePath:u,params:{}})}function CR(e,o,a,u){return ia(a.const)?ko(u,Re(a.const)):Ey(u,Wo(a.const))}function Tf(e,o,a,u){return ia(a.const)?C(u,a.const):Da(u,a.const)}function vR(e,o,a,u,p,f){return Tf(e,o,p,f)||o.AddError({keyword:"const",schemaPath:a,instancePath:u,params:{allowedValue:p.const}})}function MR(e){return!(di(e)&&C(e.minContains,0))}function ND(e,o,a,u){let[p,f]=[ir(),ir()],h=zn(ko(bt(u,"length"),Re(0))),g=kM(u,[p,f],On(Gt(e,o,a.contains,p),o.AddIndex(f)));return On(h,g)}function qD(e,o,a,u){let[p]=[ir()],f=zn(ko(bt(u,"length"),Re(0))),h=RM(u,[p,"_"],Gt(e,o,a.contains,p));return On(f,h)}function OR(e,o,a,u){if(!MR(a))return Re(!0);return o.UseUnevaluated()?ND(e,o,a,u):qD(e,o,a,u)}function Rf(e,o,a,u){if(!MR(a))return!0;return!C(u.length,0)&&py(u,(p,f)=>Pt(e,o,a.contains,p)&&o.AddIndex(f))}function _R(e,o,a,u,p,f){return Rf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:1}})}function LR(e,o,a,u){let p=ko(bt(ua(u),"length"),Re(0)),f=Fn(pn(a.dependencies).map(([h,g])=>{let I=zn(ca(u,Re(h))),E=Gt(e,o,g,u),S=(k)=>Fn(k.map((A)=>ca(u,Re(A))));return br(I,Le(g)?S(g):E)}));return br(p,f)}function NR(e,o,a,u){let p=C(Ee(u).length,0),f=on(pn(a.dependencies),0,([h,g])=>!me(u,h)||(Le(g)?g.every((I)=>me(u,I)):Pt(e,o,g,u)));return p||f}function qR(e,o,a,u,p,f){let h=C(Ee(f).length,0),g=Dn(pn(p.dependencies),0,([I,E])=>{let S=`${a}/dependencies/${I}`;return!me(f,I)||(Le(E)?E.every((k)=>me(f,k)||o.AddError({keyword:"dependencies",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})):dr(e,o,S,u,E,f))});return h||g}function DR(e,o,a,u){let p=ko(bt(ua(u),"length"),Re(0)),f=Fn(pn(a.dependentRequired).map(([h,g])=>{let I=zn(ca(u,Re(h))),E=Fn(g.map((S)=>ca(u,Re(S))));return br(I,E)}));return br(p,f)}function FR(e,o,a,u){let p=C(Ee(u).length,0),f=on(pn(a.dependentRequired),0,([h,g])=>!me(u,h)||g.every((I)=>me(u,I)));return p||f}function jR(e,o,a,u,p,f){let h=C(Ee(f).length,0),g=Dn(pn(p.dependentRequired),0,([I,E])=>!me(f,I)||Dn(E,0,(S)=>me(f,S)||o.AddError({keyword:"dependentRequired",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})));return h||g}function UR(e,o,a,u){let p=ko(bt(ua(u),"length"),Re(0)),f=Fn(pn(a.dependentSchemas).map(([h,g])=>{let I=zn(ca(u,Re(h))),E=Gt(e,o,g,u);return br(I,E)}));return br(p,f)}function BR(e,o,a,u){let p=C(Ee(u).length,0),f=on(pn(a.dependentSchemas),0,([h,g])=>!me(u,h)||Pt(e,o,g,u));return p||f}function GR(e,o,a,u,p,f){let h=C(Ee(f).length,0),g=Dn(pn(p.dependentSchemas),0,([I,E])=>{let S=`${a}/dependentSchemas/${I}`;return!me(f,I)||dr(e,o,S,u,E,f)});return h||g}function KR(e,o,a,u){let p=e.DynamicRef(a)??!1;return gi(e,o,p,u)}function HR(e,o,a,u){let p=e.DynamicRef(a)??!1;return Ye(p)&&Pt(e,o,p,u)}function WR(e,o,a,u,p,f){let h=e.DynamicRef(p)??!1;return Ye(h)&&dr(e,o,"#",u,h,f)}function zR(e,o,a,u){return ad(a.enum.map((p)=>{if(ia(p))return ko(u,Re(p));let f=Wo(p);return Ey(u,f)}))}function Af(e,o,a,u){return qa(a.enum,(p)=>ia(p)?C(u,p):Da(u,p))}function VR(e,o,a,u,p,f){return Af(e,o,p,f)||o.AddError({keyword:"enum",schemaPath:a,instancePath:u,params:{allowedValues:p.enum}})}function JR(e,o,a,u){return sd(u,Re(a.exclusiveMaximum))}function Pf(e,o,a,u){return Mu(u,a.exclusiveMaximum)}function QR(e,o,a,u,p,f){return Pf(e,o,p,f)||o.AddError({keyword:"exclusiveMaximum",schemaPath:a,instancePath:u,params:{comparison:"<",limit:p.exclusiveMaximum}})}function XR(e,o,a,u){return xy(u,Re(a.exclusiveMinimum))}function $f(e,o,a,u){return sa(u,a.exclusiveMinimum)}function YR(e,o,a,u,p,f){return $f(e,o,p,f)||o.AddError({keyword:"exclusiveMinimum",schemaPath:a,instancePath:u,params:{comparison:">",limit:p.exclusiveMinimum}})}var DD=[0,31,28,31,30,31,30,31,31,30,31,30,31],FD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function jD(e){return e%4===0&&(e%100!==0||e%400===0)}function pu(e){let o=FD.exec(e);if(!o)return!1;let a=+o[1],u=+o[2],p=+o[3];return u>=1&&u<=12&&p>=1&&p<=(u===2&&jD(a)?29:DD[u])}var UD=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function lu(e,o=!0){let a=UD.exec(e);if(!a)return!1;if(o&&!a[4]&&!a[5])return!1;let u=+a[1],p=+a[2],f=+a[3];if(u>23||p>59||f>60)return!1;if(a[5]){let S=+a[6],k=+a[7];if(S>23||k>59)return!1}if(f<60)return!0;let h=a[5]==="-"?-1:1,g=+(a[6]||0),I=+(a[7]||0);return((u*60+p-h*(g*60+I))%1440+1440)%1440===1439}function Sp(e){let o=e.split(/T/i);return o.length===2&&pu(o[0])&&lu(o[1])}var BD=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function wp(e){return BD.test(e)}var GD=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function Tp(e){return GD.test(e)}var ZR=/^(?!-).*(?<!-)$/,ek=/^(?!..--)/,tk=/^[a-zA-Z0-9-]*$/;var du=/[^\p{ASCII}]/u;var KD=/[0-9]/,rk=/[\u{0660}-\u{0669}]/u,HD=/[\u{06f0}-\u{06f9}]/u,WD=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,zD=/[\u{002d}\u{002b}]/u,Cf=/\p{Mn}/u,VD=/\p{Mc}/u;var nk=/[\p{Mn}\p{Mc}\p{Me}]/u,vf=/\p{L}/u,JD=/\p{Nd}/u,ok=/\p{Script=Greek}/u,Rp=/\p{Script=Hebrew}/u,sk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,ik=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Mf=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,ak=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,QD=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,XD=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,uk=new RegExp([KD,HD].map((e)=>e.source).join("|"),"u"),ck=new RegExp([vf,zD,WD,JD,Cf,VD,QD,XD].map((e)=>e.source).join("|"),"u");function mk(e){return ZR.test(e)&&ek.test(e)&&tk.test(e)}var $s=36,Dc=1,Fc=26,ZD=38,eF=700,lk=72,dk=128;function Of(){throw null}function kp(e){return e.toLowerCase().startsWith("xn--")}function fk(e,o,a){e=a?Math.floor(e/eF):e>>1,e+=Math.floor(e/o);let u=0;while(e>($s-Dc)*Fc>>1)e=Math.floor(e/($s-Dc)),u+=$s;return u+Math.floor(($s-Dc+1)*e/(e+ZD))}function Ap(e){let o=[],a=dk,u=0,p=lk,f=e.lastIndexOf("-");if(f>0)for(let g=0;g<f;g++){let I=e.charCodeAt(g);if(I>=128)Of();o.push(I)}let h=f<0?0:f+1;while(h<e.length){let g=u,I=1,E=$s;while(!0){if(h>=e.length)Of();let k=e.charCodeAt(h++),A;if(k>=97&&k<=122)A=k-97;else if(k>=48&&k<=57)A=k-48+26;else Of();u+=A*I;let P=E<=p?Dc:E>=p+Fc?Fc:E-p;if(A<P)break;I*=$s-P,E+=$s}let S=o.length+1;p=fk(u-g,S,g===0),a+=Math.floor(u/S),u%=S,o.splice(u,0,a),u++}return String.fromCodePoint(...o)}function pk(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var tF=new RegExp(du.source,"gu");function hk(e){let o=e.replace(tF,""),a=o.length,u=a>0?[o,"-"]:[],p=Array.from(e,(E)=>E.codePointAt(0)),f=dk,h=0,g=lk,I=a;while(I<p.length){let E=1/0;for(let S of p)if(S>=f&&S<E)E=S;h+=(E-f)*(I+1),f=E;for(let S of p){if(S<f)h++;if(S===f){let k=h;for(let A=$s;;A+=$s){let P=A<=g?Dc:A>=g+Fc?Fc:A-g;if(k<P)break;let v=P+(k-P)%($s-P);u.push(pk(v)),k=Math.floor((k-P)/($s-P))}u.push(pk(k)),g=fk(h,I+1,I===a),h=0,I++}}h++,f++}return u.join("")}var rF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,gk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,nF=/^(?:R|AL|AN)$/;function yk(e){if(kp(e))try{return Pp(Ap(e.slice(4).toLowerCase()))}catch{return!1}return Pp(e)}function xk(e){let o=String.fromCodePoint(e);return uk.test(o)?"EN":rk.test(o)?"AN":Cf.test(o)?"NSM":Rp.test(o)?"R":ik.test(o)?"AL":vf.test(o)?"L":"ON"}function Pp(e){for(let o of e)if(nF.test(xk(o.codePointAt(0))))return!0;return!1}function $p(e){let o=!1,a=gk,u=!1,p=!1,f=!0;for(let h of e){let g=xk(h.codePointAt(0));if(f){if(g!=="L"&&g!=="R"&&g!=="AL")return!1;o=g==="R"||g==="AL",a=o?rF:gk,f=!1}if(!a.test(g))return!1;if(g==="EN")u=!0;else if(g==="AN")p=!0}if(o&&u&&p)return!1;return!0}function oF(e){return du.test(e)&&hk(e).length+4>63}function sF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Cp(e){if(oF(e))return!1;if(Pp(e)&&!$p(e))return!1;let o=[...e],a=o.map((f)=>f.codePointAt(0)),u=a.length;if(sF(o))return!1;if(nk.test(o[0]))return!1;let p=!1;for(let f=0;f<u;f++){let h=a[f],g=o[f];if(ak.test(g))return!1;if(!ck.test(g))return!1;if(sk.test(g))p=!0;let I=a[f-1],E=a[f+1];switch(h){case 183:if(I!==108||E!==108)return!1;break;case 885:if(!E||!ok.test(o[f+1]))return!1;break;case 1523:case 1524:if(!I||!Rp.test(o[f-1]))return!1;break;case 8204:if(!I||I<128&&!Mf.test(o[f-1]))return!1;break;case 8205:if(!I||!Mf.test(o[f-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function vp(e){if(!kp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let a=Ap(o);if(!du.test(a))return!1;return Cp(a)}catch{return!1}}function iF(e){return e.length>0&&e.length<=63}function aF(e){return iF(e)&&(vp(e)||mk(e))}function Sk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>aF(o))}function uF(e){return e.length>0&&e.length<=63}function cF(e){return uF(e)&&(vp(e)||Cp(e))}function mF(e){return e.replace(/[\uff01-\uff5e]/g,(o)=>String.fromCharCode(o.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function wk(e){if(e.length===0||e.includes(" "))return!1;let o=mF(e);if(o.length>253)return!1;let a=o.split("."),u=a.some((p)=>yk(p));return a.every((p)=>cF(p)&&(!u||$p(p)))}function Mp(e){return Sk(e)}var pF=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Op(e){return pF.test(e.normalize("NFC"))}function _p(e){return wk(e)}var lF=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Lp(e){return lF.test(e)}var dF=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function Np(e){return dF.test(e)}var fF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,hF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function qp(e){return!fF.test(e)&&!hF.test(e)&&URL.canParse(e,"http://example.com")}var gF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,yF=/[\x00-\x20<>\^`{|}\\]/,xF=/%(?![0-9a-fA-F]{2})/;function IF(e){return e.length<2048?e.replace(gF,"[::1]"):e}function Dp(e){if(yF.test(e))return!1;if(xF.test(e))return!1;return URL.canParse(IF(e))}var EF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Fp(e){return EF.test(e)}var bF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function jp(e){return bF.test(e)}function Up(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var SF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Bp(e){return SF.test(e)}var wF=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Gp(e){return wF.test(e)}var TF=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Kp(e){return TF.test(e)}var RF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Hp(e){return RF.test(e)}function Wp(e){return URL.canParse(e)}var kF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function zp(e){return kF.test(e)}var Rr=new Map;function Rk(){Rr.clear()}function AF(){return[...Rr.entries()]}function PF(e,o){Rr.set(e,o)}function $F(e){return Rr.has(e)}function CF(e){return Rr.get(e)}function kk(e,o){return Rr.get(e)?.(o)??!0}function Ak(){Rk(),Rr.set("date-time",Sp),Rr.set("date",pu),Rr.set("duration",wp),Rr.set("email",Tp),Rr.set("hostname",Mp),Rr.set("idn-email",Op),Rr.set("idn-hostname",_p),Rr.set("ipv4",Lp),Rr.set("ipv6",Np),Rr.set("iri-reference",qp),Rr.set("iri",Dp),Rr.set("json-pointer-uri-fragment",Fp),Rr.set("json-pointer",jp),Rr.set("regex",Up),Rr.set("relative-json-pointer",Bp),Rr.set("time",lu),Rr.set("uri-reference",Gp),Rr.set("uri-template",Kp),Rr.set("uri",Hp),Rr.set("url",Wp),Rr.set("uuid",zp)}Ak();function Pk(e,o,a,u){return Sr(bt("Format","Test"),[Re(a.format),u])}function Lf(e,o,a,u){return kk(a.format,u)}function $k(e,o,a,u,p,f){return Lf(e,o,p,f)||o.AddError({keyword:"format",schemaPath:a,instancePath:u,params:{format:p.format}})}function Ck(e,o,a,u){let p=Lc(a)?a.then:!0,f=bc(a)?a.else:!0;return PM(Gt(e,o,a.if,u),Gt(e,o,p,u),Gt(e,o,f,u))}function vk(e,o,a,u){let p=Lc(a)?a.then:!0,f=bc(a)?a.else:!0;return Pt(e,o,a.if,u)?Pt(e,o,p,u):Pt(e,o,f,u)}function Mk(e,o,a,u,p,f){let h=Lc(p)?p.then:!0,g=bc(p)?p.else:!0,I=new Hn,E=dr(e,I,`${a}/if`,u,p.if,f)?dr(e,I,`${a}/then`,u,h,f)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"then"}}):dr(e,o,`${a}/else`,u,g,f)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"else"}});if(E)o.Merge([I]);return E}function vF(e,o,a,u){return Fn(a.items.map((p,f)=>{let h=aa(bt(u,"length"),Re(f)),g=Io(e,o,p,`${u}[${f}]`),I=o.AddIndex(Re(f));return br(h,On(g,I))}))}function MF(e,o,a,u){return Fn(a.items.map((p,f)=>{let h=aa(bt(u,"length"),Re(f)),g=Io(e,o,p,`${u}[${f}]`);return br(h,g)}))}function OF(e,o,a,u){return o.UseUnevaluated()?vF(e,o,a,u):MF(e,o,a,u)}function _F(e,o,a,u){return on(a.items,0,(p,f)=>Ls(u.length,f)||Do(e,o,p,u[f])&&o.AddIndex(f))}function LF(e,o,a,u,p,f){return Dn(p.items,0,(h,g)=>{let I=`${a}/items/${g}`,E=`${u}/${g}`;return Ls(f.length,g)||Fo(e,o,I,E,h,f[g])&&o.AddIndex(g)})}function NF(e,o,a,u){let p=Ss(a)?a.prefixItems.length:0,f=Io(e,o,a.items,"element"),h=o.AddIndex("index");return Ns(u,Re(p),["element","index"],On(f,h))}function qF(e,o,a,u){let p=Ss(a)?a.prefixItems.length:0,f=Io(e,o,a.items,"element");return Ns(u,Re(p),["element","index"],f)}function DF(e,o,a,u){return o.UseUnevaluated()?NF(e,o,a,u):qF(e,o,a,u)}function FF(e,o,a,u){let p=Ss(a)?a.prefixItems.length:0;return on(u,p,(f,h)=>Do(e,o,a.items,f)&&o.AddIndex(h))}function jF(e,o,a,u,p,f){let h=Ss(p)?p.prefixItems.length:0;return Dn(f,h,(g,I)=>{let E=`${a}/items`,S=`${u}/${I}`;return Fo(e,o,E,S,p.items,g)&&o.AddIndex(I)})}function Ok(e,o,a,u){return Tc(a)?OF(e,o,a,u):DF(e,o,a,u)}function _k(e,o,a,u){return Tc(a)?_F(e,o,a,u):FF(e,o,a,u)}function Lk(e,o,a,u,p,f){return Tc(p)?LF(e,o,a,u,p,f):jF(e,o,a,u,p,f)}function Nk(e){return Vs(e)}function qk(e,o,a,u){if(!Nk(a))return Re(!0);let[p]=[ir()],f=um(u,[p,"_"],Gt(e,o,a.contains,p));return aa(f,Re(a.maxContains))}function Nf(e,o,a,u){if(!Nk(a))return!0;let p=td(u,(f)=>Pt(e,o,a.contains,f));return Ls(p,a.maxContains)}function Dk(e,o,a,u,p,f){let h=di(p)?p.minContains:1;return Nf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:h,maxContains:p.maxContains}})}function Fk(e,o,a,u){return aa(u,Re(a.maximum))}function qf(e,o,a,u){return Ls(u,a.maximum)}function jk(e,o,a,u,p,f){return qf(e,o,p,f)||o.AddError({keyword:"maximum",schemaPath:a,instancePath:u,params:{comparison:"<=",limit:p.maximum}})}function Uk(e,o,a,u){return aa(bt(u,"length"),Re(a.maxItems))}function Df(e,o,a,u){return Ls(u.length,a.maxItems)}function Bk(e,o,a,u,p,f){return Df(e,o,p,f)||o.AddError({keyword:"maxItems",schemaPath:a,instancePath:u,params:{limit:p.maxItems}})}function Gk(e,o,a,u){return TM(u,Re(a.maxLength))}function Ff(e,o,a,u){return cy(u,a.maxLength)}function Kk(e,o,a,u,p,f){return Ff(e,o,p,f)||o.AddError({keyword:"maxLength",schemaPath:a,instancePath:u,params:{limit:p.maxLength}})}function Hk(e,o,a,u){return aa(bt(ua(u),"length"),Re(a.maxProperties))}function jf(e,o,a,u){return Ls(Ee(u).length,a.maxProperties)}function Wk(e,o,a,u,p,f){return jf(e,o,p,f)||o.AddError({keyword:"maxProperties",schemaPath:a,instancePath:u,params:{limit:p.maxProperties}})}function zk(e){return Vs(e)}function UF(e,o,a,u){let[p,f]=[ir(),ir()],h=um(u,[p,f],On(Gt(e,o,a.contains,p),o.AddIndex(f)));return _u(h,Re(a.minContains))}function BF(e,o,a,u){let[p]=[ir()],f=um(u,[p,"_"],Gt(e,o,a.contains,p));return _u(f,Re(a.minContains))}function Vk(e,o,a,u){if(!zk(a))return Re(!0);return o.UseUnevaluated()?UF(e,o,a,u):BF(e,o,a,u)}function Uf(e,o,a,u){if(!zk(a))return!0;let p=td(u,(f,h)=>Pt(e,o,a.contains,f)&&o.AddIndex(h));return Na(p,a.minContains)}function Jk(e,o,a,u,p,f){return Uf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:p.minContains}})}function Qk(e,o,a,u){return _u(u,Re(a.minimum))}function Bf(e,o,a,u){return Na(u,a.minimum)}function Xk(e,o,a,u,p,f){return Bf(e,o,p,f)||o.AddError({keyword:"minimum",schemaPath:a,instancePath:u,params:{comparison:">=",limit:p.minimum}})}function Yk(e,o,a,u){return _u(bt(u,"length"),Re(a.minItems))}function Gf(e,o,a,u){return Na(u.length,a.minItems)}function Zk(e,o,a,u,p,f){return Gf(e,o,p,f)||o.AddError({keyword:"minItems",schemaPath:a,instancePath:u,params:{limit:p.minItems}})}function eA(e,o,a,u){return wM(u,Re(a.minLength))}function Kf(e,o,a,u){return my(u,a.minLength)}function tA(e,o,a,u,p,f){return Kf(e,o,p,f)||o.AddError({keyword:"minLength",schemaPath:a,instancePath:u,params:{limit:p.minLength}})}function rA(e,o,a,u){return _u(bt(ua(u),"length"),Re(a.minProperties))}function Hf(e,o,a,u){return Na(Ee(u).length,a.minProperties)}function nA(e,o,a,u,p,f){return Hf(e,o,p,f)||o.AddError({keyword:"minProperties",schemaPath:a,instancePath:u,params:{limit:p.minProperties}})}function oA(e,o,a,u){return $M(u,Re(a.multipleOf))}function Wf(e,o,a,u){return ay(u,a.multipleOf)}function sA(e,o,a,u,p,f){return Wf(e,o,p,f)||o.AddError({keyword:"multipleOf",schemaPath:a,instancePath:u,params:{multipleOf:p.multipleOf}})}function GF(e,o,a,u){return Xi(e,o,[a.not],u,zn(ko(bt("results","length"),Re(1))))}function KF(e,o,a,u){return zn(Gt(e,o,a.not,u))}function iA(e,o,a,u){return o.UseUnevaluated()?GF(e,o,a,u):KF(e,o,a,u)}function zf(e,o,a,u){let p=new Kn;return!Pt(e,p,a.not,u)&&o.Merge([p])}function aA(e,o,a,u,p,f){return zf(e,o,p,f)||o.AddError({keyword:"not",schemaPath:a,instancePath:u,params:{}})}function HF(e,o,a,u){return Xi(e,o,a.oneOf,u,ko(bt("results","length"),Re(1)))}function WF(e,o,a,u){let[p]=[ir()],f=AM(a.oneOf.map((g)=>Gt(e,o,g,u))),h=um(f,[p,"_"],ko(p,Re(!0)));return ko(h,Re(1))}function uA(e,o,a,u){return o.UseUnevaluated()?HF(e,o,a,u):WF(e,o,a,u)}function cA(e,o,a,u){let p=a.oneOf.reduce((f,h)=>{let g=new Kn;return Pt(e,g,h,u)?[...f,g]:f},[]);return C(p.length,1)&&o.Merge(p)}function mA(e,o,a,u,p,f){let h=[],g=[],I=p.oneOf.reduce((S,k,A)=>{let P=new Hn,v=`${a}/oneOf/${A}`,M=dr(e,P,v,u,k,f);if(M)g.push(A);if(!M)h.push(P);return M?[...S,P]:S},[]),E=C(I.length,1)&&o.Merge(I);if(!E&&C(g.length,0))h.forEach((S)=>S.GetErrors().forEach((k)=>o.AddError(k)));return E||o.AddError({keyword:"oneOf",schemaPath:a,instancePath:u,params:{passingSchemas:g}})}function pA(e,o,a,u){let p=Wo(gt(a.pattern)?Rs(a.pattern):a.pattern);return Sr(bt(p,"test"),[u])}function Vf(e,o,a,u){return(gt(a.pattern)?Rs(a.pattern):a.pattern).test(u)}function lA(e,o,a,u,p,f){return Vf(e,o,p,f)||o.AddError({keyword:"pattern",schemaPath:a,instancePath:u,params:{pattern:p.pattern}})}function dA(e,o,a,u){return Fn(pn(a.patternProperties).map(([p,f])=>{let[h,g]=[ir(),ir()],I=Wo(Rs(p)),E=zn(Sr(bt(I,"test"),[h])),S=Io(e,o,f,g),k=o.AddKey(h),A=o.UseUnevaluated()?br(E,On(S,k)):br(E,S);return Ns(Iy(u),Re(0),[`[${h}, ${g}]`,"_"],A)}))}function fA(e,o,a,u){return on(pn(a.patternProperties),0,([p,f])=>{let h=Rs(p);return on(pn(u),0,([g,I])=>!h.test(g)||Do(e,o,f,I)&&o.AddKey(g))})}function hA(e,o,a,u,p,f){return Dn(pn(p.patternProperties),0,([h,g])=>{let I=`${a}/patternProperties/${h}`,E=Rs(h);return Dn(pn(f),0,([S,k])=>{let A=`${u}/${S}`;return!E.test(S)||Fo(e,o,I,A,g,k)&&o.AddKey(S)})})}function gA(e,o,a,u){return Fn(a.prefixItems.map((p,f)=>{let h=aa(bt(u,"length"),Re(f)),g=Io(e,o,p,`${u}[${f}]`),I=o.AddIndex(Re(f)),E=o.UseUnevaluated()?On(g,I):g;return br(h,E)}))}function yA(e,o,a,u){return C(u.length,0)||on(a.prefixItems,0,(p,f)=>Ls(u.length,f)||Do(e,o,p,u[f])&&o.AddIndex(f))}function xA(e,o,a,u,p,f){return C(f.length,0)||Dn(p.prefixItems,0,(h,g)=>{let I=`${a}/prefixItems/${g}`,E=`${u}/${g}`;return Ls(f.length,g)||Fo(e,o,I,E,h,f[g])&&o.AddIndex(g)})}function Vp(e,o){return e.includes(o)||ss().exactOptionalPropertyTypes}function IA(e,o){return od(bt(e,o))}function Jf(e,o){return rr(e[o])}function EA(e,o,a,u){let p=ws(a)?a.required:[],f=pn(a.properties).map(([h,g])=>{let I=zn(ca(u,Re(h))),E=Io(e,o,g,bt(u,h)),S=o.AddKey(Re(h)),k=o.UseUnevaluated()?On(E,S):E,A=p.includes(h)?k:br(I,k);return Vp(p,h)?A:br(IA(u,h),A)});return Fn(f)}function bA(e,o,a,u){let p=ws(a)?a.required:[];return on(pn(a.properties),0,([h,g])=>{let I=!me(u,h)||Do(e,o,g,u[h])&&o.AddKey(h);return Vp(p,h)?I:Jf(u,h)||I})}function SA(e,o,a,u,p,f){let h=ws(p)?p.required:[];return Dn(pn(p.properties),0,([I,E])=>{let S=`${a}/properties/${I}`,k=`${u}/${I}`,A=()=>!me(f,I)||Fo(e,o,S,k,E,f[I])&&o.AddKey(I);return Vp(h,I)?A():Jf(f,I)||A()})}function wA(e,o,a,u){let[p,f]=[ir(),ir()];return Ns(ua(u),Re(0),[p,f],Gt(e,o,a.propertyNames,p))}function TA(e,o,a,u){return on(Ee(u),0,(p,f)=>Pt(e,o,a.propertyNames,p))}function RA(e,o,a,u,p,f){let h=[];return Dn(Ee(f),0,(I,E)=>{let S=`${u}/${I}`,k=`${a}/propertyNames`,A=dr(e,o,k,S,p.propertyNames,I);if(!A)h.push(I);return A})||o.AddError({keyword:"propertyNames",schemaPath:a,instancePath:u,params:{propertyNames:h}})}function kA(e,o,a,u){let p=e.RecursiveRef(a)??!1;return gi(e,o,p,u)}function AA(e,o,a,u){let p=e.RecursiveRef(a)??!1;return Ye(p)&&Pt(e,o,p,u)}function PA(e,o,a,u,p,f){let h=e.RecursiveRef(p)??!1;return Ye(h)&&dr(e,o,"#",u,h,f)}function zF(e,o,a,u){let p=Ti(["context","value"],gi(e,o,a,"value")),f=Ti(["context","value"],cm([ei("nextContext",id("CheckContext",[])),ei("result",Sr(p,["nextContext","value"])),by("result",o.Merge("[nextContext]")),mm("result")]));return Sr(f,["context",u])}function VF(e,o,a,u){return gi(e,o,a,u)}function $A(e,o,a,u){let p=e.Ref(a)??!1;return o.UseUnevaluated()?zF(e,o,p,u):VF(e,o,p,u)}function CA(e,o,a,u){let p=e.Ref(a)??!1,f=new Kn,h=Ye(p)&&Pt(e,f,p,u);if(h)o.Merge([f]);return h}function vA(e,o,a,u,p,f){let h=e.Ref(p)??!1,g=new Hn,I=Ye(h)&&dr(e,g,"#",u,h,f);if(I)o.Merge([g]);if(!I)g.GetErrors().forEach((E)=>o.AddError(E));return I}function MA(e,o,a,u){return Fn(a.required.map((p)=>ca(u,Re(p))))}function OA(e,o,a,u){return on(a.required,0,(p)=>me(u,p))}function _A(e,o,a,u,p,f){let h=[];return Dn(p.required,0,(I)=>{let E=me(f,I);if(!E)h.push(I);return E})||o.AddError({keyword:"required",schemaPath:a,instancePath:u,params:{requiredProperties:h}})}function LA(e,o,a,u){return C(a,"object")?hy(u):C(a,"array")?am(u):C(a,"boolean")?yM(u):C(a,"integer")?xM(u):C(a,"number")?fy(u):C(a,"null")?IM(u):C(a,"string")?yy(u):C(a,"bigint")?dy(u):C(a,"constructor")?SM(u):C(a,"function")?bM(u):C(a,"symbol")?EM(u):C(a,"undefined")?od(u):C(a,"void")?od(u):Re(!0)}function Qf(e,o,a,u,p){return C(a,"object")?rs(p):C(a,"array")?Le(p):C(a,"boolean")?cn(p):C(a,"integer")?im(p):C(a,"number")?Ut(p):C(a,"null")?Mo(p):C(a,"string")?gt(p):C(a,"bigint")?Kr(p):C(a,"constructor")?Zl(p):C(a,"function")?_s(p):C(a,"symbol")?ed(p):C(a,"undefined")?rr(p):C(a,"void")?rr(p):!0}function JF(e,o,a,u){return ad(a.map((p)=>LA(e,o,p,u)))}function NA(e,o,a,u,p){return qa(a,(f)=>Qf(e,o,f,u,p))}function qA(e,o,a,u){return Le(a.type)?JF(e,o,a.type,u):LA(e,o,a.type,u)}function DA(e,o,a,u){return Le(a.type)?NA(e,o,a.type,a,u):Qf(e,o,a.type,a,u)}function FA(e,o,a,u,p,f){return(Le(p.type)?NA(e,o,p.type,p,f):Qf(e,o,p.type,p,f))||o.AddError({keyword:"type",schemaPath:a,instancePath:u,params:{type:p.type}})}function jA(e,o,a,u){let[p,f]=[ir(),ir()],h=Sr(bt("context","GetIndices"),[]),g=Sr(bt("indices","has"),[p]),I=Gt(e,o,a.unevaluatedItems,f),E=Sr(bt("context","AddIndex"),[p]),S=Ns(u,Re(0),[f,p],On(br(g,I),E));return Sr(Ti(["context"],cm([ei("indices",h),mm(S)])),["context"])}function UA(e,o,a,u){let p=o.GetIndices();return on(u,0,(f,h)=>(p.has(h)||Pt(e,o,a.unevaluatedItems,f))&&o.AddIndex(h))}function BA(e,o,a,u,p,f){let h=o.GetIndices(),g=[];return Dn(f,0,(E,S)=>{let k=new Hn,A=(h.has(S)||dr(e,k,a,u,p.unevaluatedItems,E))&&o.AddIndex(S);if(!A)g.push(S);return A})||o.AddError({keyword:"unevaluatedItems",schemaPath:a,instancePath:u,params:{unevaluatedItems:g}})}function GA(e,o,a,u){let[p,f]=[ir(),ir()],h=Sr(bt("context","GetKeys"),[]),g=Sr(bt("keys","has"),[p]),I=Sr(bt("context","AddKey"),[p]),E=Gt(e,o,a.unevaluatedProperties,f),S=Ns(Iy(u),Re(0),[`[${p}, ${f}]`,"_"],br(g,On(E,I)));return Sr(Ti(["context"],cm([ei("keys",h),mm(S)])),["context"])}function KA(e,o,a,u){let p=o.GetKeys();return on(pn(u),0,([f,h])=>p.has(f)||Pt(e,o,a.unevaluatedProperties,h)&&o.AddKey(f))}function HA(e,o,a,u,p,f){let h=o.GetKeys(),g=[];return Dn(pn(f),0,([E,S])=>{let k=new Hn,A=h.has(E)||dr(e,k,a,u,p.unevaluatedProperties,S)&&o.AddKey(E);if(!A)g.push(E);return A})||o.AddError({keyword:"unevaluatedProperties",schemaPath:a,instancePath:u,params:{unevaluatedProperties:g}})}function Xf(e){return!C(e.uniqueItems,!1)}function WA(e,o,a,u){if(!Xf(a))return Re(!0);let p=bt(id("Set",[Sr(bt(u,"map"),[bt("Hashing","Hash")])]),"size"),f=bt(u,"length");return ko(p,f)}function zA(e,o,a,u){if(!Xf(a))return!0;let p=new Set(u.map(md)).size,f=u.length;return C(p,f)}function VA(e,o,a,u,p,f){if(!Xf(p))return!0;let h=new Set,g=f.reduce((E,S,k)=>{let A=md(S);if(h.has(A))return[...E,k];return h.add(A),E},[]);return C(g.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:a,instancePath:u,params:{duplicateItems:g}})}function jc(e,o){return Nc(e)&&(Le(e.type)&&sa(e.type.length,0)&&on(e.type,0,(a)=>C(a,o))||C(e.type,o))}function QF(e){return jc(e,"object")}function XF(e){return Tn(e)&&(Ho(e)||xc(e)||Ic(e)||au(e)||hi(e)||fi(e)||cu(e)||Aa(e)||Pc(e)||ws(e)||zi(e))}function YF(e){return jc(e,"array")}function ZF(e){return Tn(e)&&(iu(e)||pi(e)||Vs(e)||kc(e)||uu(e)||di(e)||Ui(e)||Ss(e)||Gi(e)||Bi(e))}function e1(e){return jc(e,"string")}function t1(e){return Tn(e)&&(ka(e)||Ac(e)||Ra(e)||Pa(e))}function r1(e){return jc(e,"number")||jc(e,"bigint")}function n1(e){return Tn(e)&&(Is(e)||Rc(e)||Sc(e)||xs(e)||$c(e))}function Io(e,o,a,u){return o.UseUnevaluated()?On(On(o.Push(),Gt(e,o,a,u)),o.Pop()):Gt(e,o,a,u)}function Gt(e,o,a,u){e.Push(a);let p=[];if(ui(a))return PR(e,o,a,u);if(Nc(a))p.push(qA(e,o,a,u));if(XF(a)){let h=[];if(ws(a))h.push(MA(e,o,a,u));if(Ho(a))h.push(IR(e,o,a,u));if(xc(a))h.push(LR(e,o,a,u));if(Ic(a))h.push(DR(e,o,a,u));if(au(a))h.push(UR(e,o,a,u));if(fi(a))h.push(dA(e,o,a,u));if(hi(a))h.push(EA(e,o,a,u));if(cu(a))h.push(wA(e,o,a,u));if(Aa(a))h.push(rA(e,o,a,u));if(Pc(a))h.push(Hk(e,o,a,u));let g=Fn(h),I=br(zn(hy(u)),g);p.push(QF(a)?g:I)}if(ZF(a)){let h=[];if(iu(a))h.push(gR(e,o,a,u));if(Vs(a))h.push(OR(e,o,a,u));if(pi(a))h.push(Ok(e,o,a,u));if(kc(a))h.push(qk(e,o,a,u));if(uu(a))h.push(Uk(e,o,a,u));if(di(a))h.push(Vk(e,o,a,u));if(Ui(a))h.push(Yk(e,o,a,u));if(Ss(a))h.push(gA(e,o,a,u));if(Bi(a))h.push(WA(e,o,a,u));let g=Fn(h),I=br(zn(am(u)),g);p.push(YF(a)?g:I)}if(t1(a)){let h=[];if(Ac(a))h.push(Gk(e,o,a,u));if(ka(a))h.push(eA(e,o,a,u));if(Ra(a))h.push(Pk(e,o,a,u));if(Pa(a))h.push(pA(e,o,a,u));let g=Fn(h),I=br(zn(yy(u)),g);p.push(e1(a)?g:I)}if(n1(a)){let h=[];if(Sc(a))h.push(JR(e,o,a,u));if(xs(a))h.push(XR(e,o,a,u));if(Rc(a))h.push(Fk(e,o,a,u));if(Is(a))h.push(Qk(e,o,a,u));if($c(a))h.push(oA(e,o,a,u));let g=Fn(h),I=br(zn(br(fy(u),dy(u))),g);p.push(r1(a)?g:I)}if(_c(a))p.push($A(e,o,a,u));if(Oc(a))p.push(kA(e,o,a,u));if(Ec(a))p.push(KR(e,o,a,u));if(xp(a))p.push(CR(e,o,a,u));if(Ip(a))p.push(zR(e,o,a,u));if(wc(a))p.push(Ck(e,o,a,u));if(Cc(a))p.push(iA(e,o,a,u));if(hc(a))p.push(SR(e,o,a,u));if(yc(a))p.push(RR(e,o,a,u));if(vc(a))p.push(uA(e,o,a,u));if(Gi(a))p.push(br(zn(am(u)),jA(e,o,a,u)));if(zi(a))p.push(br(zn(gy(u)),GA(e,o,a,u)));if(fc(a))p.push(dR(e,o,a,u));let f=Fn(p);return e.Pop(a),f}function Do(e,o,a,u){return o.Push()&&Pt(e,o,a,u)&&o.Pop()}function Pt(e,o,a,u){e.Push(a);let p=ui(a)?wf(e,o,a,u):(!Nc(a)||DA(e,o,a,u))&&(!(lt(u)&&!Le(u))||(!ws(a)||OA(e,o,a,u))&&(!Ho(a)||ER(e,o,a,u))&&(!xc(a)||NR(e,o,a,u))&&(!Ic(a)||FR(e,o,a,u))&&(!au(a)||BR(e,o,a,u))&&(!fi(a)||fA(e,o,a,u))&&(!hi(a)||bA(e,o,a,u))&&(!cu(a)||TA(e,o,a,u))&&(!Aa(a)||Hf(e,o,a,u))&&(!Pc(a)||jf(e,o,a,u)))&&(!Le(u)||(!iu(a)||yR(e,o,a,u))&&(!Vs(a)||Rf(e,o,a,u))&&(!pi(a)||_k(e,o,a,u))&&(!kc(a)||Nf(e,o,a,u))&&(!uu(a)||Df(e,o,a,u))&&(!di(a)||Uf(e,o,a,u))&&(!Ui(a)||Gf(e,o,a,u))&&(!Ss(a)||yA(e,o,a,u))&&(!Bi(a)||zA(e,o,a,u)))&&(!gt(u)||(!Ac(a)||Ff(e,o,a,u))&&(!ka(a)||Kf(e,o,a,u))&&(!Ra(a)||Lf(e,o,a,u))&&(!Pa(a)||Vf(e,o,a,u)))&&(!(Ut(u)||Kr(u))||(!Sc(a)||Pf(e,o,a,u))&&(!xs(a)||$f(e,o,a,u))&&(!Rc(a)||qf(e,o,a,u))&&(!Is(a)||Bf(e,o,a,u))&&(!$c(a)||Wf(e,o,a,u)))&&(!_c(a)||CA(e,o,a,u))&&(!Oc(a)||AA(e,o,a,u))&&(!Ec(a)||HR(e,o,a,u))&&(!xp(a)||Tf(e,o,a,u))&&(!Ip(a)||Af(e,o,a,u))&&(!wc(a)||vk(e,o,a,u))&&(!Cc(a)||zf(e,o,a,u))&&(!hc(a)||wR(e,o,a,u))&&(!yc(a)||kR(e,o,a,u))&&(!vc(a)||cA(e,o,a,u))&&(!Gi(a)||(!Le(u)||UA(e,o,a,u)))&&(!zi(a)||(!lt(u)||KA(e,o,a,u)))&&(!fc(a)||fR(e,o,a,u));return e.Pop(a),p}function Fo(e,o,a,u,p,f){return o.Push()&&dr(e,o,a,u,p,f)&&o.Pop()}function dr(e,o,a,u,p,f){if(o.AtCapacity())return!1;e.Push(p);let h=ui(p)?$R(e,o,a,u,p,f):!!(+(!Nc(p)||FA(e,o,a,u,p,f))&+(!(lt(f)&&!Le(f))||!!(+(!ws(p)||_A(e,o,a,u,p,f))&+(!Ho(p)||bR(e,o,a,u,p,f))&+(!xc(p)||qR(e,o,a,u,p,f))&+(!Ic(p)||jR(e,o,a,u,p,f))&+(!au(p)||GR(e,o,a,u,p,f))&+(!fi(p)||hA(e,o,a,u,p,f))&+(!hi(p)||SA(e,o,a,u,p,f))&+(!cu(p)||RA(e,o,a,u,p,f))&+(!Aa(p)||nA(e,o,a,u,p,f))&+(!Pc(p)||Wk(e,o,a,u,p,f))))&+(!Le(f)||!!(+(!iu(p)||xR(e,o,a,u,p,f))&+(!Vs(p)||_R(e,o,a,u,p,f))&+(!pi(p)||Lk(e,o,a,u,p,f))&+(!kc(p)||Dk(e,o,a,u,p,f))&+(!uu(p)||Bk(e,o,a,u,p,f))&+(!di(p)||Jk(e,o,a,u,p,f))&+(!Ui(p)||Zk(e,o,a,u,p,f))&+(!Ss(p)||xA(e,o,a,u,p,f))&+(!Bi(p)||VA(e,o,a,u,p,f))))&+(!gt(f)||!!(+(!Ac(p)||Kk(e,o,a,u,p,f))&+(!ka(p)||tA(e,o,a,u,p,f))&+(!Ra(p)||$k(e,o,a,u,p,f))&+(!Pa(p)||lA(e,o,a,u,p,f))))&+(!(Ut(f)||Kr(f))||!!(+(!Sc(p)||QR(e,o,a,u,p,f))&+(!xs(p)||YR(e,o,a,u,p,f))&+(!Rc(p)||jk(e,o,a,u,p,f))&+(!Is(p)||Xk(e,o,a,u,p,f))&+(!$c(p)||sA(e,o,a,u,p,f))))&+(!_c(p)||vA(e,o,a,u,p,f))&+(!Oc(p)||PA(e,o,a,u,p,f))&+(!Ec(p)||WR(e,o,a,u,p,f))&+(!xp(p)||vR(e,o,a,u,p,f))&+(!Ip(p)||VR(e,o,a,u,p,f))&+(!wc(p)||Mk(e,o,a,u,p,f))&+(!Cc(p)||aA(e,o,a,u,p,f))&+(!hc(p)||TR(e,o,a,u,p,f))&+(!yc(p)||AR(e,o,a,u,p,f))&+(!vc(p)||mA(e,o,a,u,p,f))&+(!Gi(p)||(!Le(f)||BA(e,o,a,u,p,f)))&+(!zi(p)||(!lt(f)||HA(e,o,a,u,p,f))))&&(!fc(p)||hR(e,o,a,u,p,f));return e.Pop(p),h}var JA=[0],Jp=new Map,Uc=new Map;function o1(){return`${JA[0]++}`}function s1(e,o){if(!Jp.has(e))Jp.set(e,new Map);let a=Jp.get(e);if(a.has(o))return a.get(o);let u=o1();return a.set(o,u),u}function i1(e,o,a,u){return e.UseUnevaluated()?Sr(`check_${a}`,["context",u]):Sr(`check_${a}`,[u])}function a1(e,o,a,u){let p=Gt(e,o,a,"value");return o.UseUnevaluated()?ei(`check_${u}`,Ti(["context","value"],p)):ei(`check_${u}`,Ti(["value"],p))}function QA(){JA[0]=0,Jp.clear(),Uc.clear()}function XA(){return[...Uc.values()]}function gi(e,o,a,u){let p=s1(a,e.LexicalBaseURL()),f=i1(o,a,p,u);if(Uc.has(p))return f;return Uc.set(p,""),Uc.set(p,a1(e,o,a,p)),f}function u1(e,o){return lt(o)&&!Ou(e)?o[e]:void 0}function c1(e,o){return e.reduce((a,u)=>u1(u,a),o)}function m1(e){if(C(e.length,0))return[];let o=e.split("/").map((a)=>a.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function p1(e,o){let a=m1(o);return c1(a,e)}var Xp="https://json-schema.org";function ZA(e,o){if(lt(e)&&mi(e)&&C(e.$dynamicAnchor,o))return e;if(lt(e))for(let a of Ee(e)){let u=ZA(e[a],o);if(u)return u}return}function Yf(e,o,a){if(C(e,a))return o.href;let u=Tn(e)&&qo(e)?new URL(e.$id,o.href):o;if(Le(e))for(let p of e){let f=Yf(p,u,a);if(!rr(f))return f}else if(lt(e))for(let p of Ee(e)){let f=Yf(e[p],u,a);if(!rr(f))return f}return}function l1(e,o,a){if(C(e.$id,a.hash))return e;let u=new URL(a.href,o.href);if(C(o.pathname,u.pathname))return a.hash.startsWith("#")?eP(e,a):e;return}function d1(e,o,a){let u=new URL(`#${e.$anchor}`,o.href),p=new URL(a.href,o.href);return C(u.href,p.href)?e:void 0}function f1(e,o,a){let u=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(a.href,o.href);return C(u.href,p.href)?e:void 0}function eP(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let a=decodeURIComponent(o.hash.slice(1));if(!a.startsWith("/"))return;return p1(e,a)}function h1(e,o,a){if(qo(e)){let u=l1(e,o,a);if(!rr(u))return u}if(gc(e)){let u=d1(e,o,a);if(!rr(u))return u}if(mi(e)){let u=f1(e,o,a);if(!rr(u))return u}return eP(e,a)}function g1(e,o,a){return e.reduce((u,p)=>{let f=Yp(p,o,a);return!rr(f)?f:u},void 0)}function y1(e){return C(e,"const")||C(e,"enum")}function x1(e,o,a){return Ee(e).reduce((u,p)=>{if(y1(p))return u;let f=Yp(e[p],o,a);return!rr(f)?f:u},void 0)}function Yp(e,o,a){let u=Tn(e)&&qo(e)?new URL(e.$id,o.href):o;if(Tn(e)){let p=h1(e,u,a);if(!rr(p))return p}if(Le(e))return g1(e,u,a);if(lt(e))return x1(e,u,a);return}function I1(e,o,a){return Yf(e,new URL(o||".",Xp),a)}function E1(e,o,a,u){let p=Zp(e,o,a,u,!1);return Tn(p)&&qo(p)?p:void 0}function YA(e){return e.href.split("#")[0]}function b1(e,o){return me(e,o)?e[o]:void 0}function S1(e,o,a){return Yp(e,o,a)}function w1(e,o,a){let u=YA(a);if(C(u,YA(o)))return;if(!me(e,u))return;let p=e[u],f=Tn(p)&&qo(p)?new URL(p.$id,u):new URL(u);return C(a.hash,"")?p:Yp(p,f,a)}function T1(e,o,a,u,p){if(!u.$ref.startsWith("#"))return;if(me(e,"$schema"))return;let f=I1(o,a,p);if(rr(f)||C(f,a))return;return{target:p,base:f,root:o}}function R1(e,o,a){let u=e[o];if(!Tn(u))return;return{target:a,base:o,root:u}}function k1(e,o,a,u,p){let f=p?R1(e.context,u,a):void 0;if(!rr(f))return f;return T1(e.root,e.lexicalSchema,e.referenceBase,o,a)}function A1(e,o,a,u,p,f){if(qo(p))return;let h=E1(e,o,a,u);if(!h||f.includes(h))return;return{target:p,resource:h}}function Zp(e,o,a,u,p=!0){let f=new URL(a||".",Xp),h=p&&qo(o)?new URL(o.$id,f):f,g=new URL(u,h.href);return b1(e,u)??S1(o,h,g)??w1(e,h,g)}function P1(e,o,a,u,p,f){let h=new URL(a||".",Xp),g=p.$dynamicRef.startsWith("#")?u:o,I=Zp(e,g,a,p.$dynamicRef,!1);if(rr(I)){let k=new URL(p.$dynamicRef,h).hash;if(!k.startsWith("#/")&&k.startsWith("#")){let A=decodeURIComponent(k.slice(1));return f.find((v)=>C(v.$dynamicAnchor,A))??ZA(o,A)}return}if(!Tn(I)||!mi(I))return I;if(new URL(p.$dynamicRef,h).hash.startsWith("#/"))return I;return f.find((k)=>C(k.$dynamicAnchor,I.$dynamicAnchor))??I}function $1(e,o){let a=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:a,p=Zp(e.context,u,e.referenceBase,o.$ref,!1);if(!p||!Tn(p))return{schema:p};let f=new URL(o.$ref,e.referenceBase).href.split("#")[0],h=!C(f,e.resourceBase),g=k1(e,o,p,f,h),I=h?A1(e.context,e.root,e.referenceBase,f,p,e.ids):void 0;return{schema:p,retrievedResource:g,resolvedResource:I}}function C1(e,o){let a=Mc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Zp(e.context,a,e.lexicalBase,o.$recursiveRef,!1)}function v1(e,o){return P1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var Br=function(e,o,a,u){if(a==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?u:a==="a"?u.call(e):u?u.value:o.get(e)},$r,tl,iP,rh,el,tP,rP,nP,oP,eh,th,nh,oh,sP,aP;class Yi{constructor(e,o){$r.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return Br(this,$r,"m",rh).call(this,this.ids)}Push(e){if(!Tn(e))return;if(qo(e))Br(this,$r,"m",nh).call(this,e);if(gc(e))this.anchors.push(e);if(Mc(e))this.recursiveAnchors.push(e);if(mi(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!Tn(e))return;if(qo(e))Br(this,$r,"m",oh).call(this,e);if(gc(e))this.anchors.pop();if(Mc(e))this.recursiveAnchors.pop();if(mi(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Br(this,$r,"m",aP).call(this,e)}Ref(e){let o=$1(Br(this,$r,"m",tl).call(this),e);return Br(this,$r,"m",iP).call(this,o),o.schema}RecursiveRef(e){let o=C1(Br(this,$r,"m",tl).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=v1(Br(this,$r,"m",tl).call(this),e);if(o)this.pendingResource=!0;return o}}$r=new WeakSet,tl=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Br(this,$r,"m",rP).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Br(this,$r,"m",tP).call(this),resourceBase:Br(this,$r,"m",el).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},iP=function(o){if(!rr(o.schema))this.pendingResource=!0;if(!rr(o.resolvedResource))Br(this,$r,"m",sP).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!rr(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},rh=function(o){let a=this.retrievedFrames[this.retrievedFrames.length-1],u=a?new URL(a.base):new URL(Xp);return(a?o.slice(a.idDepth):o).reduce((f,h)=>new URL(h.$id,f),u).href},el=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return Br(this,$r,"m",rh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((a,u)=>new URL(u.$id,a),new URL(o.base)).href},tP=function(){if(this.retrievedFrames.length>0)return Br(this,$r,"m",el).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return Br(this,$r,"m",el).call(this)},rP=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(o)return this.ids.length>o.idDepth?this.ids[this.ids.length-1]:o.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},nP=function(o){o.forEach((a)=>Br(this,$r,"m",eh).call(this,a,!1))},oP=function(o){o.forEach((a)=>Br(this,$r,"m",th).call(this,a,!1))},eh=function e(o,a=!0){if(ui(o))return;if(Le(o))return Br(this,$r,"m",nP).call(this,o);if(!Tn(o))return;let u=o;if(!a&&qo(u))return;if(!a&&mi(u))this.dynamicAnchors.push(u);for(let p of Ee(u))Br(this,$r,"m",e).call(this,u[p],!1)},th=function e(o,a=!0){if(ui(o))return;if(Le(o))return Br(this,$r,"m",oP).call(this,o);if(!Tn(o))return;let u=o;if(!a&&qo(u))return;if(!a&&mi(u))this.dynamicAnchors.pop();for(let p of Ee(u))Br(this,$r,"m",e).call(this,u[p],!1)},nh=function(o){this.ids.push(o);let a=this.pendingResource;if(this.pendingResource=!1,a)this.resourceIds.push(o);Br(this,$r,"m",eh).call(this,o,!0)},oh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&C(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();Br(this,$r,"m",th).call(this,o,!0)},sP=function(o,a){Br(this,$r,"m",nh).call(this,a),this.resolvedResources.set(o,a)},aP=function(o){if(!this.resolvedResources.has(o))return;let a=this.resolvedResources.get(o);Br(this,$r,"m",oh).call(this,a),this.resolvedResources.delete(o)};function M1(e){let o=e.Functions().join(`;
|
|
23
|
-
`),a=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${a.join("; ")} }`}function O1(e,o){return Fy("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Kn,_,fu,da,e.External().variables)}function _1(e){let o=new Yi(e.Context(),e.Schema()),a=new Kn;return(u)=>Pt(o,a,e.Schema(),u)}function L1(e,o){return Dy()?O1(e,o):_1(e)}class uP{constructor(e,o,a){this.isAccelerated=e,this.code=o,this.check=a}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class cP{constructor(e,o,a,u,p,f){this.context=e,this.schema=o,this.external=a,this.functions=u,this.entry=p,this.useUnevaluated=f}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=M1(this),o=L1(this,e);return new uP(Dy(),e,o)}}function rl(...e){let[o,a]=Ln(e,{2:(I,E)=>[I,E],1:(I)=>[{},I]});pR(),QA();let u=new Yi(o,a),p=new Ef(mR(o,a)),f=gi(u,p,a,"value"),h=XA(),g=lR();return new cP(o,a,g,h,f,p.UseUnevaluated())}function nl(...e){let[o,a,u]=Ln(e,{3:(S,k,A)=>[S,k,A],2:(S,k)=>[{},S,k]}),p=new Yi(o,a),f=new Hn,h=dr(p,f,"#","",a,u),g=f.GetErrors(),I=Vy(),E=g.map((S)=>({...S,message:I(S)}));return[h,E]}function ih(...e){let[o,a,u]=Ln(e,{3:(h,g,I)=>[h,g,I],2:(h,g)=>[{},h,g]}),p=new Yi(o,a),f=new Kn;return Pt(p,f,a,u)}function mr(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return ih(o,a,u)}function Js(...e){let[o,a,u]=Ln(e,{3:(h,g,I)=>[h,g,I],2:(h,g)=>[{},h,g]}),[p,f]=nl(o,a,u);return f}class $a extends Error{constructor(e,o,a){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:a,value:o},writable:!1,configurable:!1,enumerable:!1})}}function mP(e,o,a){if(!Le(a))return a;return a.map((u)=>Rn(e,o.items,u))}function pP(e,o,a){return Rn({...e,...o.$defs},sn(o.$ref),a)}function D1(e,o){let a=me(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Go(e,o),p=qn(u);return Je(p)?gp(p,a):p}function lP(e,o,a){let u=D1(e,o);return Rn(e,u,a)}function ol(e){return me(e,"additionalProperties")?e.additionalProperties:void 0}function dP(e,o,a){if(!lt(a)||Le(a))return a;let u=ol(o);for(let p of Ee(a)){if(me(o.properties,p)){a[p]=Rn(e,o.properties[p],a[p]);continue}if(cn(u)&&C(u,!0)||Dr(u)&&mr(e,u,a[p])){a[p]=Rn(e,u,a[p]);continue}delete a[p]}return a}function fP(e,o,a){if(!lt(a))return a;let u=ol(o),[p,f]=[new RegExp(Sn(o)),hr(o)];for(let h of Ee(a)){if(p.test(h)){a[h]=Rn(e,f,a[h]);continue}if(cn(u)&&C(u,!0)||Dr(u)&&mr(e,u,a[h])){a[h]=Rn(e,u,a[h]);continue}delete a[h]}return a}function hP(e,o,a){return me(e,o.$ref)?Rn(e,e[o.$ref],a):a}function gP(e,o,a){if(!Le(a))return a;let u=Math.min(a.length,o.items.length);for(let p=0;p<u;p++)a[p]=Rn(e,o.items[p],a[p]);return sa(a.length,u)?a.slice(0,u):a}function Jr(e){return Fa(e)}function yP(e,o,a){for(let u of o.anyOf){let p=Rn(e,u,Jr(a));if(mr(e,u,p))return p}return a}function Rn(e,o,a){return Tt(o)?mP(e,o,a):cr(o)?pP(e,o,a):ze(o)?lP(e,o,a):Je(o)?dP(e,o,a):nr(o)?fP(e,o,a):zt(o)?hP(e,o,a):ft(o)?gP(e,o,a):ye(o)?yP(e,o,a):a}function F1(e,o){for(let a of Ee(e)){if(me(o,a))continue;o[a]=e[a]}return o}function j1(e){let o={};for(let a of Ee(e))o[a]=Bc(e[a]);return o}function U1(e){return ah(rR(e))}function ah(e){return e.map((o)=>Bc(o))}function Bc(e){let o=Tt(e)?H(Bc(e.items),ja(e)):ze(e)?jn(ah(e.allOf)):ye(e)?y(U1(e.anyOf)):Je(e)?l(j1(e.properties)):nr(e)?Qe(Oi(e),Bc(hr(e))):ft(e)?zr(ah(e.items)):e;return F1(e,o)}function hu(e){return Bc(e)}function zo(...e){let[o,a,u]=Ln(e,{3:(f,h,g)=>[f,h,g],2:(f,h)=>[{},f,h]}),p=ss().unionPrioritySort?hu(a):a;return Rn(o,p,u)}function vo(e){return lt(e)&&me(e,"value")}function je(e){return{value:e}}function Mr(){return}function B1(e){return Le(e)?je(e):je([e])}function G1(e){return C(e,!0)?je(BigInt(1)):je(BigInt(0))}var K1=/^-?(0|[1-9]\d*)n$/,H1=/^-?(0|[1-9]\d*)\.\d+$/,W1=/^-?(0|[1-9]\d*)$/;function z1(e){return K1.test(e)}function V1(e){return H1.test(e)}function J1(e){return W1.test(e)}function Q1(e){let o=e.toLowerCase();return z1(e)?je(BigInt(e.slice(0,e.length-1))):V1(e)?je(BigInt(e.split(".")[0])):J1(e)?je(BigInt(e)):C(o,"false")?je(BigInt(0)):C(o,"true")?je(BigInt(1)):Mr()}function sl(e){return Kr(e)?je(e):cn(e)?G1(e):Ut(e)?je(BigInt(Math.trunc(e))):Mo(e)?je(BigInt(0)):gt(e)?Q1(e):rr(e)?je(BigInt(0)):Mr()}function X1(e){return C(e,BigInt(0))?je(!1):C(e,BigInt(1))?je(!0):Mr()}function Y1(e){return C(e,0)?je(!1):C(e,1)?je(!0):Mr()}function Z1(e){return C(e.toLowerCase(),"false")?je(!1):C(e.toLowerCase(),"true")?je(!0):C(e,"0")?je(!1):C(e,"1")?je(!0):Mr()}function xP(e){return Kr(e)?X1(e):cn(e)?je(e):Ut(e)?Y1(e):Mo(e)?je(!1):gt(e)?Z1(e):rr(e)?je(!1):Mr()}function ej(e){return C(e,BigInt(0))?je(null):Mr()}function tj(e){return C(e,!1)?je(null):Mr()}function rj(e){return C(e,0)?je(null):Mr()}function nj(e){let o=e.toLowerCase();return C(o,"undefined")||C(o,"null")||C(e,"")||C(e,"0")?je(null):Mr()}function oj(e){return Kr(e)?ej(e):cn(e)?tj(e):Ut(e)?rj(e):Mo(e)?je(null):gt(e)?nj(e):rr(e)?je(null):Mr()}var IP=BigInt(Number.MAX_SAFE_INTEGER),EP=BigInt(Number.MIN_SAFE_INTEGER);function sj(e){return e<=IP&&e>=EP?je(Number(e)):Mr()}function ij(e){return je(e?1:0)}function aj(e){let o=+e;if(Ut(o))return je(o);let a=e.toLowerCase();if(C(a,"false"))return je(0);if(C(a,"true"))return je(1);let u=sl(e);if(vo(u))return u.value<=IP&&u.value>=EP?je(Number(u.value)):Mr();return Mr()}function uh(e){return Kr(e)?sj(e):cn(e)?ij(e):Ut(e)?je(e):Mo(e)?je(0):gt(e)?aj(e):rr(e)?je(0):Mr()}function bP(e){return Kr(e)?je(e.toString()):cn(e)?je(e.toString()):Ut(e)?je(e.toString()):Mo(e)?je("null"):gt(e)?je(e):rr(e)?je(""):Mr()}function uj(e){return C(e,BigInt(0))?je(void 0):Mr()}function cj(e){return C(e,!1)?je(void 0):Mr()}function mj(e){return C(e,0)?je(void 0):Mr()}function pj(e){let o=e.toLowerCase();return C(o,"undefined")||C(o,"null")||C(e,"")||C(e,"0")?je(void 0):Mr()}function SP(e){return Kr(e)?uj(e):cn(e)?cj(e):Ut(e)?mj(e):Mo(e)?je(void 0):gt(e)?pj(e):rr(e)?je(e):Mr()}function wP(e,o,a){return B1(a).value.map((p)=>Qr(e,o.items,p))}function TP(e,o,a){let u=sl(a);return vo(u)?u.value:a}function RP(e,o,a){let u=xP(a);return vo(u)?u.value:a}function kP(e,o,a){return Qr({...e,...o.$defs},sn(o.$ref),a)}function AP(e,o,a){return Qr(e,qn(o),a)}function PP(e,o,a){let u=uh(a);return vo(u)?Math.trunc(u.value):a}function $P(e,o,a){let u=Go(e,o),p=qn(u);return Qr(e,p,a)}function lj(e,o,a){let u=sl(a);return vo(u)&&C(o.const,u.value)?u.value:a}function dj(e,o,a){let u=xP(a);return vo(u)&&C(o.const,u.value)?u.value:a}function fj(e,o,a){let u=uh(a);return vo(u)&&C(o.const,u.value)?u.value:a}function hj(e,o,a){let u=bP(a);return vo(u)&&C(o.const,u.value)?u.value:a}function CP(e,o,a){if(C(o.const,a))return a;return ox(o)?lj(e,o,a):sx(o)?dj(e,o,a):Em(o)?fj(e,o,a):bm(o)?hj(e,o,a):Wr()}function vP(e,o,a){let u=oj(a);return vo(u)?u.value:a}function MP(e,o,a){let u=uh(a);return vo(u)?u.value:a}function il(e,o,a,u){let p=Ee(u);for(let[f,h]of o)for(let g of p)if(!f.test(g))u[g]=Qr(e,a,u[g]);return u}function Gc(e,o,a){return an(e)&&rr(a[o])}function gj(e,o,a){let u=rd(o.properties),p=Ee(a);for(let[f,h]of u)for(let g of p){if(!f.test(g)||Gc(h,g,a))continue;a[g]=Qr(e,h,a[g])}return me(o,"additionalProperties")&<(o.additionalProperties)?il(e,u,o.additionalProperties,a):a}function OP(e,o,a){return rs(a)?gj(e,o,a):a}function yj(e,o,a){let u=rd(o.patternProperties),p=Ee(a);for(let[f,h]of u)for(let g of p)if(f.test(g))a[g]=Qr(e,h,a[g]);return me(o,"additionalProperties")&<(o.additionalProperties)?il(e,u,o.additionalProperties,a):a}function _P(e,o,a){return rs(a)?yj(e,o,a):a}function LP(e,o,a){return me(e,o.$ref)?Qr(e,e[o.$ref],a):a}function NP(e,o,a){let u=bP(a);return vo(u)?u.value:a}function qP(e,o,a){return Qr(e,qn(o),a)}function DP(e,o,a){if(!Le(a))return a;for(let u=0;u<Math.min(o.items.length,a.length);u++)a[u]=Qr(e,o.items[u],a[u]);return a}function FP(e,o,a){let u=SP(a);return vo(u)?u.value:a}function jP(e,o,a){if(o.anyOf.some((h)=>mr(e,h,a)))return a;let f=o.anyOf.map((h)=>Qr(e,h,Jr(a))).find((h)=>mr(e,o,h));return rr(f)?a:f}function UP(e,o,a){let u=SP(a);return vo(u)?void 0:a}function Qr(e,o,a){return Tt(o)?wP(e,o,a):Po(o)?TP(e,o,a):yo(o)?RP(e,o,a):cr(o)?kP(e,o,a):rn(o)?AP(e,o,a):In(o)?PP(e,o,a):ze(o)?$P(e,o,a):yt(o)?CP(e,o,a):Bs(o)?vP(e,o,a):Lr(o)?MP(e,o,a):Je(o)?OP(e,o,a):nr(o)?_P(e,o,a):zt(o)?LP(e,o,a):nn(o)?NP(e,o,a):lr(o)?qP(e,o,a):ft(o)?DP(e,o,a):ys(o)?FP(e,o,a):ye(o)?jP(e,o,a):$o(o)?UP(e,o,a):a}function vs(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return Qr(o,a,u)}function BP(e,o,a){if(!Le(a))return a;for(let u=0;u<a.length;u++)a[u]=kn(e,o.items,a[u]);return a}function GP(e,o,a){return kn({...e,...o.$defs},sn(o.$ref),a)}function KP(e,o){if(!rr(o))return o;return _s(e.default)?e.default():Jr(e.default)}function HP(e,o,a){let u=Go(e,o),p=qn(u);return kn(e,p,a)}function WP(e,o,a){if(!lt(a))return a;let u=Ee(o.properties);for(let p of u){let f=kn(e,o.properties[p],a[p]);if(rr(f)&&(an(o.properties[p])||!me(o.properties[p],"default")))continue;a[p]=f}if(!Ho(o)||cn(o.additionalProperties))return a;for(let p of Ee(a)){if(u.includes(p))continue;a[p]=kn(e,o.additionalProperties,a[p])}return a}function zP(e,o,a){if(!lt(a))return a;let[u,p]=[new RegExp(Sn(o)),hr(o)];for(let f of Ee(a)){if(!(u.test(f)&&No(p)))continue;a[f]=kn(e,p,a[f])}if(!Ho(o))return a;for(let f of Ee(a)){if(u.test(f))continue;a[f]=kn(e,o.additionalProperties,a[f])}return a}function VP(e,o,a){return me(e,o.$ref)?kn(e,e[o.$ref],a):a}function JP(e,o,a){if(!Le(a))return a;let[u,p]=[o.items,Math.max(o.items.length,a.length)];for(let f=0;f<p;f++)if(f<u.length)a[f]=kn(e,u[f],a[f]);return a}function QP(e,o,a){for(let u of o.anyOf){let p=kn(e,u,Jr(a));if(mr(e,u,p))return p}return a}function kn(e,o,a){let u=No(o)?KP(o,a):a;return Tt(o)?BP(e,o,u):cr(o)?GP(e,o,u):ze(o)?HP(e,o,u):Je(o)?WP(e,o,u):nr(o)?zP(e,o,u):zt(o)?VP(e,o,u):ft(o)?JP(e,o,u):ye(o)?QP(e,o,u):u}function yi(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return kn(o,a,u)}function gu(e){return(...o)=>{let[a,u,p]=Ln(o,{3:(f,h,g)=>[f,h,g],2:(f,h)=>[{},f,h]});return e.reduce((f,h)=>h(a,u,f),p)}}function xj(e,o,a){return o["~codec"].decode(a)}function Ij(e,o,a){return o["~codec"].encode(a)}function Or(e,o,a,u){if(!Qn(a))return u;return C(e,"Decode")?xj(o,a,u):Ij(o,a,u)}function Ej(e,o,a,u){if(!Le(u))return u;for(let p=0;p<u.length;p++)u[p]=qr(e,o,a.items,u[p]);return Or(e,o,a,u)}function bj(e,o,a,u){let p=Or(e,o,a,u);if(!Le(p))return p;for(let f=0;f<p.length;f++)p[f]=qr(e,o,a.items,p[f]);return p}function XP(e,o,a,u){return C(e,"Decode")?Ej(e,o,a,u):bj(e,o,a,u)}function YP(e,o,a,u){return u=qr(e,{...o,...a.$defs},sn(a.$ref),u),Or(e,o,a,u)}function ZP(e){return e.reduce((o,a)=>({...o,...a}),{})}function e$(e,o){for(let a of o)if(!Da(e,a))return a;return e}function Sj(e,o,a,u){if(C(a.allOf.length,0))return Or(e,o,a,u);let p=a.allOf.map((g)=>qr(e,o,g,zo(g,Jr(u)))),h=p.every((g)=>lt(g))?ZP(p):e$(u,p);return Or(e,o,a,h)}function wj(e,o,a,u){if(C(a.allOf.length,0))return Or(e,o,a,u);let p=Or(e,o,a,u),f=a.allOf.map((g)=>qr(e,o,g,zo(g,Jr(p))));if(f.every((g)=>lt(g)))return ZP(f);return e$(p,f)}function t$(e,o,a,u){return C(e,"Decode")?Sj(e,o,a,u):wj(e,o,a,u)}function Tj(e,o,a,u){if(!rs(u))return u;for(let p of Ee(a.properties)){if(!me(u,p)||Gc(a.properties[p],p,u))continue;u[p]=qr(e,o,a.properties[p],u[p])}return Or(e,o,a,u)}function Rj(e,o,a,u){let p=Or(e,o,a,u);if(!rs(p))return p;for(let f of Ee(a.properties)){if(!me(p,f)||Gc(a.properties[f],f,p))continue;p[f]=qr(e,o,a.properties[f],p[f])}return p}function r$(e,o,a,u){return C(e,"Decode")?Tj(e,o,a,u):Rj(e,o,a,u)}function kj(e,o,a,u){if(!rs(u))return u;let p=new RegExp(Sn(a));for(let f of Ee(u)){if(!p.test(f))continue;u[f]=qr(e,o,hr(a),u[f])}return Or(e,o,a,u)}function Aj(e,o,a,u){let p=Or(e,o,a,u);if(!rs(p))return p;let f=new RegExp(Sn(a));for(let h of Ee(p)){if(!f.test(h))continue;p[h]=qr(e,o,hr(a),p[h])}return p}function n$(e,o,a,u){return C(e,"Decode")?kj(e,o,a,u):Aj(e,o,a,u)}function o$(e,o,a,u){return me(o,a.$ref)?qr(e,o,o[a.$ref],u):u}function s$(e,o,a,u){return C(e,"Decode")?Or(e,o,a,o$(e,o,a,u)):o$(e,o,a,Or(e,o,a,u))}function Pj(e,o,a,u){if(!Le(u))return u;for(let p=0;p<Math.min(a.items.length,u.length);p++)u[p]=qr(e,o,a.items[p],u[p]);return Or(e,o,a,u)}function $j(e,o,a,u){let p=Or(e,o,a,u);if(!Le(p))return u;for(let f=0;f<Math.min(a.items.length,p.length);f++)p[f]=qr(e,o,a.items[f],p[f]);return p}function i$(e,o,a,u){return C(e,"Decode")?Pj(e,o,a,u):$j(e,o,a,u)}function Cj(e,o,a,u){for(let p of a.anyOf){if(!mr(o,p,u))continue;let f=qr(e,o,p,u);return Or(e,o,a,f)}return u}function vj(e,o,a,u){let p=Or(e,o,a,u);for(let f of a.anyOf){let h=qr(e,o,f,Jr(p));if(!mr(o,f,h))continue;return h}return p}function a$(e,o,a,u){return C(e,"Decode")?Cj(e,o,a,u):vj(e,o,a,u)}function qr(e,o,a,u){return Tt(a)?XP(e,o,a,u):cr(a)?YP(e,o,a,u):ze(a)?t$(e,o,a,u):Je(a)?r$(e,o,a,u):nr(a)?n$(e,o,a,u):zt(a)?s$(e,o,a,u):ft(a)?i$(e,o,a,u):ye(a)?a$(e,o,a,u):Or(e,o,a,u)}class u$ extends $a{constructor(e,o){super("Decode",e,o)}}function Mj(e,o,a){if(!mr(e,o,a))throw new u$(a,Js(e,o,a));return a}function Oj(e,o,a){let u=ss().unionPrioritySort?hu(o):o;return qr("Decode",e,u,a)}var _j=gu([(e,o,a)=>Jr(a),(e,o,a)=>yi(e,o,a),(e,o,a)=>vs(e,o,a),(e,o,a)=>zo(e,o,a),(e,o,a)=>Mj(e,o,a),(e,o,a)=>Oj(e,o,a)]);function ch(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return _j(o,a,u)}class c$ extends $a{constructor(e,o){super("Encode",e,o)}}function Lj(e,o,a){if(!mr(e,o,a))throw new c$(a,Js(e,o,a));return a}function Nj(e,o,a){let u=ss().unionPrioritySort?hu(o):o;return qr("Encode",e,u,a)}var qj=gu([(e,o,a)=>Jr(a),(e,o,a)=>Nj(e,o,a),(e,o,a)=>yi(e,o,a),(e,o,a)=>vs(e,o,a),(e,o,a)=>zo(e,o,a),(e,o,a)=>Lj(e,o,a)]);function mh(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return qj(o,a,u)}function Dj(e,o){return Qn(o)||Zi(e,o.items)}function Fj(e,o){return Qn(o)||m$({...e,...o.$defs},sn(o.$ref))}function jj(e,o){return Qn(o)||o.allOf.some((a)=>Zi(e,a))}function Uj(e,o){return Qn(o)||Ee(o.properties).some((a)=>Zi(e,o.properties[a]))}function Bj(e,o){return Qn(o)||Zi(e,hr(o))}function m$(e,o){if(ph.has(o.$ref))return!1;return ph.add(o.$ref),Qn(o)||me(e,o.$ref)&&Zi(e,e[o.$ref])}function Gj(e,o){return Qn(o)||o.items.some((a)=>Zi(e,a))}function Kj(e,o){return Qn(o)||o.anyOf.some((a)=>Zi(e,a))}function Zi(e,o){return Tt(o)?Dj(e,o):cr(o)?Fj(e,o):ze(o)?jj(e,o):Je(o)?Uj(e,o):nr(o)?Bj(e,o):zt(o)?m$(e,o):ft(o)?Gj(e,o):ye(o)?Kj(e,o):Qn(o)}var ph=new Set;function lh(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return ph.clear(),Zi(o,a)}class Ms extends Error{constructor(e,o){super(o);this.type=e}}function p$(e,o){return _s(o.default)?o.default(o):lt(o.default)?Jr(o.default):o.default}function l$(e,o){if(Bi(o)&&!No(o))throw new Ms(o,"Arrays with uniqueItems constraints must specify a default annotation");let a=Ui(o)?o.minItems:0;return Array.from({length:a},()=>Xr(e,o.items))}function d$(e,o){return xs(o)?BigInt(o.exclusiveMinimum)+BigInt(1):Is(o)?BigInt(o.minimum):BigInt(0)}function f$(e,o){return!1}function h$(e,o){let a=Xr(e,o.instanceType);return class{constructor(){Object.assign(this,a)}}}function g$(e,o){return Xr({...e,...o.$defs},sn(o.$ref))}function y$(e,o){return Xr(e,qn(o))}function x$(e,o){let a=Xr(e,o.returnType);return()=>a}function I$(e,o){return xs(o)&&Ut(o.exclusiveMinimum)?o.exclusiveMinimum+1:Is(o)?o.minimum:0}function E$(e,o){let a=Go(e,o),u=qn(a);return Xr(e,u)}function b$(e,o){return o.const}function S$(e,o){throw new Ms(o,"Cannot create TNever types")}function w$(e,o){return null}function T$(e,o){return xs(o)&&Ut(o.exclusiveMinimum)?o.exclusiveMinimum+1:Is(o)?o.minimum:0}function R$(e,o){return(rr(o.required)?[]:o.required).reduce((u,p)=>({...u,[p]:Xr(e,o.properties[p])}),{})}function k$(e,o){if(Aa(o)&&!No(o))throw new Ms(o,"Record with the minProperties constraint must have a default annotation");return{}}function A$(e,o){return me(e,o.$ref)?Xr(e,e[o.$ref]):(()=>{throw new Ms(o,"Unable to deref Ref")})()}function P$(e,o){if((Pa(o)||Ra(o))&&!No(o))throw Error("Strings with format or pattern constraints must specify default");let u=ka(o)?o.minLength:0;return"".padEnd(u)}function $$(e,o){return Symbol()}function C$(e,o){let a=Bu(o.pattern);if(nn(a))throw new Ms(o,"Unable to create TemplateLiteral due to infinite type expansion");return Xr(e,a)}function v$(e,o){return Array.from({length:o.minItems},(a,u)=>Xr(e,o.items[u]))}function M$(e,o){return}function O$(e,o){if(C(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Xr(e,o.anyOf[0])}function _$(e,o){return}function Xr(e,o){return No(o)?p$(e,o):Tt(o)?l$(e,o):Po(o)?d$(e,o):yo(o)?f$(e,o):Yr(o)?h$(e,o):cr(o)?g$(e,o):rn(o)?y$(e,o):Zr(o)?x$(e,o):In(o)?I$(e,o):ze(o)?E$(e,o):yt(o)?b$(e,o):Ao(o)?S$(e,o):Bs(o)?w$(e,o):Lr(o)?T$(e,o):Je(o)?R$(e,o):nr(o)?k$(e,o):zt(o)?A$(e,o):nn(o)?P$(e,o):Gs(o)?$$(e,o):lr(o)?C$(e,o):ft(o)?v$(e,o):ys(o)?M$(e,o):ye(o)?O$(e,o):$o(o)?_$(e,o):void 0}function Qs(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Xr(o,a)}class al extends $a{constructor(e,o){super("Parse",e,o)}}function Hj(e,o,a){if(!mr(e,o,a))throw new al(a,Js(e,o,a));return a}var L$=gu([(e,o,a)=>Jr(a),(e,o,a)=>yi(e,o,a),(e,o,a)=>vs(e,o,a),(e,o,a)=>zo(e,o,a),(e,o,a)=>Hj(e,o,a)]);var zj=l({type:i("insert"),path:s(),value:Q()}),Vj=Object({type:i("update"),path:s(),value:Q()}),Jj=l({type:i("delete"),path:s()}),UMe=y([zj,Vj,Jj]);class ul{constructor(e,o){this.hasCodec=lh(e,o),this.buildResult=rl(e,o),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(ss().correctiveParse)return L$(this.Context(),this.Type(),e);throw new al(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Js(this.Context(),this.Type(),e)}Clean(e){return zo(this.Context(),this.Type(),e)}Convert(e){return vs(this.Context(),this.Type(),e)}Create(){return Qs(this.Context(),this.Type())}Default(e){return yi(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?ch(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?mh(this.Context(),this.Type(),e):this.Parse(e)}}function fh(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return new ul(o,a)}var q$=new WeakMap,Yj=Symbol.for("TypeBox.Kind");function Zj(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function eU(e,o){switch(o){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function hh(e){try{return F$(e)}catch{return}}function tU(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isFinite(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isInteger(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function rU(e,o){let a=o.properties,u=new Set(a?Object.keys(a):[]);if(a)for(let[p,f]of Object.entries(a)){if(!(p in e))continue;e[p]=va(e[p],f)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[p,f]of Object.entries(e)){if(u.has(p))continue;e[p]=va(f,o.additionalProperties)}}function nU(e,o){if(Array.isArray(o.items)){for(let a=0;a<e.length;a++){let u=o.items[a];if(!u)continue;e[a]=va(e[a],u)}return}if(o.items&&typeof o.items==="object")for(let a=0;a<e.length;a++)e[a]=va(e[a],o.items)}function D$(e,o){for(let a of o)if(hh(a)?.Check(e))return e;for(let a of o){let u=structuredClone(e),p=va(u,a);if(hh(a)?.Check(p))return p}return e}function va(e,o){let a=e;if(Array.isArray(o.allOf))for(let f of o.allOf)a=va(a,f);if(Array.isArray(o.anyOf))a=D$(a,o.anyOf);if(Array.isArray(o.oneOf))a=D$(a,o.oneOf);let u=Zj(o),p=u.length>1&&u.some((f)=>eU(a,f));if(u.length>0&&!p)for(let f of u){let h=tU(a,f);if(h!==a){a=h;break}}if(u.includes("object")&&typeof a==="object"&&a!==null&&!Array.isArray(a))rU(a,o);if(u.includes("array")&&Array.isArray(a))nU(a,o);return a}function cl(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let p=0;p<e.length;p++){let f=o.items[p];if(f)cl(e[p],f)}else if(o.items)for(let p of e)cl(p,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let a=e,u=new Set(o.required??[]);for(let[p,f]of Object.entries(o.properties)){if(!(p in a))continue;if(a[p]===null&&!u.has(p)&&typeof f.$ref!=="string"&&hh(f)?.Check(null)===!1)delete a[p];else cl(a[p],f)}}function F$(e){let o=e,a=q$.get(o);if(a)return a;let u=fh(e);return q$.set(o,u),u}function oU(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function sU(e,o){let a=e.find((u)=>u.name===o.name);if(!a)throw Error(`Tool "${o.name}" not found`);return yu(a,o)}function yu(e,o){let a=structuredClone(o.arguments);cl(a,e.parameters),vs(e.parameters,a);let u=F$(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Yj)){let h=va(a,e.parameters);if(h!==a)if(typeof a==="object"&&a!==null&&typeof h==="object"&&h!==null){for(let g of Object.keys(a))delete a[g];Object.assign(a,h)}else return u.Check(h)?h:a}if(u.Check(a))return a;let p=u.Errors(a).map((h)=>` - ${oU(h)}: ${h.message}`).join(`
|
|
24
|
-
`)||"Unknown validation error",f=`Validation failed for tool "${o.name}":
|
|
25
|
-
${p}
|
|
26
|
-
|
|
27
|
-
Received arguments:
|
|
28
|
-
${JSON.stringify(o.arguments,null,2)}`;throw Error(f)}var j$;function Kc(){if(!j$)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return j$}async function U$(e,o,a,u,p,f){let h=K$(o,e),g=[...h],I={...o,messages:[...o.messages,...h]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let E of h)await u({type:"message_start",message:E}),await u({type:"message_end",message:E});return await G$(I,g,a,p,u,f??Kc()),g}async function B$(e,o,a,u,p){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let f=[],h={...e};return await a({type:"agent_start"}),await a({type:"turn_start"}),await G$(h,f,o,u,a,p??Kc()),f}async function G$(e,o,a,u,p,f){let h=e,g=a,I,E=!1,S=await g.getSteeringMessages?.()||[];while(!0){let k=!0;while(k||S.length>0){let P=[];if(I){let j=await g.prepareNextTurn?.(I);if(j)h=j.context??h,P=j.messages??[],g={...g,model:j.model??g.model,reasoning:j.thinkingLevel===void 0?g.reasoning:j.thinkingLevel==="off"?void 0:j.thinkingLevel};if(S.length===0)S=await g.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let j of K$(h,[...P,...S]))await p({type:"message_start",message:j}),await p({type:"message_end",message:j}),h.messages.push(j),o.push(j);S=[];let v=await g.prepareRequest?.({context:h,model:g.model,thinkingLevel:g.reasoning??"off"},u);if(v)h=v.context??h,g={...g,model:v.model??g.model,reasoning:v.thinkingLevel===void 0?g.reasoning:v.thinkingLevel==="off"?void 0:v.thinkingLevel};let M=await aU(h,g,u,p,f);if(o.push(M),M.stopReason==="error"||M.stopReason==="aborted"){I={message:M,toolResults:[],context:h,newMessages:o},await g.finishTurn?.(I,u),await p({type:"turn_end",message:M,toolResults:[]}),await p({type:"agent_end",messages:o});return}let J=M.content.filter((j)=>j.type==="toolCall"),O=[];if(k=!1,J.length>0){let j=M.stopReason==="length"?await uU(J,p):await cU(h,M,g,u,p);O.push(...j.messages),k=!j.terminate;for(let te of O)h.messages.push(te),o.push(te)}I={message:M,toolResults:O,context:h,newMessages:o};let V=await g.finishTurn?.(I,u);if(await p({type:"turn_end",message:M,toolResults:O}),V?.action==="end"){await p({type:"agent_end",messages:o});return}if(E=V?.action==="continue",S=await g.getSteeringMessages?.()||[],k||S.length>0)E=!1}let A=await g.getFollowUpMessages?.()||[];if(A.length>0){E=!1,S=A;continue}if(E){E=!1;continue}break}await p({type:"agent_end",messages:o})}function K$(e,o){let a=-1;for(let S=o.length-1;S>=0;S--)if(o[S].role==="system"){a=S;break}let u=o[a],p=u?o.map((S,k)=>k===a?gh(u,iU):S):o,f=ci(ce([...e.messages,...p]),(e.tools??[]).map(pt)),h=f.toolsAdded.length===0&&f.toolsRemoved.length===0;if(u){if(h&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return p.map((S,k)=>k===a?gh(u,f):S)}if(h)return o;let g=gh({role:"system",content:"",timestamp:Date.now()},f),I=o.findIndex((S)=>S.role!=="system"),E=I===-1?o.length:I;return[...o.slice(0,E),g,...o.slice(E)]}var iU={toolsAdded:[],toolsRemoved:[]};function gh(e,{toolsAdded:o,toolsRemoved:a}){let{toolsAdded:u,toolsRemoved:p,...f}=e;return{...f,...o.length>0?{toolsAdded:o}:{},...a.length>0?{toolsRemoved:a}:{}}}async function aU(e,o,a,u,p){let f=e.messages;if(o.transformContext)f=await o.transformContext(f,a);let h=await o.convertToLlm(f),g=At({messages:h}),I=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,E=await p(o.model,g,{...o,apiKey:I,signal:a}),S=async()=>Object.assign(await E.result(),{thinkingLevel:o.reasoning??"off"}),k=null,A=!1;for await(let v of E)switch(v.type){case"start":k=v.partial,e.messages.push(k),A=!0,await u({type:"message_start",message:{...k}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(k)k=v.partial,e.messages[e.messages.length-1]=k,await u({type:"message_update",assistantMessageEvent:v,message:{...k}});break;case"done":case"error":{let M=await S();if(A)e.messages[e.messages.length-1]=M;else e.messages.push(M);if(!A)await u({type:"message_start",message:{...M}});return await u({type:"message_end",message:M}),M}}let P=await S();if(A)e.messages[e.messages.length-1]=P;else e.messages.push(P),await u({type:"message_start",message:{...P}});return await u({type:"message_end",message:P}),P}async function uU(e,o){let a=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let p={toolCall:u,result:Ii(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Hc(p,o);let f=yh(p);await xh(f,o),a.push(f)}return{messages:a,terminate:!1}}async function cU(e,o,a,u,p){let f=o.content.filter((g)=>g.type==="toolCall"),h=f.some((g)=>e.tools?.find((I)=>I.name===g.name)?.executionMode==="sequential");if(a.toolExecution==="sequential"||h)return mU(e,o,f,a,u,p);return pU(e,o,f,a,u,p)}async function mU(e,o,a,u,p,f){let h=[],g=[];for(let I of a){await f({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let E=await W$(e,o,I,u,p),S;if(E.kind==="immediate")S={toolCall:I,result:E.result,isError:E.isError};else{let A=await V$(E,p,z$(I,f));S=await J$(e,o,E,A,u,p)}await Hc(S,f);let k=yh(S);if(await xh(k,f),h.push(S),g.push(k),p?.aborted)break}return{messages:g,terminate:H$(h)}}async function pU(e,o,a,u,p,f){let h=[];for(let E of a){await f({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await W$(e,o,E,u,p);if(S.kind==="immediate"){let k={toolCall:E,result:S.result,isError:S.isError};if(await Hc(k,f),h.push(k),p?.aborted)break;continue}if(h.push(async()=>{if(p?.aborted){let P={toolCall:E,result:Ii("Operation aborted"),isError:!0};return await Hc(P,f),P}let k=await V$(S,p,z$(E,f)),A=await J$(e,o,S,k,u,p);return await Hc(A,f),A}),p?.aborted)break}let g=await Promise.all(h.map((E)=>typeof E==="function"?E():Promise.resolve(E))),I=[];for(let E of g){let S=yh(E);await xh(S,f),I.push(S)}return{messages:I,terminate:H$(g)}}function H$(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function lU(e,o){if(!e.prepareArguments)return o;let a=e.prepareArguments(o.arguments);if(a===o.arguments)return o;return{...o,arguments:a}}async function W$(e,o,a,u,p,f=e.tools??[]){let h=f.find((g)=>g.name===a.name);if(!h)return{kind:"immediate",result:Ii(`Tool ${a.name} not found`),isError:!0};try{let g=lU(h,a),I=yu(h,g);if(u.beforeToolCall){let E=await u.beforeToolCall({assistantMessage:o,toolCall:a,args:I,context:e},p);if(p?.aborted)return{kind:"immediate",result:Ii("Operation aborted"),isError:!0};if(E?.block){let S=Ii(E.reason||"Tool execution was blocked");if(E.terminate===!0)S.terminate=!0;return{kind:"immediate",result:S,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Ii("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:a,tool:h,args:I}}catch(g){return{kind:"immediate",result:Ii(g instanceof Error?g.message:String(g)),isError:!0}}}function z$(e,o){return(a)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:a})}async function V$(e,o,a){let u=[],p=!0,f=performance.now(),h=()=>Math.round(performance.now()-f);try{let g=await e.tool.execute(e.toolCall.id,e.args,o,(E)=>{if(!p)return;u.push(Promise.resolve(a(E)))}),I=h();return p=!1,await Promise.all(u),{result:g,isError:g.isError===!0,durationMs:I}}catch(g){let I=h();return p=!1,await Promise.all(u),{result:Ii(g instanceof Error?g.message:String(g)),isError:!0,durationMs:I}}finally{p=!1}}async function J$(e,o,a,u,p,f){let{result:h,isError:g}=u;if(p.afterToolCall)try{let I=await p.afterToolCall({assistantMessage:o,toolCall:a.toolCall,args:a.args,result:h,isError:g,context:e},f);if(I){let E=I.structuredContent??(I.content?void 0:h.structuredContent);if(h={...h,content:I.content??h.content,details:I.details??h.details,usage:I.usage??h.usage,terminate:I.terminate??h.terminate},E===void 0)delete h.structuredContent;else h.structuredContent=E;g=I.isError??g}}catch(I){h=Ii(I instanceof Error?I.message:String(I)),g=!0}return{toolCall:a.toolCall,result:h,isError:g,durationMs:u.durationMs}}function Ii(e){return{content:[{type:"text",text:e}],details:{}}}async function Hc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function yh(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs},timestamp:Date.now()}}async function xh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function dU(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var fU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},hU={id:"unknown",name:"unknown",api:"unknown",provider:"unknown",baseUrl:"",reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function gU(e){let o=e?.tools?.slice()??[],a=e?.messages?.slice()??[],u=mo(e?.systemPrompt,o.map(pt));if(a[0]?.role!=="system"&&u)a.unshift(u);return{get systemPrompt(){return li(a)},model:e?.model??hU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(p){o=p.slice()},get messages(){return a},set messages(p){a=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Ih{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class Eh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let o=e??{};this._state=gU(o.initialState),this.convertToLlm=o.convertToLlm??dU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Kc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new Ih(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Ih(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=An(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let a=this.normalizePromptInput(e,o);await this.runPromptMessages(a)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let a=this.followUpQueue.drain();if(a.length>0){await this.runPromptMessages(a);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let a=[{type:"text",text:e}];if(o&&o.length>0)a.push(...o);return[{role:"user",content:a,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(a)=>{await U$(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),a,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await B$(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(a)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(a,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,a=()=>{},u=new Promise((p)=>{a=p});this.activeRun={promise:u,resolve:a,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(p){await this.handleRunFailure(p,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let a={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:fU,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:a}),await this.processEvents({type:"message_end",message:a}),await this.processEvents({type:"turn_end",message:a,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[a]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let a=new Set(this._state.pendingToolCalls);a.add(e.toolCallId),this._state.pendingToolCalls=a;break}case"tool_execution_end":{let a=new Set(this._state.pendingToolCalls);a.delete(e.toolCallId),this._state.pendingToolCalls=a;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let a of this.listeners)await a(e,o)}}var ml=Symbol("basalt.rebind-fetch");function ve(e,...o){return Object.assign(e,{aliases:o})}function Ma(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function yU(e){let o=[],a="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(a)o.push(a);a="";continue}if(u>="A"&&u<="Z"&&a&&!/[A-Z]$/.test(a))o.push(a),a="";a+=u}if(a)o.push(a);return o}function Q$(e,o){if(e.some((v)=>v.name===o))return o;let a=e.map((v)=>v.name),u=(v)=>a.filter((M)=>Ma(M)===v),p=u(Ma(o));if(p.length===1&&p[0])return p[0];if(p.length>1)return o;let f=o.split(/[.:/]/).pop()??o,h=f===o?[]:u(Ma(f));if(h.length===1&&h[0])return h[0];let g=new Map;for(let v of e)for(let M of v.aliases??[]){let J=Ma(M);g.set(J,(g.get(J)??new Set).add(v.name))}let I=(v)=>[...new Set([...u(v),...g.get(v)??[]])],E=I(Ma(f));if(E.length===1&&E[0])return E[0];if(E.length>1)return o;let S=yU(f),k=new Set;S.forEach((v,M)=>{k.add(Ma(v));let J=S[M+1];if(J)k.add(Ma(v+J))});let A=new Set;for(let v of k)for(let M of I(v))A.add(M);let P=[...A];return P.length===1&&P[0]?P[0]:o}function T(e){return e}function Cn(e,o){let a=o.indexOf("/");if(a<=0)return;return e.getModel(o.slice(0,a),o.slice(a+1))}function Mt(e){return`${e.provider}/${e.id}`}function Z$(e,o,a){let u=async(f,h)=>{try{if(o){let I=f instanceof Request?f:void 0;o({at:Date.now(),method:h?.method??I?.method??"GET",url:typeof f==="string"?f:f instanceof URL?f.toString():f.url,headers:X$(h?.headers??I?.headers),body:xU(h?.body!==void 0?h.body:I?.body??void 0)})}}catch{}let g=await e(f,h);if(a)try{let I=Date.now(),{status:E,statusText:S}=g,k=X$(g.headers);if(!g.body)return a({at:I,status:E,statusText:S,headers:k,body:""}),g;let A="",P=new TextDecoder,v=new TransformStream({transform(O,V){V.enqueue(O),A+=P.decode(O,{stream:!0}),a({at:I,status:E,statusText:S,headers:k,body:A})},flush(){A+=P.decode(),a({at:I,status:E,statusText:S,headers:k,body:A})}}),M=g.body.pipeThrough(v),J=new Response(M,g);try{Object.defineProperty(J,"url",{value:g.url})}catch{}return J}catch{}return g},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:p,[ml]:(f)=>Z$(f,o,a)})}function X$(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,p)=>{o[p]=u}),o;let a=Array.isArray(e)?e:Object.entries(e);for(let u of a)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function xU(e){if(e===void 0||e===null)return"";if(typeof e==="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e))return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));return`<${typeof e==="object"&&typeof e.constructor==="function"?e.constructor.name:typeof e}: \u975E\u6587\u672C\u8BF7\u6C42\u4F53\uFF0C\u672A\u8BB0\u5F55\u539F\u6587>`}function IU(e,o){return Q$(e,o)}function EU(e,o,a){let u=Date.now(),p=new WeakSet,f=(I)=>{if(!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;let E=Date.now(),S=Math.max(10,E-u);I.generationMs=S},h=async(I)=>{if(!a||!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;if(f(I),p.has(I))return;p.add(I),Object.assign(I,await a(I))},g=(I)=>{let E=I?.content;if(!Array.isArray(E))return;for(let S of E)if(S&&S.type==="toolCall"&&typeof S.name==="string")S.name=IU(o(),S.name)};return{async*[Symbol.asyncIterator](){for await(let I of e){let{partial:E,message:S}=I;g(E),await h(S),g(S),yield I}},result:async()=>{let I=await e.result();return f(I),await h(I),g(I),I}}}function Wc(e,o){let a=(o??[]).filter((g)=>g.kind==="path").map((g)=>`<file path=${JSON.stringify(g.data)} />`),u=(o??[]).filter((g)=>g.kind==="text").map((g)=>`<file name=${JSON.stringify(g.name)}>
|
|
29
|
-
${g.data}
|
|
30
|
-
</file>`),p=(o??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),f=(o??[]).filter((g)=>g.kind==="image"&&g.id).map((g)=>`<image id=${JSON.stringify(g.id)} name=${JSON.stringify(g.name)} />`);return{merged:[...a,...u,...f,...e.trim()?[e]:[]].join(`
|
|
31
|
-
|
|
32
|
-
`),images:p}}function bh(e,o){let{merged:a,images:u}=Wc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:a},...u]:a,timestamp:Date.now()}}var Y$=!1;function eC(e){let o=new Set;for(let g of e.tools){let I=g.name.toLowerCase();if(o.has(I))throw Error(`Tool names collide ignoring case: ${g.name}`);o.add(I)}let a=new Eh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(g,I,E)=>{let{captureRequest:S,captureResponse:k}=e,A=S||k?{...E,fetch:Z$(E?.fetch??globalThis.fetch,S?(v)=>S({...v,model:Mt(g)}):void 0,k?(v)=>k({...v,model:Mt(g)}):void 0)}:E,P=g.api==="openai-completions"||g.api==="openai-responses"?{...g,compat:{...g.compat,supportsDeveloperRole:!1}}:g;return EU(e.models.streamSimple(P,I,A),()=>a.state.tools,e.hooks.response)},convertToLlm:(g)=>g,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:g,model:I})=>{let E=g.messages.findIndex((P)=>P.role!=="system"),S=g.messages.slice(0,E===-1?g.messages.length:E),k=e.hooks.prepare,A=e.hooks.tools?.()??g.tools;if(A){a.state.tools=A;let P=S[0];if(P?.role==="system")S[0]={...P,toolsAdded:A.map(pt),toolsRemoved:void 0}}return{context:{...g,tools:A,messages:await k(S,A,I)}}}:void 0}),u=new Map,p=new Map,f=new WeakSet,h;return a.subscribe((g)=>{if(g.type==="message_update"&&g.message.role==="assistant"){p.clear(),e.hooks.draft(tC(g.message));return}if(g.type==="tool_execution_update"){let E=u.get(g.toolCallId)??Ne(g.toolName,g.args),S=Array.isArray(g.partialResult?.content)?g.partialResult.content.map((k)=>k.type==="text"&&typeof k.text==="string"?k.text:"").join(""):"";p.set(g.toolCallId,{type:"tool_call",id:g.toolCallId,name:E.name,input:E.input,...E.source?{source:E.source}:{},output:S}),e.hooks.draft([...p.values()]);return}if(g.type==="tool_execution_end"){if(p.delete(g.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(g.type!=="message_end")return;if(f.has(g.message)){e.steerConsumed?.(g.message);return}let I=g.message.role==="user"&&h?{type:"user",text:h.text,...h.attachments?.length?{attachments:h.attachments}:{}}:bU(g.message);if(g.message.role==="user")h=void 0;if(I?.type==="assistant"){for(let E of I.parts)if(E.type==="tool_call")u.set(E.id,E)}if(I?.type==="tool_result"){let E=u.get(I.callID);if(E?.source)Object.assign(I,{name:E.name,source:E.source})}if(I)e.hooks.message(I,g.message);if(g.message.role==="assistant")e.hooks.draft(null)}),{agent:a,prompt:(g,I)=>{h={text:g,attachments:I};let{merged:E,images:S}=Wc(g,I);return a.prompt(E,S.length>0?S:void 0)},retry:async()=>{let g=a.state.messages;if(g.at(-1)?.role==="assistant")a.state.messages=g.slice(0,-1);await a.continue()},resume:()=>a.continue(),steer:(g)=>{f.add(g),a.steer(g)},unsteer:(g)=>{let E=a.steeringQueue?.messages;if(!Array.isArray(E)){if(!Y$)Y$=!0,console.warn("pi Agent.steeringQueue.messages is missing; steering messages cannot be recalled");return!1}let S=E.indexOf(g);if(S<0){let A=JSON.stringify(g);S=E.findIndex((P)=>JSON.stringify(P)===A)}if(S<0)return!1;let[k]=E.splice(S,1);if(k)f.delete(k);return!0},abort:()=>a.abort()}}function Sh(e){if(e?.role!=="assistant")return{reason:"done"};if(e.stopReason==="aborted")return{reason:"aborted"};if(e.stopReason==="error")return{reason:"error",error:e.errorMessage};return{reason:"done"}}function pl(e,o="\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"){let{name:a,source:u}=Ne(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:a,...u?{source:u}:{},output:o,isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:o}],isError:!0,timestamp:Date.now()}}}function tC(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...Ne(o.name,o.arguments)}})}function bU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:tC(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((a)=>a.type==="image").map((a)=>({mimeType:a.mimeType,data:a.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((a)=>a.type==="text"?a.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class tt extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function R(e){return e}import{createHash as rC}from"crypto";import{existsSync as SU}from"fs";import{readFile as nC,realpath as ll}from"fs/promises";import{dirname as wU,isAbsolute as oC,relative as sC,resolve as iC,sep as aC}from"path";var uC=[...Vi];class dl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class fl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let a=wU(iC(e)),u=iC(a,o??"web.tsx");if(!o&&!SU(u))return;let p=sC(await ll(a),await ll(u));if(oC(p)||p===".."||p.startsWith(`..${aC}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let a=this.pending.get(e);if(a)return a;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let a=this.cache.get(e);if(a){let E=!0;for(let[S,k]of a.inputs){let A=await nC(S).catch(()=>{return});if(!A||rC("sha256").update(A).digest("hex")!==k){E=!1;break}}if(E)return a.source;this.cache.delete(e)}let u=await ll(o),p=new Map,f=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:uC,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(E){E.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(S)=>{if(!uC.includes(S.path))throw Error(`Unsupported shared web import: ${S.path}`);return{path:S.path,external:!0}}),E.onLoad({filter:/.*/},async(S)=>{let k=sC(u,await ll(S.path));if(oC(k)||k===".."||k.startsWith(`..${aC}`))throw Error("Plugin web imports must stay inside its plugin directory");let A=await nC(S.path);p.set(S.path,rC("sha256").update(A).digest("hex"));return})}}]}).catch((E)=>{let k=(E instanceof AggregateError?E.errors:[E]).map((A)=>A instanceof Error?A.message:String(A));throw Error(`Plugin web build failed: ${k.join("; ")}`,{cause:E})});if(!f.success)throw new dl(f.logs.filter((E)=>E.level==="error").map((E)=>({file:E.position?.file??null,line:E.position?.line??null,message:E.message})));let h=f.outputs.find((E)=>E.kind==="entry-point"&&E.path.endsWith(".js")),g=f.outputs.find((E)=>E.path.endsWith(".css"));if(!h||f.outputs.some((E)=>E!==h&&E!==g))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let I=await h.text();return this.cache.set(e,{source:I,css:await g?.text(),inputs:p}),I}}function es(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Xs(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((a)=>a.type==="text"?a.text:"[image]").join("")}function hl(e){return e.content.flatMap((a)=>a.type==="text"&&a.text.trim()?[a.text.trim()]:[]).join(`
|
|
33
|
-
|
|
34
|
-
`)}function xu(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function Iu(e){return e.role==="assistant"&&e.content.length>0}function Ge(e){let o=[],a=new Map,u=0;for(let p of e){let f=p.raw;if(f.role==="assistant"){if(Iu(f))u++;for(let h of f.content){if(h.type!=="toolCall")continue;let g={call:h,step:u,message:f};o.push(g),a.set(h.id,g)}}else if(f.role==="toolResult"){let h=a.get(f.toolCallId);if(h)h.result=f}}return o}var gl=new Set(["edit","write"]),cC=new Set(["grep","glob"]);function Ro(e,o){let a=Ne(e.name,e.arguments).input?.[o];return typeof a==="string"?a:void 0}function mC(e){return[...new Set(Ge(e).flatMap((o)=>gl.has(Ne(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&Ro(o.call,"path")?[Ro(o.call,"path")]:[]))]}function wh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function yl(e){let o=[{source:"ASSISTANT_TOOL",text:`${Ne(e.call.name,e.call.arguments).name}(${es(Ne(e.call.name,e.call.arguments).input)}) [${wh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:xu(e.result)});return o}function F(e){let o=0,a=0,u=0;for(let p of e){let f=p.codePointAt(0);if(f<=127)o++;else if(f>=19968&&f<=40959||f>=12288&&f<=12351||f>=65280&&f<=65519||f>=131072&&f<=173791)a++;else u++}return Math.max(0,Math.ceil(o/4+a+u/2))}var Th=8192;function G(e){let o=e,a=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let p of o.content)if(p.type==="text")u+=p.text;else a++;else if(o.role==="assistant")for(let p of o.content)if(p.type==="text")u+=p.text;else if(p.type==="thinking")u+=p.thinking;else u+=`${p.name}${es(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")u+=p.text;else a++;else u=es(e);return F(u)+16+a*Th}function Lt(e=[]){return e.reduce((o,a)=>o+F(a.name+a.description+es(a.parameters))+16,0)}function Wn(e,o){let a=e.replace(/\s+/g," ").trim();if(F(a)<=o)return a;let u=Math.min(a.length,o*4);while(u>0&&F(a.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${a.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function jo(e,o,a=Number.POSITIVE_INFINITY){if(F(e)<=o&&e.length<=a)return e;let u=`
|
|
35
|
-
[... omitted; use history tools for the full text ...]
|
|
36
|
-
`,p=Math.floor((o-F(u))/2);if(p<=0)return"";let f=(h)=>{let g=0,I=Math.max(0,Math.min(e.length,p*4,Math.floor((a-u.length)/2)));while(g<I){let E=Math.ceil((g+I)/2),S=h?e.slice(-E):e.slice(0,E);if(F(S)<=p)g=E;else I=E-1}if(!g)return"";return h?e.slice(-g).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,g).replace(/[\uD800-\uDBFF]$/,"")};return`${f(!1)}${u}${f(!0)}`}function xl(e,o){if(F(e.join(`
|
|
37
|
-
`))<=o)return e;let a=(S)=>`- [... ${S} steps omitted; use history tools for the full text ...]`,u=o-F(a(e.length)),p=[],f=[],h=0,g=0,I=e.length-1;while(g<=I){let S=p.length<=f.length,k=S?e[g]:e[I],A=F(`${k}
|
|
38
|
-
`);if(h+A>u)break;if(h+=A,S)p.push(e[g++]);else f.unshift(e[I--])}let E=I-g+1;return[...p,...E>0?[a(E)]:[],...f]}function rt(e){let o=[],a;for(let u of e){let p=u.entry;if(p.type==="run"&&p.state==="start"){a={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(a);continue}if(p.type==="run"&&p.state==="end"){if(a)a.end=p.seq,a.status=TU(p.reason,a.records);a=void 0;continue}if(p.type==="extension"||!u.raw)continue;if(!a&&p.type==="user"&&p.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!a)a={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(a);a.records.push(u)}for(let u of o)u.records=Jo(u.records);return o}function Jo(e){if(e.length<=1)return[...e];let o=[],a=[],u=new Set;for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;let h=f.raw?.role;if(h==="assistant"){let I=f.raw.content?.filter((E)=>E.type==="toolCall")??[];if(I.length>0)for(let E of I)u.add(E.id);if(o.push(f),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(h==="toolResult"){let g=f.raw;if(g.toolCallId)u.delete(g.toolCallId);if(o.push(f),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(h==="user"){if(o.length===0){o.push(f);continue}let g=e.slice(p+1).some((I)=>I.raw?.role==="assistant");if(u.size>0||g){a.push(f);continue}o.push(f);continue}o.push(f)}if(a.length>0)o.push(...a);return o}function TU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let a=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return a?.stopReason==="error"&&Ta(a)?"interrupted":"failed";if(!a)return"completed";switch(a.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return Ta(a)?"interrupted":"failed";default:return"interrupted"}}function wt(e){for(let o=e.length-1;o>=0;o--){let a=e[o]?.entry;if(a?.type==="compaction")return a.through}return 0}function Il(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((a)=>a.entry.seq<=o)}function Rh(e,o){return e.find((a)=>a.start<o&&!Il(a,o)&&a.records.some((u)=>u.entry.seq<=o))}function _r(e){let o=wt(e),u=rt(e).findLast((p)=>p.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function Xn(e){let o=wt(e);return Rh(rt(e),o)?.end}function dn(e,o){let a=wt(e),u=rt(e).at(-1);if(!u||u.end!==void 0)return;let p=u.records.filter((S)=>S.entry.seq>a),f=[],h=new Set;for(let S of p){let k=S.raw,A=G(S.raw);if(k.role==="assistant"){for(let P of k.content)if(P.type==="toolCall")h.add(P.id)}else if(k.role==="toolResult")h.delete(k.toolCallId);if(Iu(k)||!f.length||k.role==="user"&&f.at(-1)?.assistant)f.push({end:S.entry.seq,tokens:A,assistant:Iu(k),pending:h.size});else{let P=f.at(-1);P.end=S.entry.seq,P.tokens+=A,P.pending=h.size}}let g=f.findLastIndex((S)=>S.assistant),I=0,E;for(let S=f.length-1;S>=0;S--){let k=f[S];if(S<g&&k.assistant&&k.pending===0&&(I<=o||E===void 0))E=k.end;if(I+=k.tokens,I>o&&E!==void 0)break}if(I<=o)return;return E}var pC=2000;function Ot(e,o){let a=F(o);if(a<=pC)return o;let u=new TextEncoder().encode(o).length,p=o.split(`
|
|
39
|
-
`).length,f=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${p} lines, approximately ${a} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
|
|
40
|
-
`),h="</user-text-reference>",g=pC-F(`${f}
|
|
41
|
-
|
|
42
|
-
${h}`);if(g<=0)return o;let I=`${f}
|
|
43
|
-
${jo(o,g,o.length-f.length-h.length-3)}
|
|
44
|
-
${h}`;return I.length<o.length&&F(I)<a?I:o}function lC(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let p=Ot(e.entry.seq,o.content);return p===o.content?o:{...o,content:p}}let a=!1,u=o.content.map((p)=>{if(p.type!=="text")return p;let f=Ot(e.entry.seq,p.text);if(f!==p.text)a=!0;return f===p.text?p:{...p,text:f}});return a?{...o,content:u}:o}function kh(e,o=!1){let a=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),u=a.flatMap((P)=>{let v=P.raw.content;return typeof v==="string"?[]:v.filter((M)=>M.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,f=e.status==="open"?"interrupted":e.status,h="";if(a.length){let P=o?jo(a.map((v)=>Xs(v.raw)).join(`
|
|
45
|
-
|
|
46
|
-
`),600):a.map((v,M)=>`<user-message sequence="${M+1}">
|
|
47
|
-
${Ot(v.entry.seq,Xs(v.raw))}
|
|
48
|
-
</user-message>`).join(`
|
|
49
|
-
|
|
50
|
-
`);h=[`<chunk-input id="${e.id}" status="${f}"${o?' excerpt="true"':""}>`,P,...o?[p]:[],"</chunk-input>"].join(`
|
|
51
|
-
`)}let I=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,E=I?hl(I):"",S=[];if(f!=="completed"){let P=Ge(e.records),v=new Map(P.map((j)=>[j.call,j])),M=P.slice(-3),J=new Set(M.map((j)=>j.message)),O=[],V=[];for(let j of e.records){let te=j.raw;if(te.role!=="assistant")continue;let se=J.has(te);for(let L of te.content)if(L.type==="text"&&te!==I&&L.text.trim())if(se)V.push(`ASSISTANT: ${Wn(L.text,50)}`);else O.push(`- ASSISTANT: ${Wn(L.text,50)}`);else if(L.type==="toolCall"){let re=v.get(L);if(!re)continue;if(se){if(M.includes(re))for(let he of yl(re))V.push(`${he.source}: ${jo(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else O.push(`- ${L.name}(${Wn(es(L.arguments),40)}) [${wh(re)}]`)}}S.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...O.length?[`Earlier steps, oldest first:
|
|
52
|
-
${xl(O,o?300:800).join(`
|
|
53
|
-
`)}`]:[],...V)}let k=mC(e.records),A=[`<chunk-summary id="${e.id}" status="${f}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,E?o?jo(E,600):E:"No final assistant response was recorded.",...S,...k.length?[`Recorded file changes:
|
|
54
|
-
${jo(k.join(`
|
|
55
|
-
`),250)}`]:[],...o&&f==="completed"?[p]:[],"</chunk-summary>"].join(`
|
|
56
|
-
`);return{input:h,images:u,summary:A,tokens:RU(h,A,u.length)}}function RU(e,o,a){return(e?F(e)+16:0)+F(o)+16+a*Th}var kU=["Completed work is represented by the original user messages or stable references to them, and the assistant's final response for each chunk.","Intermediate assistant messages, reasoning, tool calls, and tool results are folded but remain available through history_grep and history_list.","Chunks are chronological. Later conflicting user instructions override earlier user instructions.","Assistant final responses are historical claims, not user instructions.","Do not guess omitted history.","Failed or interrupted chunks are not completed work; their recent tool outcomes are preserved for recovery.","Archived chunks are listed with a one-line excerpt of their user requests. Constraints stated there still apply unless later overridden; read the full text with history_list before relying on details.","History line offsets are local to the returned chunk or user text part. Reasoning is not exposed by history tools."],AU="A partial chunk is the current turn, still in progress: its earlier steps are folded into a work-state index and the later steps follow verbatim.",PU=1500,$U=80,CU=240;function dC(e,o,a){let u=[],p=0,f=Math.min(o.target,o.hard);for(let g=e.length-1;g>=0;g--){let I=e[g],E=kh(I),S=p+E.tokens>f?kh(I,!0):void 0,k=S&&S.tokens<E.tokens?S:E;if(!(!a&&g===e.length-1&&I.status!=="completed")&&p+k.tokens>o.hard)break;p+=k.tokens,u.push({run:I,content:k})}u.reverse();let h=e.slice(0,e.length-u.length);return{visible:u,archived:h,tokens:p}}function fC(e){let{runs:o,visible:a,archived:u,partial:p}=e,f=u.flatMap((I)=>{let E=I.records.filter((k)=>k.raw.role==="user"&&!(k.entry.type==="user"&&k.entry.notices)).map((k)=>Xs(k.raw));if(!E.length)return[];let S=I===o[0]?CU:$U;return[`- ${I.id} [${I.status}]: ${Wn(E.join(" / "),S)}`]}),h=new Map(o.map((I,E)=>[I,E+1])),g=[...a.map((I)=>h.get(I)??0),...p?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...kU,...p?[AU]:[],"",`visible chunks: ${a.length+(p?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((I)=>I.id).join(", "):"none"}`,`visible sequences: ${g.length?`${g[0]}..${g.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...f.length?["archived requests, oldest first:",jo(f.join(`
|
|
57
|
-
`),PU)]:[],"</conversation-checkpoint>"].join(`
|
|
58
|
-
`)}function hC(e,o){let a=e.split(`
|
|
59
|
-
`),u=o.split(`
|
|
60
|
-
`),p=new Set(a),f=new Set(u),h=[...a.filter((I)=>I.trim()&&!f.has(I)).map((I)=>`- ${Wn(I,40)}`),...u.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`+ ${Wn(I,40)}`)],g=a.find((I)=>I.trim()&&f.has(I));return[...h.slice(0,6),...h.length>6?[`\u2026 ${h.length-6} more changed lines`]:[],...g&&h.every((I)=>I.startsWith("+"))?[`@ ${Wn(g,40)}`]:[]]}function El(e,o){if(!o)return e;let a=o.endsWith("/")?o:`${o}/`;return e.startsWith(a)?e.slice(a.length):e}function vU(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((a)=>{let u=a&&typeof a==="object"?a.path:void 0;return typeof u==="string"?[u]:[]})}function MU(e,o){let a=Ro(e,"path");if(gl.has(e.name)&&a)return`file:${El(a,o)}`;let u=Ro(e,"command");if(u)return`command:${u}`;return`${e.name}:${es(e.arguments)}`}function OU(e,o){let a={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let f of Ge(e)){let h=u.get(f.step)??[];h.push(f),u.set(f.step,h)}let p=new Map;for(let f of e){let h=f.raw;if(!Iu(h))continue;let g=++a.steps,I=hl(h);if(I)a.narration.push({step:g,text:Wn(I,60)});for(let{call:E,result:S}of u.get(g)??[]){if(!S)continue;let k=Ne(E.name,E.arguments),A={...E,name:k.name,arguments:k.input},P=MU(A,o),v=xu(S);if(S.isError){let te=Ro(A,"command"),se=te?`${A.name} \`${Wn(te,40)}\``:`${A.name} ${P.startsWith("file:")?P.slice(5):Wn(es(A.arguments),40)}`,L={step:g,key:P,what:se,detail:jo(v.trim().split(`
|
|
61
|
-
`).slice(0,8).join(`
|
|
62
|
-
`),200)};a.errors.push(L);let re=p.get(P)??[];re.push(L),p.set(P,re);continue}for(let te of p.get(P)??[])te.resolved=g;p.delete(P);let M=Ro(A,"path");if(gl.has(A.name)&&M){let te=El(M,o),se=a.files.get(te)??{count:0,first:g,last:g,diffs:[]};if(se.count++,se.last=g,se.diffs.push({step:g,lines:A.name==="edit"?Ro(A,"old_string")!==void 0?hC(Ro(A,"old_string")??"",Ro(A,"new_string")??""):[]:hC("",Ro(A,"content")??"")}),se.diffs.length>3)se.diffs.shift();a.files.set(te,se);continue}let J=A.name==="read"?[...M?[M]:[],...vU(A)]:[];if(J.length){for(let te of J){let se=El(te,o),L=a.reads.get(se)??[];L.push(g),a.reads.set(se,L)}continue}if(cC.has(A.name)){let te=M?` in ${El(M,o)}`:"",se=A.name==="grep"&&Ro(A,"glob")?` (${Ro(A,"glob")})`:"",L=`${A.name} ${Ro(A,"pattern")??""}${te}${se}`.replace(/\s+/g," "),re=a.searches.get(L)??{steps:[],head:""};re.steps.push(g),re.head=Wn(v.trim().split(`
|
|
63
|
-
`)[0]??"",25),a.searches.set(L,re);continue}let O=Ro(A,"command");if(O){let te=v.trim().split(`
|
|
64
|
-
`);a.commands.push({step:g,command:Wn(O,40),exit:"0",lines:te.length,tail:te.slice(-3).map((se)=>Wn(se,40))});continue}let V=`${A.name} ${Wn(es(A.arguments),40)}`,j=a.other.get(V)??[];j.push(g),a.other.set(V,j)}}return a}function gC(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function zc(e,o,a){let u=(E,S)=>S===void 0||!E.length?E:xl(E,S),p=[`<work-state chunk="${o.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${o.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],f=[...e.files];p.push("",`## Modified files (${f.length})`),f.forEach(([E,S],k)=>{if(p.push(`- ${E}: ${S.count} change${S.count>1?"s":""} (step ${S.first}${S.last!==S.first?`-${S.last}`:""})`),k<f.length-a.diffFiles)return;for(let A of S.diffs)p.push(` step ${A.step}:`,...A.lines.map((P)=>` ${P}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((E)=>E.resolved?`- step ${E.step} ${E.what} (resolved at step ${E.resolved})${a.lists===void 0?`: ${E.detail.replace(/\n/g,`
|
|
65
|
-
`)}`:""}`:`- step ${E.step} ${E.what} (UNRESOLVED): ${E.detail.replace(/\n/g,`
|
|
66
|
-
`)}`)),p.push("","## Steps",...u(e.narration.map((E)=>`- ${E.step}. ${E.text}`),a.narration));let h=[...e.reads].map(([E,S])=>`- ${E} @ ${S.join(",")}`);p.push("",`## Files read (${h.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(h,a.lists));let g=[...e.searches].map(([E,S])=>`- ${E} \u2192 ${S.head||"(no output)"} (${gC(S.steps)})`);p.push("",`## Searches (${g.length})`,...u(g,a.lists));let I=e.commands.map((E)=>[`- ${E.step}. \`${E.command}\` exit=${E.exit}, ${E.lines} output lines, last ${E.tail.length}:`,...E.tail.map((S)=>` ${S}`)].join(`
|
|
67
|
-
`));if(p.push("",`## Commands (${I.length})`,...u(I,a.lists)),e.other.size){let E=[...e.other].map(([S,k])=>`- ${S} (${gC(k)})`);p.push("",`## Other tool calls (${E.length})`,...u(E,a.lists))}return p.push("</work-state>"),p.join(`
|
|
68
|
-
`)}function Yn(e,o,a,u){let p=OU(e,u),f=zc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(F(f)<=a)return f;let h={...p,narration:[]};for(let E of[Number.POSITIVE_INFINITY,20,10,5]){let S=F(zc(h,o,{diffFiles:E}));if(S>a*0.7)continue;return zc(p,o,{narration:Math.max(500,a-S),diffFiles:E})}let g=Math.max(300,Math.floor(a*0.1)),I=F(zc(h,o,{diffFiles:0,lists:g}));return zc(p,o,{narration:Math.max(500,a-I),diffFiles:0,lists:g})}function bl(e){return{role:"user",content:e,timestamp:0}}function Ah(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function yC(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:bl(e.input)}function Eu(e){let o=[];for(let a of e){let u=o.at(-1),p=a;if(u?.role==="user"&&p.role==="user"){let f=(h)=>typeof h.content==="string"?[{type:"text",text:h.content}]:h.content;o[o.length-1]={...p,content:[...f(u),{type:"text",text:`
|
|
69
|
-
|
|
70
|
-
`},...f(p)],timestamp:Math.max(u.timestamp,p.timestamp)};continue}o.push(a)}return o}function xC(e){let o=[],a=new Map;for(let u of e){let p=u;if(p.role==="toolResult"){if(!a.has(p.toolCallId))continue;let f=a.get(p.toolCallId);if(f===void 0)a.set(p.toolCallId,o.length),o.push(u);else o[f]=u;continue}if(p.role==="assistant"){if(p.content.length===0)continue;if(a=new Map,p.stopReason!=="error"&&p.stopReason!=="aborted"){for(let f of p.content)if(f.type==="toolCall")a.set(f.id,void 0)}}else if(p.role==="user")a=new Map;o.push(u)}return o}function _U(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Ce(e,o,a,u={}){let p=wt(e),f=rt(e),h=f.filter((X)=>Il(X,p)),g=Rh(f,p),I=[],E=[],S=0;for(let X of f){if(Il(X,p))continue;let Y=[];for(let xe of X.records){if(X===g&&xe.entry.seq<=p)continue;let Ve=xe.raw.role==="user"?lC(xe):xe.raw;S+=G(Ve),I.push(Ve),Y.push(Ve)}if(u.inspect&&Y.length)E.push({id:`recent-${X.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${X.id}`,tokens:Y.reduce((xe,Ve)=>xe+G(Ve),0),detail:JSON.stringify(Y,_U,2)})}if(!h.length&&!g)return{items:E,messages:Eu(I),visible:0,archived:0,open:S,tokens:S,untrimmed:S};let k=dC(h,a,!!g),{visible:A,archived:P}=k,v=k.tokens,M=[],J="",O="";if(g){let X=g.records.filter((xe)=>xe.entry.seq<=p),Y=X.filter((xe)=>xe.entry.type==="user"&&!xe.entry.notices&&xe.raw.role==="user");if(Y.length){J=[`<chunk-input id="${g.id}" status="partial">`,...Y.map((Ve,He)=>`<user-message sequence="${He+1}">
|
|
71
|
-
${Ot(Ve.entry.seq,Xs(Ve.raw))}
|
|
72
|
-
</user-message>`),"</chunk-input>"].join(`
|
|
73
|
-
`);let xe=Y.flatMap((Ve)=>{let He=Ve.raw.content;return typeof He==="string"?[]:He.filter((ar)=>ar.type==="image")});M.push(xe.length?{role:"user",content:[{type:"text",text:J},...xe],timestamp:0}:bl(J))}O=Yn(X,g,a.index,u.cwd),M.push(Ah(O,o))}let V=e.flatMap((X)=>{let Y=X.raw;if(X.entry.seq>p||Y?.role!=="toolResult"||Y.toolName!=="skill")return[];return[bl(Y.content.filter((xe)=>xe.type==="text").map((xe)=>xe.text).join(`
|
|
74
|
-
`))]}),j="",te=e.findLast((X)=>X.entry.type==="compaction")?.entry.time??0,se=()=>{j=fC({runs:h,visible:A.map((Y)=>Y.run),archived:P,partial:!!g,tokens:v,budget:a});let X=[bl(j)];for(let{content:Y}of A){if(Y.input)X.push(yC(Y));X.push(Ah(Y.summary,o))}return[...X,...V,...M].map((Y)=>({...Y,timestamp:te}))},L=(X)=>X.reduce((Y,xe)=>Y+G(xe),0),re=se(),he=L(re)+S,we=he,{trim:We}=u;while(We&&We.fixed+he>We.limit){let X=g||A.at(-1)?.run.status==="completed"?A:A.slice(0,-1);if(!X.length)break;let Y=0,xe=0;for(let Ve of X)if(xe++,Y+=Ve.content.tokens,Y>=We.fixed+he-We.limit)break;P=[...P,...A.slice(0,xe).map((Ve)=>Ve.run)],A=A.slice(xe),v-=Y,re=se(),he=L(re)+S}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:G(re[0]),detail:j},...A.map(({run:X,content:Y})=>({id:X.id,label:`Chunk ${X.id}`,state:"sealed",tokens:(Y.input?G(yC(Y)):0)+G(Ah(Y.summary,o)),detail:[Y.input,Y.summary].filter(Boolean).join(`
|
|
75
|
-
|
|
76
|
-
`)})),...P.map((X)=>({id:X.id,label:`Chunk ${X.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...g?[{id:g.id,label:`Chunk ${g.id}`,state:"folded",tokens:L(M),detail:[J,O].filter(Boolean).join(`
|
|
77
|
-
|
|
78
|
-
`)}]:[],...E]:[],messages:Eu([...re,...I]),visible:A.length,archived:P.length,open:S,tokens:he,untrimmed:we}}function de(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Ph=0.97,LU=0.97,IC=0.5,NU=0.05,qU=20000,DU=24000;function mn(e){return{target:qU,hard:DU,index:Math.floor(de(e)*NU)}}function $h(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class hn{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,a=()=>{return}){this.records=e;this.fold=o;this.cwd=a}budget(e){return mn(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(de(e)*Ph/this.ratio)}prepare(e,o,a,u){let p=de(a),f=mn(a),h=e.reduce((L,re)=>L+G(re),0)+Lt(o),g=this.records().at(-1)?.entry.seq??0,I=()=>u?[...u,...this.records().filter((L)=>L.entry.seq>g)]:this.records(),E=()=>Ce(I(),a,f,{cwd:this.cwd(),trim:{fixed:h,limit:Math.floor(p*Ph/this.ratio)}}),S=I().findLast((L)=>L.raw?.role==="assistant"),k=S?I().filter((L)=>L.entry.seq>S.entry.seq&&L.raw):[],A=S?.raw,P=()=>S!==void 0&&(S.entry.seq===this.reshapedAfter||I().some((L)=>L.entry.type==="compaction"&&L.entry.seq>S.entry.seq)),v=this.dueSeal(a);if(v!==void 0)this.fold(v,!1),this.reshapedAfter=S?.entry.seq??-1;let M=E(),J=k.reduce((L,re)=>L+G(re.raw),0);if(this.lastEstimate===0&&S&&A&&!P()){let L=A.usage.input+A.usage.cacheRead+A.usage.cacheWrite,re=h+M.untrimmed-G(A)-J;if(L>0&&re>0)this.ratio=Math.min(2,Math.max(0.5,L/re))}let V=((L)=>{let re=h+L.untrimmed,he=h+L.tokens;return((S&&A&&!P()&&$h(A)>0?$h(A)+Math.round(this.ratio*J):void 0)??Math.round(re*this.ratio))-Math.round((re-he)*this.ratio)})(M);if(V>p*LU){let L=V-M.open*this.ratio,re=Math.max(1000,Math.floor((p*IC-L-f.index)/this.ratio)),he=S?.entry.seq??-1,we=I().findLast((xe)=>xe.entry.type==="compaction"&&xe.entry.partial)?.entry.seq??-1,We=Math.max(this.lastFoldSeq,we),Y=(We>0?I().filter((xe)=>xe.entry.seq>We&&xe.raw?.role==="assistant").length:999)<=1;if(!Y||this.consecutivePartialFolds<2){let xe=dn(I(),re);if(xe!==void 0)this.fold(xe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=Y?this.consecutivePartialFolds+1:1,M=E()}}else this.consecutivePartialFolds=0;this.lastEstimate=h+M.tokens;let j=M.messages,te=h+M.tokens;if(Math.round(te*this.ratio)>p)j=FU(j,Math.floor((p-h)/this.ratio)),te=h+j.reduce((L,re)=>L+G(re),0);return this.lastEstimate=te,{messages:Eu([...e,...j]),estimate:te}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((a)=>a.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(Xn(o)===void 0){let a=o.findLast((g)=>g.raw?.role==="assistant"),u=a?.raw,p=a!==void 0&&(a.entry.seq===this.reshapedAfter||o.some((g)=>g.entry.type==="compaction"&&g.entry.seq>a.entry.seq)),h=(a?o.filter((g)=>g.entry.seq>a.entry.seq&&g.raw):[]).reduce((g,I)=>g+G(I.raw),0);if(p||!u||$h(u)+h<Math.floor(de(e)*Ph))return}return _r(o)}recover(e){let o=de(e),a=mn(e),u=Ce(this.records(),e,a,{cwd:this.cwd()}),p=Math.floor((o*IC-(o-u.open*this.ratio)-a.index)/this.ratio),f=dn(this.records(),p);if(f===void 0)return!1;return this.fold(f,!0),this.reshapedAfter=this.records().findLast((h)=>h.raw?.role==="assistant")?.entry.seq??-1,!0}}var Ch=500;function FU(e,o){let a=[...e],u=a.map((f)=>G(f)),p=u.reduce((f,h)=>f+h,0);while(p>o){let f=-1;for(let[k,A]of a.entries()){if(A.role!=="toolResult"||(u[k]??0)<=Ch)continue;if(f<0||(u[k]??0)>(u[f]??0))f=k}if(f<0)break;let h=a[f],g=u[f]??0,I=Math.max(Ch,Math.floor(g/2)),E={...h,content:h.content.map((k)=>k.type==="text"?{...k,text:jo(k.text,I)}:k)},S=G(E);u[f]=S<g?S:Ch,a[f]=E,p-=g-S}return a}var jU=2000;function bu(e,o){let a=[];for(let u of o.replace(/\r\n/g,`
|
|
79
|
-
`).split(`
|
|
80
|
-
`))for(let p=0;p<Math.max(u.length,1);){let f=Math.min(u.length,p+jU);if(f<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(f-1)))f--;a.push({source:e,text:u.slice(p,f)}),p=f>p?f:p+1}return a}function Ar(e){let o=[],a=Ge(e.records),u=new Map(a.map((f)=>[f.call,f])),p=new Set(a.flatMap((f)=>f.result?[f.result]:[]));for(let f of e.records){let h=f.raw;if(h.role==="user")o.push(...bu(f.entry.type==="user"&&f.entry.notices?"NOTICE":"USER",Xs(h)));else if(h.role==="assistant"){for(let g of h.content)if(g.type==="text"&&g.text.trim())o.push(...bu("ASSISTANT",g.text));else if(g.type==="toolCall"){let I=u.get(g);if(I)for(let E of yl(I))o.push(...bu(E.source,E.text))}}else if(h.role==="toolResult"&&!p.has(h))o.push(...bu(h.isError?"TOOL_ERROR":"TOOL_OUTPUT",xu(h)))}return o.map((f,h)=>({chunk:e.id,line:h,...f}))}function Zn(e,o){let a=e.find((u)=>u.entry.seq===o);if(a?.entry.type!=="user"||a.entry.notices||!a.raw||a.raw.role!=="user")return;return bu("USER",Xs(a.raw)).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function eo(e,o){let a=e.find((u)=>u.entry.seq===o)?.entry;if(a?.type!=="extension"||!a.display)return;return bu("EXTENSION",a.display.text).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function fn(e,o=""){return e.map((a,u)=>{let p=e[u-1],f=p&&p.source===a.source&&p.chunk===a.chunk&&p.line===a.line-1;return`${o}${f?`${a.line}:`:`${a.line} ${a.source}:`} ${a.text}`}).join(`
|
|
81
|
-
`)}import{AsyncLocalStorage as UU}from"async_hooks";import{chmodSync as wC,existsSync as BU,mkdirSync as GU,readFileSync as KU,renameSync as HU,writeFileSync as WU}from"fs";import{dirname as zU,join as VU}from"path";function EC(){let e=Bun.version.split(".").map(Number);if(!((e[0]??0)>1||e[0]===1&&(e[1]??0)>4||e[0]===1&&e[1]===4&&(e[2]??0)>=3))throw Error("\u4EE3\u7406\u4F20\u8F93\u9700\u8981 Bun 1.4.3 \u6216\u66F4\u65B0\u7248\u672C\uFF0C\u8BF7\u5148\u5347\u7EA7 Bun")}function bC(e=process.env){let o={...e};for(let a of["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY"])delete o[a],delete o[a.toLowerCase()];return o}function Vc(e){let o=e.hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1]??o;return u==="localhost"||u.endsWith(".localhost")||u==="::1"||u==="::"||/^(?:0\.|127\.)/.test(u)}function SC(e,o){let a=async(p,f,h)=>{let g=await e(p,{...f,...o.proxy?{proxy:o.proxy}:{proxy:!1},...o.tls==="insecure"?{tls:{rejectUnauthorized:!1}}:{},redirect:"manual"});if(![301,302,303,307,308].includes(g.status))return g;let I=g.headers.get("location");if(!I)return g;if(h>=10)throw Error("\u4EE3\u7406\u8BF7\u6C42\u91CD\u5B9A\u5411\u6B21\u6570\u8FC7\u591A");let E=p instanceof Request?p:void 0,S=new URL(E?.url??String(p)),k=new URL(I,S);if(k.protocol!=="http:"&&k.protocol!=="https:")throw Error("\u62D2\u7EDD\u91CD\u5B9A\u5411\u5230\u975E HTTP \u5730\u5740");if(Vc(k)&&!Vc(S))throw Error("\u62D2\u7EDD\u4ECE\u516C\u7F51\u91CD\u5B9A\u5411\u5230\u56DE\u73AF\u5730\u5740");let A=new Headers(E?.headers);if(new Headers(f?.headers).forEach((M,J)=>{A.set(J,M)}),S.origin!==k.origin)A.delete("authorization"),A.delete("cookie"),A.delete("proxy-authorization");let P=(f?.method??E?.method??"GET").toUpperCase(),v={...f,method:P,headers:A};if(g.status===303||(g.status===301||g.status===302)&&P==="POST")v.method="GET",delete v.body,A.delete("content-length"),A.delete("content-type");else if(P!=="GET"&&P!=="HEAD"&&f?.body===void 0&&E?.body)throw Error("\u65E0\u6CD5\u5B89\u5168\u91CD\u5B9A\u5411\u5E26\u6D41\u5F0F\u8BF7\u6C42\u4F53\u7684\u8BF7\u6C42");return await g.body?.cancel(),a(k,v,h+1)};return Object.assign((p,f)=>a(p,f,0),{preconnect:e.preconnect})}var vh=Qi,RC=Cr,TC=new UU;class $i{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;EC(),this.path=VU(e,"proxy.json");let a=async(u,p)=>{let f=TC.getStore();if(!f)return this.baseFetch(u,p);return this.createFetch(f)(u,p)};globalThis.fetch=Object.assign(a,{preconnect:o.preconnect})}load(){if(!BU(this.path))return;this.config=this.validate(JSON.parse(KU(this.path,"utf8")))}settings(){return{...this.config,defaultProfileID:this.config.defaultProfileID,routes:{...this.config.routes},profiles:this.config.profiles.map((e)=>{let{password:o,...a}=e;return{...a,hasPassword:Boolean(o)}})}}save(e){let o=this.validate(e);for(let a of o.profiles)a.password||=this.config.profiles.find((u)=>u.id===a.id)?.password;try{GU(zU(this.path),{recursive:!0});let a=`${this.path}.tmp-${process.pid}`;WU(a,`${JSON.stringify(o,null,2)}
|
|
82
|
-
`,{mode:384}),wC(a,384),HU(a,this.path),wC(this.path,384)}catch(a){throw Error("\u4FDD\u5B58\u4EE3\u7406\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:a})}return this.config=o,this.settings()}createFetch(e,o=this.baseFetch){let a=(p,f="verify")=>SC(o,{proxy:p,tls:f});return Object.assign(async(p,f)=>{let h=p instanceof Request?p.url:String(p),I=this.profileFor(e)?.noProxy?.some((S)=>XU(h,S))??!1;if(Vc(new URL(h))||I)return a()(p,f);let E=this.proxyURL(e);return a(E,this.profileFor(e)?.tls)(p,f)},{preconnect:o.preconnect})}models(e){return new kC(e,this)}providerOptions(e,o,a){let u=Object.assign({},e),p=e?.fetch,h=p?.[ml]?.call(p,this.baseFetch)??p??this.baseFetch;u.fetch=this.createFetch(o,h);let g=bC({...process.env,...e?.env}),I=!1;if(a)try{I=Vc(new URL(a))}catch{}let E=I?void 0:this.proxyURL(o),S=this.profileFor(o);return u.env={...g,...E?{HTTP_PROXY:E,HTTPS_PROXY:E,ALL_PROXY:E}:{},...S?.noProxy?.length?{NO_PROXY:S.noProxy.join(",")}:{}},u}run(e,o){return TC.run(e,o)}wrapProvider(e){let o=jt(e.id),a={...e.auth},u=e.auth.oauth;if(u){let S=e.id==="openai"||e.id===vt?vh:o;a.oauth={...u,login:(k,A)=>this.run(S,()=>u.login(k,A)),refresh:(k,A)=>this.run(S,()=>u.refresh(k,A)),toAuth:(k)=>this.run(S,()=>u.toAuth(k))}}let p={...e,auth:a},f=e.refreshModels;if(f)p.refreshModels=(S)=>this.run(o,()=>f(S));p.stream=(S,k,A)=>this.run(o,()=>e.stream(S,k,this.providerOptions(A,o,S.baseUrl))),p.streamSimple=(S,k,A)=>this.run(o,()=>e.streamSimple(S,k,this.providerOptions(A,o,S.baseUrl)));let h=e.fetchDeferred;if(h)p.fetchDeferred=(S,k,A)=>this.run(o,()=>h(S,k,this.providerOptions(A,o,S.baseUrl)));let g=e.cancelDeferred;if(g)p.cancelDeferred=(S,k,A)=>this.run(o,()=>g(S,k,this.providerOptions(A,o,S.baseUrl)));let I=e.generateImages;if(I)p.generateImages=(S,k,A)=>this.run(o,()=>I(S,k,this.providerOptions(A,o,S.baseUrl)));let E=e.classify;if(E)p.classify=(S,k,A)=>this.run(o,()=>E(S,k,this.providerOptions(A,o,S.baseUrl)));return p}proxyURL(e){let o=this.profileFor(e);if(!o)return;let a=ti(o.address),u=o.username?`${encodeURIComponent(o.username)}:${encodeURIComponent(o.password??"")}@`:"",p=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return`${a.protocol}://${u}${p}:${a.port}`}profileFor(e){let o=e?this.config.routes[e]:this.config.defaultProfileID,a=e&&o!==void 0?o:this.config.defaultProfileID;if(!a)return;let u=this.config.profiles.find((p)=>p.id===a);if(!u)throw Error(`\u4EE3\u7406\u7EBF\u8DEF ${a} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u9875\u91CD\u65B0\u9009\u62E9`);return u}validate(e){let o=Mh(e);if(o?.version!==1)throw new t("\u4EE3\u7406\u914D\u7F6E\u7248\u672C\u65E0\u6548");let u=(Array.isArray(o.profiles)?o.profiles:[]).map(JU),p=new Set(u.map((I)=>I.id));if(p.size!==u.length)throw new t("\u4EE3\u7406\u914D\u7F6E ID \u4E0D\u80FD\u91CD\u590D");let f=QU(o.defaultProfileID);if(f&&!p.has(f))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let h=Mh(o.routes)??{},g={};for(let[I,E]of Object.entries(h)){if(I!==vh&&I!==RC&&!Ji(I))throw new t(`\u4EE3\u7406\u7528\u9014\u65E0\u6548\uFF1A${I}`);if(E!==null&&(typeof E!=="string"||!p.has(E)))throw new t(`\u7528\u9014 ${I} \u7684\u7EBF\u8DEF\u4E0D\u5B58\u5728`);g[I]=E}return{version:1,defaultProfileID:f,routes:g,profiles:u}}}class kC{source;manager;wrapped=new Map;constructor(e,o){this.source=e;this.manager=o;for(let a of e.getProviders())this.install(a)}getProviders(){return this.source.getProviders().map((e)=>this.wrap(e))}getProvider(e){let o=this.source.getProvider(e);return o?this.wrap(o):void 0}getModels(...e){return this.source.getModels(...e)}getModel(...e){return this.source.getModel(...e)}getModelsOfType(e,o){return this.source.getModelsOfType(e,o)}getModelOfType(e,o,a){return this.source.getModelOfType(e,o,a)}getAllModels(...e){return this.source.getAllModels(...e)}refresh(...e){return this.source.refresh(...e)}checkAuth(...e){return this.source.checkAuth(...e)}getAvailable(...e){return this.source.getAvailable(...e)}getAvailableOfType(e,o,a){return this.source.getAvailableOfType(e,o,a)}getAllAvailable(...e){return this.source.getAllAvailable(...e)}getAuth(e,o){if(typeof e==="string")return this.source.getAuth(e,o);return this.source.getAuth(e,o)}login(...e){return this.source.login(...e)}logout(...e){return this.source.logout(...e)}stream(e,o,a){return this.source.stream(e,o,a)}complete(e,o,a){return this.source.complete(e,o,a)}streamSimple(...e){return this.source.streamSimple(...e)}completeSimple(...e){return this.source.completeSimple(...e)}streamDeferred(...e){return this.source.streamDeferred(...e)}fetchDeferred(...e){return this.source.fetchDeferred(...e)}cancelDeferred(...e){return this.source.cancelDeferred(...e)}generateImages(...e){return this.source.generateImages(...e)}classify(...e){return this.source.classify(...e)}setProvider(e){this.install(e)}deleteProvider(e){this.source.deleteProvider(e),this.wrapped.delete(e)}clearProviders(){this.source.clearProviders(),this.wrapped.clear()}wrap(e){return this.wrapped.get(e.id)??this.install(e)}install(e){if(this.wrapped.get(e.id)===e)return this.source.setProvider(e),e;let o=this.manager.wrapProvider(e);return this.wrapped.set(e.id,o),this.source.setProvider(o),o}}function jt(e){return`${Ki}${e}`}function As(e){return[{id:vh,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:RC,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:jt(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function JU(e){let o=Mh(e);if(!o)throw new t("\u4EE3\u7406\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof o.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(o.id))throw new t("\u4EE3\u7406\u914D\u7F6E ID \u65E0\u6548");let a;try{a=ti(String(o.address??""))}catch(f){throw new t(f instanceof Error?f.message:"\u4EE3\u7406\u5730\u5740\u65E0\u6548")}let u=Array.isArray(o.noProxy)?o.noProxy:[];if(!u.every((f)=>typeof f==="string"&&f.trim()))throw new t("\u76F4\u8FDE\u4F8B\u5916\u5FC5\u987B\u662F\u975E\u7A7A\u4E3B\u673A");let p=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return{id:o.id,name:typeof o.name==="string"&&o.name.trim()?o.name.trim():a.hostname,address:`${a.protocol}://${p}:${a.port}`,username:typeof o.username==="string"&&o.username?o.username:void 0,password:typeof o.password==="string"&&o.password?o.password:void 0,tls:o.tls==="insecure"?"insecure":"verify",noProxy:u.map((f)=>String(f).trim())}}function QU(e){if(e===void 0||e===null||e==="")return;if(typeof e!=="string")throw new t("\u4EE3\u7406\u7EBF\u8DEF ID \u65E0\u6548");return e}function Mh(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function XU(e,o){try{let a=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/^\./,"");return a===u||a.endsWith(`.${u}`)}catch{return!1}}import{join as Sg}from"path";import{existsSync as HC}from"fs";import{realpath as WC}from"fs/promises";import{dirname as zC,isAbsolute as fB,join as VC,relative as hB,resolve as Fh,sep as gB}from"path";import{existsSync as YU,watch as ZU}from"fs";import{readdir as eB,stat as tB}from"fs/promises";import{basename as Oh,dirname as rB,join as AC,resolve as nB}from"path";class _h{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,a,u=150){this.host=e;this.slots=o;this.watching=a;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let a=[],u=[];for(let g of[...new Set(e)]){let I;try{I=await eB(g)}catch(E){if(E instanceof Error&&"code"in E&&E.code==="ENOENT")continue;throw E}for(let E of I.sort()){let S=AC(g,E),k=(await tB(S)).isDirectory()?AC(S,"index.ts"):S;if(!k.endsWith(".ts")||k.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(k),path:k})}catch(A){let P=Oh(k)==="index.ts"?Oh(rB(k)):Oh(k,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let v={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};a.push({definition:v,path:k}),this.slots.set(P,{definition:v,path:k,enabled:!0,discoveryFailed:!0,error:A instanceof Error?A.message:String(A)})}}}let p=o.filter((g)=>![...u,...a].some((I)=>I.definition.id===g.definition.id)),f=[...p,...u],h=this.order(f.map(({definition:g})=>g));for(let g of h){let I=f.find((S)=>S.definition===g)?.path,E=p.some((S)=>S.definition===g);try{await this.host.install(g,I,E)}catch(S){this.slots.set(g.id,{definition:g,path:I,builtin:E,enabled:!0,error:S instanceof Error?S.message:String(S)})}}if(this.watching())for(let g of[...f,...a]){if(!YU(g.path))continue;let I=ZU(g.path,()=>{let E=g.definition.id,S=this.debounceTimers.get(E);if(S)clearTimeout(S);let k=setTimeout(()=>{this.debounceTimers.delete(E),this.host.reload(E).catch((A)=>{let P=this.slots.get(E);if(P)P.error=A instanceof Error?A.message:String(A)})},this.debounceMs);k.unref?.(),this.debounceTimers.set(E,k)});I.on("error",(E)=>{let S=this.slots.get(g.definition.id);if(S)S.error=E.message,this.host.changed()}),this.watchers.push(I)}}order(e,o=!1){let a=new Map;for(let g of e){if(this.validate(g),a.has(g.id)||!o&&this.slots.has(g.id))throw Error(`Duplicate plugin: ${g.id}`);a.set(g.id,g)}let u=[],p=new Set,f=new Set,h=(g)=>{if(f.has(g.id))return;if(p.has(g.id))throw Error(`Plugin dependency cycle: ${g.id}`);p.add(g.id);for(let I of g.deps??[]){let E=a.get(I);if(E)h(E);else if(!this.slots.has(I))throw Error(`Missing plugin dependency: ${I}`)}p.delete(g.id),f.add(g.id),u.push(g)};for(let g of e)h(g);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${nB(e)}?v=${++this.revision}`);if(!o.default)throw Error("Plugin module must export a default definition");return this.validate(o.default),o.default}}async function PC(e,o,a=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,p;try{return await Promise.race([a?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((f,h)=>{p=setTimeout(()=>{u.abort(),h(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as oB}from"async_hooks";import{isDeepStrictEqual as $C}from"util";var Oa=new oB;function Ys(){let e=Oa.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function Su(e){let o=structuredClone(e),a=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let p of Object.values(u))a(p)};return a(o),o}function CC(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let I of["seq","time","session_id","raw"])if(I in o)throw Error(`Entry replacement contains protected field: ${I}`);let a=JSON.parse(JSON.stringify(o,(I,E)=>{if(typeof E==="function"||typeof E==="symbol"||typeof E==="number"&&!Number.isFinite(E))throw Error("Entry replacement must contain JSON values");return E}));if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Entry replacement must serialize to a body");let u=a,p=[];switch(e.type){case"user":p.push("text","attachments");break;case"assistant":p.push("parts","error");break;case"tool_result":p.push("output","images");break;case"extension":p.push("payload","display");break;case"notice_pending":p.push("notice");break;case"run":if(e.state==="end")p.push("error");break;case"compaction":break}let f={...e};for(let I of new Set([...Object.keys(e),...Object.keys(u)])){if(!p.includes(I)&&!$C(f[I],u[I]))throw Error(`Entry replacement changed protected field: ${I}`);if(["seq","time","session_id","raw"].includes(I))throw Error(`Entry replacement contains protected field: ${I}`)}let h=(I)=>I===void 0||typeof I==="string",g=!0;switch(e.type){case"user":g=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((I)=>I&&typeof I.name==="string"&&typeof I.mimeType==="string"&&ao.includes(I.kind)&&typeof I.data==="string"));break;case"assistant":g=h(u.error)&&Array.isArray(u.parts)&&u.parts.every((I)=>I&&(["text","thinking"].includes(I.type)&&typeof I.text==="string"||I.type==="tool_call"&&typeof I.id==="string"&&typeof I.name==="string"&&("input"in I)));break;case"tool_result":g=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((I)=>I&&typeof I.mimeType==="string"&&typeof I.data==="string"));break;case"extension":{let I=u.display;g="payload"in u&&(I===void 0||I!==null&&typeof I==="object"&&("text"in I)&&typeof I.text==="string"&&(!("title"in I)||h(I.title)));break}case"notice_pending":{let E=["text"],S=f.notice,k=u.notice;if(g=!!k&&typeof k==="object"&&!Array.isArray(k),!g)break;let A=k;for(let P of new Set([...Object.keys(S),...Object.keys(A)]))if(E.includes(P)){if(typeof A[P]!=="string")g=!1}else if(!$C(S[P],A[P]))g=!1;break}case"run":g=h(u.error);break;case"compaction":break}if(!g)throw Error("Invalid entry replacement content");return a}function vC(e,o,a,u,p,f){let h=u;for(let g of a.generations)for(let I of g.hooks.get("entry.before_append")??[]){if(g.disabled)break;let E={phase:"before",violated:!1};try{let S=Oa.run(E,()=>{let k=Su(h),A=performance.now(),P=I(k,{sessionID:p,seq:f});if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")throw Promise.resolve(P).catch(()=>{}),Error("entry.before_append must be synchronous");let v=P===void 0?void 0:CC(h,P);if(E.violated)throw Error("entry.before_append attempted a database write");return{validated:v,slow:performance.now()-A>e}});if(S.validated&&JSON.stringify(S.validated)!==JSON.stringify(h))h=S.validated;if(S.slow)throw Error("entry.before_append exceeded budget");g.beforeFailures=0,g.failures=0}catch(S){g.failures=g.beforeFailures++,o(g,S)}}return h}function sB(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return Su(o);return structuredClone(o)}async function MC(e,o,a,u,p,f,h,g,I="end"){let E=f;for(let S of u){if(S.disabled)continue;let k=S.hooks.get(p)??[];for(let A of k){if(S.disabled)break;let P=S.hookOptions.get(A);if(p==="prompt.fragments"&&(P?.promptPosition??"end")!==I)continue;let v=p==="prompt.fragments"?JSON.stringify([h?.id,E]):void 0,M=v===void 0?void 0:S.promptCache.get(A)?.get(v);try{let J=sB(p,E),O=P?.timeoutMs,V=typeof O==="function"?O({runtime:e.runtime,session:h,connection:g}):O,j=await o((te)=>A(J,{runtime:e.runtime,session:h,connection:g,signal:te}),V);if(v!==void 0){let te=j===void 0?E:j;if(!Array.isArray(te)||te.some((L)=>typeof L!=="string"))throw Error("Prompt fragments must be strings");if(P?.promptMutable!==!0&&M&&JSON.stringify(M)!==JSON.stringify(te))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let se=S.promptCache.get(A)??new Map;se.set(v,[...te]),S.promptCache.set(A,se)}if(S.failures=0,j!==void 0&&p!=="entry.after_append")E=j}catch(J){if(M)E=structuredClone(M);if(a(S,J),P?.errorMode==="propagate")throw J}}}return E}class Jc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,a,u,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,a,u,p)}has(e,o){return this.generations.some((a)=>!a.disabled&&(a.hooks.get(e)??[]).some((u)=>o===void 0||(a.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...a)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...a)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((a)=>a(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let a of this.generations){if(a.disabled)continue;for(let u of a.historyResolvers){let p=u(e,o);if(p)return p}}}policy(e){return this.generations.findLast((o)=>!o.disabled&&o.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as iB}from"fs";import{dirname as aB,resolve as OC}from"path";var Lh=new WeakMap;function _C(e){return[...e].map((o)=>{let a=Boolean(o.path&&(Boolean(o.definition.webEntry)||iB(OC(aB(OC(o.path)),"web.tsx"))));if(o.current&&!Lh.has(o.current))Lh.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:a,webRevision:o.current?Lh.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class Nh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,a){this.host=e;this.deadline=o;this.fail=a}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,a){let u=this.host.pin(),p=(async()=>{try{let f=[];for(let h of u.generations){if(h.disabled)continue;for(let g of h.hooks.get(e)??[]){let I=h.hookOptions.get(g)?.timeoutMs,E=typeof I==="function"?I({runtime:this.host.runtime,session:o,connection:a}):I;f.push(this.deadline((S)=>g(o,{runtime:this.host.runtime,session:o,connection:a,signal:S}),E,!0).catch((S)=>this.fail(h,S)))}}await Promise.all(f)}finally{await u.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,o,a){let u=a===void 0?void 0:Su(a),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Oa.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,p),this.pending.add(p);let f=()=>{if(this.pending.delete(p),this.entryQueues.get(o)===p)this.entryQueues.delete(o)};p.then(f,f)}}function LC(e){return e.replace(/(?:(?:request[- ]?)?headers?)["']?\s*[=:][\s\S]*/gi,"[headers redacted]").replace(/\b(?:api[-_ ]?key|authorization|cookie|password|secret|access[-_ ]?token)\b[^\n]*/gi,"[redacted]").replace(/\bBearer\s+[^\s"',}]+/gi,"[redacted]").replace(/(?:authorization|[\w-]*api[-_]?key|password|secret|cookie|[\w-]*token|key)["']?\s*[=:][^\n]*/gi,"[redacted]").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi,"[address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[address]").replace(/\blocalhost(?::\d+)?\b/gi,"[address]").replace(/\b(?:sk|key)-[\w-]+/gi,"[redacted]").replace(/[\r\n\t]+/g," ").slice(0,300)}function uB(e){if(typeof e.prompt!=="string"||!e.prompt.trim())throw Error("Completion prompt must not be empty");if(e.system!==void 0&&typeof e.system!=="string")throw Error("Invalid completion system prompt");if(e.sessionID!==void 0&&typeof e.sessionID!=="string")throw Error("Invalid completion sessionID")}async function cB(e,o){let a=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!a)throw Error("Completion session not found");let u=o.model??a?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=Cn(e.options.models,u);if(!p&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!p){let f=(await e.models()).models.filter((g)=>g.available===!0),h=p?Mt(p):u;if(!f.some((g)=>g.id===h)){let g=f[0];if(g)p=Cn(e.options.models,g.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function NC(e,o){uB(o);let a=await cB(e,o),u=o.maxTokens??Math.min(a.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>a.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let p="",f=!1;try{let h=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],g=e.options.models.streamSimple(a,{messages:h},{maxTokens:u,signal:o.signal});for await(let I of g){if(o.signal?.aborted)throw Error("cancelled");if(I.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${LC(I.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(I.type==="text_delta")p+=I.delta;if(I.type==="done"){if(I.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(I.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${I.reason}\uFF09`);f=!0}}}catch(h){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${LC(h instanceof Error?h.message:String(h))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!f)throw Error("Model completion ended without a stop response; retry");return{text:p,model:Mt(a)}}var mB=["active","archived","all"];function qC(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function pB(e){let{projectID:o,children:a,archive:u,since:p}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(a!==void 0&&typeof a!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!mB.includes(u))throw Error("sessions archive must be active, archived or all");if(p!==void 0&&!Number.isFinite(p))throw Error("sessions since must be a finite timestamp in milliseconds")}function lB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function DC(e){function o(a,u={}){let{types:p,bodies:f}=u;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let h=qC(u.limit),g=u.after??0;if(!Number.isSafeInteger(g)||g<0)throw Error("sessions after must be a non-negative integer");let I=(e.get(a)?.entries(g,p,f!==!1)??[]).slice(0,h);return structuredClone(f===!1?I.map(lB):I)}return{list(a={}){pB(a);let u=a.limit===void 0?void 0:qC(a.limit),p=e.list(a.children??!1,{archive:a.archive}).filter((f)=>a.projectID===void 0||f.projectID===a.projectID).filter((f)=>a.since===void 0||f.created>=a.since);return structuredClone(u===void 0?p:p.slice(0,u))},get(a){return structuredClone(e.get(a)?.info())},entries:o}}async function FC(e,o,a,u,p,f){let h={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},g=e.runtime.store.db,I=new Map,E=!1,S=!0,k=()=>{if(!S||h.disposed)throw Error("Plugin registration scope is closed")},A=(O,V)=>{if(k(),!E){I.set(O,V);return}if(V===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,O);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,O,V)},P={get:(O)=>{k();let V=I.has(O)?I.get(O):g.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,O)?.value;return V==null?void 0:JSON.parse(V)},set:(O,V)=>{let j=JSON.stringify(V);if(j===void 0)throw Error("Plugin KV values must be JSON serializable");A(O,j)},delete:(O)=>A(O,null)},v=()=>{if(k(),E)throw Error("Register resources during setup only")},M=[...o.migrations??[]].sort((O,V)=>O.version-V.version),J=new Set;try{for(let O of M){if(!Number.isSafeInteger(O.version)||O.version<1||J.has(O.version))throw Error("Plugin migration versions must be unique positive integers");if(J.add(O.version),g.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,O.version))continue;g.transaction(()=>{if(O.sql!==void 0)g.run(O.sql);else O.up({...P,db:g});for(let[V,j]of I)if(j===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,j);g.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,O.version)})(),e.runtime.store.invalidateEntryCache(),I.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:DC(e.runtime),complete:(O)=>NC(e.runtime,O),kv:P,database:g,broadcast:(O)=>{e.runtime.emitEvent(O)},registerInputGate:(O)=>{v(),h.gates.push(O)},registerNoticeSource:(O,V)=>{if(v(),!O||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");h.noticeSources.set(O,{...V})},provide:(O,V)=>{if(v(),O.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(h.services.has(O.name))throw Error(`Duplicate plugin service: ${O.name}`);if(!O.validate(V))throw Error(`Invalid plugin service: ${O.name}`);h.services.set(O.name,V)},on:(O,V,j)=>{if(v(),(j?.promptPosition||j?.promptMutable)&&O!=="prompt.fragments")throw Error("promptPosition and promptMutable only apply to prompt.fragments");let te=h.hooks.get(O)??[];if(te.push(V),h.hooks.set(O,te),j)h.hookOptions.set(V,j)},registerHistoryResolver:(O)=>{v(),h.historyResolvers.push(O)},registerTool:(O,V)=>{if(v(),!O.name||["toolsearch","tool_search","tool_call"].includes(O.name.toLowerCase())||dB(e,p,o.id).has(O.name.toLowerCase())||h.tools.some((te)=>te.name.toLowerCase()===O.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${O.name}`);let j=a?"always":"defer";if(typeof V?.defer==="boolean")j=V.defer?"defer":"always";else if(V?.defer!==void 0)j=V.defer;h.tools.push({...O,defer:j,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:a})},registerRoute:(O)=>{if(v(),!(O.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>O.path===V||O.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(O.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(h.routes.some((V)=>V.path===O.path&&V.method===O.method))throw Error("Duplicate plugin route");h.routes.push(O)},registerWebSocket:(O)=>{if(v(),!O.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(h.websockets.some((V)=>V.path===O.path))throw Error("Duplicate plugin WebSocket route");h.websockets.push(O)},registerCommand:(O)=>{v(),h.commands.push(O)},registerWebContribution:(O)=>{v(),h.web.push(O)},registerToolPolicy:(O,V)=>{v(),h.policies.set(O,V)},appendExtension:(O,V)=>{if(Ys(),k(),!E)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(O,V)},onDeactivate:(O)=>{v(),h.deactivators.push(O)},onDispose:(O)=>{v(),h.disposers.push(O)}})),g.transaction(()=>{for(let[O,V]of I)if(V===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,O);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,O,V)})(),I.clear(),E=!0,h}catch(O){throw S=!1,await f(h),O}}function dB(e,o,a){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,f]of o){if(p===a)continue;for(let h of f.current?.tools??[])u.add(h.name.toLowerCase())}return u}class qh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function jC(e,o,a,u){for(let p of o){let f=p.current;if(!f||f.disabled||f.retired)continue;let h=f.websockets.find((g)=>g.path===u);if(!h)continue;return{connect:(g)=>{let I=!1;f.references++,f.connections.add(g);let E={send:(k)=>{if(I||f.retired||f.disabled)return;g.send(k)},close:(k,A)=>g.close(k,A)},S=async(k)=>{if(I||f.retired||f.disabled){g.close(1012,"Plugin unavailable");return}try{await a(k),f.failures=0}catch(A){if(f.failures++,f.error=A instanceof Error?A.message:String(A),g.close(1011,"Plugin callback failed"),f.failures>=e.failureThreshold){f.disabled=!0;for(let P of f.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>S(()=>h.open?.(E)),message:(k)=>S(()=>h.message(E,k)),close:async()=>{if(I)return;I=!0,f.connections.delete(g);try{await a(()=>h.close?.(E))}catch(k){f.error=k instanceof Error?k.message:String(k)}finally{f.references--,await e.collect(f)}}}}}}return}function Dh(e,o){let a=e.split("/"),u=new URL(o.url).pathname.split("/");if(a.length!==u.length)return;let p={};return a.every((h,g)=>{let I=u[g];if(I===void 0)return!1;if(!h.startsWith(":"))return I===h;try{p[h.slice(1)]=decodeURIComponent(I)}catch{return!1}return I.length>0})?p:void 0}async function UC(e,o,a,u,p){let f=e.pin();try{let h=f.generations.find((g)=>g.definition.id===a)?.commands.find((g)=>g.id===u);if(!h)throw new m("Plugin command is unavailable");return await o(()=>h.execute(p))}finally{await f.release()}}function BC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((p)=>p.method===o.method&&Dh(p.path,o)!==void 0))}finally{a.release()}}function GC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((p)=>p.public===!0&&p.method===o.method&&Dh(p.path,o)!==void 0))}finally{a.release()}}async function KC(e,o,a){let u=e.pin(),p=!0;try{for(let f of u.generations)for(let h of f.routes){if(h.method!==a.method)continue;let g=Dh(h.path,a);if(g){let I=await o(()=>h.handler(a,g),h.timeoutMs);if(!I)return;if(I.body&&I.body instanceof ReadableStream){p=!1;let E=!1,S=()=>{if(E)return;E=!0,u.release()},k=I.body.getReader(),A=new ReadableStream({async pull(P){try{let{done:v,value:M}=await k.read();if(v)P.close(),S();else P.enqueue(M)}catch(v){P.error(v),S()}},async cancel(P){try{await k.cancel(P)}finally{S()}}});return new Response(A,{status:I.status,statusText:I.statusText,headers:I.headers})}return I}}return}finally{if(p)await u.release()}}class jh{runtime;options;slots=new Map;retirement=new qh(this.deadline.bind(this));observers=new Nh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new fl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,o={}){this.runtime=e;this.options=o;if(o.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(o.beforeAppendBudgetMs)||o.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new _h(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new m(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let a=o.current.services.get(e.name);if(!e.validate(a))throw new m(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return a}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((a)=>a(e)))}noticeSource(e){return[...this.slots.values()].findLast((a)=>a.enabled&&a.current&&!a.current.disabled&&a.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let a=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==a)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let a of e)this.directories.add(Fh(a));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await WC(e),a=[...this.directories,VC(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>VC(u.directory,".basalt","plugins"))];for(let u of a){if(!HC(u))continue;let p=hB(await WC(u),o);if(p&&p!==".."&&!p.startsWith(`..${gB}`)&&!fB(p)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),a=await this.checkEntry(o);if(!a.ok)throw new tt(a.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((a)=>a.level==="error").map((a)=>({file:a.position?.file??null,line:a.position?.line??null,column:a.position?.column??null,message:a.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,a=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,a)})}async installDefinition(e,o,a=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:o,builtin:a,enabled:u?.enabled!==0};if(p.enabled)p.current=await this.stage(e,a);this.slots.set(e.id,p)}reload(e){return this.exclusive(async()=>{let o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let g=await this.checkEntry(o.path);if(!g.ok)throw new tt(g.errors)}let a=o.builtin&&!HC(o.path)?o.definition:await this.catalog.read(o.path);if(a.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((g)=>g.definition.id===e?a:g.definition),!0),p=await this.stage(a),f=o.current;o.definition=a,o.current=p,o.error=void 0,o.discoveryFailed=!1;let h=new Map(this.slots);this.slots.clear();for(let g of u){let I=h.get(g.id);if(I)this.slots.set(g.id,I)}if(f)await this.retirement.retire(f)}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}})}setEnabled(e,o){return this.exclusive(async()=>{let a=this.require(e);if(o===a.enabled&&(!o||a.current&&!a.current.disabled))return;if(!o){for(let h of this.slots.values())if(h.enabled&&h.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${h.definition.id}`)}let u=o&&a.discoveryFailed&&a.path?await this.catalog.read(a.path):a.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let p=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let f=a.current;if(a.definition=u,o)a.discoveryFailed=!1;if(a.enabled=o,a.current=p,a.error=void 0,f)await this.retirement.retire(f)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let a of e.deps??[])if(a===e.id||!this.slots.get(a)?.current||this.slots.get(a)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${a}`);return FC(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,a){this.observers.notify(e,o,a)}resolveHistory(e,o){for(let a of this.slots.values()){if(!a.enabled||!a.current||a.current.disabled)continue;for(let u of a.current.historyResolvers){let p=u(e,o);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Jc(this,e)}async invoke(e,o,a,u,p,f="end"){return MC(this,this.deadline.bind(this),this.fail.bind(this),e,o,a,u,p,f)}pinEntry(e){if(Oa.getStore()?.phase==="after")return;let o;for(let a of this.slots.values()){let u=a.current;if(!a.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Jc(this,o)}beforeEntry(e,o,a,u){return vC(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,a,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let a of e.connections)a.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,a){this.observers.finishEntry(e,o,a)}deadline(e,o=this.timeoutMs,a=!1){return PC(e,o,a)}appendExtension(e,o){return Ys(),new Promise((a)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),a(p)})}list(){return _C(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(a&&o.path)await this.webBuilder.build(a,zC(Fh(o.path)));return{ok:!0}}catch(o){if(o instanceof dl)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!a)return;return this.webBuilder.build(a,zC(Fh(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);return a?this.webBuilder.cache.get(a)?.css:void 0}command(e,o,a){return UC(this,this.deadline.bind(this),e,o,a)}hasRoute(e){return BC(this,e)}isPublicRoute(e){return GC(this,e)}route(e){return KC(this,this.deadline.bind(this),e)}websocket(e){return jC(this,this.slots.values(),this.deadline.bind(this),e)}collect(e){return this.retirement.collect(e)}async close(){this.catalog.close(),await this.serial,await this.idle(),this.closed=!0;for(let e of this.slots.values())if(e.current)await this.retirement.retire(e.current);await this.retirement.collectRetired()}}import{statSync as JC}from"fs";import{join as yB}from"path";var xB=500,IB=1000,EB=3600000,QC=5000,bB=2000,SB=3,wB=1073741824;class Uh{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;pauseQueue=Promise.resolve();constructor(e){this.options=e;if(this.indexPath=yB(e.dataDir,cs),this.features={...us(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,a=o?.backfill;if(!o||!a)return{...e,state:"backfilling"};if(a.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(a.total,a.done),indexed:a.done,state:a.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=JC(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=JC(this.options.store.path).size}catch{}return Math.max(wB,Math.round(e*0.6))}async setEnabled(e){if(this.closed||e===this.enabledFlag)return;if(this.enabledFlag=e,this.failure=void 0,this.restarts=0,e){if(this.clearTimer)clearInterval(this.clearTimer);if(this.clearTimer=void 0,this.usable)this.start();else this.idleMaintenance()}else await this.stopWorker(),this.idleMaintenance();this.pushStatus()}async rebuild(){if(!this.usable)return;await this.stopWorker(),go(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.pauseQueue.then(async()=>{let a=this.worker;if(!a)return e();Atomics.store(this.flags,Xe,1);try{a.postMessage({type:"pause"});let u=Date.now()+QC;while(Atomics.load(this.flags,Et)===0){if(this.worker!==a)throw Error("\u641C\u7D22\u7D22\u5F15\u5DF2\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6574\u7406");if(Date.now()>=u)throw Error("\u641C\u7D22\u7D22\u5F15\u6B63\u5FD9\uFF0C\u6682\u505C\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6574\u7406");await new Promise((p)=>setTimeout(p,10))}if(this.worker!==a)throw Error("\u641C\u7D22\u7D22\u5F15\u5DF2\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6574\u7406");return e()}finally{Atomics.store(this.flags,Xe,0),Atomics.notify(this.flags,Xe);let u=Date.now()+QC;while(this.worker===a&&Atomics.load(this.flags,Et)!==0){if(Date.now()>=u){await this.stopWorker();break}await new Promise((p)=>setTimeout(p,10))}}});return this.pauseQueue=o.then(()=>{},()=>{}),o}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=ds(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,Xe,0),Atomics.store(this.flags,Et,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,a=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),a&&this.restarts<SB&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.worker=void 0,this.stopping=(async()=>{Atomics.store(this.flags,Xe,0),Atomics.notify(this.flags,Xe);let o=new Promise((a)=>{this.stopped=a});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(bB)]),e.terminate(),this.stopped=void 0,this.closeReader(),this.resolveFlushes(),this.prune()})();try{await this.stopping}finally{this.stopping=void 0}}resolveFlushes(){for(let e of this.flushes.values())e();this.flushes.clear()}closeReader(){this.reader?.close(),this.reader=void 0}schedulePrune(){if(this.pruneTimer)return;let e=Math.max(0,xB-(performance.now()-this.lastPrune));this.pruneTimer=setTimeout(()=>{this.pruneTimer=void 0,this.prune()},e),this.pruneTimer.unref?.()}prune(){let e=this.engineStatus?.queueDone??0;if(e<=this.pruned)return;this.lastPrune=performance.now();try{this.options.store.db.query("DELETE FROM search_queue WHERE id <= ?").run(e),this.pruned=e}catch{}}idleMaintenance(){if(this.engineStatus=void 0,!this.enabledFlag)go(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),EB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch(e){let o=e instanceof Error?e.message:String(e);if(/closed|busy|locked/i.test(o))return;console.error("search queue cleanup failed:",e)}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,IB-(performance.now()-this.lastPush)),a=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),p=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(u)};if(o===0)a();else this.statusTimer=setTimeout(a,o),this.statusTimer.unref?.()}}import{closeSync as CB,existsSync as Ru,mkdirSync as vB,openSync as MB,readdirSync as o0,readFileSync as YC,readSync as OB,realpathSync as Bh,statSync as Rl,writeFileSync as Gh}from"fs";import{dirname as Tl,isAbsolute as Kh,relative as s0,resolve as _B}from"path";import{existsSync as Qc}from"fs";import{dirname as PB,join as Tu}from"path";import{mkdirSync as TB,writeFileSync as RB}from"fs";import{tmpdir as kB}from"os";import{join as XC}from"path";var Sl=2000,Pe=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function wu(e,o){return e.map((a,u)=>{let p=a.length>Sl?`${a.slice(0,Sl)}\u2026 [line truncated]`:a;return`${String(o+u).padStart(6)} ${p}`}).join(`
|
|
83
|
-
`)}function le(e,o){if(e.length<=o)return e;let a=Math.floor(o*0.4),u=o-a,p=e.length-a-u,f=e.slice(a,e.length-u).split(`
|
|
84
|
-
`).length-1;return`${e.slice(0,a)}
|
|
85
|
-
|
|
86
|
-
\u2026 [${p} characters, ~${f} lines omitted] \u2026
|
|
87
|
-
|
|
88
|
-
${e.slice(-u)}`}var AB=0;function nt(e,o,a){if(e.length<=o)return e;let u=le(e,o);try{let p=a?Zo(a):XC(kB(),"basalt-output");TB(p,{recursive:!0});let f=XC(p,`${process.pid}-${Date.now().toString(36)}-${AB++}.txt`);return RB(f,e),`${u}
|
|
89
|
-
[Full output saved to ${f}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var Er=120000,Tr=600000,_a;function $B(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function Pr(){if(_a!==void 0)return _a||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let p=Tu(u,"bash.exe");if($B(p))continue;if(Qc(p))return _a=p,p}for(let u of o){let p=Tu(u,"git.exe");if(Qc(p)){let f=PB(u),h=Tu(f,"bin","bash.exe");if(Qc(h))return _a=h,h;let g=Tu(f,"usr","bin","bash.exe");if(Qc(g))return _a=g,g}}let a=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?Tu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?Tu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of a)if(Qc(u))return _a=u,u;_a="";return}class to{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let a=0;while(a<o.length){if(o[a]<128){a+=1;continue}let p=o[a+1];if(p===void 0)break;let f=p>=48&&p<=57?4:2;if(a+f>o.length)break;a+=f}return this.gbkPending=o.slice(a),this.gbk.decode(o.subarray(0,a))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let a=new Uint8Array(this.sniffPending.length+e.length);if(a.set(this.sniffPending),a.set(e,this.sniffPending.length),a.length<2)return this.sniffPending=a,"";this.sniffPending=void 0;let u=a[0]===255&&a[1]===254,p=!1;for(let f=1;f<a.length;f+=2)if(a[f]===0){p=!0;break}this.isUtf16=u||p,o=a}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Nt(e,o){let a=process.platform==="win32",u=o??"auto";if(!a)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash"||u==="auto"){let p=Pr();if(p||u==="bash")return{argv:[p??"bash","-c",e],shellName:"bash",isWindows:!0}}return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}function Xo(e,o){let a=process.platform==="win32";return{...process.env,...Hi(e),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...a?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o?{[Object.keys(process.env).find((u)=>u.toLowerCase()==="path")??"PATH"]:o}:{}}}function Vt(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128)e.kill()}else process.kill(-e.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}async function Kt(e,o){let{argv:a,isWindows:u,shellName:p}=Nt(e,o.shell),f=await qe(e,o.signal,p);if(f)return{output:f,code:126,timedOut:!1};if(o.signal?.aborted)return{output:"[aborted before the command started]",code:null,timedOut:!1};let h=Bun.spawn(a,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!u,windowsHide:!0,env:Xo(o.cwd,o.extraPath)}),g=!1,I,E=()=>{try{Vt(h)}catch(re){I=re}},S=setTimeout(()=>{g=!0,E()},o.timeout);o.signal?.addEventListener("abort",E,{once:!0});let k=Pe*2,A="",P="",v=0,M=0,J=!1,O="",V=(re=!1)=>{let he=v-A.length-P.length,we=he>0?`${A}
|
|
90
|
-
\u2026 [${he} characters omitted] \u2026
|
|
91
|
-
${P}`:A+P;if(!re)return le(we,Pe);return nt(O.length===v?O:we,Pe,o.cwd)},j=()=>{let re=new to;return async(he)=>{for await(let We of he){let X=re.decode(We);if(v+=X.length,O.length<4000000)O+=X;if(A.length<k)A+=X;else P=(P+X).slice(-k);if(o.onOutput&&!J){let Y=performance.now();if(Y-M>=80){M=Y;try{o.onOutput(V())}catch{J=!0}}}}let we=re.flush();if(we){if(v+=we.length,O.length<4000000)O+=we;if(A.length<k)A+=we;else P=(P+we).slice(-k)}}},te=Promise.all([j()(h.stdout),j()(h.stderr)]),se=await h.exited;if(clearTimeout(S),o.signal?.removeEventListener("abort",E),await Promise.race([te.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))P+=`
|
|
92
|
-
[background processes are still running; their later output is not captured]`;if(I)P+=`
|
|
93
|
-
[failed to kill the process tree: ${String(I)}]`;return{output:V(!0),code:g?null:se,timedOut:g}}class Hh{seen=new Map;mark(e,o=Rl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Rl(e).mtimeMs!==o?"changed":void 0}}var ZC=2000,LB=500,NB=10485760,e0=67108864,wl=20,qB=6,DB=40000,FB=80000;function t0(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return}function i0(e,o,a=[],u){let p=(v)=>Kh(v)?v:_B(e,v),f=(v)=>{let M=s0(e,v);return M&&!M.startsWith("..")&&!Kh(M)?M:v},h=(v)=>{let M=v;while(!Ru(M)&&Tl(M)!==M)M=Tl(M);let J=Bh(M);if(a.some((O)=>Ru(O)&&n0(Bh(O),J))&&!n0(Bh(e),J))throw Error("External directories are read-only")},g=(v,M,J)=>{let O=p(v);if(!Ru(O))throw Error(`No such file or directory: ${O}${GB(O)}`);let V=Rl(O);if(V.isDirectory()){let Y=o0(O,{withFileTypes:!0}).map((He)=>He.isDirectory()?`${He.name}/`:He.name).sort(),xe=Y.slice(0,LB),Ve=Y.length-xe.length;return c(`${xe.join(`
|
|
94
|
-
`)}${Ve>0?`
|
|
95
|
-
\u2026 and ${Ve} more entries`:""}`||"(empty directory)").content}if(V.size>NB){let Y=Buffer.alloc(8192),xe=MB(O,"r"),Ve=0;try{Ve=OB(xe,Y,0,Y.length,0)}finally{CB(xe)}if(t0(Y.subarray(0,Ve)))throw Error(`${O} exceeds the 10 MB image limit (${V.size} bytes)`);if(V.size>e0)throw Error(`${O} is too large to read (${V.size} bytes, limit ${e0}); inspect it with head, tail or grep instead`)}let j=YC(O),te=t0(j);if(te)return o.mark(O),[{type:"text",text:`Read image ${f(O)} (${te}, ${V.size} bytes)`},{type:"image",data:j.toString("base64"),mimeType:te}];if(j.subarray(0,8192).includes(0))throw Error(`${O} looks like a binary file (${V.size} bytes)`);o.mark(O);let se=j.toString("utf8");if(!se)return c("(empty file)").content;let L=se.replace(/\r?\n$/,"").split(/\r?\n/),re=(M??1)-1;if(re>=L.length)throw Error(`offset ${M} is past the end of the file (${L.length} lines)`);let he=Math.min(L.length,re+(J??ZC)),we=0,We=re;while(We<he){let Y=L[We]?.length??0;if(We>re&&we+Y>DB)break;we+=Y,We++}let X=wu(L.slice(re,We),re+1);if(We<he)X+=`
|
|
96
|
-
|
|
97
|
-
(Showing lines ${re+1}-${We} of ${L.length} (truncated at line ${We} due to safety budget). Use offset/limit to read specific windows.)`;else if(re>0||We<L.length)X+=`
|
|
98
|
-
|
|
99
|
-
(Showing lines ${re+1}-${We} of ${L.length}. Use offset/limit to read other parts.)`;return c(X).content},I=T({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
|
|
100
|
-
- path may be absolute or relative to the working directory.
|
|
101
|
-
- By default reads up to ${ZC} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
|
|
102
|
-
- Lines longer than ${Sl} characters are truncated.
|
|
103
|
-
- Reading a directory lists its entries (directories end with /).
|
|
104
|
-
- Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
|
|
105
|
-
- To read several files at once, give paths instead of path (up to ${wl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
|
|
106
|
-
- Always read a file before editing or overwriting it.`,parameters:l({path:n(s({description:"File or directory path"})),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"})),paths:n(H(l({path:s({description:"File or directory path"}),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:wl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(v,M){let J=[...M.path!==void 0?[{path:M.path,offset:M.offset,limit:M.limit}]:[],...M.paths??[]];if(J.length===0)throw Error("Give path, or paths to read several files");if(J.length===1){let se=J[0];return{content:g(se.path,se.offset,se.limit),details:void 0}}if(J.length>wl)throw Error(`Read at most ${wl} paths per call`);let O=[],V=[],j=0,te=(se)=>{let L=O.at(-1);if(se.type==="text"&&L?.type==="text")L.text+=`
|
|
107
|
-
|
|
108
|
-
${se.text}`;else O.push(se)};for(let se of J){let L=`==> ${f(p(se.path))} <==`;if(j>=FB){te({type:"text",text:`${L}
|
|
109
|
-
(Skipped due to total read safety budget; read in separate calls)`});continue}try{let re=g(se.path,se.offset,se.limit);for(let he=0;he<re.length;he++){let we=re[he];if(!we)continue;if(we.type==="text")j+=we.text.length,te(he===0?{...we,text:`${L}
|
|
110
|
-
${we.text}`}:we);else te(we)}}catch(re){let he=re instanceof Error?re.message:String(re);V.push(he),te({type:"text",text:`${L}
|
|
111
|
-
Error: ${he}`})}}if(V.length===J.length)throw Error(V.join(`
|
|
112
|
-
`));return{content:O,details:void 0}}}),E=async(v,M,J,O)=>{let V=O?.update,j=await Kt(v,{cwd:e,timeout:120000,signal:J,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:V?(he)=>V(c(`${O.prefix}
|
|
113
|
-
|
|
114
|
-
$ ${v}
|
|
115
|
-
${he.trimEnd()}`)):void 0}),te=j.output.trimEnd()||"(no output)",se=j.timedOut?"killed after 120s timeout":j.code===0?"exit code 0":`exit code ${j.code}`,L=j.timedOut||j.code!==0,re=L?`
|
|
116
|
-
${M}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
|
|
117
|
-
|
|
118
|
-
$ ${v}
|
|
119
|
-
${te}
|
|
120
|
-
[${se}]${re}`,failed:L}},S=(v,M=!1)=>{let J=o.check(v);if(J==="changed")return`Note: ${f(v)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(J==="unread"&&M)return`Note: ${f(v)} existed and had not been read; it was replaced whole.`;return},k=T({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
|
|
121
|
-
- An existing file is replaced whole, including changes made since you last read it.
|
|
122
|
-
- Prefer the edit tool for changing existing files; use write for new files or full rewrites.
|
|
123
|
-
- then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
|
|
124
|
-
- Do not create documentation or README files unless asked.`,parameters:l({path:s({description:"File path"}),content:s({description:"The full file content"}),then_run:n(s({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(v,M,J,O){let V=p(M.path);h(V);let j=Ru(V),te;if(j){if(Rl(V).isDirectory())throw Error(`${V} is a directory`);te=S(V,!0)}vB(Tl(V),{recursive:!0}),Gh(V,M.content),o.mark(V);let se=M.content?M.content.split(`
|
|
125
|
-
`).length:0,L=`${j?"Overwrote":"Created"} ${f(V)} (${se} lines)${te?`
|
|
126
|
-
${te}`:""}`;if(M.then_run){let re=await E(M.then_run,`${f(V)} was written as given`,J,{prefix:L,update:O});if(L+=re.out,re.failed)return{...c(L),isError:!0}}return c(L)}}),A=(v,M,J,O)=>{let V=p(v);if(!Ru(V))throw Error(`File not found: ${V} (use write to create it)`);h(V);let j=S(V),te=YC(V,"utf8"),se=te,L=se.includes(`\r
|
|
127
|
-
`),re=[],he=[],we=0,We=0;return M.forEach((X,Y)=>{let xe=O?`edits[${J+Y}]: `:"";try{if(X.old_string===X.new_string)throw Error(`${xe}old_string and new_string are identical`);if(!X.old_string)throw Error(`${xe}old_string is empty (use write to create or replace a whole file)`);let Ve=L&&!X.old_string.includes(`\r
|
|
128
|
-
`),He=Ve?X.old_string.replace(/\n/g,`\r
|
|
129
|
-
`):X.old_string,ar=Ve?X.new_string.replace(/\n/g,`\r
|
|
130
|
-
`):X.new_string,ke=jB(se,He).map(($t)=>[$t,$t+He.length]);if(ke.length===0)ke=UB(se,He);if(ke.length===0)throw Error(`${xe}old_string not found in ${f(V)}; read the relevant lines and copy the exact text.${BB(se,He)}`);if(ke.length>1&&!X.replace_all){let $t=ke.map(([at])=>r0(se,at)).join(", ");throw Error(`${xe}old_string occurs ${ke.length} times (lines ${$t}); add surrounding lines to make it unique, or set replace_all.`)}let Me=r0(se,ke[0][0]),Wt=X.replace_all?ke:[ke[0]],ht="",Ft=0;for(let[$t,at]of Wt)ht+=se.slice(Ft,$t)+ar,Ft=at;se=ht+se.slice(Ft),we++,We+=Wt.length;let xr=se.split(/\r?\n/),fr=Me+ar.split(/\r?\n/).length-1,Zt=Math.max(1,Me-1),st=Math.min(xr.length,fr+1);if(st-Zt+1<=qB+2)re.push(wu(xr.slice(Zt-1,st),Zt));else re.push(`${wu(xr.slice(Zt-1,Me+1),Zt)}
|
|
131
|
-
\u2026 (${fr-Me-3} lines as given)
|
|
132
|
-
${wu(xr.slice(fr-2,st),fr-1)}`)}catch(Ve){he.push(Ve instanceof Error?Ve.message:String(Ve))}}),{path:V,original:te,content:se,echoes:re,applied:we,total:We,count:M.length,note:j,failed:he}},P=T({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
|
|
133
|
-
- No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
|
|
134
|
-
- For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
|
|
135
|
-
- Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
|
|
136
|
-
- Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
|
|
137
|
-
- To create a file use write; to delete or move files use bash.
|
|
138
|
-
- then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
|
|
139
|
-
- Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(s({description:"File path (the default for edits items without their own path)"})),old_string:n(s({description:"The exact text to replace (only when edits is absent)"})),new_string:n(s({description:"The replacement text (only when edits is absent)"})),replace_all:n(D({description:"Replace every occurrence (default false)"})),edits:n(H(l({path:n(s({description:"The file of this replacement, when it is not path"})),old_string:s({description:"The exact text to replace"}),new_string:s({description:"The replacement text"}),replace_all:n(D({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(s({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(v,M,J,O){let V=M.edits&&M.edits.length>0?M.edits.map((X)=>({path:X.path??M.path,step:X})):M.old_string!==void 0&&M.new_string!==void 0?[{path:M.path,step:{old_string:M.old_string,new_string:M.new_string,replace_all:M.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let j=V.length>1,te=new Map;V.forEach((X,Y)=>{if(!X.path)throw Error(`${j?`edits[${Y}]: `:""}path is required`);let xe=p(X.path),Ve=te.get(xe)??{raw:X.path,steps:[],offset:Y};Ve.steps.push(X.step),te.set(xe,Ve)});let se=[],L=[];for(let X of te.values())try{let Y=A(X.raw,X.steps,X.offset,j);if(Y.applied>0)se.push(Y);L.push(...Y.failed)}catch(Y){let xe=Y instanceof Error?Y.message:String(Y);L.push(`${j?`edits[${X.offset}]: `:""}${xe}`)}if(se.length===0)throw Error(L.join(`
|
|
140
|
-
`));let re=[];try{for(let X of se)Gh(X.path,X.content),re.push(X)}catch(X){for(let Y of re)Gh(Y.path,Y.original);throw X}for(let X of se)o.mark(X.path);let we=se.map((X)=>{let Y=X.total===1?"1 occurrence":`${X.total} occurrences`,xe=X.note?`
|
|
141
|
-
${X.note}`:"";if(!j)return`Edited ${f(X.path)} (${Y}).${xe}
|
|
142
|
-
${X.echoes[0]}`;let Ve=X.failed.length>0?`, ${X.failed.length} failed`:"";return`Edited ${f(X.path)} (${X.applied} edits${Ve}, ${Y}). Regions are shown as they were right after each edit; later edits may shift line numbers.${xe}
|
|
143
|
-
${X.echoes.map((He,ar)=>`--- edit ${ar+1}
|
|
144
|
-
${He}`).join(`
|
|
145
|
-
`)}`}).join(`
|
|
146
|
-
|
|
147
|
-
`),We=!1;if(M.then_run){let X=await E(M.then_run,"The edits above were applied",J,{prefix:we,update:O});if(we+=X.out,X.failed)We=!0}if(L.length>0)we+=`
|
|
148
|
-
|
|
149
|
-
${L.length===1?"1 edit":`${L.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
|
|
150
|
-
- ${L.join(`
|
|
151
|
-
- `)}`,We=!0;return We?{...c(we),isError:!0}:c(we)}});return[ve(I,"cat","view","read_file","view_file","open_file","open"),ve(k,"write_file","create_file","new_file","save_file"),ve(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function jB(e,o){let a=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))a.push(u);return a}function r0(e,o){let a=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)a++;return a}function UB(e,o){let a=o.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),u=[],p=e.split(`
|
|
152
|
-
`),f=0;for(let I of p)u.push(f),f+=I.length+1;let h=p.map((I)=>I.replace(/\r$/,"").trimEnd()),g=[];for(let I=0;I+a.length<=h.length;I++)if(a.every((E,S)=>h[I+S]===E)){let E=I+a.length-1,S=u[E]+p[E].replace(/\r$/,"").length,k=o.endsWith(`
|
|
153
|
-
`)&&S<e.length?e[S]==="\r"?2:1:0;g.push([u[I],S+k]),I+=a.length-1}return g}function BB(e,o){let a=(g)=>g.replace(/\s+/g," ").trim(),u=a(o);if(!u)return"";let p=e.split(/\r?\n/),f=o.split(/\r?\n/).length;for(let g=0;g+f<=p.length;g++)if(a(p.slice(g,g+f).join(`
|
|
154
|
-
`))===u)return` A match ignoring whitespace exists at line ${g+1}; copy the exact indentation and line breaks from the read output:
|
|
155
|
-
${le(wu(p.slice(g,g+f),g+1),4000)}`;let h=o.split(/\r?\n/).find((g)=>g.trim())?.trim();if(h){let g=p.findIndex((I)=>I.includes(h));if(g!==-1)return` Its first line appears at line ${g+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function GB(e){let o=Tl(e);if(!Ru(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let p=o0(o).filter((f)=>{let h=f.toLowerCase().replace(/\.[^.]*$/,"");return h&&(h.includes(u)||u.includes(h))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function n0(e,o){let a=s0(e,o);return a===""||!a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&a!==".."&&!Kh(a)}var Wh=20,zh=80,KB=5,HB=(e)=>e!==void 0&&e>0?e:void 0;function a0(e,o){let a=Zn(e,o)??eo(e,o);if(!a)throw Error(`No user message with seq ${o}`);return a}function kl(e,o){let a=(h)=>{if(o)return o(h);if(h.source&&h.source!=="self"||h.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(h)=>{let g=a(h),I=HB(h.seq);return{scope:g,seq:I,runs:()=>rt(g.records),reference:`session_id=${g.sessionID}`,both:I!==void 0&&h.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
156
|
-
`:""}},p=T({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
|
|
157
|
-
- Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
|
|
158
|
-
- Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),pattern:s({minLength:1,description:"Text to search for"}),also:n(H(s({minLength:1}),{maxItems:KB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(s({description:"Only search this chunk"})),seq:n(x({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(D({description:"Default false"})),head_limit:n(x({minimum:1,maximum:Wh,description:`Hits to return (default ${Wh})`})),offset:n(x({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(h,g){let{scope:I,seq:E,runs:S,reference:k,both:A}=u(g),P;if(E!==void 0)P=[a0(I.records,E)];else{let re=S(),he=g.chunk_id?re.filter((we)=>we.id===g.chunk_id):re;if(g.chunk_id&&!he.length)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);P=he.map(Ar)}let v=(re)=>g.case_sensitive?re:re.toLowerCase(),M=[g.pattern,...(g.also??[]).filter(Boolean)].map(v),J=g.head_limit??Wh,O=g.offset??0,V=[],j=new Map,te=0;for(let re of P)re.forEach((he,we)=>{let We=v(he.text);if(!M.every((Y)=>We.includes(Y)))return;if(j.set(he.chunk,(j.get(he.chunk)??0)+1),te++,te<=O||V.length>=J)return;let X=re.slice(Math.max(0,we-2),we+3);V.push(`${k} chunk ${he.chunk} line ${he.line}:
|
|
159
|
-
${fn(X," ")}`)});if(!te)return c(`${A}No matches`);if(!V.length)return c(`${A}No matches at offset ${O} (total ${te})`);let se=te-O-V.length,L=j.size>1?` (all matches by chunk: ${[...j].map(([re,he])=>`${re} ${he}`).join(", ")})`:"";return c(`${A}${V.join(`
|
|
160
|
-
|
|
161
|
-
`)}${se>0?`
|
|
162
|
-
|
|
163
|
-
\u2026 ${se} more matches${L}; continue with offset=${O+V.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),f=T({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),chunk_id:n(s({description:"Chunk to read"})),seq:n(x({description:"User message to read (from a user-text-reference)"})),offset:n(x({minimum:0,description:"First line (default 0)"})),limit:n(x({minimum:1,maximum:zh,description:`Lines to return (default ${zh})`}))}),async execute(h,g){let{scope:I,seq:E,runs:S,reference:k,both:A}=u(g),P;if(E!==void 0)P=a0(I.records,E);else if(g.chunk_id){let O=S().find((V)=>V.id===g.chunk_id);if(!O)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);P=Ar(O)}else{let O=S().map((V)=>`${k} ${V.id} (${V.status}, ${Ar(V).length} lines)`);return c(O.length?`Pass chunk_id or seq. Chunks in this session:
|
|
164
|
-
${O.join(`
|
|
165
|
-
`)}`:"This session has no history yet")}let v=g.offset??0,M=P.slice(v,v+(g.limit??zh));if(!M.length)return c(`No lines at offset ${v} (total ${P.length})`);let J=P.length-v-M.length;return c(`${A}${k} ${E!==void 0?`seq=${E}`:g.chunk_id}
|
|
166
|
-
${fn(M)}${J>0?`
|
|
167
|
-
|
|
168
|
-
\u2026 ${J} more lines; continue with offset=${v+M.length}`:""}`)}});return[p,f]}import{existsSync as WB,statSync as u0}from"fs";import{isAbsolute as c0,relative as zB,resolve as m0}from"path";var Al=200,VB=30000,Pl=Bun.which("rg");async function Vh(e,o,a){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:a,windowsHide:!0}),[p,f,h]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(h>1)throw Error(f.trim()||`${e[0]} exited with ${h}`);return p}function p0(e){let o=(f)=>f?c0(f)?f:m0(e,f):e,a=(f)=>{let h=zB(e,f);return h&&!h.startsWith("..")&&!c0(h)?h:f},u=T({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
|
|
169
|
-
- Respects .gitignore and skips .git. Use it instead of find or ls -R.
|
|
170
|
-
- To search file contents, use grep.`,parameters:l({pattern:s({description:"Glob pattern, matched relative to path"}),path:n(s({description:"Directory to search (default: working directory)"}))}),async execute(f,h,g){let I=o(h.path),E=!1;try{E=u0(I).isDirectory()}catch{}if(!E)throw Error(`Directory not found: ${a(I)}`);let S;if(Pl)S=(await Vh([Pl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",h.pattern],I,g)).split(`
|
|
171
|
-
`).filter(Boolean);else{S=[];for await(let v of new Bun.Glob(h.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(v))S.push(v)}if(!S.length)return c("No files found");let k=S.map((v)=>{let M=m0(I,v);try{return{path:M,time:u0(M).mtimeMs}}catch{return{path:M,time:0}}});k.sort((v,M)=>M.time-v.time);let A=k.slice(0,Al).map((v)=>a(v.path)),P=S.length-A.length;return c(`${A.join(`
|
|
172
|
-
`)}${P>0?`
|
|
173
|
-
\u2026 ${P} more files; narrow the pattern`:""}`)}}),p=T({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
|
|
174
|
-
- output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
|
|
175
|
-
- Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
|
|
176
|
-
- Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
|
|
177
|
-
- Use this instead of running grep or rg through bash.`,parameters:l({pattern:s({description:"Regular expression"}),path:n(s({description:"File or directory to search (default: working directory)"})),glob:n(s({description:"Only search files matching this glob"})),output:n(y([i("files"),i("content"),i("count")],{description:"Output mode (default files)"})),ignore_case:n(D()),context:n(x({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(f,h,g){let I=o(h.path);if(!WB(I))throw Error(`Path not found: ${a(I)}`);let E=h.output??"files",S;if(Pl){let P=[Pl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(h.ignore_case)P.push("-i");if(h.glob)P.push("--glob",h.glob);if(E==="files")P.push("-l");else if(E==="count")P.push("-c");else if(P.push("-n","--no-heading"),h.context)P.push("-C",String(h.context));P.push("--",h.pattern,I),S=await Vh(P,e,g)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(h.ignore_case)P.push("-i");if(h.glob)P.push(`--include=${h.glob}`);if(E==="files")P.push("-l");else if(E==="count")P.push("-c");else if(P.push("-n"),h.context)P.push(`-C${h.context}`);P.push("--",h.pattern,I),S=await Vh(P,e,g)}let k=`${e}/`,A=S.split(`
|
|
178
|
-
`).filter(Boolean).map((P)=>P.startsWith(k)?P.slice(k.length):P).filter((P)=>E!=="count"||!P.endsWith(":0"));if(!A.length)return c("No matches");if(E==="files"&&A.length>Al)return c(`${A.slice(0,Al).join(`
|
|
179
|
-
`)}
|
|
180
|
-
\u2026 ${A.length-Al} more files; narrow the search`);return c(nt(A.join(`
|
|
181
|
-
`),VB,e))}});return[ve(u,"find","find_files","list_files","file_search","ls","list","list_dir"),ve(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function l0(e){return ve(T({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
|
|
182
|
-
Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
|
|
183
|
-
- Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
|
|
184
|
-
- Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
|
|
185
|
-
- Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:H(l({content:s({minLength:1,description:"What to do, in imperative form"}),status:y(ns.map((o)=>i(o)))}))}),async execute(o,a){let u=a.todos.map((h)=>({content:h.content,status:h.status}));e(u);let p=u.filter((h)=>h.status==="completed").length,f=u.find((h)=>h.status==="in_progress");return c(`Todo list updated (${p}/${u.length} completed${f?`; in progress: ${f.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function d0(e){let o=de(e);return{target:o,hard:o,index:o}}class $l{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},a){this.records=e;this.cwd=o;if(a)this.defaultPolicy=new hn(e,a,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??d0(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??de(e)}prepare(e,o,a,u,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,a,u);let f=e.reduce((E,S)=>E+G(S),0)+Lt(o),h=Math.max(0,de(a)*this.recoveryRatio-f),g=Ce(u??this.records(),a,d0(a),{cwd:this.cwd()}).messages,I=g.reduce((E,S)=>E+G(S),0);if(p&&I>h)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(I>h&&g.length>1){let E=g.shift();if(E)I-=G(E);while(g[0]?.role==="toolResult"){let S=g.shift();if(S)I-=G(S)}}if(I>h){let E=g.at(-1),S=E&&"content"in E&&typeof E.content==="string"?E.content:"[Context omitted: use history tools to retrieve earlier messages.]";g.length=0;let k=S;while(k&&G({role:"user",content:k,timestamp:0})>h)k=k.slice(Math.ceil(k.length/2));if(k)g.push({role:"user",content:k,timestamp:0});I=g.reduce((A,P)=>A+G(P),0)}return this.lastMessageCount=g.length,{messages:[...e,...g],estimate:f+I}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as Qh,readFileSync as JB}from"fs";import{homedir as QB}from"os";import{dirname as f0,join as Xh,resolve as XB}from"path";var YB=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
|
|
186
|
-
|
|
187
|
-
# How to work
|
|
188
|
-
|
|
189
|
-
- Complete the task end to end. Keep going until the user's request is fully resolved before ending your turn: investigate, make the change, verify it. Do not stop halfway to report a plan or ask "should I continue?" when the next step is clear.
|
|
190
|
-
- Ask the user only when you are genuinely blocked: the request is ambiguous in a way that changes the outcome, or the action is destructive or irreversible. Otherwise make a reasonable choice, state the assumption briefly, and proceed.
|
|
191
|
-
- If the user only asks a question or asks for a plan or review, answer it; do not start changing files. For a review, lead with findings: bugs, risks, behavior regressions and missing tests, ordered by severity with file:line. Keep any summary short and after the findings.
|
|
192
|
-
- Do not use the todo tool for a single deliverable, even a complex one (implementing a feature, fixing a bug, writing a module and its tests): work through it directly with a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later. Never make reading, environment checks or the final summary into items, and update it only together with your next action, never as a turn of its own.
|
|
193
|
-
|
|
194
|
-
# Making changes
|
|
195
|
-
|
|
196
|
-
- Investigate before changing anything. Find the relevant code with grep/glob, read it, and understand how it is used. Edit from what you have actually seen: a read, or grep output with enough context to copy the text exactly.
|
|
197
|
-
- Verify unfamiliar technical entities instead of recalling them. When a task involves a library, API, tool or version you do not confidently recognize, check the project first: package manifests and lockfiles, \`--version\`, or the installed sources. A fluent answer built on an outdated memory looks right and is wrong. Never guess URLs; use only ones the user or the project gave you.
|
|
198
|
-
- Follow the conventions of the existing code: style, naming, structure, libraries, error handling, comment density, test layout. Before using a library, confirm the project already depends on it.
|
|
199
|
-
- Fix the root cause, not the symptom. Keep changes minimal and focused on the task; do not refactor, rename or "clean up" unrelated code, and do not add features that were not requested. Between two correct approaches, prefer the smaller one. Do not add backward-compatibility code unless something concrete needs it (persisted data, shipped behavior, external consumers, an explicit requirement).
|
|
200
|
-
- Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
|
|
201
|
-
- Do not add comments that narrate the change ("added this", "fixed bug"). Comment only where the code is not self-explanatory, in the style of the surrounding code.
|
|
202
|
-
|
|
203
|
-
# Verifying
|
|
204
|
-
|
|
205
|
-
- Verify behaviour the way the user would see it. When asked to test a feature, or after a change with user-visible effects, run the real thing first: start the app or server with bash background=true, exercise the changed path (curl an endpoint, run the CLI with real input, or drive a web UI with the browser tools: open, act, then browser_screenshot and look at the image), and confirm the result matches the requirement. Unit tests complement this; they do not replace it, and "the tests pass" is not evidence the feature works.
|
|
206
|
-
- For code with no runnable surface (a library, a refactor, types, build config), or when the app cannot be started here, run the most specific tests, type checker, linter or build instead \u2014 find how in the project's README, package scripts, Makefile or CI config \u2014 and say what you could not exercise.
|
|
207
|
-
- Once the change is verified, stop: re-verify only after new changes, failures or a concrete unresolved concern. Do not re-run a check that already passed when nothing it covers has changed. Kill servers and close pages you started.
|
|
208
|
-
- Do not re-read a file after your own edit or re-check mkdir/delete/move results: an edit result already shows the new content, and a failing call reports an error. Re-read only if someone else changed the file.
|
|
209
|
-
- When a step fails, read the error and diagnose why before retrying. Do not loop on the same failing approach; after two failed attempts, step back and reconsider. If a tool call is blocked, do not retry it unchanged; follow the stated reason or ask the user.
|
|
210
|
-
|
|
211
|
-
# Tools
|
|
212
|
-
|
|
213
|
-
- Tool calls are the only way to act; describing an action does not perform it.
|
|
214
|
-
- Use the dedicated tools for files: read to view (paths reads several files in one call), edit for replacements (give edits for several changes, even across files), write to create or rewrite a file, grep to search contents, glob to find files. A quick read-only look (ls, cat, sed -n) may share a bash command with other work, such as listing a directory while checking tool versions; to only view or edit a file, use read and edit.
|
|
215
|
-
- Create files you will keep or edit later with write, passing then_run to run them or their tests in the same step. A file written by a bash heredoc has not been read through the tools, so a later edit of it costs an extra step; a heredoc is fine for a throwaway script that the same command runs.
|
|
216
|
-
- For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
|
|
217
|
-
- In bash, search with rg / rg --files when it exists (much faster than grep/find). Do not join commands with echo or printf separators such as an echo '====' line; the output gets noisy. Do not use python or other scripts just to print or edit file contents when read, edit will do. Backticks and $() inside a command still execute, so escape text carefully.
|
|
218
|
-
- Put every tool call you already know into one response. Independent reads and searches run in parallel; calls that change things (edit, write, bash) run one after another in the order you give them, so you can edit a file and run its tests in the same response. Put all replacements of one logical change (for example an import, a helper and its call sites, plus the matching test) into one edit call's edits and pass then_run with the test command, instead of one edit per spot followed by a separate test run. Pass then_run to write as well. When probing behaviour, batch the checks into one script instead of one command each.
|
|
219
|
-
- Use bash for builds, tests, git, package managers and running programs. Each bash call starts in the project directory; use absolute or project-relative paths and chain dependent steps with &&.
|
|
220
|
-
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished, including dev servers you start to verify a change. Do not busy-wait or poll repeatedly.
|
|
221
|
-
|
|
222
|
-
# Honesty
|
|
223
|
-
|
|
224
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
225
|
-
- Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
|
|
226
|
-
- When the user asks you to run something, run it, even when you can predict the result.
|
|
227
|
-
- If a step failed, was skipped or could not be verified, say which one and why.
|
|
228
|
-
|
|
229
|
-
# Safety
|
|
230
|
-
|
|
231
|
-
- Do not run destructive or irreversible commands (rm -rf on broad paths, git reset --hard, git push --force, dropping databases, killing unrelated processes) unless the user explicitly asked for exactly that.
|
|
232
|
-
- Never commit, push, create branches or rewrite git history unless the user asks. If asked to commit, write a concise message that explains why, matching the repository's existing style.
|
|
233
|
-
- Do not revert or overwrite changes you did not make; the user may be editing files at the same time. If a file changed unexpectedly, read it again and work with the new content.
|
|
234
|
-
- Never print, log or commit secrets such as API keys, tokens or passwords.
|
|
235
|
-
|
|
236
|
-
# Communication
|
|
237
|
-
|
|
238
|
-
- Reply in the same language the user writes in.
|
|
239
|
-
- Be concise and direct. No filler, no flattery, no restating the request. Do not narrate every tool call: a short sentence before a batch of related actions, and in a long run a brief progress note every few calls, is enough.
|
|
240
|
-
- Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
|
|
241
|
-
- Do not use emojis unless the user does or asks for them.
|
|
242
|
-
- When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
|
|
243
|
-
- Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,ZB=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
|
|
244
|
-
|
|
245
|
-
# Tools
|
|
246
|
-
|
|
247
|
-
- Use read to view files, edit to change them and write to create them; use grep/glob to search contents and find files in the working directory.
|
|
248
|
-
- For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
|
|
249
|
-
- Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
|
|
250
|
-
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
|
|
251
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
252
|
-
|
|
253
|
-
# Communication
|
|
254
|
-
|
|
255
|
-
- Reply in the same language the user writes in.
|
|
256
|
-
- Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
|
|
257
|
-
- Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,eG=["AGENTS.md","CLAUDE.md"],tG=20000;function h0(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?YB:ZB}],a=[];if(e.globalInstructions?.trim())a.push(Jh("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of rG(e.project.directory))a.push(Jh(u.path,u.content));if(e.project.instructions.trim())a.push(Jh(`Project "${e.project.name}" instructions`,e.project.instructions))}if(a.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
|
|
258
|
-
|
|
259
|
-
# Instructions from the user and project
|
|
260
|
-
|
|
261
|
-
The following instructions were written by the user or the project maintainers. Follow them; they override the defaults above when they conflict. More specific (deeper directory) instructions take precedence over general ones.
|
|
262
|
-
|
|
263
|
-
${a.join(`
|
|
264
|
-
|
|
265
|
-
`)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
|
|
266
|
-
|
|
267
|
-
${nG(e)}`}),o}function Jh(e,o){return`<instructions source="${e}">
|
|
268
|
-
${le(o.trim(),tG)}
|
|
269
|
-
</instructions>`}function rG(e){let o=[],a=e;for(let u=0;u<20;u++){for(let f of eG){let h=Xh(a,f);if(Qh(h))try{o.unshift({path:h,content:JB(h,"utf8")});break}catch(g){let I=g instanceof Error?g.message:String(g);o.unshift({path:h,content:`(This instruction file could not be read: ${I})`})}}if(Qh(Xh(a,".git"))||a===QB())break;let p=f0(a);if(p===a)break;a=p}return o}function nG(e){let o=e.now??new Date,a=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:f}=Nt("",e.shell),h=[`Working directory: ${p}`,`Shell: ${f}`,`Date: ${a} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)h.push(e.git??"Git: not a git repository");return`<environment>
|
|
270
|
-
${h.join(`
|
|
271
|
-
`)}
|
|
272
|
-
</environment>`}function oG(e){let o=XB(e);while(!0){if(Qh(Xh(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let a=f0(o);if(a===o)return!1;o=a}}async function g0(e,o){if(o?.aborted||oG(e))return;let a=async(...I)=>{try{let E=Bun.spawn(["git",...I],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[S,k]=await Promise.all([new Response(E.stdout).text(),E.exited]);return k===0?S.trim():void 0}catch{return}},u=await a("rev-parse","--abbrev-ref","HEAD");if(u===void 0)return;let[p="",f=""]=await Promise.all([a("status","--short"),a("log","--oneline","-5")]),h=p?p.split(`
|
|
273
|
-
`):[],g=h.length>30?[...h.slice(0,30),`\u2026 ${h.length-30} more`]:h;return[`Git branch: ${u}`,`Git status at session start:${g.length?`
|
|
274
|
-
${g.join(`
|
|
275
|
-
`)}`:" clean"}`,f?`Recent commits:
|
|
276
|
-
${f}`:"Recent commits: none"].join(`
|
|
277
|
-
`)}function Qt(e){let a=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?kl(e.records,e.history):[],u=e.directory??process.cwd();return[...i0(u,new Hh,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...p0(u),l0(e.onTodos),...a]}class ea{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!is.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!os.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let a=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete a[u];else a[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let p=u,f=p.source??"core",h=u.name.toLowerCase(),g=p.defer??"always",I="suggestion";if(o.global)g=o.global,I="global";if(Object.hasOwn(o.sources,f))g=o.sources[f]??g,I="source";if(Object.hasOwn(o.tools,h))g=o.tools[h]??g,I="tool";if(f==="core"||p.builtin&&p.defer!=="defer")g="always",I="suggestion";return{name:u.name,source:f,mode:g,origin:I,deferred:g==="defer"}})}}function Yh(e){return{name:e.name,description:e.description,parameters:e.parameters}}function Zh(e,o){if(!o)return e;let a=Array.isArray(o.type)?o.type:[o.type],u=e;if(a.includes("number")||a.includes("integer")){let p=typeof u==="string"&&u.trim()?Number(u):u;if(typeof p!=="number"||!Number.isFinite(p))return u;let f=p;if(typeof o.maximum==="number"&&f>o.maximum)f=o.maximum;if(typeof o.minimum==="number"&&f<o.minimum)f=o.minimum;return f===p?u:f}if(typeof u==="string"&&(a.includes("object")||a.includes("array")))try{let p=JSON.parse(u),f=Array.isArray(p);if(typeof p==="object"&&p!==null&&!f&&a.includes("object")||f&&a.includes("array"))u=p}catch{}if(Array.isArray(u)){let p=o.items;if(!p||typeof p!=="object"||Array.isArray(p))return u;return u.map((f)=>Zh(f,p))}if(typeof u==="object"&&u!==null&&o.properties){let p={...u};for(let[f,h]of Object.entries(o.properties))if(f in p)p[f]=Zh(p[f],h);return p}return u}function sG(e){let o=e.prepareArguments;return{...e,prepareArguments:(a)=>{let u=Zh(a,e.parameters);return o?o(u):u}}}function iG(e,o,a){let u=e.prepareArguments?e.prepareArguments(a):a;return yu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class eg{retrieved=new Map;stub(e,o){let a=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${a}
|
|
278
|
-
(Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,p,f,h)=>{let g=JSON.stringify(Yh(e)),I;try{I=iG(e,u,p??{})}catch(k){return{...c(`Invalid arguments for ${e.name}: ${String(k)}
|
|
279
|
-
Schema: ${g}`),isError:!0}}let E=await e.execute(u,I,f,h),S=E.content.map((k)=>k.type==="text"?{...k,text:nt(k.text,Pe,o)}:k);return{...E,content:S}}}}assemble(e,o,a,u){let p=e.map(sG),f=new Set(o.filter((g)=>g.deferred).map((g)=>g.name));if(!f.size)return p;let h=p.filter((g)=>f.has(g.name)&&a(g.name)).sort((g,I)=>g.name<I.name?-1:g.name>I.name?1:0);return[...p.filter((g)=>!f.has(g.name)),...h.map((g)=>this.stub(g,u)),ve(T({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:s(),max_results:n(x({minimum:1,maximum:100}))}),execute:async(g,I)=>{let E=I.query.trim().toLowerCase(),S=E.startsWith("select:")?E.slice(7).split(",").map((A)=>A.trim()):void 0,k=h.filter((A)=>a(A.name)&&(S?S.includes(A.name.toLowerCase()):`${A.name} ${A.description}`.toLowerCase().includes(E))).slice(0,I.max_results??5);return c(JSON.stringify(k.map((A)=>{let P=JSON.stringify(Yh(A)),v=this.retrieved.get(A.name);if(v?.schema===P)return{name:A.name,status:"\u5DF2\u53D6\u56DE",callID:v.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(A.name,{schema:P,callID:g}),Yh(A)})))}}),"tool_search")]}}async function Cl(e,o,a,u){let p=await o.setup(e,u),f=a?.has("projection.policy")?await a.invoke("projection.policy",void 0,e):void 0;if(e.context.use(f),!a)return p;if(a.has("session.setup"))p=await a.invoke("session.setup",p,e);if(a.has("tools.configure"))p=await a.invoke("tools.configure",p,e);let h=p.systemPrompt,g=p.systemParts?.at(-1);if(g?.label==="\u8FD0\u884C\u73AF\u5883"&&a.has("prompt.fragments","before-environment")){let k=await a.invoke("prompt.fragments",[],e,void 0,"before-environment"),A=h.length-g.detail.length;h=h.slice(0,A)+k.join("")+g.detail}let I=await a.invoke("prompt.fragments",[],e),E=[...p.tools,...a.tools()],S=a.has("tools.visible")?await a.invoke("tools.visible",E,e):E;return{...p,systemPrompt:h+I.join(""),tools:S}}var aG=3,y0={attempts:10,delayMs:2000},uG=/\b(400|401|402|403|404|405|413|422)\b|invalid[_ ]?(api[_ ]?key|request|argument|model)|unauthori[sz]ed|forbidden|permission|authentication|incorrect api key|not[_ ]found|insufficient|billing|quota|credit|content[_ ]?(policy|filter)|safety|unsupported|does not support/i;function cG(e,o){if(e.stopReason!=="error")return!1;if(Ta(e,o))return!1;return!uG.test(e.errorMessage??"")}function x0(e,o,a){if(Ta(e,o))return!0;if(a?.preserveHistory!==!0)return!1;return e.errorMessage===(a.overflowError??"Context exceeds the request budget")}var I0="\u4E0A\u4E0B\u6587\u5DF2\u6EE1\uFF0C\u6A21\u578B\u6CA1\u6709\u5269\u4F59\u7684\u8F93\u51FA\u7A7A\u95F4\uFF0C\u56DE\u590D\u88AB\u622A\u65AD\uFF1B\u8BF7\u538B\u7F29\u4F1A\u8BDD\u6216\u6362\u7528\u4E0A\u4E0B\u6587\u66F4\u5927\u7684\u6A21\u578B";function E0(e){if(e.stopReason!=="length")return!1;return!e.content.some((o)=>o.type==="text"&&o.text.trim()||o.type==="toolCall")}function mG(e,o){return new Promise((a,u)=>{if(o.aborted)return u(o.reason);let p=setTimeout(()=>{o.removeEventListener("abort",f),a()},e),f=()=>{clearTimeout(p),u(o.reason)};o.addEventListener("abort",f,{once:!0})})}async function b0(e,o,a,u,p,f,h,g,I=!1){let E=I?void 0:await o?.invoke("run.start",{text:f},e);if(E)f=E.text;if(g.throwIfAborted(),f===void 0)await u.resume();else await u.prompt(f,h);let S=0,k=0;while(S<aG){let M=e.records.findLast((O)=>O.raw?.role==="assistant")?.raw;if(M&&E0(M)){if(!e.context.recover(p))throw Error(I0);g.throwIfAborted(),S++,await u.retry();continue}if(M?.stopReason!=="error")return;if(!x0(M,p.contextWindow,a)){if(!cG(M,p.contextWindow)||k>=y0.attempts)return;k++,await mG(y0.delayMs,g),await u.retry();continue}if(!e.context.recover(p)){if(a?.preserveHistory===!0)throw Error(a.overflowError??"Context exceeds the request budget");return}g.throwIfAborted(),S++,await u.retry()}let P=e.records.findLast((v)=>v.raw?.role==="assistant")?.raw;if(P&&E0(P))throw Error(I0);if(a?.preserveHistory===!0&&P?.stopReason==="error"&&x0(P,p.contextWindow,a))throw Error(a.overflowError??"Context exceeds the request budget")}async function S0(e,o,a,u,p,f){f.throwIfAborted();let h,g;try{g=await Promise.race([Cl(e,o,a(),f),new Promise((A,P)=>{h=()=>P(f.reason),f.addEventListener("abort",h,{once:!0})})])}finally{if(h)f.removeEventListener("abort",h)}f.throwIfAborted();let I=a(),E=(A)=>{if(!I)return A;return{...A,execute:async(P,v,M,J)=>{let O=u()??g.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=O?I.policy(O):void 0;if(O&&!V?.(A.name,e))throw Error(`Tool ${A.name} is unavailable under tool policy ${O}`);let j=await I.invoke("tool.before_call",{name:A.name,callID:P,args:v},e);if(j.block)throw Error(j.block);let te=await N.run(e,()=>A.execute(P,j.args,M,J));return I.invoke("tool.after_result",te,e)}}};if(I)g.tools=g.tools.map(E);let S=g.tools,k=()=>{if(!S.some((P)=>P.name==="history_grep")){if(e.records.some((v)=>v.entry.type==="compaction")){let M=kl(()=>e.records,(J)=>e.resolveHistory(J)).map(E);for(let J of M)if(!S.some((O)=>O.name===J.name))S.push(J)}}let A=new ea(o.store).partition(S);return g.tools=p.assemble(S,A,(P)=>e.permitsTool(P),g.cwd),g.tools};return g.tools=k(),{setup:g,executionTools:S,assemble:k}}function w0(e,o,a,u,p,f,h){return{response:async(g)=>{let I=await o()?.invoke("model.after_response",g,e)??g;if(I.role==="assistant")for(let E of I.content){if(E.type!=="toolCall"||E.name.toLowerCase()!=="tool_call")continue;let S=E.arguments.name;if(typeof S==="string"){let k=h.find((A)=>A.name.toLowerCase()===S.toLowerCase());E.arguments.name=k?.name??S}}return I},payload:(g)=>o()?.invoke("model.before_request",g,e)??Promise.resolve(g),transformContext:(g)=>o()?.invoke("transformContext",g,e)??Promise.resolve(g),boundary:async()=>{if(u())return!0;let g=await o()?.invoke("step.after",{notices:[]},e);for(let E of g?.notices??[])e.notice(E);await f.work;let I=await f.flushNotices();if(I&&!p())e.agent?.steer(I)},prepare:async(g,I,E)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let S=await o()?.invoke("model.check",{},e);if(S?.error)throw Error(S.error);let k=await o()?.invoke("step.before",{notices:[]},e);for(let O of k?.notices??[])e.notice(O);await f.work,await f.flushNotices();let A=await o()?.invoke("projection.before",e.records,e),P=await o()?.invoke("projection.prefix",[],e)??[],v=e.context.prepare([...g,...P],I,E,A,a()?.preserveHistory===!0);if(a()?.preserveHistory===!0&&v.estimate>de(E))throw Error(a()?.overflowError??"Context exceeds the request budget");let M=v.messages,J=await o()?.invoke("projection.after",M,e)??M;return Eu(xC(J))}}}async function T0(e,o,a){let u=o.store.pendingNotices(e.id);if(!u.length)return;let p=u,f=o.plugins?.pin();try{if(f){let P=await f.invoke("notice.deliver",u,e);p=u.map((v,M)=>({...v,text:P[M]?.text??v.text}))}}finally{await f?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let h=p.map((P)=>P.text).join(`
|
|
280
|
-
`),g=p.map((P)=>o.plugins?.noticeSource(P.sourceKind)),I=Math.max(800,...g.map((P)=>P?.summaryLimit??800)),E=h.length>I?`
|
|
281
|
-
[\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",k=`${g.find((P)=>P?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
|
|
282
|
-
${h.slice(0,I)}${E}`,A={role:"user",content:k,timestamp:Date.now()};return a({type:"user",text:k,notices:u.map(({text:P,...v})=>v)},A),A}class tg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,a,u,p,f,h,g){this.session=e;this.context=o;this.isStopped=a;this.isRunning=u;this.waiting=p;this.start=f;this.invalidateAgent=h;this.append=g}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let a of e){if(a.recovery!=="discard")continue;this.append({type:"extension",namespace:so,kind:"discarded",schemaVersion:1,payload:{dedupeKey:a.dedupeKey,sourceKind:a.sourceKind,sourceID:a.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((a)=>a.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((a)=>{this.failure=a}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=T0(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((o)=>o.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var pG=new Set(["authorization","proxy-authorization","x-api-key","api-key","x-goog-api-key","x-auth-token","x-amz-security-token","cookie","set-cookie"]);function rg(e){let o={};for(let[a,u]of Object.entries(e)){if(!pG.has(a.toLowerCase())){o[a]=u;continue}let p=/^bearer\s+/i.exec(u)?.[0];o[a]=p?`${p}***`:"***"}return o}function R0(e,o,a,u){let f=(a.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:a.systemPrompt}]).map((L,re)=>({id:`system-${re}`,label:L.label,detail:L.detail,tokens:F(L.detail)+(re===0?16:0)})),h=a.tools.map((L)=>{let re=L,he=re.defer==="defer"||L.description.includes("(Parameters not inlined: use toolsearch");return{name:L.name,description:L.description,group:re.group??"\u5185\u7F6E",schema:L.parameters,deferred:he}});f.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Lt(a.tools),detail:JSON.stringify(h,null,2)});let g=f.reduce((L,re)=>L+re.tokens,0),I=u!==void 0?e.records.filter((L)=>L.entry.seq<=u):e.records,E=Ce(I,o,e.context.budget(o),{inspect:!0,cwd:a.cwd,trim:{fixed:g,limit:e.context.previewLimit(o)}}),S,k=0,A=0;for(let L of I){if(L.raw?.role!=="assistant")continue;let re=L.raw.usage;S??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},S.input+=re.input,S.output+=re.output,S.cacheRead+=re.cacheRead,S.cacheWrite+=re.cacheWrite,S.cost+=re.cost.total;let he=L.entry.generationMs??L.raw.generationMs;if(typeof he==="number"&&he>0&&re.output>0)k+=he,A+=re.output}if(S){let L=S.input+S.cacheRead+S.cacheWrite;if(L>0)S.cacheHitRate=S.cacheRead/L}if(S&&k>0&&A>0)S.generationMs=k,S.tps=Number((A/(k/1000)).toFixed(1));let P=g+E.tokens,v=e.context.calibrationRatio??1,M=Math.round(P*v),J=I.findLast((L)=>L.raw?.role==="assistant"),O=J?.raw,j=(J?I.filter((L)=>L.entry.seq>J.entry.seq&&L.raw):I.filter((L)=>L.raw)).length>0,te,se;if(O){let L=O.usage,re=L.input+L.cacheRead+L.cacheWrite;if(re>0)te=re,se=L.cacheRead/re}return{contextWindow:o.contextWindow,usableWindow:de(o),items:[...f,...E.items],calibratedTokens:M,calibrationRatio:v,lastInputTokens:te,lastCacheHitRate:se,hasPendingOutput:j,tools:h,usage:S}}class ot extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class Z extends Error{constructor(e="session"){super(`${e} is busy`)}}var ng="medium",lG=1e6;class vl{row;ctx;events;notices;lease;policyID;discovery=new eg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Cl(this,this.ctx,e);return new ea(this.ctx.store).partition(o.tools).filter((a)=>this.permitsTool(a.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new Z;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;steerWaiter;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,a){this.row=e;this.ctx=o;this.events=a;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new tg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let p=this.entries(0,["extension","run"],!1),f=p.findLast((g)=>g.type==="extension"&&g.namespace==="session"&&g.kind==="stop_requested"),h=p.findLast((g)=>g.type==="run"&&g.state==="start");if(f&&f.seq>(h?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let g=this.entries(u.seq,["user"],!1).length>0,I=o.store.pendingNotices(e.id).some((E)=>E.wake&&E.recovery!=="discard");if(!this.stopped&&(g||I))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new $l(()=>this.records,()=>this.cwd,(g,I)=>this.appendCompaction(g,I)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=Cn(this.ctx.models,this.row.model);if(!e)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");return e}lastModelRequest(){let e=this.lastRequestSnapshot;return e?{...e,headers:rg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:rg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??ng}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get runningTools(){return this.agent?.agent.state.pendingToolCalls.size??0}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:a,model:u,thinking:p,metadata:f,created:h,updated:g,todos:I}=this.row;return{id:e,title:o,projectID:a,model:u,thinking:p??ng,metadata:f,created:h,updated:g,archivedAt:this.row.archivedAt,status:this.status,todos:I,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5,lG);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let a=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,a,e)}entriesAround(e,o,a){return this.ctx.store.entriesAround(this.row.id,e,o,a)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,a=!0){return this.ctx.store.entries(this.row.id,e,o,a)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let a=Cn(this.ctx.models,this.row.model);if(!a)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),p;try{p=this.setup??await Cl(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new ea(this.ctx.store).partition(p.tools),(h)=>this.permitsTool(h),p.cwd);let f=R0(this,a,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:f};return f})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new ot}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!Cn(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,Hl(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let a=Hl(o),u=bh(e,a),p=this.append({type:"user",text:e,...a?.length?{attachments:a}:{}},u);if(this.recallableSteers.set(p.seq,u),this.steerWaiter?.abort(Error("user steered")),this.steerWaiter=void 0,this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}userSteered(){if(this.recallableSteers.size>0)return AbortSignal.abort(Error("user steered"));return this.steerWaiter??=new AbortController,this.steerWaiter.signal}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((f)=>f.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let a=o.raw,u=this.pendingSteers.indexOf(a);if(u<0){let f=JSON.stringify(a);u=this.pendingSteers.findIndex((h)=>JSON.stringify(h)===f)}let p=!1;if(u>=0)this.pendingSteers.splice(u,1),p=!0;else p=this.agent?.unsteer(a)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,a]of this.recallableSteers){if(a!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,a){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&a===void 0)throw new Z;if(e!==void 0)this.stopped=!1;let u=Cn(this.ctx.models,this.row.model);if(!u&&a===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let p=new AbortController;if(this.starting=p,!this.row.title&&e!==void 0)this.row={...this.row,title:dG(e,o)},this.ctx.store.updateSession(this.row);let f=a??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let h=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=h.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(a!==void 0){let g=this.records.filter((k)=>k.entry.seq>f),I=g.filter((k)=>k.entry.type==="user"&&!k.raw);if(I.length>1)return{reason:"interrupted"};let E=I[0];if(E?.entry.type==="user"){if(g.some((k)=>k.entry.seq>E.entry.seq&&k.raw?.role==="assistant"))return{reason:"interrupted"};e=E.entry.text,o=E.entry.attachments,this.pendingUserSeq=E.entry.seq}for(let k of Ge(g.filter((A)=>A.raw))){if(k.result)continue;let A=k.message.stopReason;if(A==="error"||A==="aborted")continue;let{body:P,raw:v}=pl(k.call);this.append(P,v)}if(!E&&this.waitingForInput())return{reason:"waiting_user"};let S=this.records.findLast((k)=>k.entry.seq>f&&k.raw)?.raw;if(!E&&S?.role==="assistant")return Sh(S);if(!E&&!S&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let h=await this.prepareAgent(u,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let g=this.pendingSteers.shift();if(g)h.steer(g)}return await b0(this,this.lease,this.setup,h,u,e,o,p.signal,a!==void 0&&e===void 0),Sh(this.records.findLast((g)=>g.entry.seq>f&&g.raw?.role==="assistant")?.raw)}).then((h)=>p.signal.aborted?{reason:"aborted"}:h,(h)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(h)}).then(async(h)=>{try{if(!this.suspended&&h.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())h={reason:"waiting_user"};if(h.reason!=="interrupted")h=await this.lease?.invoke("run.end",{reason:h.reason,error:h.error},this)??h}}catch(g){h={reason:"error",error:String(g)}}finally{try{await this.lease?.release()}catch(g){h={reason:"error",error:String(g)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...h});let g=Cn(this.ctx.models,this.row.model);if(g)this.context.settle(g)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:a,executionTools:u,assemble:p}=await S0(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=a,this.row.parentID&&(!a.toolPolicy||!this.lease?.policy(a.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=a.cwd,this.agent=eC({models:this.ctx.models,model:e,systemPrompt:a.systemPrompt,tools:a.tools,history:this.records.filter((f)=>!this.pendingSteers.includes(f.raw)).flatMap((f)=>f.raw?[f.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??ng,captureRequest:(f)=>{this.lastRequestSnapshot=f},captureResponse:(f)=>{this.lastResponseSnapshot=f},steerConsumed:(f)=>this.markSteerConsumed(f),hooks:{tools:p,...w0(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(f,h)=>{if(this.suspended&&h.role==="assistant"&&(h.stopReason==="aborted"||h.stopReason==="error"))return;if(h.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,h);let g=this.loaded?.find((I)=>I.entry.seq===this.pendingUserSeq);if(g)g.raw=h;this.pendingUserSeq=void 0;return}if(h.role==="assistant")this.context.calibrate(h);this.append(f,h)},draft:(f)=>{this.draftParts=f,this.events.draft(f)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let a=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...a?{saved:a}:{}})}measureCompactionSavings(e,o){let a=Cn(this.ctx.models,this.row.model);if(!a)return;let u=this.context.budget(a),p=Ce(this.records,a,u,{cwd:this.cwd}).tokens,f={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},h=Ce([...this.records,f],a,u,{cwd:this.cwd}).tokens;return{before:p,after:h}}compact(){this.assertWritable();let e=_r(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}compactAt(e){if(this.assertWritable(),this.status==="busy")throw new Z;let o=rt(this.records).findLast((a)=>a.end!==void 0&&a.end<e)?.end;if(o===void 0)throw new t("\u8FD9\u6761\u6D88\u606F\u4E4B\u524D\u6CA1\u6709\u53EF\u6298\u53E0\u7684\u5DF2\u7ED3\u675F\u8F6E\u6B21");if(o<=wt(this.records))throw new t("\u8BE5\u5904\u4E4B\u524D\u7684\u5185\u5BB9\u5DF2\u5728\u6298\u53E0\u8303\u56F4\u5185");return this.appendCompaction(o,!1),this.reset(),this.info()}uncompact(e){if(this.assertWritable(),this.status==="busy")throw new Z;let o=this.records.findLast((a)=>a.entry.type==="compaction")?.entry;if(o?.type!=="compaction")throw new t("\u4F1A\u8BDD\u6CA1\u6709\u53EF\u64A4\u56DE\u7684\u6298\u53E0");if(o.seq!==e)throw new t("\u53EA\u80FD\u64A4\u56DE\u6700\u8FD1\u4E00\u6B21\u6298\u53E0");return this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.reset(),this.events.entryRemoved(e),this.events.changed(),this.info()}append(e,o){this.refreshEntries();let a=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(a.type==="user"&&!(("notices"in a)&&a.notices))this.row={...this.row,updated:a.time};return this.refreshEntries(),a}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function dG(e,o){let u=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
|
|
283
|
-
`)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var A0=new Set(["user","assistant","tool_result","run","compaction"]),fG=new Set(["user","assistant","toolResult"]);function P0(e,o,a){return{format:ii,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...a?{project:a}:{},records:o.filter((u)=>A0.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function ro(e){if(!yr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===ii)return hG(e);if(yr(e.info)&&Array.isArray(e.messages))return yG(e);throw new t("\u65E0\u6CD5\u8BC6\u522B\u7684\u4F1A\u8BDD\u6587\u4EF6\uFF1A\u53EA\u652F\u6301 Basalt \u5BFC\u51FA\u548C OpenCode \u7684 `opencode export` \u6587\u4EF6")}function hG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!yr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let a=0,u=e.records.flatMap((p,f)=>{let h=`records[${f}]`;if(!yr(p)||!yr(p.entry))throw new t(`${h} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let g=p.entry;if(g.type==="notice_pending"||g.type==="extension")return[];if(typeof g.type!=="string"||!A0.has(g.type))throw new t(`${h} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(g.type)}`);let{seq:I,time:E}=g;if(typeof I!=="number"||!Number.isSafeInteger(I)||I<=a)throw new t(`${h} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof E!=="number"||!Number.isFinite(E))throw new t(`${h} \u7F3A\u5C11\u6709\u6548\u7684 time`);a=I,gG(g,h);let S=p.raw;if(S!==void 0&&!(yr(S)&&typeof S.role==="string"&&fG.has(S.role)))throw new t(`${h} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:g,...S===void 0?{}:{raw:S}}]});return{title:Gr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(C0):[],created:Ei(o.created)??Date.now(),updated:Ei(o.updated)??Date.now(),needsRaw:!1,records:u}}function gG(e,o){let a=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);switch(e.type){case"user":if(typeof e.text!=="string")throw a("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw a("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw a("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&qi.includes(e.reason)))throw a("\u7684 state/reason \u4E0D\u5408\u6CD5");return;case"compaction":if(typeof e.through!=="number"||typeof e.partial!=="boolean")throw a("\u7F3A\u5C11 through \u6216 partial");return}}function yG(e){let o=e.info,a=yr(o.time)?o.time:{},u=yr(o.model)?o.model:void 0,p=e.messages.filter(yr).sort(xG),f=[],h=0,g=0,I=(J,O)=>{g=Math.max(g,O??g),h+=1,f.push({entry:{...J,seq:h,time:g}})},E=!1,S=(J,O)=>{if(!E)return;E=!1,I({type:"run",state:"end",reason:J,...O?{error:O}:{}},void 0)};for(let J of p){let O=yr(J.info)?J.info:{},V=Array.isArray(J.parts)?J.parts.filter(yr):[],j=Ei(yr(O.time)?O.time.created:void 0);if(O.role==="user"){S("done");let te=IG(V);if(!te)continue;I({type:"run",state:"start"},j),I(te,j),E=!0}else if(O.role==="assistant"){if(!E)I({type:"run",state:"start"},j),E=!0;SG(O,V,I);let te=$0(O.error);if(te)S(te.aborted?"aborted":"error",te.aborted?void 0:te.message)}}S("done");let k=p.findLast((J)=>yr(J.info)&&J.info.role==="assistant"),A=yr(k?.info)?k.info:void 0,P=Gr(u?.providerID)||Gr(A?.providerID),v=Gr(u?.id)||Gr(A?.modelID),M=P&&v?`${P}/${v}`:void 0;return{title:Gr(o.title),model:M,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(C0):[],created:Ei(a.created)??f[0]?.entry.time??Date.now(),updated:Ei(a.updated)??f.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:f}}function xG(e,o){let a=(p)=>(yr(p.info)&&yr(p.info.time)?Ei(p.info.time.created):void 0)??0,u=(p)=>yr(p.info)?Gr(p.info.id):"";return a(e)-a(o)||u(e).localeCompare(u(o))}function IG(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Gr(u.text)).join(`
|
|
284
|
-
|
|
285
|
-
`),a=e.flatMap((u)=>u.type==="file"?EG(u):[]);if(!o.trim()&&a.length===0)return;return{type:"user",text:o,...a.length?{attachments:a}:{}}}function EG(e){let o=Gr(e.mime)||"application/octet-stream",a=Gr(e.filename)||"file",u=Gr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(p){let f=p[3]??"";if(o.startsWith("image/"))return[{name:a,mimeType:o,kind:"image",data:p[2]?f:btoa(f)}];if(o.startsWith("text/")||o==="application/json"){let h=p[2]?new TextDecoder().decode(Uint8Array.from(atob(f),(g)=>g.charCodeAt(0))):f;return[{name:a,mimeType:o,kind:"text",data:h}]}return[]}if(u.startsWith("file://"))try{return[{name:a,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function bG(e){let o=[[]];for(let a of e){if(a.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(a.type==="reasoning"||a.type==="text"||a.type==="tool")o.at(-1)?.push(a)}return o.filter((a)=>a.length>0)}function SG(e,o,a){let u=`${Gr(e.providerID)}/${Gr(e.modelID)}`,p=$0(e.error),f=bG(o);f.forEach((h,g)=>{let I=h.flatMap((k)=>{if(k.type==="reasoning")return Gr(k.text).trim()?[{type:"thinking",text:Gr(k.text)}]:[];if(k.type==="text")return k.ignored!==!0&&Gr(k.text).trim()?[{type:"text",text:Gr(k.text)}]:[];return[{type:"tool_call",id:k0(k.callID),name:Gr(k.tool),input:yr(k.state)&&yr(k.state.input)?k.state.input:{}}]}),E=g===f.length-1,S=wG(h);a({type:"assistant",parts:I,model:u,...E&&p&&!p.aborted?{error:p.message}:{}},S);for(let k of h){if(k.type!=="tool")continue;let A=yr(k.state)?k.state:{},P=A.status==="error",v=A.status==="pending"||A.status==="running",M=P?[Gr(A.output),Gr(A.error)].filter(Boolean).join(`
|
|
286
|
-
`):v?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Gr(A.output);a({type:"tool_result",callID:k0(k.callID),name:Gr(k.tool),output:M,isError:P||v},Ei(yr(A.time)?A.time.end:void 0))}})}function k0(e){return Gr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function $0(e){if(!yr(e))return;let o=yr(e.data)?e.data:{};return{message:Gr(o.message)||Gr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function wG(e){for(let o of e){let a=yr(o.time)?Ei(o.time.start):yr(o.state)?TG(o.state):void 0;if(a!==void 0)return a}return}function TG(e){return yr(e.time)?Ei(e.time.start):void 0}function C0(e){if(!yr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function v0(e,o){let a={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let p=u.time;switch(u.type){case"user":return{entry:u,raw:RG(u,p)};case"assistant":{let f=u.parts.flatMap((g)=>{if(g.type==="text")return[{type:"text",text:g.text}];if(g.type==="thinking")return[];return[{type:"toolCall",id:g.id,name:g.name,arguments:kG(g.input)}]}),h=f.some((g)=>g.type==="toolCall");return{entry:u,raw:{role:"assistant",content:f,api:o.api,provider:o.provider,model:o.id,usage:a,stopReason:u.error?"error":h?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:p}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:p}};default:return{entry:u}}})}function RG(e,o){let a=(e.attachments??[]).flatMap((f)=>f.kind==="path"?[`<file path=${JSON.stringify(f.data)} />`]:f.kind==="text"?[`<file name=${JSON.stringify(f.name)}>
|
|
287
|
-
${f.data}
|
|
288
|
-
</file>`]:[]),u=(e.attachments??[]).filter((f)=>f.kind==="image").map((f)=>({type:"image",data:f.data,mimeType:f.mimeType})),p=[...a,...e.text.trim()?[e.text]:[]].join(`
|
|
289
|
-
|
|
290
|
-
`);return{role:"user",content:u.length?[{type:"text",text:p},...u]:p,timestamp:o}}function yr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Gr(e){return typeof e==="string"?e:""}function Ei(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function kG(e){return yr(e)?e:{}}function Jt(e,o){let a=e.at(-1)?.entry.seq??0,u,p,f;for(let{entry:E}of e){if(E.type==="run"&&E.state==="start")u=E.seq;if(E.seq===o)if(E.type==="user"&&!E.notices)a=(u??E.seq)-1;else p=u;if(E.type==="run"&&E.state==="end"){if(p!==void 0&&u===p)f=E.seq;u=void 0}}let h=e.find((E)=>E.entry.seq===o)?.entry;if(o!==void 0&&!h)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(h&&!(h.type==="user"&&!h.notices)){if(p!==void 0&&f===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");a=f??h.seq}else if(o===void 0&&u!==void 0)a=e.findLast(({entry:E})=>E.type==="run"&&E.state==="end")?.entry.seq??0;let g=e.filter(({entry:E})=>E.seq<=a&&(E.type!=="compaction"||E.through<=a)),I=new Map(g.map(({entry:E},S)=>[E.seq,S+1]));return g.map((E,S)=>{let k=structuredClone(E);if(k.entry.seq=S+1,k.entry.type==="compaction"){let A=k.entry.through,P=g.findLast(({entry:v})=>v.seq<=A);k.entry.through=P?I.get(P.entry.seq)??0:0}return k})}function Xt(e){let o=new Map,a=[];for(let u of e){if(u.type==="assistant"){for(let h of u.parts)if(h.type==="tool_call"&&h.name==="todo")o.set(h.id,h.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let p=o.get(u.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let f=[];for(let h of p.todos){if(!h||typeof h!=="object"||!("content"in h)||typeof h.content!=="string"||!("status"in h)||h.status!=="pending"&&h.status!=="in_progress"&&h.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");f.push({content:h.content,status:h.status})}a=f}return a}import{Buffer as _0}from"buffer";import{createHash as AG}from"crypto";import{isDeepStrictEqual as Ml}from"util";var Ol="@blob:";function ku(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function M0(e,o,a){if(typeof e!=="string"||e.length<256||e.startsWith(Ol))return;let u=_0.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let p=AG("sha256").update(u).digest("hex");return a.put(p,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Ol}${p}`}function O0(e,o){if(typeof e!=="string"||!e.startsWith(Ol))return;let a=o.get(e.slice(Ol.length));if(a===void 0)return;return _0.from(a.buffer,a.byteOffset,a.byteLength).toString("base64")}function _l(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let f=M0(p.data,p.mimeType,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((p)=>{let f=M0(p.data,p.mimeType,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,images:u}}return e}function bi(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let f=O0(p.data,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((p)=>{let f=O0(p.data,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,images:u}}return e}function Xc(e,o){if(!ku(o))return o;if(e.type==="user"){let{merged:a,images:u}=Wc(e.text,e.attachments),p=u.length>0?[{type:"text",text:a},...u]:a,f=Object.keys(o),{role:h,timestamp:g,content:I}=o;if(f.length===3&&h==="user"&&typeof g==="number"&&"content"in o&&Ml(I,p))return{role:"user",timestamp:g};return o}if(e.type==="tool_result"){let{role:a,toolCallId:u,toolName:p,isError:f,timestamp:h,content:g}=o;if(a!=="toolResult"||u!==e.callID||typeof p!=="string"||f!==e.isError||typeof h!=="number")return o;let I=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!Ml(o.details,e.meta):e.meta!==void 0)return o;let{role:S,toolCallId:k,toolName:A,content:P,details:v,isError:M,timestamp:J,...O}=o;if(Ml(g,I))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...O,timestamp:h};if(Array.isArray(g)){let V=e.images??[],j=0,te=!0,se=g.map((L)=>{if(ku(L)&&L.type==="image"){let re=V[j++],he=Object.keys(L);if(re&&he.length===3&&L.mimeType===re.mimeType&&L.data===re.data)return{type:"image",mimeType:L.mimeType};te=!1}return L});if(te&&j===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:se,...O,timestamp:h}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let p=!1,f=u.map((h,g)=>{let I=e.parts[g];if(ku(h)){if(h.type==="text"&&I?.type==="text"&&h.text===I.text){p=!0;let E={...h};return delete E.text,E}if(h.type==="thinking"&&I?.type==="thinking"&&h.thinking===I.text){p=!0;let E={...h};return delete E.thinking,E}if(h.type==="toolCall"&&I?.type==="tool_call"&&h.id===I.id&&h.name===I.name&&"arguments"in h&&Ml(h.arguments,I.input)){p=!0;let E={...h};return delete E.id,delete E.name,delete E.arguments,E}}return h});if(!p)return o;return{...o,content:f}}return o}function og(e,o){if(!ku(o))return o;if(e.type==="user"){let{role:a,timestamp:u}=o;if(a==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:p,images:f}=Wc(e.text,e.attachments);return{role:"user",content:f.length>0?[{type:"text",text:p},...f]:p,timestamp:u}}return o}if(e.type==="tool_result"){let{role:a,timestamp:u}=o;if(a==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:f,toolName:h,content:g,timestamp:I,...E}=o,S;if(Array.isArray(g)){let k=e.images??[],A=0;S=g.map((P)=>{if(ku(P)&&P.type==="image"&&!("data"in P)){let v=k[A++];if(v)return{type:"image",mimeType:P.mimeType,data:v.data}}return P})}else S=[{type:"text",text:e.output},...(e.images??[]).map((k)=>({type:"image",mimeType:k.mimeType,data:k.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof h==="string"?h:e.name,content:S,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...E,timestamp:u}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u))return o;let p=!1,f=u.map((h,g)=>{let I=e.parts[g];if(ku(h)){if(h.type==="text"&&!("text"in h)&&I?.type==="text"){p=!0;let{type:E,...S}=h;return{type:E,text:I.text,...S}}if(h.type==="thinking"&&!("thinking"in h)&&I?.type==="thinking"){p=!0;let{type:E,...S}=h;return{type:E,thinking:I.text,...S}}if(h.type==="toolCall"&&!("arguments"in h)&&I?.type==="tool_call"){p=!0;let{type:E,...S}=h;return{type:E,id:I.id,name:I.name,arguments:structuredClone(I.input),...S}}}return h});if(!p)return o;return{...o,content:f}}return o}function L0(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),a=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(I,E,S){o.run(I,E,S)},get(I){return a.get(I)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),f=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),h=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),g=0;return e.transaction(()=>{for(let I of p){let E;try{E=JSON.parse(I.body)}catch{continue}let S=bi(E,u),k=_l(S,u),A=k===E?I.body:JSON.stringify(k),P=I.raw;if(I.raw!==null)try{let v=JSON.parse(I.raw),M=og(S,v),J=Xc(S,M);P=JSON.stringify(J)}catch{P=I.raw}if(A!==I.body)f.run(A,P,I.session_id,I.seq),g++;else if(P!==I.raw)h.run(P,I.session_id,I.seq),g++}})(),g}import{Database as PG}from"bun:sqlite";import{chmodSync as N0,existsSync as $G,mkdirSync as CG}from"fs";import{dirname as vG}from"path";var sg=[`
|
|
291
|
-
CREATE TABLE projects (
|
|
292
|
-
id TEXT PRIMARY KEY,
|
|
293
|
-
name TEXT NOT NULL,
|
|
294
|
-
directory TEXT NOT NULL UNIQUE,
|
|
295
|
-
instructions TEXT NOT NULL DEFAULT '',
|
|
296
|
-
created INTEGER NOT NULL,
|
|
297
|
-
updated INTEGER NOT NULL
|
|
298
|
-
);
|
|
299
|
-
CREATE TABLE automations (
|
|
300
|
-
id TEXT PRIMARY KEY,
|
|
301
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
302
|
-
name TEXT NOT NULL,
|
|
303
|
-
prompt TEXT NOT NULL,
|
|
304
|
-
schedule TEXT NOT NULL,
|
|
305
|
-
model TEXT NOT NULL,
|
|
306
|
-
enabled INTEGER NOT NULL,
|
|
307
|
-
created INTEGER NOT NULL,
|
|
308
|
-
updated INTEGER NOT NULL,
|
|
309
|
-
next_run INTEGER,
|
|
310
|
-
last_run INTEGER,
|
|
311
|
-
last_session_id TEXT
|
|
312
|
-
);
|
|
313
|
-
CREATE TABLE sessions (
|
|
314
|
-
id TEXT PRIMARY KEY,
|
|
315
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
316
|
-
automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
|
|
317
|
-
title TEXT NOT NULL DEFAULT '',
|
|
318
|
-
model TEXT NOT NULL,
|
|
319
|
-
todos TEXT NOT NULL DEFAULT '[]',
|
|
320
|
-
created INTEGER NOT NULL,
|
|
321
|
-
updated INTEGER NOT NULL
|
|
322
|
-
);
|
|
323
|
-
CREATE INDEX sessions_project ON sessions(project_id);
|
|
324
|
-
CREATE TABLE entries (
|
|
325
|
-
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
326
|
-
seq INTEGER NOT NULL,
|
|
327
|
-
time INTEGER NOT NULL,
|
|
328
|
-
body TEXT NOT NULL,
|
|
329
|
-
raw TEXT,
|
|
330
|
-
PRIMARY KEY (session_id, seq)
|
|
331
|
-
) WITHOUT ROWID;
|
|
332
|
-
`,"","","",`
|
|
333
|
-
ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
|
|
334
|
-
ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
|
|
335
|
-
ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
|
|
336
|
-
CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
|
|
337
|
-
ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
|
|
338
|
-
ALTER TABLE sessions ADD COLUMN notice_floor_seq INTEGER NOT NULL DEFAULT 0;`,"ALTER TABLE sessions ADD COLUMN truncation_epoch INTEGER NOT NULL DEFAULT 0;",`CREATE TABLE plugin_kv (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
|
|
339
|
-
PRIMARY KEY (namespace, key));
|
|
340
|
-
CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
|
|
341
|
-
PRIMARY KEY (namespace, version));
|
|
342
|
-
CREATE TABLE plugin_settings (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL);`,"ALTER TABLE sessions ADD COLUMN thinking TEXT;","ALTER TABLE sessions ADD COLUMN metadata TEXT;","ALTER TABLE sessions ADD COLUMN archived_at INTEGER;",`CREATE TABLE search_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, seq INTEGER NOT NULL);
|
|
343
|
-
CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
|
|
344
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
345
|
-
END;
|
|
346
|
-
CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
|
|
347
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
|
|
348
|
-
END;
|
|
349
|
-
CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
|
|
350
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
351
|
-
END;
|
|
352
|
-
CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
|
|
353
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
354
|
-
END;
|
|
355
|
-
CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
|
|
356
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
357
|
-
END;
|
|
358
|
-
CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
|
|
359
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
|
|
360
|
-
END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
|
|
361
|
-
WHERE json_extract(body,'$.type')='compaction';
|
|
362
|
-
CREATE TABLE IF NOT EXISTS blobs (
|
|
363
|
-
hash TEXT PRIMARY KEY,
|
|
364
|
-
mime TEXT NOT NULL,
|
|
365
|
-
data BLOB NOT NULL
|
|
366
|
-
) WITHOUT ROWID;
|
|
367
|
-
CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`,"ALTER TABLE projects ADD COLUMN position INTEGER NOT NULL DEFAULT 0;","ALTER TABLE projects ADD COLUMN closed_at INTEGER;"];var MG=[20,50,100,200,400,800];function OG(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function ig(e){let o=0;while(!0)try{return e()}catch(a){let u=MG[o];if(u===void 0||!OG(a))throw a;o++,Bun.sleepSync(u)}}function q0(e,o){if(e!==":memory:")CG(vG(e),{recursive:!0});let a=new PG(e,{create:!0,strict:!0}),u=(f,h=!0)=>new Proxy(function(...g){return Reflect.apply(f,this,g)},{apply(g,I,E){Ys();let S=o.length===0&&!a.inTransaction,k=h?Reflect.get(f,"immediate"):void 0,A=()=>{let P=[];o.push(P);let v=!1;try{let M=typeof k==="function"?Reflect.apply(k,f,E):Reflect.apply(g,I,E);return v=!0,M}finally{o.pop();let M=o.at(-1);if(v&&M)M.push(...P);else for(let J of P)if(v)J.commit();else J.rollback()}};return S?ig(A):A()},get(g,I){let E=Reflect.get(f,I);if(["deferred","immediate","exclusive"].includes(String(I))&&typeof E==="function")return u(E,!1);return E}}),p=new Proxy(a,{get(f,h){let g=Reflect.get(f,h,f);if(typeof g!=="function")return g;return(...I)=>{Ys();let k=(h==="run"||h==="exec")&&o.length===0&&!a.inTransaction?ig(()=>Reflect.apply(g,f,I)):Reflect.apply(g,f,I);if(h==="transaction"&&typeof k==="function")return u(k,!0);if(h!=="query"&&h!=="prepare")return k;if(!k||typeof k!=="object")throw Error("Invalid SQL statement");return new Proxy(k,{get(A,P,v){let M=Reflect.get(A,P,A);if(typeof M!=="function")return M;return(...J)=>{Ys();let j=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!a.inTransaction?ig(()=>Reflect.apply(M,A,J)):Reflect.apply(M,A,J);return j===A?v:j}}})}}});if(e!==":memory:")N0(e,384);if(p.run("PRAGMA journal_mode = WAL"),p.run("PRAGMA synchronous = FULL"),p.run("PRAGMA foreign_keys = ON"),p.run("PRAGMA busy_timeout = 10000"),p.run("PRAGMA mmap_size = 268435456"),_G(p),p.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),p.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let f of["-wal","-shm"]){let h=e+f;if($G(h))N0(h,384)}return p}function _G(e,o=sg){let{user_version:a}=e.query("PRAGMA user_version").get();if(a>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${a} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=a;u<o.length;u++)e.transaction(()=>{let p=o[u]??"",f=Array.isArray(p)?p:u>=4?LG(p):[p];for(let h of f)try{if(h.trim())e.run(h)}catch(g){if(!(g instanceof Error)||!/already exists|duplicate column name/i.test(g.message))throw g}e.run(`PRAGMA user_version = ${u+1}`)})()}function LG(e){let o=[],a=0,u=0,p=[],f=!1,h=0,g=(I)=>{let E=e.slice(a,I).trim();if(E)o.push(E);a=I+1,p=[],f=!1,h=0};while(u<e.length){let I=e[u];if(I==="'"||I==='"'||I==="`"||I==="["){let E=I==="["?"]":I;u++;while(u<e.length)if(e[u]===E)if(E!=="]"&&e[u+1]===E)u+=2;else break;else u++;u++;continue}if(I==="-"&&e[u+1]==="-"){let E=e.indexOf(`
|
|
368
|
-
`,u);u=E===-1?e.length:E+1;continue}if(I==="/"&&e[u+1]==="*"){let E=e.indexOf("*/",u+2);u=E===-1?e.length:E+2;continue}if(/[A-Za-z_]/.test(I)){let E=u+1;while(E<e.length&&/[A-Za-z0-9_$]/.test(e[E]))E++;let S=e.slice(u,E).toUpperCase();if(p.length<3)p.push(S),f=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(f){if(S==="BEGIN"||S==="CASE"&&h>0)h++;else if(S==="END"&&h>0)h--}u=E;continue}if(I===";"&&h===0)g(u);u++}return g(e.length),o}var Ll=({position:e,closed_at:o,...a})=>({...a,closedAt:o??null}),D0=new Set,Nl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch(a){if(!D0.has(e.id))D0.add(e.id),console.warn(`session ${e.id} metadata is not valid JSON and was ignored:`,a)}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var ql=new Set(["user","run","extension","notice_pending","compaction"]);class Dl{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=q0(e,this.entryTransactions),this.blobs={put:(o,a,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,a,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Ll)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Ll(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Ll(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[a,u]of e.entries())o.run(a,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){let o=this.sessionIDs(e);for(let a of o)this.invalidateEntryCache(a);this.db.transaction(()=>{let a=new Set;for(let u of o)for(let p of this.collectSessionBlobHashes(u))a.add(p);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(a)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(Nl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(Nl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(Nl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,a){this.insertSessionWithRecords(o,Jt(this.records(e),a))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let a=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:p}of o){let{seq:f,time:h,...g}=u,I=g,E=_l(I,this.blobs),S=p===void 0?null:JSON.stringify(Xc(I,p));a.run(e.id,f,h,JSON.stringify(E),S)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{let a=this.collectSessionBlobHashes(e.id,o);this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e),this.pruneCandidateBlobs(a)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let a=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)a.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.transaction(()=>{let o=new Set,a=[e];while(a.length>0){let u=a.pop();if(!u)continue;for(let p of this.collectSessionBlobHashes(u))o.add(p);for(let p of this.childSessions(u))a.push(p.id)}this.db.query("DELETE FROM sessions WHERE id = ?").run(e),this.pruneCandidateBlobs(o)})()}collectSessionBlobHashes(e,o=1){let a=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq >= ? AND body LIKE '%@blob:%'").all(e,o),u=new Set;for(let p of a)for(let f of p.body.matchAll(/@blob:([0-9a-f]{64})/g))if(f[1])u.add(f[1]);return u}pruneCandidateBlobs(e){if(e.size===0)return;let o=this.db.query("SELECT 1 AS one FROM entries WHERE body LIKE ? LIMIT 1"),a=this.db.query("DELETE FROM blobs WHERE hash = ?");for(let u of e)if(!o.get(`%@blob:${u}%`))a.run(u)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,a,u){Ys();let p=this.plugins,f=p?.pinEntry(a),h;try{return h=this.db.transaction(()=>{let g=Math.max(o??0,this.lastSeq(e)+1),E=(f&&p?p.beforeEntry(f,a,e,g):void 0)??a,S=JSON.stringify(E),k=f?JSON.parse(S):E,A={...k,seq:g,time:Date.now()},P=_l(k,this.blobs),v=P===k&&!f?S:JSON.stringify(P),M=u===void 0?null:JSON.stringify(Xc(k,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,g,A.time,v,M),A.type==="user"&&!(("notices"in A)&&A.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(A.time,e);return this.cacheAppended(e,A,v),A})(),h}finally{if(f&&p){let g={commit:()=>p.finishEntry(f,e,h),rollback:()=>p.finishEntry(f,e)},I=this.entryTransactions.at(-1);if(I)I.push(g);else g.commit()}}}setEntryRaw(e,o,a){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let p=bi(JSON.parse(u.body),this.blobs),f=Xc(p,a);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(f),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,a,u=!0){if(a&&a.length===0)return[];let p=a?.every((h)=>ql.has(h))?this.cachedEntries(e):void 0;if(p&&a)return p.filter((g)=>g.seq>o&&a.includes(g.type)).map((g)=>({...u?bi(g,this.blobs):g}));return(a?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...a):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((h)=>({...bi(JSON.parse(h.body),u?this.blobs:void 0),seq:h.seq,time:h.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let a=[...ql],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...a).map((p)=>({...JSON.parse(p.body),seq:p.seq,time:p.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,a){let u=this.smallEntries.get(e);if(!u||!ql.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(a),seq:o.seq,time:o.time})}entriesRange(e,o,a=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,a).map((u)=>({...bi(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let a=this.lastSeq(e),u=(I)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,I),p=u(o),f=p?.type==="run"&&p.state==="start"?o+1:o;if(f>=a)return a;let h=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,f,f);if(!h)return a;if(h.end)return h.seq;let g=u(h.seq-1);return g?.type==="run"&&g.state==="start"&&h.seq-1>f?h.seq-2:h.seq-1}entriesAround(e,o,a,u){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let f=Math.min(Math.max(1,o),p),h=this.alignToUser(e,Math.max(1,f-a)),g=this.alignToTurnEnd(e,Math.min(p,f+u));return this.window(e,h,g,p)}entriesFrom(e,o,a){let u=this.lastSeq(e),p=Math.max(1,o);if(p>u)return{entries:[],from:p,to:u,hasBefore:u>0,hasAfter:!1};let f=this.alignToTurnEnd(e,Math.min(u,p+a-1));return this.window(e,p,f,u)}window(e,o,a,u){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,a+1),from:o,to:a,hasBefore:p!==null,hasAfter:a<u}}replayStart(e,o,a,u=Number.POSITIVE_INFINITY){let p=this.lastSeq(e),f=this.lastEntry(e,"compaction"),h=f?.type==="compaction"?f.through+1:1,g=Math.max(1,p-o+1),I=Math.max(1,p-a+1,Math.min(h,g));return this.alignToUser(e,I<g?Math.min(g,this.budgetStart(e,I,u)):I)}budgetStart(e,o,a){let u=this.db.query("SELECT seq, length(body) AS size FROM entries WHERE session_id = ? AND seq >= ? ORDER BY seq DESC").all(e,o),p=0;for(let f of u)if(p+=f.size,p>a)return f.seq+1;return o}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((a)=>{let u=bi(JSON.parse(a.body),this.blobs);return{entry:{...u,seq:a.seq,time:a.time},...a.raw===null?{}:{raw:og(u,JSON.parse(a.raw))}}})}lastEntry(e,o){if(ql.has(o)){let u=this.cachedEntries(e);if(u){let p=u.findLast((f)=>f.type===o);return p?{...bi(p,this.blobs)}:void 0}}let a=this.db.query("SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return a?{...bi(JSON.parse(a.body),this.blobs),seq:a.seq,time:a.time}:void 0}async enqueueNotice(e,o){let a=this.truncationEpoch(e),u=o;if(this.plugins){let p=this.plugins.pin();try{let f=await p.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(f===null)return!1;o={...f,dedupeKey:u.dedupeKey,wake:u.wake&&f.wake,recovery:u.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==a)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((g)=>g.type==="notice_pending"&&g.notice.dedupeKey===o.dedupeKey||g.type==="user"&&g.notices?.some((I)=>I.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,a=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let f of a)if(f.type==="user"&&f.notices)for(let h of f.notices)u.add(h.dedupeKey);else if(f.type==="extension"&&f.namespace===so&&f.kind==="discarded"&&f.payload&&typeof f.payload==="object"&&"dedupeKey"in f.payload&&typeof f.payload.dedupeKey==="string")u.add(f.payload.dedupeKey);let p=[];for(let f of a)if(f.type==="notice_pending"&&!u.has(f.notice.dedupeKey))p.push(f.notice);return p}}function oe(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as NG,readdirSync as U0,statSync as B0}from"fs";import{join as G0}from"path";function Yc(e){try{return B0(e).size}catch{return 0}}function K0(e){try{return Math.round(B0(e).mtimeMs)}catch{return}}function H0(e){let o=0,a=0;try{let u=U0(e,{withFileTypes:!0});for(let p of u){let f=G0(e,p.name);if(p.isDirectory()){let h=H0(f);o+=h.bytes,a+=h.files}else if(p.isFile())o+=Yc(f),a+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:a}}function qG(e){if(!NG(e))return[];try{return U0(e,{withFileTypes:!0}).flatMap((o)=>{let a=G0(DG(e),o.name),u=K0(a);if(o.isDirectory()){let p=H0(a);return[{name:o.name,kind:"directory",bytes:p.bytes,files:p.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Yc(a),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,a)=>a.bytes-o.bytes||o.name.localeCompare(a.name))}catch{return[]}}function DG(e){return e}function Si(e,o){let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return 0;let u=Object.values(a)[0];return typeof u==="number"?u:0}function F0(e,o){try{let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return;let u=Object.values(a)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var FG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},jG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function UG(e){let o=new Map;try{let a=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let f of u)a.set(f.name,f.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let f of p){let h=a.get(f.name)??f.name;if(h.startsWith("sqlite_autoindex_")){let I=h.slice(17),E=I.lastIndexOf("_");if(E>0)h=I.slice(0,E)}let g=o.get(h)??{bytes:0,pages:0};o.set(h,{bytes:g.bytes+(Number(f.bytes)||0),pages:g.pages+(Number(f.pages)||0)})}}catch{}return o}function BG(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,a=e.db.query(`SELECT
|
|
369
|
-
count(*) AS total,
|
|
370
|
-
sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
|
|
371
|
-
sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
|
|
372
|
-
sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
|
|
373
|
-
sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
|
|
374
|
-
FROM sessions`).get(),u=e.db.query(`SELECT
|
|
375
|
-
count(*) AS total,
|
|
376
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
377
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
|
|
378
|
-
min(time) AS oldest_time,
|
|
379
|
-
max(time) AS newest_time
|
|
380
|
-
FROM entries`).get(),f=e.db.query(`SELECT
|
|
381
|
-
coalesce(json_extract(body, '$.type'), 'unknown') AS type,
|
|
382
|
-
count(*) AS count,
|
|
383
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
384
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes
|
|
385
|
-
FROM entries
|
|
386
|
-
GROUP BY type
|
|
387
|
-
ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((I)=>({type:String(I.type||"unknown"),count:Number(I.count)||0,bodyBytes:Number(I.body_bytes)||0,rawBytes:Number(I.raw_bytes)||0})),h=f.find((I)=>I.type==="compaction")?.count??0,g=[];try{let I=new Map,E=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let A of E)I.set(A.namespace,Number(A.max_ver)||0);let S=e.db.query(`SELECT
|
|
388
|
-
namespace,
|
|
389
|
-
count(*) AS keys,
|
|
390
|
-
coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
|
|
391
|
-
FROM plugin_kv
|
|
392
|
-
GROUP BY namespace
|
|
393
|
-
ORDER BY bytes DESC, keys DESC`).all(),k=new Set;for(let A of S){k.add(A.namespace);let P=I.get(A.namespace);g.push({namespace:A.namespace,keys:Number(A.keys)||0,bytes:Number(A.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[A,P]of I.entries())if(!k.has(A))g.push({namespace:A,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:o,mainSessionCount:Number(a?.main_count)||0,subSessionCount:Number(a?.sub_count)||0,forkedSessionCount:Number(a?.forked_count)||0,automationSessionCount:Number(a?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:h,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:f,pluginNamespaces:g}}function Fl(e,o){let a=Si(e,"page_size"),u=Si(e,"page_count"),p=Si(e,"freelist_count"),f=e.db.query("PRAGMA journal_mode").get(),h=e.db.query("SELECT sqlite_version() AS v").get(),g=Si(e,"synchronous"),I=Si(e,"auto_vacuum"),E=Si(e,"cache_size"),S=E<0?Math.abs(E)*1024:E*a,k=Si(e,"foreign_keys")===1,A=Si(e,"busy_timeout"),P=F0(e,"encoding")??"UTF-8",v=F0(e,"quick_check(1)")??"ok",M=e.path!==":memory:"?K0(e.path):void 0,J=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),O=UG(e),V=qG(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((j,te)=>j+te.bytes,0),database:{size:Yc(e.path),walSize:Yc(`${e.path}-wal`),shmSize:Yc(`${e.path}-shm`),sqliteVersion:h?.v??"unknown",journalMode:f?.journal_mode??"unknown",synchronous:FG[g]??String(g),foreignKeys:k,busyTimeout:A,encoding:P,autoVacuum:jG[I]??String(I),cacheSizeBytes:S,pageSize:a,pageCount:u,freelistCount:p,reclaimableBytes:p*a,schemaVersion:Si(e,"user_version"),...M!==void 0?{lastModified:M}:{},integrity:v},analytics:BG(e),entries:V,tables:J.map(({name:j,sql:te})=>{let se=j.replaceAll('"','""'),L=e.db.query(`SELECT count(*) AS count FROM "${se}"`).get().count,re=e.db.query(`PRAGMA table_info("${se}")`).all().map((X)=>X.name),he=e.db.query(`PRAGMA index_list("${se}")`).all().length,we=Boolean(te&&/WITHOUT\s+ROWID/i.test(te)),We=O.get(j);return{name:j,rows:L,...We?{bytes:We.bytes,pages:We.pages}:{},indexes:he,columns:re,withoutRowid:we}})}}function j0(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let a=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let f of a)for(let h of f.body.matchAll(/@blob:([0-9a-f]{64})/g)){let g=h[1];if(g)u.add(g)}let p=[];for(let f of o)if(!u.has(f.hash))p.push(f.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let f=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let h of p)f.run(h)})()}catch{return 0}return p.length}function W0(e,o,a){let u=Fl(e,o);if(a.vacuum)L0(e.db),e.invalidateEntryCache(),j0(e),e.db.run("VACUUM");else if(a.checkpoint)j0(e);if(a.checkpoint||a.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Fl(e,o)}}var GG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class jl{plugins;builtinNames;registered=new Map;constructor(e,o){this.plugins=e;this.builtinNames=o}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let o=e.name.trim().toLowerCase();if(!o)throw Error("Tool name cannot be empty");if(GG.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function z0(e,o){let a=En(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:a.length>0?a:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function V0(e,o){let a=e.options.visibleModelProviders?.(),p=(await e.options.models.getAvailable().catch(()=>[])).filter((h)=>!a||a.includes(h.provider)).map((h)=>({...z0(Mt(h),h),available:!0})),f=new Set(p.map((h)=>h.id));for(let h of[o,...e.list(!0,{archive:"all"}).map((g)=>g.model)]){if(f.has(h))continue;let g=Cn(e.options.models,h);if(!g||a&&!a.includes(g.provider))continue;f.add(h),p.push({...z0(h,g),available:!1})}return{models:p}}function J0(e,o){if(typeof o!=="string"||!Cn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as KG,statSync as HG}from"fs";import{basename as WG,resolve as zG}from"path";class ag{runtime;sessions;emit;arm;constructor(e,o,a,u){this.runtime=e;this.sessions=o;this.emit=a;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new m("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=zG(e.directory.trim());if(!KG(o)||!HG(o).isDirectory())throw new t(`${o} is not a directory on the server`);let a=this.runtime.store.projectByDirectory(o);if(a){if(a.closedAt!==null)return this.updateProject(a.id,{closed:!1});return a}let u=Date.now(),p={id:oe("p"),name:e.name?.trim()||WG(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((p)=>p.id)),a=new Set(e);if(!(a.size===e.length&&a.size===o.size&&e.every((p)=>o.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),a=[...this.sessions.values()].filter((p)=>p.projectID===e);if(a.some((p)=>p.status==="busy"))throw new Z("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let p of a)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as fK,readFileSync as hK}from"fs";import{homedir as gK}from"os";import{join as Au}from"path";var rv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),VG={user:["user"],assistant:["assistant"],thinking:["thinking"],tool:["tool_input","tool_output"],input:["tool_input"],output:["tool_output"],tool_input:["tool_input"],tool_output:["tool_output"],error:["error"],title:["title"],attachment:["attachment"],notice:["notice"],extension:["extension"]},JG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),mg={'"':['"'],"\u201C":["\u201D",'"']},ug=(e)=>e!==void 0&&/\s/.test(e),nv=(e)=>[...new Set(e)],Zc=(e)=>[...e].length;var QG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function XG(e,o){let a=e.trim().toLowerCase(),u=new Date(o),p=u.getFullYear(),f=u.getMonth(),h=u.getDate();if(a==="today")return{start:new Date(p,f,h).getTime(),end:new Date(p,f,h+1).getTime()};if(a==="yesterday")return{start:new Date(p,f,h-1).getTime(),end:new Date(p,f,h).getTime()};let g=/^(\d+)(h|d|w|mo|y)$/.exec(a);if(g)return{start:o-Number(g[1])*QG[g[2]]};if(/^\d{4}$/.test(a))return{start:new Date(Number(a),0,1).getTime(),end:new Date(Number(a)+1,0,1).getTime()};let I=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(a);if(!I)return null;let E=Number(I[1]),S=Number(I[3]);if(S<1||S>12)return null;if(I[4]===void 0){if(I[5]!==void 0)return null;return{start:new Date(E,S-1,1).getTime(),end:new Date(E,S,1).getTime()}}let k=Number(I[4]),A=Number(I[5]??0),P=Number(I[6]??0),v=Number(I[7]??0);if(A>23||P>59||v>59)return null;let M=new Date(E,S-1,k,A,P,v);if(M.getMonth()!==S-1||M.getDate()!==k)return null;if(I[5]!==void 0)return{start:M.getTime()};return{start:M.getTime(),end:new Date(E,S-1,k+1).getTime()}}var YG=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),pg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),lg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function cg(e,o,a,u,p,f){let h=a.trim(),g=(E,S)=>e.diagnostics.push({code:E,message:S,filter:o});if(!h)return g("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return g("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let I=p?[h]:h.split(",").map((E)=>E.trim()).filter(Boolean);switch(o){case"in":case"project":for(let E of I){let S=E.toLowerCase();if(o==="in"&&S==="this")e.currentSession=!0;else if(o==="in"&&S==="title")e.fields.push("title");else e.projectID.push(E)}return;case"session":for(let E of I)if(E.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(E);return;case"from":case"role":for(let E of I){let S=VG[E.toLowerCase()];if(S)e.fields.push(...S);else g("bad_filter_value",`${o}:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...I);return;case"model":e.model.push(...I);return;case"is":for(let E of I){let S=E.toLowerCase();if(S==="error")e.isError=!u;else if(S==="archived")e.archived=!u;else if(S==="compacted")e.compacted=!u;else g("bad_filter_value",`is:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let E=XG(h,f);if(!E)return g("bad_filter_value",`${o}:${h} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=pg(e.after,E.start);else if(o==="before")e.before=lg(e.before,E.start);else if(e.after=pg(e.after,E.start),E.end!==void 0)e.before=lg(e.before,E.end)}}}function ZG(e,o){let a={},u=(v,M)=>{let J=nv([...v??[],...M]);return J.length?J:void 0},p=u(e?.projectID,o.projectID),f=u(e?.sessionID,o.sessionID),h=u(e?.fields,o.fields),g=u(e?.tools,o.tools),I=u(e?.model,o.model);if(p)a.projectID=p;if(f)a.sessionID=f;if(h)a.fields=h;if(g)a.tools=g;if(I)a.model=I;let E=o.isError??e?.isError,S=o.archived??e?.archived,k=o.compacted??e?.compacted;if(E!==void 0)a.isError=E;if(S!==void 0)a.archived=S;if(k!==void 0)a.compacted=k;let A=pg(e?.after,o.after),P=lg(e?.before,o.before);if(A!==void 0)a.after=A;if(P!==void 0)a.before=P;if(A!==void 0&&P!==void 0&&A>=P)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return a}function Q0(e,o){let a=mg[e[o]]??['"'],u="",p=o+1;while(p<e.length){let f=e[p],h=e[p+1];if(f==="\\"&&h!==void 0&&(h==="\\"||h==='"'||h==="\u201C"||h==="\u201D")){u+=h,p+=2;continue}if(a.includes(f))return{text:u,next:p+1,closed:!0};u+=f,p++}return{text:u,next:p,closed:!1}}function X0(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let a=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(a.length!==e.length-1)return;let u=a.toLowerCase();return rv.has(u)?u:void 0}function Y0(e,o,a){let u=e==="word"&&!a&&Zc(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:a,fuzzy:u}}function eK(e,o){let a=[],u=e.length,p=0;while(p<u){if(ug(e[p])){p++;continue}let f=!1;if(e[p]==="-"){if(p+1>=u||ug(e[p+1])){p++;continue}f=!0,p++}if(mg[e[p]]){let P=Q0(e,p);if(p=P.next,!P.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let v=P.text.trim();if(v)a.push({kind:"term",negated:f,term:Y0("phrase",v,!1)});continue}let h=[],g;while(p<u&&!ug(e[p])){let P=e[p],v=e[p+1];if(P==="\\"&&v!==void 0&&JG.has(v)){h.push({c:v,esc:!0}),p+=2;continue}let M=mg[P]?X0(h):void 0;if(M){let J=Q0(e,p);if(p=J.next,!J.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});g={key:M,value:J.text,quoted:!0};break}h.push({c:P,esc:!1}),p++}if(g){a.push({kind:"filter",negated:f,...g});continue}let I=h.findIndex((P,v)=>v>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),E=I>0?X0(h.slice(0,I+1)):void 0;if(E){a.push({kind:"filter",negated:f,key:E,value:h.slice(I+1).map((P)=>P.c).join(""),quoted:!1});continue}if(!f&&h.length===2&&h.every((P)=>!P.esc)&&h[0]?.c==="O"&&h[1]?.c==="R"){a.push({kind:"or"});continue}let S=h[h.length-1],k=h.length>1&&S!==void 0&&!S.esc&&S.c==="*",A=(k?h.slice(0,-1):h).map((P)=>P.c).join("");if(A)a.push({kind:"term",negated:f,term:Y0("word",A,k)})}return a}var tK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function Z0(e){let o=[];return{rest:e.replace(tK,(u,p,f,h,g)=>{let I=h.toLowerCase();if(!rv.has(I))return u;let E=g.startsWith('"')&&g.length>=2;return o.push({key:I,value:E?g.slice(1,-1).replace(/\\(["\\])/g,"$1"):g,negated:f==="-",quoted:E}),p}).trim(),filters:o}}var ev={n:`
|
|
394
|
-
`,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function rK(e){let o=[...e],a=0,u=(S)=>{let k=o.slice(a,a+S).join("");if(k.length!==S||!/^[0-9a-fA-F]+$/.test(k))return;return a+=S,String.fromCodePoint(Number.parseInt(k,16))},p=()=>{let S=o[a++];if(S===void 0)return{kind:"lit",ch:"\\"};if(S in ev)return{kind:"lit",ch:ev[S]};if("dDwWsS".includes(S))return{kind:"any"};if(S==="b"||S==="B")return{kind:"zero"};if(S>="1"&&S<="9"){while(o[a]!==void 0&&/\d/.test(o[a]))a++;return{kind:"any"}}if(S==="k"||S==="p"||S==="P"){let k=o[a];if(k==="<"||k==="{"){let A=k==="<"?">":"}",P=o.indexOf(A,a);a=P<0?o.length:P+1}return{kind:"any"}}if(S==="c")return a++,{kind:"any"};if(S==="x"){let k=u(2);return k===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:k}}if(S==="u"){if(o[a]==="{"){let A=o.indexOf("}",a),P=A<0?"":o.slice(a+1,A).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return a=A+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let k=u(4);return k===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:k}}return{kind:"lit",ch:S}},f=()=>{if(o[a]==="^")a++;while(a<o.length&&o[a]!=="]")a+=o[a]==="\\"?2:1;return a++,{kind:"any"}},h=()=>{let S="capture";if(o[a]==="?"){let A=o[a+1],P=o[a+2];if(A===":")S="plain",a+=2;else if(A==="="||A==="!")S="look",a+=2;else if(A==="<"&&(P==="="||P==="!"))S="look",a+=3;else if(A==="<"){let v=o.indexOf(">",a);a=v<0?o.length:v+1}else{S="opaque";while(a<o.length&&o[a]!==":"&&o[a]!==")")a++;if(o[a]===":")a++}}let k=E();if(o[a]===")")a++;if(S==="look")return{kind:"zero"};return{kind:"group",alts:k,opaque:S==="opaque"}},g=()=>{let S=o[a],k=1,A=!0;if(S==="*"||S==="?")k=0,a++;else if(S==="+")a++;else if(S==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(a,a+24).join(""));if(!P)return{quantified:!1,min:1};k=Number(P[1]),a+=P[0].length}else return{quantified:!1,min:1};if(o[a]==="?")a++;return{quantified:A,min:k}},I=()=>{let S=[];while(a<o.length){let k=o[a];if(k==="|"||k===")")break;a++;let A;if(k==="(")A=h();else if(k==="[")A=f();else if(k==="\\")A=p();else if(k===".")A={kind:"any"};else if(k==="^"||k==="$")A={kind:"zero"};else if(k==="*"||k==="+"||k==="?")A={kind:"zero"};else A={kind:"lit",ch:k};S.push({atom:A,...g()})}return S};function E(){let S=[I()];while(o[a]==="|")a++,S.push(I());return S}return E()}function tv(e){let o=[],a="",u=()=>{if(a)o.push([a]);a=""},p=(f)=>{for(let h of f){let g=h.atom;if(g.kind==="lit")if(h.min>=1){if(a+=g.ch,h.quantified)u()}else u();else if(g.kind==="group"&&!g.opaque&&h.min>=1)if(g.alts.length===1&&!h.quantified)p(g.alts[0]);else u(),o.push(...ov(g.alts));else u()}};return p(e),u(),o}function ov(e){if(e.length===1)return tv(e[0]);let o=[];for(let a of e){let u=tv(a).filter((p)=>p.length===1).map((p)=>p[0]);if(!u.length)return[];o.push(u.reduce((p,f)=>Zc(f)>Zc(p)?f:p))}return[nv(o)]}var nK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function oK(e){return!/^\s*$/.test(e)&&(Zc(e)>=2||nK.test(e))}function sK(e){let o;try{o=ov(rK(e))}catch{return[]}let a=o.filter((I)=>I.every(oK)),u=a.filter((I)=>I.length===1).map((I)=>I[0]),p=a.filter((I)=>{if(I.length!==1)return!0;let E=I[0];return!u.some((S)=>S!==E&&S.includes(E))}),f=new Set,h=p.filter((I)=>{let E=JSON.stringify(I);if(f.has(E))return!1;return f.add(E),!0}),g=(I)=>Math.min(...I.map(Zc));return h.sort((I,E)=>g(E)-g(I))}function iK(e){let o=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(o)}function aK(e,o){let a=`m${o?"":"i"}`;try{return new RegExp(e,`${a}u`),{flags:`${a}u`}}catch{}try{return new RegExp(e,a),{flags:a}}catch(u){let p=u instanceof Error?u.message:String(u),f="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))f="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))f="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))f="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))f="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${f}`}}}function Ul(e,o={}){let a=o.now??Date.now(),u=e.q??"",p=YG(),f=p.diagnostics,h,g=[];if(e.mode==="regex"){let M=Z0(u);for(let J of M.filters)cg(p,J.key,J.value,J.negated,J.quoted,a);h=M.rest}else{let M=Z0(u),J=/^\/([\s\S]+)\/$/.exec(M.rest);if(J){for(let O of M.filters)cg(p,O.key,O.value,O.negated,O.quoted,a);h=J[1]}else{g=[{include:[],exclude:[]}];for(let O of eK(u,f)){let V=g[g.length-1];if(O.kind==="or")g.push({include:[],exclude:[]});else if(O.kind==="filter")cg(p,O.key,O.value,O.negated,O.quoted,a);else(O.negated?V.exclude:V.include).push(O.term)}g=g.filter((O)=>O.include.length||O.exclude.length)}}let I=g.flatMap((M)=>[...M.include,...M.exclude]),E=h!==void 0?iK(h):I.some((M)=>/\p{Lu}/u.test(M.text)),S=e.caseSensitive??E,k=e.caseSensitive===void 0&&E,A,P;if(h){let M=aK(h,S);if("message"in M)P={code:"bad_regex",message:M.message};else{let J=sK(h);A={source:h,flags:M.flags,literals:J,deepScan:J.length===0}}}let v=ZG(e.filters,p);return{mode:h!==void 0?"regex":"text",branches:g,...A?{regex:A}:{},filters:v,currentSession:p.currentSession,caseSensitive:S,smartCase:k,wholeWord:e.wholeWord??!1,fuzzy:g.some((M)=>M.include.some((J)=>J.fuzzy)),hasPositive:A!==void 0||g.some((M)=>M.include.length>0),hasFilters:Object.keys(v).length>0||p.currentSession,...P?{error:P}:{},diagnostics:f}}var fg={title:8,user:5,assistant:3,error:3,tool_input:2,notice:2,extension:1,thinking:0.5,tool_output:0.5,attachment:0.5},sv=new WeakMap;function iv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,a=sv.get(e);if(a?.version===o)return a.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return sv.set(e,{version:o,terms:u}),u}var dg=32,uK=1024,em=(e)=>`"${e.replaceAll('"','""')}"`;function cK(e,o){let a=Array.from({length:o.length+1},(u,p)=>p);for(let u=0;u<e.length;u++){let p=[u+1];for(let f=0;f<o.length;f++)p.push(Math.min((p[f]??0)+1,(a[f+1]??0)+1,(a[f]??0)+Number(e[u]!==o[f])));a=p}return a[o.length]??e.length}function hg(e,o){let a=Dt(o.trim());if(!a||a.length>64)return[];let u=iv(e),p=u.filter((g)=>g.t.startsWith(a)).slice(0,8).map((g)=>g.t);if(p.length>=8||a.length<4)return p;let f=a.length>=8?2:1,h=[];for(let g of u){if(Math.abs(g.t.length-a.length)>f)continue;if(cK(a,g.t)<=f)h.push(g.t);if(h.length>=8)break}return[...new Set([...p,...h])].slice(0,8)}function av(e,o){let a=!1,u=[],p=[],f=o.filters,h=(J,O)=>{if(!O?.length)return;p.push(`${J} IN (${O.map(()=>"?").join(",")})`),u.push(...O)};if(h("s.project_id",f.projectID),f.sessionID?.length){p.push(`(${f.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let J of f.sessionID)u.push(J,J)}if(f.archived!==void 0)p.push(`s.archived_at IS ${f.archived?"NOT ":""}NULL`);let g=p.length?p.join(" AND "):"1",I=[...u];if(h("r.kind",f.fields?.map((J)=>$e[J])),h("r.tool",f.tools),f.model?.length){p.push(`(${f.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let J of f.model)u.push(J,J)}if(f.isError!==void 0)p.push("r.err = ?"),u.push(Number(f.isError));if(f.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
|
|
395
|
-
SELECT max(json_extract(body,'$.through')) FROM store.entries
|
|
396
|
-
WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
|
|
397
|
-
),0)) = ?`),u.push(Number(f.compacted));if(f.after!==void 0)p.push("r.time >= ?"),u.push(f.after);if(f.before!==void 0)p.push("r.time < ?"),u.push(f.before);let E=e.query("SELECT v FROM meta WHERE k='layout'").get(),S=E&&JSON.parse(E.v).msg==="trigram",k=!o.hasPositive||Boolean(o.regex?.deepScan),A=(J)=>{let O=(te)=>{let se=Dt(te);if(!J&&S){if([...se].length<3){let X=[...se].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(se,`${se}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(se);if([...se].length===1&&X.length>dg)X.length=dg,a=!0;if(!X.length)return em("__basalt_no_short_match__");return`(${X.map((Y)=>em(Y.term)).join(" OR ")})`}return em(se)}let L=/^[\p{Script=Latin}\p{N}]+$/u.test(te)?[se]:bs(te),re=L.filter((X)=>!/^[a-z0-9]{1,2}$/.test(X)),he=re.length?re:L;if(!he.length){k=!0;return}let we=he.map((X,Y)=>{let xe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(X),Ve=he.length>2&&Y>0&&Y<he.length-1;if(xe||Ve){let ke=e.query("SELECT n FROM term WHERE t=?").get(X)?.n??0;return{expression:em(X),frequency:ke}}let He=[X],ar=0;for(let ke of iv(e)){if(!ke.t.includes(X))continue;if(ar+=ke.n,ke.t!==X)He.push(ke.t);if(He.length>=dg){a=!0;break}}return{expression:`(${He.map(em).join(" OR ")})`,frequency:ar}});return we.sort((X,Y)=>X.frequency-Y.frequency),`(${we.slice(0,(we[0]?.frequency??1/0)<=uK?1:2).map((X)=>X.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((te)=>te.include.map((se)=>se.text));if(o.regex){let te=V.map((se)=>se.map(O));if(te.some((se)=>se.some((L)=>!L)))return;return te.map((se)=>`(${se.join(" OR ")})`).join(" AND ")||void 0}let j=V.map((te)=>{let se=te.filter((L)=>!/^[a-z0-9]{1,2}$/i.test(L));return(se.length?se:te).map(O)});if(j.some((te)=>!te.length||te.some((se)=>!se)))return;return j.map((te)=>`(${te.join(" AND ")})`).join(" OR ")||void 0},P=A(!1),v=A(!0),M=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:v,scan:k,where:p.length?p.join(" AND "):"1",bindings:u,forks:M,sessionWhere:g,sessionBindings:I,partial:a,candidateLimit:o.branches.some((J)=>J.include.length>0&&J.include.every((O)=>[...O.text].length<2))?512:void 0}}function uv(e){let o=1/0,a=-1/0;for(let u of e)o=Math.min(o,u.relevance),a=Math.max(a,u.relevance);return e.map((u)=>({...u,relevance:o===a?-1:-(0.5+0.5*(a-u.relevance)/(a-o))}))}function Bl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(fg).map(([a,u])=>`WHEN ${$e[a]} THEN ${u}`).join(" ")} ELSE 1 END) *
|
|
398
|
-
(0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function cv(e,o,a,u){let p=Math.max(0,u-a)/86400000;return Math.max(0.000000001,-e)*fg[o]*(0.3+0.7/(1+p/30))}function gg(e,o){return e.sort((a,u)=>(o==="best"?u.score-a.score:0)||(o==="recent"?u.time-a.time:0)||(a.sessionID<u.sessionID?-1:Number(a.sessionID>u.sessionID))||u.seq-a.seq||a.field.localeCompare(u.field))}var xg=512;function mv(e,o,a){let u=performance.now(),p=o.partial;Ig(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[f,h]of[["fts",o.msg],["fts_out",o.out]]){if(!h)continue;let g=o.candidateLimit??2000,I=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
|
|
399
|
-
ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(h,o.candidateLimit?g+1:g);if(o.candidateLimit&&I.length>g)I.length=g,p=!0;else if(!o.candidateLimit&&I.length===g){let S=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
|
|
400
|
-
AND rowid NOT IN (SELECT value FROM json_each(?))`).all(h,JSON.stringify(I.map((k)=>k.doc)));for(let k of S)I.push(k)}let E=uv(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
|
|
401
|
-
FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(E))}return a?.("match",performance.now()-u),p}function pv(e,o,a,u,p){let f=performance.now();if(o.candidateLimit){let g=e.query(`
|
|
402
|
-
SELECT r.session_id,r.seq,${Bl(u)} AS score
|
|
403
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
404
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
405
|
-
WHERE ${o.where} LIMIT ${o.candidateLimit+1}
|
|
406
|
-
`).all(...o.bindings);if(g.length>o.candidateLimit)g.length=o.candidateLimit,o.partial=!0;let I=new Map;for(let E of g){let S=a?E.seq:0,k=JSON.stringify([E.session_id,S]),A=I.get(k);if(!A||E.score>A.score)I.set(k,{...E,seq:S})}return p?.("filter",performance.now()-f),[...I.values()].sort((E,S)=>S.score-E.score||(E.session_id<S.session_id?-1:Number(E.session_id>S.session_id))||S.seq-E.seq)}let h=e.query(`
|
|
407
|
-
SELECT r.session_id,${a?"r.seq":"0"} AS seq,max(${Bl(u)}) AS score
|
|
408
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
409
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
410
|
-
WHERE ${o.where}
|
|
411
|
-
GROUP BY r.session_id${a?",r.seq":""}
|
|
412
|
-
ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
|
|
413
|
-
`).all(...o.bindings);return p?.("filter",performance.now()-f),h}var lv=new WeakMap,mK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
|
|
414
|
-
SELECT id,forked_from_id,forked_from_seq FROM store.sessions
|
|
415
|
-
WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
|
|
416
|
-
UNION
|
|
417
|
-
SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
|
|
418
|
-
FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
|
|
419
|
-
WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
|
|
420
|
-
)`;function Ig(e,o){if(!o.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${mK} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let a=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();lv.set(e,new Map(a.map((u)=>[u.ancestor,u.through])))}function yg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
|
|
421
|
-
SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
|
|
422
|
-
JOIN store.sessions ps ON ps.id=pr.session_id
|
|
423
|
-
WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
|
|
424
|
-
AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
|
|
425
|
-
AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
|
|
426
|
-
SELECT 1 FROM store.entries original JOIN store.entries copied
|
|
427
|
-
ON copied.session_id=r.session_id AND copied.seq=r.seq
|
|
428
|
-
WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
|
|
429
|
-
))
|
|
430
|
-
))`}function dv(e,o,a,u,p){let f=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let h=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,g=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
|
|
431
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${h>4000?"INDEXED BY ref_time":""}
|
|
432
|
-
${g} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${yg(o)}
|
|
433
|
-
ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${u} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],a);let I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(I===u){let E=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(E)e.query(`
|
|
434
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${g}
|
|
435
|
-
WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
|
|
436
|
-
AND ${o.where} AND ${yg(o)} AND NOT EXISTS (
|
|
437
|
-
SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
|
|
438
|
-
)`).run(E.session_id,E.seq,...o.bindings,...o.forks?o.bindings:[]),I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-f),I}function fv(e,o,a,u,p,f,h){let g=performance.now(),I=o.group==="none",E=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",S=e.query(`
|
|
439
|
-
SELECT r.session_id,${I?"r.seq":"0"} AS seq,
|
|
440
|
-
max(${Bl(p)}) AS relevance,max(r.time) AS time
|
|
441
|
-
FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
|
|
442
|
-
WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
|
|
443
|
-
GROUP BY r.session_id${I?",r.seq":""}
|
|
444
|
-
ORDER BY ${E},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(f),u,a);return h?.("group",performance.now()-g),S}function hv(e,o,a,u,p,f){let h=performance.now(),g=p?o:{...o,forks:!1},I=e.query(`
|
|
445
|
-
SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
|
|
446
|
-
${g.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
447
|
-
WHERE r.session_id=? ${u?"AND r.seq=?":""}
|
|
448
|
-
AND ${o.where} AND ${yg(g)}
|
|
449
|
-
${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(a.session_id,...u?[a.seq]:[],...o.bindings,...g.forks?o.bindings:[]);return f?.("filter",performance.now()-h),I}function Eg(e,o,a,u){if(!o.forks)return[];let p=lv.get(e)?.get(a.session_id);if(p===void 0||a.seq>p)return[];return e.query(`
|
|
450
|
-
SELECT DISTINCT r.session_id,s.title,e.body
|
|
451
|
-
FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
|
|
452
|
-
CROSS JOIN ref r ON r.session_id=l.child
|
|
453
|
-
JOIN store.sessions s ON s.id=r.session_id
|
|
454
|
-
LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
|
|
455
|
-
WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(a.session_id,a.doc,a.seq,a.part,...o.bindings).filter((f)=>{if(a.seq===0)return f.title===u;if(!f.body)return!1;let h=JSON.parse(f.body);return it(h,!0).some((g)=>g.part===a.part&&g.kind===bo[a.kind]&&g.text===u)}).map((f)=>f.session_id)}function pK(e,o){let a=o?e:Dt(e);if(a.length===e.length)return{normalized:a,starts:void 0,ends:void 0};let u="",p=[],f=[],h=0;for(let g of e){let I=o?g:Dt(g);u+=I;for(let E=0;E<I.length;E++)p.push(h),f.push(h+g.length);h+=g.length}return{normalized:u,starts:p,ends:f}}function Gl(e,o){if(o.regex){let I=new RegExp(o.regex.source,`${o.regex.flags}g`),E=[];for(let S of e.matchAll(I)){if(o.wholeWord&&!gv(e,S.index,S.index+S[0].length))continue;E.push([S.index,S.index+S[0].length])}return E.length?E:void 0}let{normalized:a,starts:u,ends:p}=pK(e,o.caseSensitive),f=(I)=>{let E=o.caseSensitive?I.text:Dt(I.text),S=[],k=a.indexOf(E);while(k>=0&&E){let A=u?u[k]:k,P=p?p[k+E.length-1]:k+E.length,v=A===0||A!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(A-1,A))||/[a-z0-9][A-Z]/.test(e.slice(A-1,A+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(I.text));if(A!==void 0&&P!==void 0&&(!I.prefix||v)&&(!o.wholeWord||gv(e,A,P)))S.push([A,P]);k=a.indexOf(E,k+Math.max(1,E.length))}return S};if(!o.branches.length)return[];let h=[],g=!1;for(let I of o.branches){if(I.exclude.some((S)=>f(S).length))continue;let E=I.include.map(f);if(E.some((S)=>!S.length))continue;g=!0,h.push(...E.flat())}return g?h:void 0}function gv(e,o,a){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(a===e.length||!u.test(e.slice(a,a+1)))}function Kl(e,o){let a=e.split(`
|
|
456
|
-
`),u=new Set,p=0,f=a.map((h,g)=>{let I=p;if(o.some(([E,S])=>E<=I+h.length&&S>=I))for(let E=Math.max(0,g-1);E<=Math.min(a.length-1,g+1);E++)u.add(E);return p+=h.length+1,I});if(!u.size)u.add(0);return[...u].sort((h,g)=>h-g).slice(0,5).map((h)=>{let g=a[h]??"",I=f[h]??0,E=o.filter(([P,v])=>v>I&&P<I+g.length),S=Math.max(0,(E[0]?.[0]??I)-I-100),k=g.slice(S,S+300),A=E.map(([P,v])=>[Math.max(0,P-I-S),Math.min(k.length,v-I-S)]);return{text:k,line:h+1,ranges:A.filter(([P,v])=>P<v)}})}var yv=3;function lK(e){return Boolean(e&&typeof e==="object"&&"score"in e&&typeof e.score==="number"&&Number.isFinite(e.score)&&"sessionID"in e&&typeof e.sessionID==="string"&&e.sessionID.length<=1024&&"seq"in e&&typeof e.seq==="number"&&Number.isSafeInteger(e.seq)&&e.seq>=0)}function xv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function dK(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let a=JSON.parse(Buffer.from(e,"base64url").toString());if(a&&typeof a==="object"&&"offset"in a&&"key"in a&&"now"in a&&a.key===o&&typeof a.offset==="number"&&Number.isSafeInteger(a.offset)&&a.offset>=0&&typeof a.now==="number"&&Number.isFinite(a.now)){let u="window"in a?a.window:0,p="seen"in a?a.seen:[],f="emitted"in a?a.emitted:[],h="after"in a?a.after:void 0;if(h!==void 0&&!lK(h))throw Error("invalid best cursor");let g=(I)=>Array.isArray(I)&&I.every((E)=>typeof E==="string"&&E.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&g(p)&&g(f))return{offset:a.offset,key:o,now:a.now,window:u,seen:p,emitted:f,after:h}}}catch{}throw Error("invalid search cursor")}function gn(e,o){let a=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return dK(e.cursor,a)}async function kr(e,o,a){let u="search"in e?e.search:e,p=performance.now(),f=(ke)=>{if(!a.signal?.aborted)a.onEvent(ke)};if(a.signal?.aborted)return;let h=gn(o,a.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let g=Ul(o,{now:h.now});if(g.error){f({type:"error",...g.error});return}if(g.currentSession){if(!a.sessionID){f({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}g.filters.sessionID=[a.sessionID]}if(!o.deep&&g.regex?.deepScan){f({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),a.signal?.aborted)return;let I=performance.now(),E=u.withIndex((ke)=>av(ke,g));if(!E){f({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}a.onTiming?.("plan",performance.now()-I);let S=E.partial,k=h.after,A=new Map,P=new Map,v=[],M=!1,J=new Map,O=new WeakMap,V=new Map,j=new Map,{offset:te,window:se}=h,L=[...h.seen],re=[...h.emitted],he=!1,we=Math.max(1,Math.min(200,o.limit??30)),We=Math.min(E.candidateLimit??2000,o.group==="none"?xg:Math.min(2000,Math.max(xg,we*32))),X=(ke,Me)=>{let Wt=A.get(Me);if(Wt)return Wt;let ht=ke.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Me);if(ht)A.set(Me,ht);return ht??void 0},Y=(ke,Me,Wt)=>{if(a.allowedSessionIDs&&!a.allowedSessionIDs.has(Me.session_id))return;if(a.excludeEntry?.sessionID===Me.session_id&&a.excludeEntry.seq===Me.seq)return;let ht=X(ke,Me.session_id);if(!ht)return;let Ft=bo[Me.kind];if(!Ft)return;let xr=ht.title;if(Me.seq!==0){let at=`${Me.session_id}:${Me.seq}`,ur=j.get(at);if(!ur){let un=Wt?void 0:ke.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Me.session_id,Me.seq);if(!Wt&&!un)return;let or=Wt??JSON.parse(un?.body??"null");ur=it(or,!0),j.set(at,ur)}let pr=ur.find((un)=>un.part===Me.part&&un.kind===Ft);if(!pr)return;xr=pr.text}let fr=Gl(xr,g);if(!fr)return;let Zt=P.get(ht.id);if(Zt===void 0)Zt=ke.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(ht.id)?.through??0,P.set(ht.id,Zt);let st=Me.seq>0&&Me.seq<=Zt;if(g.filters.compacted!==void 0&&st!==g.filters.compacted)return;let $t={sessionID:ht.id,seq:Me.seq,time:Me.time,field:Ft,tool:Me.tool??void 0,isError:Boolean(Me.err),model:Me.model??void 0,snippet:[],score:cv(Me.relevance,Ft,Me.time,h.now),flags:{archived:ht.archived_at!==null,compacted:st,partial:xr.length>ms+hs}};return J.set($t,{text:xr,ranges:fr}),v.push($t),M=!0,V.set($t,{doc:Me.doc,part:Me.part}),$t},xe=(ke)=>{let Me=performance.now(),Wt=[...ke].sort((st,$t)=>st.time-$t.time||st.sessionID.localeCompare($t.sessionID)),ht=[],Ft=new Map;for(let st of Wt){let $t=V.get(st),ur=A.get(st.sessionID),pr=new Set;while(ur?.forked_from_id&&ur.forked_from_seq!==null&&st.seq<=ur.forked_from_seq&&!pr.has(ur.id))pr.add(ur.id),ur=A.get(ur.forked_from_id)??u.withIndex((Uo)=>X(Uo,ur?.forked_from_id??""));let un=`${ur?.id??st.sessionID}:${st.seq}:${$t?.part}:${$t?.doc}`,or=Ft.get(un);if(or){if(or.sessionID!==st.sessionID)or.forks=[...new Set([...or.forks??[],st.sessionID])]}else Ft.set(un,st),ht.push(st)}let xr=[],fr=new Map,Zt=new Map;for(let st of ht){let $t=`${st.sessionID}:${st.seq}`,at=Zt.get($t);if(!at){Zt.set($t,st),O.set(st,[st]);continue}let ur=[...O.get(at)??[at],st],pr=st.score>at.score?st:at;if(pr.forks=[...new Set([...at.forks??[],...st.forks??[]])],!pr.forks.length)pr.forks=void 0;pr.flags={archived:at.flags.archived||st.flags.archived,compacted:at.flags.compacted||st.flags.compacted,partial:at.flags.partial||st.flags.partial},Zt.set($t,pr),O.set(pr,ur)}for(let st of gg([...Zt.values()],o.sort??"best")){let $t=A.get(st.sessionID);if(!$t)continue;let at=o.group==="none"?void 0:fr.get($t.id);if(!at)at={session:{id:$t.id,title:$t.title,projectID:$t.project_id,updated:$t.updated},hits:[],more:0,...S&&o.group!=="none"?{moreIsLowerBound:!0}:{}},xr.push(at),fr.set($t.id,at);if(at.hits.length<yv||o.group==="none")at.hits.push(st);else at.more++}return a.onTiming?.("group",performance.now()-Me),xr},Ve=(ke)=>{for(let Me of ke)for(let Wt of Me.hits){if(a.allowedSessionIDs&&Wt.forks)Wt.forks=Wt.forks.filter((xr)=>a.allowedSessionIDs?.has(xr));let ht=performance.now(),Ft=new Map;for(let xr of O.get(Wt)??[Wt]){let fr=J.get(xr);if(!fr)continue;for(let Zt of Kl(fr.text,fr.ranges)){let st=`${Zt.line}:${Zt.text}`,$t=Ft.get(st);if(!$t)Ft.set(st,Zt);else $t.ranges=[...new Map([...$t.ranges,...Zt.ranges].map((at)=>[at.join(":"),at])).values()]}}Wt.snippet=[...Ft.values()],a.onTiming?.("snippet",performance.now()-ht)}},He=o.deep||E.scan,ar=(ke,Me)=>{let Wt=X(ke,Me.session_id);if(!Wt)return[];let ht=hv(ke,E,Me,o.group==="none",Wt.forked_from_id!==null,a.onTiming);if(E.candidateLimit&&ht.length>E.candidateLimit)ht.length=E.candidateLimit,S=!0;let Ft=v.length,xr=performance.now();for(let fr of ht){if(a.signal?.aborted)break;let Zt=Y(ke,fr);if(!Zt)continue;let st=Eg(ke,E,fr,J.get(Zt)?.text??"");if(st.length)Zt.forks=st}return a.onTiming?.("body",performance.now()-xr),v.slice(Ft)};if(He){S=!1;let ke=[],Me=new Set,Wt=u.withIndex((at)=>{Ig(at,E);for(let or of at.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())A.set(or.id,or);let ur=new Set(at.query(`SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}`).all(...E.sessionBindings).map((or)=>or.id)),pr=(or)=>{if(Me.has(or.id))return;Me.add(or.id);let Uo=or.forked_from_id?A.get(or.forked_from_id):void 0;if(Uo)pr(Uo);if(ur.has(or.id))ke.push(or)};for(let or of A.values())pr(or);return(at.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
|
|
457
|
-
SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}
|
|
458
|
-
)`).get(...E.sessionBindings)?.n??0)+ur.size})??0,ht=0,Ft=0,xr=0;if(g.regex?.deepScan)f({type:"groups",groups:[]});let fr=new Set,Zt=new Set,st=new Map,$t=()=>{let at=xe(v),ur=[];for(let pr of at){let un=pr.session.id,or=o.group==="none"?void 0:st.get(un);if(o.group!=="none"&&Zt.has(un)&&!or)continue;if(!or){if(Zt.add(un),Ft<h.offset){Ft++;continue}if(xr>=we){he=!0;break}xr++,te++}if(o.group!=="none"){let Uo=(or?.count??0)+pr.hits.length+pr.more;pr.hits=pr.hits.slice(0,yv-(or?.shown??0));let Pu=(or?.shown??0)+pr.hits.length;pr.more=Uo-Pu,st.set(un,{shown:Pu,count:Uo})}ur.push(pr)}if(ur.length)Ve(ur),f({type:"groups",groups:ur});v.length=0,J.clear(),V.clear(),j.clear()};for(let at of ke){if(a.signal?.aborted||he)break;let ur=-1,pr;for(;;){if(a.signal?.aborted||he)break;let un=u.withIndex((or)=>{let Uo=or.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(at.id,Math.max(0,ur));if(ur<0)Uo.unshift({seq:0,time:at.updated,body:null});for(let ta of Uo){if(a.signal?.aborted)break;let $u=ta.body?JSON.parse(ta.body):void 0;if($u?.type==="assistant")pr=$u.model;let bv=$u?it($u,!0):[{part:0,kind:"title",text:at.title}];for(let ts of bv){if(a.signal?.aborted)break;let Zs={session_id:at.id,seq:ta.seq,part:ts.part,doc:Number(BigInt(Bun.hash(ts.text))&0x1fffffffffffffn),kind:$e[ts.kind],tool:ts.tool??null,err:Number(ts.err??!1),model:ts.model??(ts.tool?pr:void 0)??null,time:ta.time,relevance:-1};if(!or.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
|
|
459
|
-
JOIN store.sessions s ON s.id=r.session_id WHERE ${E.where}`).get(Zs.session_id,Zs.seq,Zs.kind,Zs.tool,Zs.err,Zs.model,Zs.time,...E.bindings))continue;let wi=at,wg=new Set;while(wi.forked_from_id&&wi.forked_from_seq!==null&&ta.seq<=wi.forked_from_seq&&!wg.has(wi.id)){wg.add(wi.id);let Cu=A.get(wi.forked_from_id);if(!Cu)break;wi=Cu}let Tg=`${wi.id}:${ta.seq}:${ts.part}:${Bun.hash(ts.text)}`;if(fr.has(Tg))continue;let Rg=Y(or,Zs,$u);if(Rg){if(fr.add(Tg),E.forks){let Cu=or.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(at.id,ta.seq,ts.part);if(Cu){let kg=Eg(or,E,{...Zs,doc:Cu.doc},ts.text);if(kg.length)Rg.forks=kg}}}}}let Pu=Uo.at(-1);if(Pu)ur=Pu.seq;return Uo.length});if(un===void 0){f({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(ht+=un,f({type:"progress",scanned:ht,total:Wt}),a.signal?.aborted)return;if($t(),!un||he)break;await Bun.sleep(0)}}}else u.withIndex((ke)=>{if(S=mv(ke,E,a.onTiming)||S,g.regex?g.regex.literals.every((ht)=>ht.some((Ft)=>[...Ft].length<3)):g.branches.some((ht)=>ht.include.length>0&&ht.include.every((Ft)=>[...Ft.text].length<3)))ke.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let ht=pv(ke,E,o.group==="none",h.now,a.onTiming);if(S||=E.partial,E.candidateLimit&&ht.length>E.candidateLimit)ht.length=E.candidateLimit,S=!0;let Ft=[];for(let fr of ht){if(a.signal?.aborted)return;let Zt=Ft[we]?.key.score;if(Zt!==void 0&&fr.score+0.000000000001<Zt)break;let st=v.length,$t=ar(ke,fr);v.splice(st);let at=gg([...$t],"best")[0];if(!at)continue;let ur={score:at.score,sessionID:at.sessionID,seq:o.group==="none"?at.seq:0};if(h.after&&xv(ur,h.after)<=0)continue;if(Ft.push({key:ur,hits:$t}),Ft.sort((pr,un)=>xv(pr.key,un.key)),Ft.length>we+1)Ft.length=we+1}he=Ft.length>we;let xr=Ft.slice(0,we);for(let fr of xr)v.push(...fr.hits);k=xr.at(-1)?.key;return}let Wt=0;for(;;){if(a.signal?.aborted)return;let ht=dv(ke,E,se,We,a.onTiming),Ft=E.candidateLimit!==void 0&&se+ht>=E.candidateLimit;S||=Ft;let xr=fv(ke,o,te,we-Wt+1,h.now,L,a.onTiming);he=xr.length>we-Wt;let fr=xr.slice(0,we-Wt);if(!fr.length){if(ht<We||Ft){he=!1;break}se+=ht,te=0,L=[...new Set([...L,...re])],re=[];continue}for(let Zt of fr)if(te++,ar(ke,Zt).length){if(Wt++,o.group!=="none")re.push(Zt.session_id)}if(Wt>=we){he||=!Ft&&ht>=We;break}if(!he){if(ht<We||Ft)break;se+=ht,te=0,L=[...new Set([...L,...re])],re=[]}}});if(a.signal?.aborted)return;if(!He){let ke=xe(v);Ve(ke),f({type:"groups",groups:ke})}if(!M){let ke=g.branches.flatMap((Me)=>Me.include).find((Me)=>Me.fuzzy)?.text;if(ke)f({type:"suggest",terms:u.withIndex((Me)=>hg(Me,ke))??[]})}f({type:"done",cursor:he?Buffer.from(JSON.stringify(!He&&o.sort!=="recent"?{...h,offset:0,window:0,seen:[],emitted:[],after:k}:{...h,offset:te,window:se,seen:L,emitted:re})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:S,index:u.status()})}function no(e,o){return e.withIndex((a)=>hg(a,o))??[]}function Iv(e,o,a){let u=T({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(y([s({maxLength:2000}),Un()])),scope:n(y([i("session"),i("project"),i("all"),i(""),Un()])),fields:n(y([H(vr({type:"string",enum:[...wn]})),Un()])),tool:n(y([s(),Un()])),isError:n(y([D(),Un()])),after:n(y([s(),ne(),Un()])),before:n(y([s(),ne(),Un()])),limit:n(y([x(),Un()])),session:n(y([s(),Un()])),seq:n(y([x(),Un()])),around:n(y([x(),Un()]))}),async execute(p,f,h){let g={query:f.query?.trim(),scope:f.scope||void 0,fields:f.fields?.length?f.fields:void 0,tool:f.tool?.trim(),isError:f.isError??void 0,after:f.after??void 0,before:f.before??void 0,limit:f.limit||void 0,session:f.session?.trim(),seq:f.seq??void 0,around:f.around??void 0},I=g.query?.trim(),E=!I&&Boolean(g.session?.trim())&&Number.isSafeInteger(g.seq)&&(g.seq??0)>=1;if(E&&g.around!==void 0&&(!Number.isInteger(g.around)||g.around<0||g.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(g.scope&&!["session","project","all"].includes(g.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(h?.aborted)throw Error("History search cancelled");let S=e.sessions().find((X)=>X.id===a);if(!S)throw Error("History session is unavailable");let k=(X)=>{if(X===void 0||X===0||typeof X==="string"&&!X.trim())return;if(typeof X==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(X))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let Y=typeof X==="number"?X:Date.parse(X);if(!Number.isFinite(Y)||Math.abs(Y)>8640000000000000){if(typeof X==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return Y},A=E?void 0:k(g.after),P=E?void 0:k(g.before);if(A!==void 0&&P!==void 0&&A>=P)throw Error("after must precede before");let v=[];if(E&&g.session&&g.seq!==void 0){if(!e.sessions().find((He)=>He.id===g.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let Y=g.around??3,xe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(g.session,Math.max(1,g.seq-Y),g.seq+Y);if(!xe.some((He)=>He.seq===g.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:xe.map((He)=>{let ar={...JSON.parse(He.body),seq:He.seq,time:He.time};return`[seq=${He.seq}]
|
|
460
|
-
${it(ar,!0).map((ke)=>`${ke.kind}: ${ke.kind==="error"?ke.text.replace(/^(?:error:\s*)+/i,""):ke.text}`).join(`
|
|
461
|
-
`).slice(0,4000)}`}).join(`
|
|
462
|
-
|
|
463
|
-
`)||"No history content"}],details:{groups:v,count:xe.length}}}if(!I)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let M=Number.isFinite(g.limit)?Math.max(1,Math.min(30,Math.trunc(g.limit??10))):10,J=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(a)?.seq,O=new Set(e.sessions().filter((X)=>{if(g.scope==="session")return X.id===a;if((g.scope??"project")==="project"&&S.projectID)return X.projectID===S.projectID;return!0}).map((X)=>X.id)),V={q:I,filters:{tools:g.tool?.trim()?[g.tool.trim()]:void 0,isError:g.isError,after:A,before:P},group:"none",limit:M},j=Ul(V);if(j.error)throw Error(j.error.message);if(g.fields?.length){if(j.filters.fields=g.fields.filter((X)=>(X in $e)),j.filters.fields.length!==g.fields.length)throw Error("Unknown search field")}if((g.scope??"project")==="session")j.filters.sessionID=[a];else if((g.scope??"project")==="project"&&S.projectID)j.filters.projectID=[S.projectID];let te=o.status().state!=="ready",se=!1;if(!te){let X=j.filters.fields??Object.keys($e).filter((Ve)=>(Ve in $e)),Y=X.filter((Ve)=>Ve!=="title"),xe=Y.length?[Y]:[];if(X.includes("title"))xe.push(["title"]);for(let Ve of xe){if(v.length>=M&&se)break;if(await kr(o,{...V,limit:Math.max(1,M-v.length),filters:{...j.filters,fields:Ve}},{signal:h,excludeEntry:J===void 0?void 0:{sessionID:a,seq:J},sessionID:a,allowedSessionIDs:O,onEvent(He){if(He.type==="groups")v.push(...He.groups);if(He.type==="done")se||=Boolean(He.cursor)||He.partial;if(He.type==="error")if(He.code==="unavailable")te=!0;else throw Error(He.message)}}),te)break}}let L=[],re=0;if(te){v.length=0;let X=performance.now()+2000;e:for(let Y of e.sessions()){if(!O.has(Y.id))continue;if(j.filters.sessionID&&!j.filters.sessionID.includes(Y.id))continue;if(j.filters.projectID&&(!Y.projectID||!j.filters.projectID.includes(Y.projectID)))continue;let xe=Number.MAX_SAFE_INTEGER,Ve=!0;for(;;){let He=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(Y.id,xe);if(Ve)He.push({body:"null",seq:0,time:Y.updated}),Ve=!1;if(!He.length)break;for(let ar of He){if(ar.seq>0)xe=ar.seq;if(h?.aborted)throw Error("History search cancelled");if(re>=1e4||performance.now()>X){se=!0;break e}if(re++,Y.id===a&&ar.seq===J)continue;if(j.filters.after!==void 0&&ar.time<j.filters.after||j.filters.before!==void 0&&ar.time>=j.filters.before)continue;let ke=ar.seq===0?[{part:0,kind:"title",text:Y.title,tool:void 0,err:!1}]:it(JSON.parse(ar.body),!0);for(let Me of ke){if(j.filters.fields&&!j.filters.fields.includes(Me.kind))continue;if(j.filters.tools&&(!Me.tool||!j.filters.tools.includes(Me.tool)))continue;if(j.filters.isError!==void 0&&Boolean(Me.err)!==j.filters.isError)continue;let Wt=Gl(Me.text,j);if(!Wt)continue;if(v.length>=M&&Me.kind!=="title"){se=!0;break e}(Me.kind==="title"?L:v).push({session:{id:Y.id,title:Y.title,projectID:Y.projectID,updated:Y.updated},more:0,hits:[{sessionID:Y.id,seq:ar.seq,time:ar.time,field:Me.kind,tool:Me.tool,isError:Boolean(Me.err),snippet:Kl(Me.text,Wt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(h?.aborted)throw Error("History search cancelled");if(L.length>Math.max(0,M-v.length))se=!0;if(v.push(...L.slice(0,M)),v.sort((X,Y)=>Number(X.hits[0]?.field==="title")-Number(Y.hits[0]?.field==="title")),v.length>M)se=!0;v.length=Math.min(v.length,M);let he=new Map;for(let X of v)for(let Y of X.hits){let xe=he.get(X.session.id)??[];xe.push(`[${X.session.title.replace(/[\r\n]/g," ")} \xB7 ${Y.sessionID} \xB7 ${Y.seq} \xB7 ${new Date(Y.time).toISOString()} \xB7 ${Y.field}${Y.tool?`/${Y.tool}`:""}]
|
|
464
|
-
${Y.snippet.slice(0,3).map((Ve)=>{let He=Ve.text;for(let[ar,ke]of[...Ve.ranges].sort((Me,Wt)=>Wt[0]-Me[0]))He=`${He.slice(0,ar)}\u3010${He.slice(ar,ke)}\u3011${He.slice(ke)}`;return He}).join(`
|
|
465
|
-
`)}`),he.set(X.session.id,xe)}let we="";if(te){if(we="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")we="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let We=v.reduce((X,Y)=>X+Y.hits.length,0);return{content:[{type:"text",text:[we,te&&se?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${re} \u6761`:"",[...he.values()].map((X)=>X.join(`
|
|
466
|
-
|
|
467
|
-
`)).join(`
|
|
468
|
-
|
|
469
|
-
`),We===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${We} \u6761\uFF1B${se?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
|
|
470
|
-
`)}],details:{groups:v,count:We}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var bg="basalt.git-snapshot";async function Ev(e,o,a){let u=o.projectID?e.store.project(o.projectID):void 0,p=u?.directory??process.cwd(),h=o.info().kind==="sub",g=()=>h||o.entries(0,["compaction"],!1).length>0,I=e.options.tools??Qt({directory:u?.directory,records:()=>o.records,history:(k)=>e.resolveHistory(o.id,k),onTodos:(k)=>o.setTodos(k),shell:()=>e.serverShell(),hasCompacted:g});if(e.options.tools===void 0)I.push(Iv(e.store,e.search,o.id));let E;if(u&&e.options.systemPrompt===void 0){let k=o.entries(0,["compaction"],!1).length,A=e.store.db,P=A.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(bg,o.id),v;try{v=P?JSON.parse(P.value):void 0}catch{v=void 0}if(v?.compactions===k&&(v.summary===void 0||typeof v.summary==="string"))E=v.summary;else if(E=await g0(u.directory,a),!e.isClosed&&!a?.aborted)A.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(bg,o.id,JSON.stringify({compactions:k,summary:E})),A.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(bg)}let S=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:h0({project:u,globalInstructions:xK(e),git:E,shell:e.serverShell()});return{systemPrompt:S.map((k)=>k.detail).join(""),systemParts:S,tools:[...I,...e.tools.snapshot()],cwd:p}}var yK=[Au(".basalt","AGENTS.md"),Au(".agents","AGENTS.md"),Au(".opencode","AGENTS.md"),Au(".claude","CLAUDE.md"),Au(".codex","AGENTS.md")];function xK(e){let o=e.options.homeDir??gK();for(let a of yK){let u=Au(o,a);try{if(fK(u))return hK(u,"utf8")}catch{return}}return}class Yo{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new ag(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Dl(Sg(e.dataDir,"basalt.db")),this.plugins=new jh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new jl(this.plugins,()=>this.builtinToolNames()),this.search=new Uh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let a=this.open(o,"restore");this.sessions.set(o.id,a),this.restored.add(a)}}static async create(e){let o=new Yo(e);try{return await o.initialize(),o}catch(a){throw await o.close(),a}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Sg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Sg(e.directory,".basalt","plugins"))],this.options.plugins?.builtins===!1?[]:this.options.builtinPlugins??[]).then(async()=>{for(let e of this.restored)this.plugins.notify("session.open",e);if(this.initialized=!0,await this.plugins.idle(),!this.closed)for(let e of this.restored)e.recover();this.restored.clear()}),this.initialization}get ready(){return this.initialize()}builtinToolNames(){if(this.options.tools)return this.options.tools.map((e)=>e.name);return["read","write","edit","grep","glob","bash","todo","history_grep","history_list"]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}models(){return V0(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Fl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>W0(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((a)=>e||a.info().parentID===null).map((a)=>a.info()).filter((a)=>{let u=o.archive??"active";return u==="all"||a.archivedAt!==null===(u==="archived")}).sort((a,u)=>u.updated-a.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let a=this.get(e);if(!a)throw new t("History session is unavailable");return a.resolveHistory(o)}openStoredSession(e,o="restore"){let a=this.open(e,o);return this.sessions.set(e.id,a),this.emit({type:"session",session:a.info()}),a}create(e={}){let o=e.model??this.defaultModel;if(!Cn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let a=Date.now(),u={id:oe("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:a,updated:a,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let p=this.open(u);return this.sessions.set(u.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,o,a){o={...o,archivedAt:null},this.store.copySession(e,o,a);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new m("no such session");let a=o.info(),u=a.projectID?this.store.project(a.projectID):void 0;return P0(a,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let a=[o.model,e.model,this.defaultModel].find((h)=>h!==void 0&&Cn(this.options.models,h)!==void 0),u=a?Cn(this.options.models,a):void 0;if(!a||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:oe("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:a,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?v0(e.records,u):e.records);let f=this.open(p);return this.sessions.set(p.id,f),this.emit({type:"session",session:f.info()}),f}truncateHistory(e,o){let a=this.sessions.get(e.id);if(!a)throw new m("no such session");if(a.assertWritable(),a.status==="busy")throw new Z;if(!Cn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);a.close();for(let h of this.sessions.values()){if(h.info().parentID!==e.id)continue;if(h.status==="busy")h.abort();h.close()}this.store.truncateSession(e,o);let u=[],p=this.store.lastEntry(e.id,"run");if(p?.type==="run"&&p.state==="start"){let h=this.store.records(e.id,p.seq).filter((g)=>g.raw);for(let g of Ge(h)){if(g.result)continue;let{body:I,raw:E}=pl(g.call,"\u4E4B\u540E\u7684\u6D88\u606F\u88AB\u7528\u6237\u4FEE\u6539\uFF0C\u8FD9\u6B21\u8C03\u7528\u7684\u7ED3\u679C\u5DF2\u968F\u622A\u65AD\u4E22\u5F03\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\u3002");u.push(this.store.appendEntry(e.id,void 0,I,E))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let f=this.open(e,"replay");this.sessions.set(e.id,f),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let h of u)this.emit({type:"entry",sessionID:e.id,entry:h});return f}setArchived(e,o){let a=this.sessions.get(e);if(!a)throw new m("no such session");let u=a.info().parentID;if(!o&&u&&this.sessions.get(u)?.isArchived)throw new t("\u8BF7\u5148\u6062\u590D\u6240\u5C5E\u7236\u4F1A\u8BDD");let p=this.sessionTree(a);if(p.some((f)=>f.status==="busy"))throw new Z;if(a.isArchived===o)return a.info();this.store.setArchived(p.map((f)=>f.id),o?Date.now():null);for(let f of p)f.refreshArchive();for(let f of p)f.archiveChanged();return a.info()}sessionTree(e){let o=[e];for(let a=0;a<o.length;a++){let u=o[a];if(!u)continue;for(let p of this.sessions.values())if(p.info().parentID===u.id)o.push(p)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new m("no such session");if(o.status==="busy")throw new Z;let a=this.sessionTree(o).slice(1),u=()=>{for(let p of a)p.close(),this.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!a.length)return u();o.close();for(let p of a)p.close(),p.abort();return Promise.allSettled(a.map((p)=>p.idle())).then((p)=>{u();let f=p.find((h)=>h.status==="rejected");if(f)throw f.reason})}open(e,o="create"){let a=e.id,u=new vl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p,f)=>Ev(this,p,f)},{entry:(p)=>{this.emit({type:"entry",sessionID:a,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:a,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:a})},draft:(p)=>this.emit({type:"draft",sessionID:a,parts:p}),changed:()=>{let p=this.sessions.get(a);if(p)this.emit({type:"session",session:p.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new ea(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!ni.includes(e))throw new t(`Invalid shell type; must be ${ni.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return J0(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(a){console.error("runtime listener failed",a)}}}export{Ke,ct,Fi,N,Vo,Jn,Ko,qe,H,n,l,Q,vr,D,x,i,ne,s,y,Qe,Oe,Qo,ve,T,Mt,tt,R,Ge,F,G,Lt,rt,Jo,wt,_r,Xn,dn,Ot,Yn,Ce,de,mn,hn,Ar,Zn,eo,fn,$i,jt,As,Pe,c,le,nt,Er,Tr,Pr,to,Nt,Xo,Vt,Kt,Qt,ot,Z,ro,Jt,Xt,oe,gn,kr,no,Yo};
|