@bkm016/basalt 0.1.19 → 0.1.20
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-0bgg0hdd.js +2 -0
- package/chunk-0g8rtf05.js +18 -0
- package/chunk-0wwd4q6h.js +5 -0
- package/chunk-11xxfc0x.js +3 -0
- package/chunk-1gaj43fx.js +2 -0
- package/chunk-1tbv5t08.js +5 -0
- package/chunk-204c01mz.js +25 -0
- package/chunk-29g01nrz.js +20 -0
- package/chunk-2fts9k52.js +3 -0
- package/chunk-30bbdzma.js +16 -0
- package/chunk-3phf8eg6.js +3 -0
- package/chunk-3r38vbt5.js +2 -0
- package/chunk-3sg32v3n.js +2 -0
- package/chunk-4dgqcp6q.js +2 -0
- package/chunk-4fbj3k59.js +3 -0
- package/chunk-4wc2gbhe.js +2 -0
- package/chunk-51pfvmhh.js +470 -0
- package/chunk-5e7yegea.js +2 -0
- package/chunk-5ja0vsam.js +10 -0
- package/chunk-5tsfqsmf.js +2 -0
- package/chunk-6en06hkk.js +2 -0
- package/chunk-6hatfwsq.js +2 -0
- package/chunk-78ky455y.js +4 -0
- package/chunk-7kz9435k.js +11 -0
- package/chunk-8mqaq042.js +2 -0
- package/chunk-9qzyn98b.js +3 -0
- package/chunk-a1vdrgsh.js +59 -0
- package/chunk-a2z1cy84.js +2 -0
- package/chunk-a3fpx924.js +3 -0
- package/chunk-agb771ak.js +3 -0
- package/chunk-ak9rkrf3.js +5 -0
- package/chunk-as2mwf79.js +2 -0
- package/chunk-bkhsva5n.js +7 -0
- package/chunk-c5pg2875.js +3552 -0
- package/chunk-cks36jdh.js +8 -0
- package/chunk-cwrf78vs.js +3 -0
- package/chunk-d2f0hq8z.js +2 -0
- package/chunk-e0ytnnwt.js +3 -0
- package/chunk-e3bgzeb3.js +3 -0
- package/chunk-enmrpjpt.js +3 -0
- package/chunk-eps1epfr.js +4 -0
- package/chunk-ewr51fwc.js +3 -0
- package/chunk-eyyxqb6y.js +7 -0
- package/chunk-fgjw0r6g.js +12 -0
- package/chunk-g9hsrrj5.js +2 -0
- package/chunk-gg3kfa12.js +3 -0
- package/chunk-gpceyezp.js +2 -0
- package/chunk-gs5aebwh.js +2 -0
- package/chunk-h2pp8mnh.js +4 -0
- package/chunk-h4n0gg11.js +2 -0
- package/chunk-jzya0e5n.js +7 -0
- package/chunk-mde2dd79.js +2 -0
- package/chunk-ncb0tyaw.js +2 -0
- package/chunk-np2xnt1g.js +3 -0
- package/chunk-nszq2z0w.js +2 -0
- package/chunk-p0e82mee.js +3 -0
- package/chunk-qxpx8dn6.js +12 -0
- package/chunk-s819vmwh.js +3 -0
- package/chunk-s8m4svhf.js +3 -0
- package/chunk-sm9fpy18.js +390 -0
- package/chunk-svx7mz0w.js +25 -0
- package/chunk-tb3zsqe8.js +3 -0
- package/chunk-tp885r8h.js +39 -0
- package/chunk-tpeg9fkd.js +2 -0
- package/chunk-tpetsqzt.js +9 -0
- package/chunk-v0mw006s.js +15 -0
- package/chunk-v7da0aqn.js +7 -0
- package/chunk-vzrmdaba.js +2 -0
- package/chunk-w045zk55.js +2 -0
- package/chunk-w6nc3jn7.js +2 -0
- package/chunk-w9fdcchk.js +3 -0
- package/chunk-wj09qkyw.js +3 -0
- package/chunk-x1y4s01x.js +31 -0
- package/chunk-y3vap4a1.js +10 -0
- package/chunk-y83tnkr3.js +11 -0
- package/chunk-yk29stq0.js +5 -0
- package/chunk-ys2fds2x.js +3 -0
- package/chunk-yshdvnsp.js +2 -0
- package/chunk-z9p2ry9w.js +3 -0
- package/chunk-zkjnt298.js +3 -0
- package/compiled.js +8 -8
- package/package.json +1 -1
- package/ui-test-worker.js +35 -35
- package/web/chunk-08w40agf.js +34 -0
- package/web/chunk-08w40agf.js.br +0 -0
- package/web/chunk-08w40agf.js.gz +0 -0
- package/web/chunk-0bfypmyv.js +1 -0
- package/web/chunk-0bfypmyv.js.br +2 -0
- package/web/chunk-0bfypmyv.js.gz +0 -0
- package/web/chunk-0h0whn75.js +24 -0
- package/web/chunk-0h0whn75.js.br +0 -0
- package/web/chunk-0h0whn75.js.gz +0 -0
- package/web/chunk-0pzs9k06.js +1 -0
- package/web/chunk-0pzs9k06.js.br +0 -0
- package/web/chunk-0pzs9k06.js.gz +0 -0
- package/web/chunk-0rvx1z2b.js +1 -0
- package/web/chunk-0rvx1z2b.js.br +0 -0
- package/web/chunk-0rvx1z2b.js.gz +0 -0
- package/web/chunk-0tcmnvab.js +2 -0
- package/web/chunk-0tcmnvab.js.br +0 -0
- package/web/chunk-0tcmnvab.js.gz +0 -0
- package/web/chunk-0wqmwnd8.js +2 -0
- package/web/chunk-0wqmwnd8.js.br +0 -0
- package/web/chunk-0wqmwnd8.js.gz +0 -0
- package/web/chunk-0z10aqp1.js +2 -0
- package/web/chunk-0z10aqp1.js.br +0 -0
- package/web/chunk-0z10aqp1.js.gz +0 -0
- package/web/chunk-12vcrj7y.js +1 -0
- package/web/chunk-12vcrj7y.js.br +0 -0
- package/web/chunk-12vcrj7y.js.gz +0 -0
- package/web/chunk-186rp10x.js +62 -0
- package/web/chunk-186rp10x.js.br +0 -0
- package/web/chunk-186rp10x.js.gz +0 -0
- package/web/chunk-1cwyy3gh.js +2 -0
- package/web/chunk-1cwyy3gh.js.br +0 -0
- package/web/chunk-1cwyy3gh.js.gz +0 -0
- package/web/chunk-1ecsxh85.js +1 -0
- package/web/chunk-1ecsxh85.js.br +0 -0
- package/web/chunk-1ecsxh85.js.gz +0 -0
- package/web/chunk-1ghnag5v.js +2 -0
- package/web/chunk-1ghnag5v.js.br +0 -0
- package/web/chunk-1ghnag5v.js.gz +0 -0
- package/web/chunk-1ps9fj5n.js +2 -0
- package/web/chunk-1ps9fj5n.js.br +0 -0
- package/web/chunk-1ps9fj5n.js.gz +0 -0
- package/web/chunk-1ratg1jd.js +332 -0
- package/web/chunk-1ratg1jd.js.br +0 -0
- package/web/chunk-1ratg1jd.js.gz +0 -0
- package/web/chunk-1yvcxpp2.js +7 -0
- package/web/chunk-1yvcxpp2.js.br +0 -0
- package/web/chunk-1yvcxpp2.js.gz +0 -0
- package/web/chunk-2r3w0pt0.js +8 -0
- package/web/chunk-2r3w0pt0.js.br +0 -0
- package/web/chunk-2r3w0pt0.js.gz +0 -0
- package/web/chunk-2rnnvxa5.js +291 -0
- package/web/chunk-2rnnvxa5.js.br +0 -0
- package/web/chunk-2rnnvxa5.js.gz +0 -0
- package/web/chunk-2stffcvc.js +1 -0
- package/web/chunk-2stffcvc.js.br +0 -0
- package/web/chunk-2stffcvc.js.gz +0 -0
- package/web/chunk-2svqgkqw.js +1 -0
- package/web/chunk-2svqgkqw.js.br +0 -0
- package/web/chunk-2svqgkqw.js.gz +0 -0
- package/web/chunk-366a11ec.js +1 -0
- package/web/chunk-366a11ec.js.br +0 -0
- package/web/chunk-366a11ec.js.gz +0 -0
- package/web/chunk-37hmswdk.js +7 -0
- package/web/chunk-37hmswdk.js.br +0 -0
- package/web/chunk-37hmswdk.js.gz +0 -0
- package/web/chunk-3fd6mgf0.js +1 -0
- package/web/chunk-3fd6mgf0.js.br +0 -0
- package/web/chunk-3fd6mgf0.js.gz +0 -0
- package/web/chunk-4mypk63p.js +2 -0
- package/web/chunk-4mypk63p.js.br +0 -0
- package/web/chunk-4mypk63p.js.gz +0 -0
- package/web/chunk-52tt9qt4.js +2 -0
- package/web/chunk-52tt9qt4.js.br +0 -0
- package/web/chunk-52tt9qt4.js.gz +0 -0
- package/web/chunk-53cg6pxm.js +142 -0
- package/web/chunk-53cg6pxm.js.br +0 -0
- package/web/chunk-53cg6pxm.js.gz +0 -0
- package/web/chunk-59h87pvn.js +12 -0
- package/web/chunk-59h87pvn.js.br +0 -0
- package/web/chunk-59h87pvn.js.gz +0 -0
- package/web/chunk-5cp4n5ck.js +2 -0
- package/web/chunk-5cp4n5ck.js.br +0 -0
- package/web/chunk-5cp4n5ck.js.gz +0 -0
- package/web/chunk-6a3wt5c5.js +30 -0
- package/web/chunk-6a3wt5c5.js.br +0 -0
- package/web/chunk-6a3wt5c5.js.gz +0 -0
- package/web/chunk-6n1ha6ta.js +7 -0
- package/web/chunk-6n1ha6ta.js.br +0 -0
- package/web/chunk-6n1ha6ta.js.gz +0 -0
- package/web/chunk-6pbhqbv0.js +1 -0
- package/web/chunk-6pbhqbv0.js.br +0 -0
- package/web/chunk-6pbhqbv0.js.gz +0 -0
- package/web/chunk-72st75n7.js +70 -0
- package/web/chunk-72st75n7.js.br +0 -0
- package/web/chunk-72st75n7.js.gz +0 -0
- package/web/chunk-7cf1kk45.js +1 -0
- package/web/chunk-7cf1kk45.js.br +2 -0
- package/web/chunk-7cf1kk45.js.gz +0 -0
- package/web/chunk-7h59ac2b.js +38 -0
- package/web/chunk-7h59ac2b.js.br +0 -0
- package/web/chunk-7h59ac2b.js.gz +0 -0
- package/web/chunk-81xbfpbq.js +41 -0
- package/web/chunk-81xbfpbq.js.br +0 -0
- package/web/chunk-81xbfpbq.js.gz +0 -0
- package/web/chunk-82q4e8ff.js +1 -0
- package/web/chunk-82q4e8ff.js.br +0 -0
- package/web/chunk-82q4e8ff.js.gz +0 -0
- package/web/chunk-89crtpnw.js +1 -0
- package/web/chunk-89crtpnw.js.br +0 -0
- package/web/chunk-89crtpnw.js.gz +0 -0
- package/web/chunk-89e8629e.js +1 -0
- package/web/chunk-89e8629e.js.br +0 -0
- package/web/chunk-89e8629e.js.gz +0 -0
- package/web/chunk-9n1nsdqs.js +1 -0
- package/web/chunk-9n1nsdqs.js.br +0 -0
- package/web/chunk-9n1nsdqs.js.gz +0 -0
- package/web/chunk-9r7nbre7.js +2 -0
- package/web/chunk-9r7nbre7.js.br +0 -0
- package/web/chunk-9r7nbre7.js.gz +0 -0
- package/web/chunk-9y9nwaqj.js +1 -0
- package/web/chunk-9y9nwaqj.js.br +0 -0
- package/web/chunk-9y9nwaqj.js.gz +0 -0
- package/web/chunk-a8qe7kvz.js +1 -0
- package/web/chunk-a8qe7kvz.js.br +0 -0
- package/web/chunk-a8qe7kvz.js.gz +0 -0
- package/web/chunk-ahdca62g.js +1 -0
- package/web/chunk-ahdca62g.js.br +0 -0
- package/web/chunk-ahdca62g.js.gz +0 -0
- package/web/chunk-apr33amc.js +140 -0
- package/web/chunk-apr33amc.js.br +0 -0
- package/web/chunk-apr33amc.js.gz +0 -0
- package/web/chunk-aw9bwd4w.js +3 -0
- package/web/chunk-aw9bwd4w.js.br +0 -0
- package/web/chunk-aw9bwd4w.js.gz +0 -0
- package/web/chunk-bg0qgabv.js +1 -0
- package/web/chunk-bg0qgabv.js.br +0 -0
- package/web/chunk-bg0qgabv.js.gz +0 -0
- package/web/chunk-bks2k04k.js +2 -0
- package/web/chunk-bks2k04k.js.br +0 -0
- package/web/chunk-bks2k04k.js.gz +0 -0
- package/web/chunk-c28crzwk.js +120 -0
- package/web/chunk-c28crzwk.js.br +0 -0
- package/web/chunk-c28crzwk.js.gz +0 -0
- package/web/chunk-cmhxtckb.js +2 -0
- package/web/chunk-cmhxtckb.js.br +0 -0
- package/web/chunk-cmhxtckb.js.gz +0 -0
- package/web/chunk-d7f85w1y.js +1 -0
- package/web/chunk-d7f85w1y.js.br +0 -0
- package/web/chunk-d7f85w1y.js.gz +0 -0
- package/web/chunk-dmhezjv3.js +217 -0
- package/web/chunk-dmhezjv3.js.br +0 -0
- package/web/chunk-dmhezjv3.js.gz +0 -0
- package/web/chunk-dmzvhbpn.js +292 -0
- package/web/chunk-dmzvhbpn.js.br +0 -0
- package/web/chunk-dmzvhbpn.js.gz +0 -0
- package/web/chunk-e2z3kdhw.js +39 -0
- package/web/chunk-e2z3kdhw.js.br +0 -0
- package/web/chunk-e2z3kdhw.js.gz +0 -0
- package/web/chunk-e65y60v1.js +2 -0
- package/web/chunk-e65y60v1.js.br +0 -0
- package/web/chunk-e65y60v1.js.gz +0 -0
- package/web/chunk-ed8qqn45.js +2 -0
- package/web/chunk-ed8qqn45.js.br +0 -0
- package/web/chunk-ed8qqn45.js.gz +0 -0
- package/web/chunk-ef1h0tt7.js +2 -0
- package/web/chunk-ef1h0tt7.js.br +0 -0
- package/web/chunk-ef1h0tt7.js.gz +0 -0
- package/web/chunk-eqmghkwh.js +1 -0
- package/web/chunk-eqmghkwh.js.br +0 -0
- package/web/chunk-eqmghkwh.js.gz +0 -0
- package/web/chunk-esckazz2.js +1 -0
- package/web/chunk-esckazz2.js.br +0 -0
- package/web/chunk-esckazz2.js.gz +0 -0
- package/web/chunk-ezj5rjqr.js +4 -0
- package/web/chunk-ezj5rjqr.js.br +0 -0
- package/web/chunk-ezj5rjqr.js.gz +0 -0
- package/web/chunk-fjrgg82c.js +139 -0
- package/web/chunk-fjrgg82c.js.br +0 -0
- package/web/chunk-fjrgg82c.js.gz +0 -0
- package/web/chunk-g3vbtxgy.js +2 -0
- package/web/chunk-g3vbtxgy.js.br +0 -0
- package/web/chunk-g3vbtxgy.js.gz +0 -0
- package/web/chunk-gbcf0rdk.js +1 -0
- package/web/chunk-gbcf0rdk.js.br +0 -0
- package/web/chunk-gbcf0rdk.js.gz +0 -0
- package/web/chunk-gj6bdv1y.js +200 -0
- package/web/chunk-gj6bdv1y.js.br +0 -0
- package/web/chunk-gj6bdv1y.js.gz +0 -0
- package/web/chunk-gk1bc3c3.js +2 -0
- package/web/chunk-gk1bc3c3.js.br +0 -0
- package/web/chunk-gk1bc3c3.js.gz +0 -0
- package/web/chunk-gpjytpyw.js +2 -0
- package/web/chunk-gpjytpyw.js.br +0 -0
- package/web/chunk-gpjytpyw.js.gz +0 -0
- package/web/chunk-h1c0m3g4.js +99 -0
- package/web/chunk-h1c0m3g4.js.br +0 -0
- package/web/chunk-h1c0m3g4.js.gz +0 -0
- package/web/chunk-h1qv0cpd.css +1 -0
- package/web/chunk-h1qv0cpd.css.br +0 -0
- package/web/chunk-h1qv0cpd.css.gz +0 -0
- package/web/chunk-hj067dfg.js +1 -0
- package/web/chunk-hj067dfg.js.br +2 -0
- package/web/chunk-hj067dfg.js.gz +0 -0
- package/web/chunk-hq7e5xgd.js +1 -0
- package/web/chunk-hq7e5xgd.js.br +0 -0
- package/web/chunk-hq7e5xgd.js.gz +0 -0
- package/web/chunk-hqt1f3fm.js +24 -0
- package/web/chunk-hqt1f3fm.js.br +0 -0
- package/web/chunk-hqt1f3fm.js.gz +0 -0
- package/web/chunk-hwxj58j5.js +2 -0
- package/web/chunk-hwxj58j5.js.br +0 -0
- package/web/chunk-hwxj58j5.js.gz +0 -0
- package/web/chunk-hxzb25a8.js +1 -0
- package/web/chunk-hxzb25a8.js.br +0 -0
- package/web/chunk-hxzb25a8.js.gz +0 -0
- package/web/chunk-j4942vkb.js +1 -0
- package/web/chunk-j4942vkb.js.br +0 -0
- package/web/chunk-j4942vkb.js.gz +0 -0
- package/web/chunk-jmnzcm1f.js +21 -0
- package/web/chunk-jmnzcm1f.js.br +0 -0
- package/web/chunk-jmnzcm1f.js.gz +0 -0
- package/web/chunk-js940jjj.js +40 -0
- package/web/chunk-js940jjj.js.br +0 -0
- package/web/chunk-js940jjj.js.gz +0 -0
- package/web/chunk-jy9vkfbf.js +1 -0
- package/web/chunk-jy9vkfbf.js.br +0 -0
- package/web/chunk-jy9vkfbf.js.gz +0 -0
- package/web/chunk-k1d0y72z.js +2 -0
- package/web/chunk-k1d0y72z.js.br +0 -0
- package/web/chunk-k1d0y72z.js.gz +0 -0
- package/web/chunk-k4pknkvp.js +16 -0
- package/web/chunk-k4pknkvp.js.br +0 -0
- package/web/chunk-k4pknkvp.js.gz +0 -0
- package/web/chunk-k6fwzn0z.js +324 -0
- package/web/chunk-k6fwzn0z.js.br +0 -0
- package/web/chunk-k6fwzn0z.js.gz +0 -0
- package/web/chunk-kdegb6pd.js +169 -0
- package/web/chunk-kdegb6pd.js.br +0 -0
- package/web/chunk-kdegb6pd.js.gz +0 -0
- package/web/chunk-kedjfh66.js +2 -0
- package/web/chunk-kedjfh66.js.br +0 -0
- package/web/chunk-kedjfh66.js.gz +0 -0
- package/web/chunk-kh0xyffx.js +1 -0
- package/web/chunk-kh0xyffx.js.br +0 -0
- package/web/chunk-kh0xyffx.js.gz +0 -0
- package/web/chunk-ktvxgxsd.js +2 -0
- package/web/chunk-ktvxgxsd.js.br +0 -0
- package/web/chunk-ktvxgxsd.js.gz +0 -0
- package/web/chunk-mbpv2w5h.js +78 -0
- package/web/chunk-mbpv2w5h.js.br +0 -0
- package/web/chunk-mbpv2w5h.js.gz +0 -0
- package/web/chunk-mh3nkkpx.js +84 -0
- package/web/chunk-mh3nkkpx.js.br +0 -0
- package/web/chunk-mh3nkkpx.js.gz +0 -0
- package/web/chunk-mhzqgzh0.js +89 -0
- package/web/chunk-mhzqgzh0.js.br +0 -0
- package/web/chunk-mhzqgzh0.js.gz +0 -0
- package/web/chunk-mj8dzc8q.js +214 -0
- package/web/chunk-mj8dzc8q.js.br +0 -0
- package/web/chunk-mj8dzc8q.js.gz +0 -0
- package/web/chunk-mwfrxgbs.js +2 -0
- package/web/chunk-mwfrxgbs.js.br +0 -0
- package/web/chunk-mwfrxgbs.js.gz +0 -0
- package/web/chunk-n419cees.js +1 -0
- package/web/chunk-n419cees.js.br +0 -0
- package/web/chunk-n419cees.js.gz +0 -0
- package/web/chunk-n45fgfyt.js +1 -0
- package/web/chunk-n45fgfyt.js.br +2 -0
- package/web/chunk-n45fgfyt.js.gz +0 -0
- package/web/chunk-n5v71fas.js +2 -0
- package/web/chunk-n5v71fas.js.br +0 -0
- package/web/chunk-n5v71fas.js.gz +0 -0
- package/web/chunk-nb58m79v.js +89 -0
- package/web/chunk-nb58m79v.js.br +0 -0
- package/web/chunk-nb58m79v.js.gz +0 -0
- package/web/chunk-nsna2v2r.js +1 -0
- package/web/chunk-nsna2v2r.js.br +0 -0
- package/web/chunk-nsna2v2r.js.gz +0 -0
- package/web/chunk-nxdp58nf.js +1 -0
- package/web/chunk-nxdp58nf.js.br +0 -0
- package/web/chunk-nxdp58nf.js.gz +0 -0
- package/web/chunk-nytgs01h.js +1 -0
- package/web/chunk-nytgs01h.js.br +0 -0
- package/web/chunk-nytgs01h.js.gz +0 -0
- package/web/chunk-p76f6cf4.js +2 -0
- package/web/chunk-p76f6cf4.js.br +0 -0
- package/web/chunk-p76f6cf4.js.gz +0 -0
- package/web/chunk-pkxn54jm.js +1 -0
- package/web/chunk-pkxn54jm.js.br +0 -0
- package/web/chunk-pkxn54jm.js.gz +0 -0
- package/web/chunk-q0srq8g5.js +1 -0
- package/web/chunk-q0srq8g5.js.br +0 -0
- package/web/chunk-q0srq8g5.js.gz +0 -0
- package/web/chunk-qgtqwmkb.js +1 -0
- package/web/chunk-qgtqwmkb.js.br +2 -0
- package/web/chunk-qgtqwmkb.js.gz +0 -0
- package/web/chunk-qjg6dw46.js +1134 -0
- package/web/chunk-qjg6dw46.js.br +0 -0
- package/web/chunk-qjg6dw46.js.gz +0 -0
- package/web/chunk-qjjxevxe.js +1 -0
- package/web/chunk-qjjxevxe.js.br +0 -0
- package/web/chunk-qjjxevxe.js.gz +0 -0
- package/web/chunk-qx5ab39c.js +4 -0
- package/web/chunk-qx5ab39c.js.br +0 -0
- package/web/chunk-qx5ab39c.js.gz +0 -0
- package/web/chunk-qygjhm63.js +1 -0
- package/web/chunk-qygjhm63.js.br +0 -0
- package/web/chunk-qygjhm63.js.gz +0 -0
- package/web/chunk-recfg8af.js +2 -0
- package/web/chunk-recfg8af.js.br +0 -0
- package/web/chunk-recfg8af.js.gz +0 -0
- package/web/chunk-rfsg5rke.js +1 -0
- package/web/chunk-rfsg5rke.js.br +2 -0
- package/web/chunk-rfsg5rke.js.gz +0 -0
- package/web/chunk-s7h50avx.js +2 -0
- package/web/chunk-s7h50avx.js.br +0 -0
- package/web/chunk-s7h50avx.js.gz +0 -0
- package/web/chunk-sk47kk5j.js +1 -0
- package/web/chunk-sk47kk5j.js.br +0 -0
- package/web/chunk-sk47kk5j.js.gz +0 -0
- package/web/chunk-t9heac9a.js +2 -0
- package/web/chunk-t9heac9a.js.br +0 -0
- package/web/chunk-t9heac9a.js.gz +0 -0
- package/web/chunk-tg3f9xmp.js +1 -0
- package/web/chunk-tg3f9xmp.js.br +0 -0
- package/web/chunk-tg3f9xmp.js.gz +0 -0
- package/web/chunk-tgeeggkh.js +1 -0
- package/web/chunk-tgeeggkh.js.br +0 -0
- package/web/chunk-tgeeggkh.js.gz +0 -0
- package/web/chunk-v2bkkhb8.js +303 -0
- package/web/chunk-v2bkkhb8.js.br +0 -0
- package/web/chunk-v2bkkhb8.js.gz +0 -0
- package/web/chunk-v5p2fds9.js +36 -0
- package/web/chunk-v5p2fds9.js.br +0 -0
- package/web/chunk-v5p2fds9.js.gz +0 -0
- package/web/chunk-v6snw1sw.js +1 -0
- package/web/chunk-v6snw1sw.js.br +0 -0
- package/web/chunk-v6snw1sw.js.gz +0 -0
- package/web/chunk-veadbga2.js +1 -0
- package/web/chunk-veadbga2.js.br +2 -0
- package/web/chunk-veadbga2.js.gz +0 -0
- package/web/chunk-vh2prc6k.js +1 -0
- package/web/chunk-vh2prc6k.js.br +0 -0
- package/web/chunk-vh2prc6k.js.gz +0 -0
- package/web/chunk-vhpzp7zd.js +2 -0
- package/web/chunk-vhpzp7zd.js.br +0 -0
- package/web/chunk-vhpzp7zd.js.gz +0 -0
- package/web/chunk-vpbnyz43.js +98 -0
- package/web/chunk-vpbnyz43.js.br +0 -0
- package/web/chunk-vpbnyz43.js.gz +0 -0
- package/web/chunk-vxadngbp.js +2 -0
- package/web/chunk-vxadngbp.js.br +3 -0
- package/web/chunk-vxadngbp.js.gz +0 -0
- package/web/chunk-wa8wr2y9.js +106 -0
- package/web/chunk-wa8wr2y9.js.br +0 -0
- package/web/chunk-wa8wr2y9.js.gz +0 -0
- package/web/chunk-wbxz2bjb.js +1 -0
- package/web/chunk-wbxz2bjb.js.br +0 -0
- package/web/chunk-wbxz2bjb.js.gz +0 -0
- package/web/chunk-wgzatts8.js +1 -0
- package/web/chunk-wgzatts8.js.br +0 -0
- package/web/chunk-wgzatts8.js.gz +0 -0
- package/web/chunk-whczyxqw.js +1 -0
- package/web/chunk-whczyxqw.js.br +0 -0
- package/web/chunk-whczyxqw.js.gz +0 -0
- package/web/chunk-wmzz2crn.js +1 -0
- package/web/chunk-wmzz2crn.js.br +0 -0
- package/web/chunk-wmzz2crn.js.gz +0 -0
- package/web/chunk-wvqcbp4a.js +1 -0
- package/web/chunk-wvqcbp4a.js.br +0 -0
- package/web/chunk-wvqcbp4a.js.gz +0 -0
- package/web/chunk-wvvrdqgb.js +1 -0
- package/web/chunk-wvvrdqgb.js.br +2 -0
- package/web/chunk-wvvrdqgb.js.gz +0 -0
- package/web/chunk-x2hxq5yr.js +55 -0
- package/web/chunk-x2hxq5yr.js.br +0 -0
- package/web/chunk-x2hxq5yr.js.gz +0 -0
- package/web/chunk-x8bnp6vr.js +1 -0
- package/web/chunk-x8bnp6vr.js.br +0 -0
- package/web/chunk-x8bnp6vr.js.gz +0 -0
- package/web/chunk-xp9tdb5t.js +1 -0
- package/web/chunk-xp9tdb5t.js.br +2 -0
- package/web/chunk-xp9tdb5t.js.gz +0 -0
- package/web/chunk-xvmzsftt.js +2 -0
- package/web/chunk-xvmzsftt.js.br +0 -0
- package/web/chunk-xvmzsftt.js.gz +0 -0
- package/web/chunk-y10hsdq4.js +1 -0
- package/web/chunk-y10hsdq4.js.br +0 -0
- package/web/chunk-y10hsdq4.js.gz +0 -0
- package/web/chunk-ye7vge7s.js +1 -0
- package/web/chunk-ye7vge7s.js.br +0 -0
- package/web/chunk-ye7vge7s.js.gz +0 -0
- package/web/chunk-zbzgd8kn.js +2 -0
- package/web/chunk-zbzgd8kn.js.br +0 -0
- package/web/chunk-zbzgd8kn.js.gz +0 -0
- package/web/chunk-zhwqscat.js +1 -0
- package/web/chunk-zhwqscat.js.br +0 -0
- package/web/chunk-zhwqscat.js.gz +0 -0
- package/web/chunk-znrsm604.js +370 -0
- package/web/chunk-znrsm604.js.br +0 -0
- package/web/chunk-znrsm604.js.gz +0 -0
- package/web/chunk-zthww0ws.js +1 -0
- package/web/chunk-zthww0ws.js.br +0 -0
- package/web/chunk-zthww0ws.js.gz +0 -0
- package/web/index.html +3 -1
- package/web/index.html.br +0 -0
- package/web/index.html.gz +0 -0
- package/worker.js +1 -1
- package/chunk-13pbt8mn.js +0 -2
- package/chunk-14085qqt.js +0 -8
- package/chunk-2dph65ye.js +0 -3
- package/chunk-2v8anxgd.js +0 -9
- package/chunk-37f4ks5f.js +0 -3
- package/chunk-3q1hxwxb.js +0 -5
- package/chunk-3qs33s9g.js +0 -2
- package/chunk-53m94h0b.js +0 -7
- package/chunk-5jy2cnyr.js +0 -18
- package/chunk-5wfyn3k0.js +0 -3
- package/chunk-69v706tc.js +0 -5
- package/chunk-79h4rzza.js +0 -2
- package/chunk-7xfde6se.js +0 -3
- package/chunk-8bf4g2d7.js +0 -3
- package/chunk-adq8c7vt.js +0 -25
- package/chunk-ahpg469e.js +0 -3
- package/chunk-ary9gky8.js +0 -7
- package/chunk-becsymjn.js +0 -2
- package/chunk-beqps81c.js +0 -4
- package/chunk-bnvynyww.js +0 -3
- package/chunk-c785tr0e.js +0 -4078
- package/chunk-cc19pbgm.js +0 -12
- package/chunk-d6g5m56z.js +0 -2
- package/chunk-etkktxdc.js +0 -2
- package/chunk-etxsj2ey.js +0 -10
- package/chunk-f2ajxymw.js +0 -2
- package/chunk-f2bcfa6z.js +0 -7
- package/chunk-f47qdrkp.js +0 -2
- package/chunk-f5yg6yd0.js +0 -3
- package/chunk-fjk9ztjc.js +0 -11
- package/chunk-g99n5ywc.js +0 -3
- package/chunk-grwavjp7.js +0 -2
- package/chunk-gsek3gpd.js +0 -3
- package/chunk-gv9hbv9j.js +0 -2
- package/chunk-h045t6f1.js +0 -2
- package/chunk-h4g1tzk6.js +0 -11
- package/chunk-had2k7b9.js +0 -20
- package/chunk-hbm45044.js +0 -25
- package/chunk-hd2hars5.js +0 -3
- package/chunk-hfh230tm.js +0 -2
- package/chunk-hkx7d1j9.js +0 -7
- package/chunk-jbk2tmza.js +0 -5
- package/chunk-jv9sy0np.js +0 -2
- package/chunk-kdc8tq70.js +0 -2
- package/chunk-m1nevdw6.js +0 -3
- package/chunk-m6yrpt1f.js +0 -5
- package/chunk-mrchbvsy.js +0 -4
- package/chunk-n9x6akk3.js +0 -2
- package/chunk-ne94brn4.js +0 -3
- package/chunk-nv1jg79d.js +0 -2
- package/chunk-pvdt969t.js +0 -59
- package/chunk-q22dnah8.js +0 -3
- package/chunk-q2zayphb.js +0 -10
- package/chunk-q4h6djtp.js +0 -2
- package/chunk-qa8mne61.js +0 -2
- package/chunk-r9z9m75h.js +0 -16
- package/chunk-rmyzxqkd.js +0 -467
- package/chunk-rq647zmf.js +0 -2
- package/chunk-sj4jvm9p.js +0 -2
- package/chunk-sq0ra5m8.js +0 -4
- package/chunk-sxg03n4v.js +0 -2
- package/chunk-t0m1wjrn.js +0 -3
- package/chunk-td52edcm.js +0 -31
- package/chunk-tdnwaaw4.js +0 -12
- package/chunk-teky87xx.js +0 -3
- package/chunk-v1avwm7q.js +0 -3
- package/chunk-wcmk8ee3.js +0 -3
- package/chunk-wf9r0frb.js +0 -3
- package/chunk-wx697mre.js +0 -2
- package/chunk-wzz64ygm.js +0 -2
- package/chunk-xb9mwt5a.js +0 -2
- package/chunk-xbkbaa84.js +0 -2
- package/chunk-xjy31n64.js +0 -3
- package/chunk-xzn34n38.js +0 -389
- package/chunk-yprp5s5v.js +0 -3
- package/chunk-yyhdabhq.js +0 -15
- package/chunk-z2jp61ze.js +0 -39
- package/chunk-zt5szcek.js +0 -3
- package/chunk-zxb6cg3m.js +0 -2
- package/web/chunk-0ays2hhj.js +0 -41
- package/web/chunk-0ays2hhj.js.br +0 -0
- package/web/chunk-0ays2hhj.js.gz +0 -0
- package/web/chunk-0na4c1bp.js +0 -139
- package/web/chunk-0na4c1bp.js.br +0 -0
- package/web/chunk-0na4c1bp.js.gz +0 -0
- package/web/chunk-0y0p0ct0.js +0 -1
- package/web/chunk-0y0p0ct0.js.br +0 -0
- package/web/chunk-0y0p0ct0.js.gz +0 -0
- package/web/chunk-191v8amv.js +0 -1
- package/web/chunk-191v8amv.js.br +0 -0
- package/web/chunk-191v8amv.js.gz +0 -0
- package/web/chunk-1c6rhsft.js +0 -200
- package/web/chunk-1c6rhsft.js.br +0 -0
- package/web/chunk-1c6rhsft.js.gz +0 -0
- package/web/chunk-1mwkrh5f.js +0 -370
- package/web/chunk-1mwkrh5f.js.br +0 -0
- package/web/chunk-1mwkrh5f.js.gz +0 -0
- package/web/chunk-1q4r17he.js +0 -2
- package/web/chunk-1q4r17he.js.br +0 -0
- package/web/chunk-1q4r17he.js.gz +0 -0
- package/web/chunk-1sm3c8an.js +0 -8
- package/web/chunk-1sm3c8an.js.br +0 -0
- package/web/chunk-1sm3c8an.js.gz +0 -0
- package/web/chunk-1vmjpvy5.js +0 -1
- package/web/chunk-1vmjpvy5.js.br +0 -0
- package/web/chunk-1vmjpvy5.js.gz +0 -0
- package/web/chunk-1x4z5w5e.js +0 -1
- package/web/chunk-1x4z5w5e.js.br +0 -2
- package/web/chunk-1x4z5w5e.js.gz +0 -0
- package/web/chunk-22ncha3b.js +0 -142
- package/web/chunk-22ncha3b.js.br +0 -0
- package/web/chunk-22ncha3b.js.gz +0 -0
- package/web/chunk-239rqgmj.js +0 -24
- package/web/chunk-239rqgmj.js.br +0 -0
- package/web/chunk-239rqgmj.js.gz +0 -0
- package/web/chunk-2c6zessc.js +0 -2
- package/web/chunk-2c6zessc.js.br +0 -0
- package/web/chunk-2c6zessc.js.gz +0 -0
- package/web/chunk-2m7b1wmp.js +0 -1
- package/web/chunk-2m7b1wmp.js.br +0 -0
- package/web/chunk-2m7b1wmp.js.gz +0 -0
- package/web/chunk-2qncw4c0.js +0 -2
- package/web/chunk-2qncw4c0.js.br +0 -0
- package/web/chunk-2qncw4c0.js.gz +0 -0
- package/web/chunk-2r497559.js +0 -2
- package/web/chunk-2r497559.js.br +0 -0
- package/web/chunk-2r497559.js.gz +0 -0
- package/web/chunk-2t43cra8.js +0 -1
- package/web/chunk-2t43cra8.js.br +0 -0
- package/web/chunk-2t43cra8.js.gz +0 -0
- package/web/chunk-2v379e1v.js +0 -1
- package/web/chunk-2v379e1v.js.br +0 -2
- package/web/chunk-2v379e1v.js.gz +0 -0
- package/web/chunk-2ywd0vz2.js +0 -1
- package/web/chunk-2ywd0vz2.js.br +0 -0
- package/web/chunk-2ywd0vz2.js.gz +0 -0
- package/web/chunk-3626tdgf.js +0 -1
- package/web/chunk-3626tdgf.js.br +0 -0
- package/web/chunk-3626tdgf.js.gz +0 -0
- package/web/chunk-3fq54zbf.js +0 -2
- package/web/chunk-3fq54zbf.js.br +0 -0
- package/web/chunk-3fq54zbf.js.gz +0 -0
- package/web/chunk-3jptvn0z.js +0 -1
- package/web/chunk-3jptvn0z.js.br +0 -0
- package/web/chunk-3jptvn0z.js.gz +0 -0
- package/web/chunk-3k31m9yk.js +0 -7
- package/web/chunk-3k31m9yk.js.br +0 -0
- package/web/chunk-3k31m9yk.js.gz +0 -0
- package/web/chunk-3wrebqcz.js +0 -1
- package/web/chunk-3wrebqcz.js.br +0 -0
- package/web/chunk-3wrebqcz.js.gz +0 -0
- package/web/chunk-42z866aa.js +0 -1
- package/web/chunk-42z866aa.js.br +0 -0
- package/web/chunk-42z866aa.js.gz +0 -0
- package/web/chunk-46r5s1ag.js +0 -1
- package/web/chunk-46r5s1ag.js.br +0 -2
- package/web/chunk-46r5s1ag.js.gz +0 -0
- package/web/chunk-4h8kxmac.js +0 -1
- package/web/chunk-4h8kxmac.js.br +0 -2
- package/web/chunk-4h8kxmac.js.gz +0 -0
- package/web/chunk-4hmp8qcv.js +0 -1
- package/web/chunk-4hmp8qcv.js.br +0 -0
- package/web/chunk-4hmp8qcv.js.gz +0 -0
- package/web/chunk-4ryyn6k5.js +0 -1
- package/web/chunk-4ryyn6k5.js.br +0 -0
- package/web/chunk-4ryyn6k5.js.gz +0 -0
- package/web/chunk-4zp7b44y.js +0 -78
- package/web/chunk-4zp7b44y.js.br +0 -0
- package/web/chunk-4zp7b44y.js.gz +0 -0
- package/web/chunk-52n1enqe.js +0 -1
- package/web/chunk-52n1enqe.js.br +0 -0
- package/web/chunk-52n1enqe.js.gz +0 -0
- package/web/chunk-5m5jve5q.js +0 -2
- package/web/chunk-5m5jve5q.js.br +0 -0
- package/web/chunk-5m5jve5q.js.gz +0 -0
- package/web/chunk-62ssrwet.js +0 -1
- package/web/chunk-62ssrwet.js.br +0 -0
- package/web/chunk-62ssrwet.js.gz +0 -0
- package/web/chunk-6e14fdx8.js +0 -1
- package/web/chunk-6e14fdx8.js.br +0 -0
- package/web/chunk-6e14fdx8.js.gz +0 -0
- package/web/chunk-6kckk3j9.js +0 -1
- package/web/chunk-6kckk3j9.js.br +0 -2
- package/web/chunk-6kckk3j9.js.gz +0 -0
- package/web/chunk-6vdh5wx5.js +0 -1
- package/web/chunk-6vdh5wx5.js.br +0 -0
- package/web/chunk-6vdh5wx5.js.gz +0 -0
- package/web/chunk-6wyrfrh1.js +0 -1
- package/web/chunk-6wyrfrh1.js.br +0 -0
- package/web/chunk-6wyrfrh1.js.gz +0 -0
- package/web/chunk-77pcpdb5.js +0 -303
- package/web/chunk-77pcpdb5.js.br +0 -0
- package/web/chunk-77pcpdb5.js.gz +0 -0
- package/web/chunk-7dq3x88k.js +0 -120
- package/web/chunk-7dq3x88k.js.br +0 -0
- package/web/chunk-7dq3x88k.js.gz +0 -0
- package/web/chunk-7ebwmmjn.js +0 -34
- package/web/chunk-7ebwmmjn.js.br +0 -0
- package/web/chunk-7ebwmmjn.js.gz +0 -0
- package/web/chunk-7jra5kj0.js +0 -1
- package/web/chunk-7jra5kj0.js.br +0 -0
- package/web/chunk-7jra5kj0.js.gz +0 -0
- package/web/chunk-8dgtprxa.js +0 -2
- package/web/chunk-8dgtprxa.js.br +0 -0
- package/web/chunk-8dgtprxa.js.gz +0 -0
- package/web/chunk-8mrw5mgn.js +0 -1
- package/web/chunk-8mrw5mgn.js.br +0 -0
- package/web/chunk-8mrw5mgn.js.gz +0 -0
- package/web/chunk-8n1cyb8k.js +0 -99
- package/web/chunk-8n1cyb8k.js.br +0 -0
- package/web/chunk-8n1cyb8k.js.gz +0 -0
- package/web/chunk-8nxjthxc.js +0 -1
- package/web/chunk-8nxjthxc.js.br +0 -0
- package/web/chunk-8nxjthxc.js.gz +0 -0
- package/web/chunk-8ssjqdky.js +0 -1
- package/web/chunk-8ssjqdky.js.br +0 -2
- package/web/chunk-8ssjqdky.js.gz +0 -0
- package/web/chunk-90k6xrsa.js +0 -2
- package/web/chunk-90k6xrsa.js.br +0 -0
- package/web/chunk-90k6xrsa.js.gz +0 -0
- package/web/chunk-926v5sg8.js +0 -24
- package/web/chunk-926v5sg8.js.br +0 -0
- package/web/chunk-926v5sg8.js.gz +0 -0
- package/web/chunk-9kvr6dkh.js +0 -106
- package/web/chunk-9kvr6dkh.js.br +0 -0
- package/web/chunk-9kvr6dkh.js.gz +0 -0
- package/web/chunk-9s6zj1sh.js +0 -217
- package/web/chunk-9s6zj1sh.js.br +0 -0
- package/web/chunk-9s6zj1sh.js.gz +0 -0
- package/web/chunk-9vf3zy3d.js +0 -2
- package/web/chunk-9vf3zy3d.js.br +0 -0
- package/web/chunk-9vf3zy3d.js.gz +0 -0
- package/web/chunk-acpyx69f.js +0 -1
- package/web/chunk-acpyx69f.js.br +0 -0
- package/web/chunk-acpyx69f.js.gz +0 -0
- package/web/chunk-amch1hp8.js +0 -1
- package/web/chunk-amch1hp8.js.br +0 -0
- package/web/chunk-amch1hp8.js.gz +0 -0
- package/web/chunk-azjpkz26.js +0 -38
- package/web/chunk-azjpkz26.js.br +0 -0
- package/web/chunk-azjpkz26.js.gz +0 -0
- package/web/chunk-b2zmxzm0.js +0 -2
- package/web/chunk-b2zmxzm0.js.br +0 -0
- package/web/chunk-b2zmxzm0.js.gz +0 -0
- package/web/chunk-bgn0bkad.js +0 -98
- package/web/chunk-bgn0bkad.js.br +0 -0
- package/web/chunk-bgn0bkad.js.gz +0 -0
- package/web/chunk-bka3pbzn.js +0 -4
- package/web/chunk-bka3pbzn.js.br +0 -0
- package/web/chunk-bka3pbzn.js.gz +0 -0
- package/web/chunk-ck23t8as.js +0 -2
- package/web/chunk-ck23t8as.js.br +0 -0
- package/web/chunk-ck23t8as.js.gz +0 -0
- package/web/chunk-cp5ec63g.js +0 -30
- package/web/chunk-cp5ec63g.js.br +0 -0
- package/web/chunk-cp5ec63g.js.gz +0 -0
- package/web/chunk-cw21gjwg.js +0 -39
- package/web/chunk-cw21gjwg.js.br +0 -0
- package/web/chunk-cw21gjwg.js.gz +0 -0
- package/web/chunk-cxcpk0qt.js +0 -2
- package/web/chunk-cxcpk0qt.js.br +0 -0
- package/web/chunk-cxcpk0qt.js.gz +0 -0
- package/web/chunk-d3s30py8.js +0 -1
- package/web/chunk-d3s30py8.js.br +0 -0
- package/web/chunk-d3s30py8.js.gz +0 -0
- package/web/chunk-dj4jc1ec.js +0 -1
- package/web/chunk-dj4jc1ec.js.br +0 -0
- package/web/chunk-dj4jc1ec.js.gz +0 -0
- package/web/chunk-drr7mqg2.js +0 -1
- package/web/chunk-drr7mqg2.js.br +0 -0
- package/web/chunk-drr7mqg2.js.gz +0 -0
- package/web/chunk-ef2xw0kb.js +0 -1
- package/web/chunk-ef2xw0kb.js.br +0 -0
- package/web/chunk-ef2xw0kb.js.gz +0 -0
- package/web/chunk-emxa4wv3.js +0 -2
- package/web/chunk-emxa4wv3.js.br +0 -0
- package/web/chunk-emxa4wv3.js.gz +0 -0
- package/web/chunk-fek0yrg5.js +0 -2
- package/web/chunk-fek0yrg5.js.br +0 -0
- package/web/chunk-fek0yrg5.js.gz +0 -0
- package/web/chunk-fgm2r34b.js +0 -36
- package/web/chunk-fgm2r34b.js.br +0 -0
- package/web/chunk-fgm2r34b.js.gz +0 -0
- package/web/chunk-fpqs301q.js +0 -2
- package/web/chunk-fpqs301q.js.br +0 -0
- package/web/chunk-fpqs301q.js.gz +0 -0
- package/web/chunk-fv6se8xf.js +0 -1
- package/web/chunk-fv6se8xf.js.br +0 -2
- package/web/chunk-fv6se8xf.js.gz +0 -0
- package/web/chunk-g0nagyx2.js +0 -1
- package/web/chunk-g0nagyx2.js.br +0 -0
- package/web/chunk-g0nagyx2.js.gz +0 -0
- package/web/chunk-g5fp9ep9.js +0 -1
- package/web/chunk-g5fp9ep9.js.br +0 -0
- package/web/chunk-g5fp9ep9.js.gz +0 -0
- package/web/chunk-gh1fmd3j.js +0 -3
- package/web/chunk-gh1fmd3j.js.br +0 -0
- package/web/chunk-gh1fmd3j.js.gz +0 -0
- package/web/chunk-gq5825re.js +0 -70
- package/web/chunk-gq5825re.js.br +0 -0
- package/web/chunk-gq5825re.js.gz +0 -0
- package/web/chunk-gy57dyny.js +0 -1
- package/web/chunk-gy57dyny.js.br +0 -0
- package/web/chunk-gy57dyny.js.gz +0 -0
- package/web/chunk-j6jjk46a.js +0 -2
- package/web/chunk-j6jjk46a.js.br +0 -0
- package/web/chunk-j6jjk46a.js.gz +0 -0
- package/web/chunk-j7p6xhe2.js +0 -1
- package/web/chunk-j7p6xhe2.js.br +0 -0
- package/web/chunk-j7p6xhe2.js.gz +0 -0
- package/web/chunk-jb8xfsc6.js +0 -2
- package/web/chunk-jb8xfsc6.js.br +0 -0
- package/web/chunk-jb8xfsc6.js.gz +0 -0
- package/web/chunk-jqyxnnn0.js +0 -1
- package/web/chunk-jqyxnnn0.js.br +0 -0
- package/web/chunk-jqyxnnn0.js.gz +0 -0
- package/web/chunk-jtwct1bx.js +0 -1133
- package/web/chunk-jtwct1bx.js.br +0 -0
- package/web/chunk-jtwct1bx.js.gz +0 -0
- package/web/chunk-k22kq2t7.js +0 -12
- package/web/chunk-k22kq2t7.js.br +0 -0
- package/web/chunk-k22kq2t7.js.gz +0 -0
- package/web/chunk-k2ry7k7s.js +0 -1
- package/web/chunk-k2ry7k7s.js.br +0 -0
- package/web/chunk-k2ry7k7s.js.gz +0 -0
- package/web/chunk-k3aa37pw.js +0 -2
- package/web/chunk-k3aa37pw.js.br +0 -0
- package/web/chunk-k3aa37pw.js.gz +0 -0
- package/web/chunk-kdbrrecz.js +0 -332
- package/web/chunk-kdbrrecz.js.br +0 -0
- package/web/chunk-kdbrrecz.js.gz +0 -0
- package/web/chunk-kes2tf1q.js +0 -2
- package/web/chunk-kes2tf1q.js.br +0 -3
- package/web/chunk-kes2tf1q.js.gz +0 -0
- package/web/chunk-ksrzt6c5.js +0 -1
- package/web/chunk-ksrzt6c5.js.br +0 -0
- package/web/chunk-ksrzt6c5.js.gz +0 -0
- package/web/chunk-m2ethr1n.js +0 -84
- package/web/chunk-m2ethr1n.js.br +0 -0
- package/web/chunk-m2ethr1n.js.gz +0 -0
- package/web/chunk-m7tcm69z.js +0 -292
- package/web/chunk-m7tcm69z.js.br +0 -0
- package/web/chunk-m7tcm69z.js.gz +0 -0
- package/web/chunk-m8bz4e6n.js +0 -2
- package/web/chunk-m8bz4e6n.js.br +0 -0
- package/web/chunk-m8bz4e6n.js.gz +0 -0
- package/web/chunk-mva687p4.js +0 -1
- package/web/chunk-mva687p4.js.br +0 -0
- package/web/chunk-mva687p4.js.gz +0 -0
- package/web/chunk-n8fe9j5b.js +0 -214
- package/web/chunk-n8fe9j5b.js.br +0 -0
- package/web/chunk-n8fe9j5b.js.gz +0 -0
- package/web/chunk-nckx4yfd.js +0 -62
- package/web/chunk-nckx4yfd.js.br +0 -0
- package/web/chunk-nckx4yfd.js.gz +0 -0
- package/web/chunk-ncynjha5.js +0 -2
- package/web/chunk-ncynjha5.js.br +0 -0
- package/web/chunk-ncynjha5.js.gz +0 -0
- package/web/chunk-nq7dp0wj.js +0 -291
- package/web/chunk-nq7dp0wj.js.br +0 -0
- package/web/chunk-nq7dp0wj.js.gz +0 -0
- package/web/chunk-pagep4k3.js +0 -1
- package/web/chunk-pagep4k3.js.br +0 -0
- package/web/chunk-pagep4k3.js.gz +0 -0
- package/web/chunk-pbrk7zdw.js +0 -1
- package/web/chunk-pbrk7zdw.js.br +0 -0
- package/web/chunk-pbrk7zdw.js.gz +0 -0
- package/web/chunk-q0cs1bhg.js +0 -2
- package/web/chunk-q0cs1bhg.js.br +0 -0
- package/web/chunk-q0cs1bhg.js.gz +0 -0
- package/web/chunk-q749pgke.js +0 -1
- package/web/chunk-q749pgke.js.br +0 -0
- package/web/chunk-q749pgke.js.gz +0 -0
- package/web/chunk-q7yry602.js +0 -1
- package/web/chunk-q7yry602.js.br +0 -0
- package/web/chunk-q7yry602.js.gz +0 -0
- package/web/chunk-qkeaa97s.js +0 -1
- package/web/chunk-qkeaa97s.js.br +0 -0
- package/web/chunk-qkeaa97s.js.gz +0 -0
- package/web/chunk-qx7afyba.js +0 -1
- package/web/chunk-qx7afyba.js.br +0 -0
- package/web/chunk-qx7afyba.js.gz +0 -0
- package/web/chunk-qxvqkkmw.js +0 -1
- package/web/chunk-qxvqkkmw.js.br +0 -0
- package/web/chunk-qxvqkkmw.js.gz +0 -0
- package/web/chunk-qych3sbs.js +0 -1
- package/web/chunk-qych3sbs.js.br +0 -0
- package/web/chunk-qych3sbs.js.gz +0 -0
- package/web/chunk-rcaqmcm4.js +0 -40
- package/web/chunk-rcaqmcm4.js.br +0 -0
- package/web/chunk-rcaqmcm4.js.gz +0 -0
- package/web/chunk-s5kbbker.js +0 -89
- package/web/chunk-s5kbbker.js.br +0 -0
- package/web/chunk-s5kbbker.js.gz +0 -0
- package/web/chunk-sdq69ysp.js +0 -2
- package/web/chunk-sdq69ysp.js.br +0 -0
- package/web/chunk-sdq69ysp.js.gz +0 -0
- package/web/chunk-sgbc835w.js +0 -2
- package/web/chunk-sgbc835w.js.br +0 -0
- package/web/chunk-sgbc835w.js.gz +0 -0
- package/web/chunk-sk0cmsbx.js +0 -7
- package/web/chunk-sk0cmsbx.js.br +0 -0
- package/web/chunk-sk0cmsbx.js.gz +0 -0
- package/web/chunk-smmcx1z4.js +0 -324
- package/web/chunk-smmcx1z4.js.br +0 -0
- package/web/chunk-smmcx1z4.js.gz +0 -0
- package/web/chunk-sq7ntjp0.js +0 -16
- package/web/chunk-sq7ntjp0.js.br +0 -0
- package/web/chunk-sq7ntjp0.js.gz +0 -0
- package/web/chunk-st27df9w.js +0 -2
- package/web/chunk-st27df9w.js.br +0 -0
- package/web/chunk-st27df9w.js.gz +0 -0
- package/web/chunk-svxkg8n3.js +0 -2
- package/web/chunk-svxkg8n3.js.br +0 -0
- package/web/chunk-svxkg8n3.js.gz +0 -0
- package/web/chunk-t9nzrp2p.js +0 -1
- package/web/chunk-t9nzrp2p.js.br +0 -0
- package/web/chunk-t9nzrp2p.js.gz +0 -0
- package/web/chunk-t9t9v1r8.js +0 -55
- package/web/chunk-t9t9v1r8.js.br +0 -0
- package/web/chunk-t9t9v1r8.js.gz +0 -0
- package/web/chunk-tzpv48j3.js +0 -2
- package/web/chunk-tzpv48j3.js.br +0 -0
- package/web/chunk-tzpv48j3.js.gz +0 -0
- package/web/chunk-vgsk4ppw.js +0 -7
- package/web/chunk-vgsk4ppw.js.br +0 -0
- package/web/chunk-vgsk4ppw.js.gz +0 -0
- package/web/chunk-vq41ta7n.js +0 -4
- package/web/chunk-vq41ta7n.js.br +0 -0
- package/web/chunk-vq41ta7n.js.gz +0 -0
- package/web/chunk-vszya05r.js +0 -2
- package/web/chunk-vszya05r.js.br +0 -0
- package/web/chunk-vszya05r.js.gz +0 -0
- package/web/chunk-w08egbqf.js +0 -1
- package/web/chunk-w08egbqf.js.br +0 -0
- package/web/chunk-w08egbqf.js.gz +0 -0
- package/web/chunk-wcmq0qgh.js +0 -1
- package/web/chunk-wcmq0qgh.js.br +0 -0
- package/web/chunk-wcmq0qgh.js.gz +0 -0
- package/web/chunk-wctq02yb.js +0 -2
- package/web/chunk-wctq02yb.js.br +0 -0
- package/web/chunk-wctq02yb.js.gz +0 -0
- package/web/chunk-wfa1c8dn.js +0 -1
- package/web/chunk-wfa1c8dn.js.br +0 -0
- package/web/chunk-wfa1c8dn.js.gz +0 -0
- package/web/chunk-wfwadf3r.js +0 -2
- package/web/chunk-wfwadf3r.js.br +0 -0
- package/web/chunk-wfwadf3r.js.gz +0 -0
- package/web/chunk-wgas5t5y.js +0 -1
- package/web/chunk-wgas5t5y.js.br +0 -0
- package/web/chunk-wgas5t5y.js.gz +0 -0
- package/web/chunk-x7k4eyee.js +0 -21
- package/web/chunk-x7k4eyee.js.br +0 -0
- package/web/chunk-x7k4eyee.js.gz +0 -0
- package/web/chunk-xpv38q1f.js +0 -140
- package/web/chunk-xpv38q1f.js.br +0 -0
- package/web/chunk-xpv38q1f.js.gz +0 -0
- package/web/chunk-xt671z8e.js +0 -1
- package/web/chunk-xt671z8e.js.br +0 -0
- package/web/chunk-xt671z8e.js.gz +0 -0
- package/web/chunk-xwrrkwwx.css +0 -1
- package/web/chunk-xwrrkwwx.css.br +0 -0
- package/web/chunk-xwrrkwwx.css.gz +0 -0
- package/web/chunk-xwy3gth5.js +0 -89
- package/web/chunk-xwy3gth5.js.br +0 -0
- package/web/chunk-xwy3gth5.js.gz +0 -0
- package/web/chunk-xwyadj9p.js +0 -2
- package/web/chunk-xwyadj9p.js.br +0 -0
- package/web/chunk-xwyadj9p.js.gz +0 -0
- package/web/chunk-xzgvnd23.js +0 -1
- package/web/chunk-xzgvnd23.js.br +0 -0
- package/web/chunk-xzgvnd23.js.gz +0 -0
- package/web/chunk-y05m6rvz.js +0 -1
- package/web/chunk-y05m6rvz.js.br +0 -2
- package/web/chunk-y05m6rvz.js.gz +0 -0
- package/web/chunk-z51mtwh3.js +0 -169
- package/web/chunk-z51mtwh3.js.br +0 -0
- package/web/chunk-z51mtwh3.js.gz +0 -0
- package/web/chunk-z77xrqc1.js +0 -1
- package/web/chunk-z77xrqc1.js.br +0 -0
- package/web/chunk-z77xrqc1.js.gz +0 -0
- package/web/chunk-z946nbmn.js +0 -2
- package/web/chunk-z946nbmn.js.br +0 -0
- package/web/chunk-z946nbmn.js.gz +0 -0
package/chunk-rmyzxqkd.js
DELETED
|
@@ -1,467 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ni,vn,z}from"./chunk-jbk2tmza.js";import{is,Je,Mt,ss,fo,ls,cs,us,Lt,ms,Fe,yo,nt}from"./chunk-hbm45044.js";import{St,mn,oo,Xt,$i,io}from"./chunk-fjk9ztjc.js";import{Xo,hn,fn,Wi,t,m,wt,qi,Gi,zi,Tr,Zo,ji,Sn,ei,Zi,ri,so,es,ts,Oe}from"./chunk-hkx7d1j9.js";import{ao,xs,xn}from"./chunk-gsek3gpd.js";import{b,ue}from"./chunk-t3mq64c8.js";import{lo,F,_n,Ne,ie,oi,co,lt,ns,Zt,Ie,U,uo,xt,De,Pr,q,Ue,po,vt,fe,er,ce,An,ii,Be,ae,ct,mo,si,_e,vs,os,Ae,ho,d,_s,Z,En,K,As}from"./chunk-tdnwaaw4.js";import{r,Ye}from"./chunk-37f4ks5f.js";var Og=r(function(dK,Mg){var hv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Gl=/[\n\r\u2028\u2029]/,gv=/[\s#!"$&'():;<=>@\\^`|~]/g;Mg.exports=function(o){var a=!1;return o.map(function(u){if(a&&typeof u==="string"&&Gl.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(Gl.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(gv,"\\$&")}if("op"in u&&typeof u.op==="string"){if(hv.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(Gl.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 Ug=r(function(fK,jg){var Dg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",_g=new RegExp("^"+Dg+"$"),Lg="|&;()<> \\t",yv="'([^']*?)'",Fg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Ng="\\$'"+Fg+"'",Yc=new RegExp("\\$'"+Fg+"(?:(')|\\\\?$)","g"),xv="abeEfnrtv",Iv=`\x07\b\x1B\x1B\f
|
|
3
|
-
\r \v`,Ev=/^#$/,Kl="'",qg='"',ku="$",Yi="",bv=4294967296;for(Xc=0;Xc<4;Xc++)Yi+=(bv*Math.random()).toString(16);var Xc,Sv=new RegExp("^"+Yi);function wv(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 Tv(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+Yi+JSON.stringify(u)+Yi;return o+u}var Rv=/\\([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 kv(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=xv.indexOf(o);return f<0?o:Iv.charAt(f)}function Av(e){return e.replace(Rv,kv).split("\x00")[0]}function Pv(e,o){return Yc.lastIndex=o,!!Yc.exec(e)[1]}function $v(e,o,a){if(!a)a={};var u=a.escape||"\\",p=a.splitUnquoted===!0?`
|
|
4
|
-
`:typeof a.splitUnquoted==="string"?a.splitUnquoted:"",f="(\\"+u+`['"$\\`+u+Lg+"]|\\$\\$|\\$(?!"+Ng.slice(2)+`)|[^\\s'"$`+Lg+"])+",h='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',g=new RegExp(["("+Dg+")","("+Ng+"|"+f+"|"+h+"|"+yv+")+"].join("|"),"g"),I=wv(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(_g.test(k))return{op:k};var A=!1,P=!1,C="",M=[],V=!1,_=null,J=!1,j;function Y(){j+=1;var ee,be,Xe=k.charAt(j);if(Xe==="{"){if(j+=1,k.charAt(j)==="}")throw Error("Bad substitution: "+k.slice(j-2,j+1));var Ge=1;ee=j;while(Ge>0&&ee<k.length){if(k.charAt(ee)==="{"&&k.charAt(ee-1)==="$")Ge+=1;else if(k.charAt(ee)==="}")Ge-=1;ee+=1}if(Ge!==0)throw Error("Bad substitution: "+k.slice(j));ee-=1,be=k.slice(j,ee),j=ee}else if(/[*@#?$!-]/.test(Xe))be=Xe;else{var ar=k.slice(j);if(ee=ar.match(/[^\w\d_]/),!ee)be=ar,j=k.length;else be=ar.slice(0,ee.index),j+=ee.index-1}return Tv(o,"",be)}function te(){if(_===null)return;if(_===0){if(C!=="")M[M.length]=C,C=""}else{M[M.length]=C,C="";for(var ee=1;ee<_;ee+=1)M[M.length]=""}_=null}for(j=0;j<k.length;j++){var L=k.charAt(j);if(p&&L!==ku)te();if(J=J||!A&&(L==="*"||L==="?"),P)C+=L,P=!1;else if(A)if(L===A)A=!1;else if(A==Kl)C+=L;else if(L===u)if(j+=1,L=k.charAt(j),L===qg||L===u||L===ku)C+=L;else C+=u+L;else if(L===ku)C+=Y();else C+=L;else if(L===qg||L===Kl)A=L,V=!0;else if(_g.test(L))return{op:k};else if(Ev.test(L)){E=!0;var se={comment:e.slice(S.index+j+1)};if(C.length)return[C,se];return[se]}else if(L===u)P=!0;else if(L===ku&&k.charAt(j+1)===Kl&&Pv(k,j))te(),V=!0,C+=Av(k.slice(j+2,Yc.lastIndex-1)),j=Yc.lastIndex-1;else if(L===ku){var he=Y();if(!p)C+=he;else for(var Me=0;Me<he.length;Me+=1){var ze=he.charAt(Me);if(p.indexOf(ze)<0)te(),C+=ze;else if(_===null)_=ze===" "||ze==="\t"||ze===`
|
|
5
|
-
`?0:1;else if(ze!==" "&&ze!=="\t"&&ze!==`
|
|
6
|
-
`)_+=1}}else C+=L}if(J)return{op:"glob",pattern:C};if(p){if(_!==null&&_>0){M[M.length]=C,C="";for(var X=1;X<_;X+=1)M[M.length]=""}if(C!==""||V&&M.length===0)M[M.length]=C;return M}return C}).reduce(function(S,k){if(typeof k>"u")return S;return[].concat(k).forEach(function(A){S[S.length]=A}),S},[])}jg.exports=function(o,a,u){var p=$v(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("("+Yi+".*?"+Yi+")","g"));if(g.length===1)return f[f.length]=g[0],f;return g.filter(Boolean).forEach(function(I){f[f.length]=Sv.test(I)?JSON.parse(I.split(Yi)[1]):I}),f},[])}});var Ko={};Ye(Ko,{AssistantMessageEventStream:()=>F,AssistantMessageFrameEncoder:()=>eR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>nR,EventStream:()=>lo,InMemoryCredentialStore:()=>co,InMemoryModelsStore:()=>uo,ModelsError:()=>U,StringEnum:()=>uD,Type:()=>Le,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>Z,clampThinkingLevel:()=>K,cleanupSessionResources:()=>xs,collapseSystemMessages:()=>Be,contentText:()=>Pr,createAssistantMessageDiagnostic:()=>Zt,createAssistantMessageEventStream:()=>_n,createFauxCore:()=>$i,createInitialSystemMessage:()=>po,createModels:()=>ho,createProvider:()=>d,declarationsEqual:()=>mo,defaultProviderAuthContext:()=>oi,envApiKeyAuth:()=>b,extractDiagnosticError:()=>ns,fauxAssistantMessage:()=>Xt,fauxProvider:()=>io,fauxText:()=>St,fauxThinking:()=>mn,fauxToolCall:()=>oo,formatThrownValue:()=>lt,getCurrentSystemMessage:()=>An,getCurrentSystemPrompt:()=>ii,getCurrentTools:()=>ce,getDeclaredTools:()=>_e,getInitialSystemMessage:()=>fe,getModelType:()=>xt,getOverflowPatterns:()=>nD,getSupportedThinkingLevels:()=>En,getSystemMessageText:()=>q,getToolStateChanges:()=>si,hasApi:()=>_s,hasNonAdditiveToolChanges:()=>os,hasToolRedefinitions:()=>vs,isContextOverflow:()=>Ea,isModelType:()=>De,isRecoverableLength:()=>rD,isRetryableAssistantError:()=>sR,lazyApi:()=>ie,lazyOAuth:()=>ue,lazyStream:()=>Ne,modelsAreEqual:()=>As,normalizeContext:()=>vt,parseJsonWithRepair:()=>vn,parseStreamingJson:()=>z,reduceAssistantMessageFrames:()=>Zq,registerSessionResourceCleanup:()=>ao,renderSystemMessageUpdate:()=>Ue,repairJson:()=>ni,resolveTranscript:()=>ae,resolveTranscriptTools:()=>Ae,retryAssistantCall:()=>aD,retryDelayMs:()=>oR,toToolDeclaration:()=>ct,uuidv7:()=>xn,validateToolArguments:()=>lu,validateToolCall:()=>zj,withoutInitialSystemMessage:()=>er});var O={};Ye(O,{Counted:()=>Xl,Entries:()=>an,EntriesRegExp:()=>Yl,Every:()=>tn,EveryAll:()=>Ln,GraphemeCount:()=>eM,HasPropertyKey:()=>me,IsArray:()=>$e,IsBigInt:()=>Ur,IsBoolean:()=>sn,IsClassInstance:()=>oy,IsConstructor:()=>Jl,IsDeepEqual:()=>Oa,IsEqual:()=>v,IsFunction:()=>Ps,IsGreaterEqualThan:()=>va,IsGreaterThan:()=>ta,IsInteger:()=>tm,IsLessEqualThan:()=>$s,IsLessThan:()=>Pu,IsMaxLength:()=>sy,IsMinLength:()=>iy,IsMultipleOf:()=>ny,IsNull:()=>Po,IsNumber:()=>Ft,IsObject:()=>mt,IsObjectNotArray:()=>Yo,IsString:()=>ht,IsSymbol:()=>Ql,IsUndefined:()=>rr,IsUnsafePropertyKey:()=>$u,IsValueLike:()=>ra,Keys:()=>xe,ShiftLeft:()=>yt,Some:()=>Ma,SomeAll:()=>ay,Symbols:()=>uy,Values:()=>Zl});var ca={};Ye(ca,{Hash:()=>id,HashCode:()=>By});var Ut={};Ye(Ut,{ExtendsFalse:()=>ot,ExtendsTrue:()=>Ee,ExtendsUnion:()=>Pd,IsExtendsFalse:()=>vd,IsExtendsTrue:()=>Cd,IsExtendsTrueLike:()=>Eo,IsExtendsUnion:()=>$d,Match:()=>Sr});var Le={};Ye(Le,{Any:()=>qa,Array:()=>W,BigInt:()=>Lu,Boolean:()=>D,Call:()=>tw,Capitalize:()=>uw,Codec:()=>pm,Conditional:()=>gw,Constructor:()=>Ms,ConstructorParameters:()=>xw,Cyclic:()=>Ns,Decode:()=>Wy,DecodeBuilder:()=>mm,Dependent:()=>ua,Encode:()=>zy,EncodeBuilder:()=>cm,Enum:()=>My,Evaluate:()=>On,Exclude:()=>Ew,Extends:()=>Mn,ExtendsResult:()=>Ut,Extract:()=>Sw,Function:()=>Os,Generic:()=>Si,Identifier:()=>Nu,Immutable:()=>Vy,Index:()=>kw,Infer:()=>_u,InstanceType:()=>Xw,Instantiate:()=>Fo,Integer:()=>x,Interface:()=>NS,Intersect:()=>qn,IsAny:()=>Nr,IsArray:()=>kt,IsBigInt:()=>To,IsBoolean:()=>zn,IsCall:()=>Ja,IsCodec:()=>Wn,IsConstructor:()=>Jr,IsCyclic:()=>cr,IsDependent:()=>Br,IsEnum:()=>Zr,IsEnumValue:()=>vy,IsFunction:()=>Qr,IsGeneric:()=>Na,IsIdentifier:()=>Yy,IsImmutable:()=>ma,IsInfer:()=>Yr,IsInteger:()=>yn,IsIntersect:()=>We,IsKind:()=>Se,IsLiteral:()=>gt,IsNever:()=>wo,IsNull:()=>Ds,IsNumber:()=>Cr,IsObject:()=>Qe,IsOptional:()=>nn,IsParameter:()=>rx,IsReadonly:()=>la,IsRecord:()=>nr,IsRef:()=>Yt,IsRefine:()=>lm,IsRest:()=>Pi,IsSchema:()=>Lr,IsString:()=>en,IsSymbol:()=>Fs,IsTemplateLiteral:()=>lr,IsThis:()=>km,IsTuple:()=>dt,IsUndefined:()=>fs,IsUnion:()=>ye,IsUnknown:()=>Xr,IsUnsafe:()=>um,IsVoid:()=>Ro,KeyOf:()=>Zw,Literal:()=>i,Lowercase:()=>cw,Mapped:()=>aT,Module:()=>JT,Never:()=>sr,NonNullable:()=>pT,Null:()=>Dn,Number:()=>re,Object:()=>l,Omit:()=>dT,Optional:()=>n,Parameter:()=>da,Parameters:()=>gT,Partial:()=>xT,Pick:()=>RT,Readonly:()=>Jy,ReadonlyObject:()=>af,ReadonlyType:()=>PT,Record:()=>Ke,RecordKey:()=>Ai,RecordPattern:()=>In,RecordValue:()=>hr,Ref:()=>rn,Refine:()=>Qy,Required:()=>GT,Rest:()=>ha,ReturnType:()=>HT,Script:()=>ZT,String:()=>s,Symbol:()=>ja,TemplateLiteral:()=>nS,This:()=>Rm,Tuple:()=>Kr,Uncapitalize:()=>mw,Undefined:()=>Ga,Union:()=>y,Unknown:()=>Q,Unsafe:()=>xr,Uppercase:()=>pw,Void:()=>Am,With:()=>pp});var cu={};Ye(cu,{Clear:()=>bk,Entries:()=>hF,Get:()=>xF,Has:()=>yF,IsDate:()=>iu,IsDateTime:()=>yp,IsDuration:()=>xp,IsEmail:()=>Ip,IsHostname:()=>Ap,IsIPv4:()=>Cp,IsIPv6:()=>vp,IsIdnEmail:()=>Pp,IsIdnHostname:()=>$p,IsIri:()=>Op,IsIriReference:()=>Mp,IsJsonPointer:()=>Lp,IsJsonPointerUriFragment:()=>_p,IsRegex:()=>Np,IsRelativeJsonPointer:()=>qp,IsTime:()=>au,IsUri:()=>jp,IsUriReference:()=>Dp,IsUriTemplate:()=>Fp,IsUrl:()=>Up,IsUuid:()=>Bp,Reset:()=>wk,Set:()=>gF,Test:()=>Sk});var Ve=10,dv=15000000;function at(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"&&so.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=dv}function jl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as wg,existsSync as Tg,fsyncSync as Rg,mkdirSync as kg,openSync as Ag,readFileSync as Pg,renameSync as $g,writeFileSync as Cg}from"fs";import{dirname as Ul,join as vg}from"path";class Di{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=vg(e,"auth.json"),this.deviceIdPath=vg(e,"device-id")}load(){if(!Tg(this.path))return;let e;try{e=JSON.parse(Pg(this.path,"utf8"))}catch{this.quarantine();return}let o=Bl(e);if(o?.version!==1){this.quarantine();return}let a=Bl(o.providers);if(!a){this.quarantine();return}for(let[u,p]of Object.entries(a)){if(!fv(p))continue;this.providers[u]=p}}deviceId(){if(Tg(this.deviceIdPath)){let o=Pg(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return kg(Ul(this.deviceIdPath),{recursive:!0}),Cg(this.deviceIdPath,`${e}
|
|
7
|
-
`),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[wt]??=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){kg(Ul(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,a=Ag(o,"w",384);try{Cg(a,`${JSON.stringify({version:1,providers:e},null,2)}
|
|
8
|
-
`),Rg(a)}finally{wg(a)}if($g(o,this.path),process.platform==="win32")return;let u=Ag(Ul(this.path),"r");try{Rg(u)}catch(p){if(!(p instanceof Error&&("code"in p)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(p.code))))throw p}finally{wg(u)}}quarantine(){try{$g(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function Bl(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function fv(e){let o=Bl(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 Cv=Og(),Hl=Ug();import{AsyncLocalStorage as vv}from"async_hooks";var N=new vv;var Mv=3,Bg=160,Ov=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),_v=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),Hg=/^[A-Za-z_][A-Za-z0-9_]*=/,Lv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),Nv=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),qv=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,Dv=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),Fv=new Set(["command","builtin","nohup","time","exec"]),jv=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir","-S","--split-string"]],["nice",["-n","--adjustment"]]]);function Zc(e){return{out:e.out,depth:e.depth+1}}function Gg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function Wl(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 Uv(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 C=e.charAt(P);if(C==="\\"){P+=2;continue}if(C==="`")break;P++}return o.subs.push(e.slice(E+1,P)),P<p?P+1:p}if(e.charAt(E+1)==="("){let P=Wl(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=Wl(e,E+1,"{","}"),A=e.slice(E+2,k-1);for(let P=0;P<A.length;P++){let C=A.charAt(P);if(C==="\\"){P++;continue}if(C==="`"){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(C==="$"&&A.charAt(P+1)==="("){let M=Wl(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==="\\"){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==="#"){let S=a.at(-1);if(S===void 0||`
|
|
9
|
-
;&|()`.includes(S)){while(f<p&&e.charAt(f)!==`
|
|
10
|
-
`)f++;continue}a.push(E),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 C=e.indexOf(P,k+1);if(C<0)break;A+=e.slice(k+1,C),k=C+1;continue}if(P==="\\"){A+=e.charAt(k+1),k+=2;continue}if(` \r
|
|
11
|
-
;&|()<>`.includes(P))break;A+=P,k++}if(A)u.push(A);f=S;continue}if(E===`
|
|
12
|
-
`){if(u.length>0){let S=qv.test(a.slice(h).join(""));f++;for(let k of u.splice(0)){let A=f,P=p;while(f<p){let C=e.indexOf(`
|
|
13
|
-
`,f),M=C<0?p:C;if(e.slice(f,M).trim()===k){P=f,f=C<0?p:C+1;break}f=C<0?p:C+1}if(S&&P>A)o.heredocs.push(e.slice(A,P))}}else f++;a.push(";",`
|
|
14
|
-
`),h=a.length;continue}a.push(E),f++}return o.text=a.join(""),o}function Au(e,o){if(o.depth>Mv)return;let a=Uv(e),u;try{u=Hl(a.text)}catch{return}let p=[];for(let f of u){if(typeof f==="string"){p.push({kind:"word",text:f});continue}if("pattern"in f){p.push({kind:"word",text:f.pattern});continue}if("op"in f)p.push({kind:"op",text:f.op})}Bv(p,o);for(let f of a.subs)Au(f,Zc(o));for(let f of a.heredocs)Au(f,Zc(o))}function Bv(e,o){let a=[],u=()=>{if(a.length>0)Gv(a,o);a=[]};for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;if(f.kind==="op"){if(Lv.has(f.text)){u();continue}if(Nv.has(f.text)){if(/^\d+$/.test(a.at(-1)??""))a.pop();p++}continue}a.push(f.text)}u()}function Gv(e,o){let a=0;for(;;){let h=e[a];if(h===void 0)return;if(_v.has(h)||Hg.test(h)){a++;continue}let g=Hv(Gg(h),e,a);if(g===a)break;a=g}let u=e[a];if(u===void 0)return;let p=Gg(u),f=e.slice(a+1);if(p==="git"){zv(u,f,o);return}if(Ov.has(p)){Kv(f,o);return}if(p==="powershell"||p==="pwsh")Kg(f,/^-(command|c)$/i,o);if(p==="cmd")Kg(f,/^\/[ck]$/i,o)}function Kg(e,o,a){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let p=e.slice(u+1).join(" ");if(p.trim())Au(p,Zc(a));return}}function Kv(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)Au(f,Zc(o));return}if(u.startsWith("-")||u==="")continue;return}}function Hv(e,o,a){if(Fv.has(e)){let f=a+1;while(o[f]?.startsWith("-"))f++;return f}let u=jv.get(e);if(!u)return a;let p=a+1;for(;;){let f=o[p];if(f===void 0)return p;if(u.includes(f)){p+=2;continue}if(Hg.test(f)||f.startsWith("-")){p++;continue}return p}}function zo(e,o){return e.some((a)=>a.length>1&&a.startsWith("-")&&!a.startsWith("--")&&a.slice(1).includes(o))}function go(e,o){return e.some((a)=>a===`--${o}`||a.startsWith(`--${o}=`))}var Wv={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(zo(e,"f")||zo(e,"i")||go(e,"force")||go(e,"interactive"))&&!(zo(e,"n")||go(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>zo(e,"f")||go(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>zo(e,"f")||go(e,"force")||zo(e,"C")||go(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)=>zo(e,"f")||go(e,"force")||go(e,"force-with-lease")||go(e,"force-if-includes")||go(e,"delete")||go(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)=>go(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>zo(e,"D")||zo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\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)=>go(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>zo(e,"f")||go(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"&&(zo(e,"f")||go(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function zv(e,o,a){let u=0;for(;;){let I=o[u];if(I===void 0)break;if(Dv.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=Wv[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>Bg?`${g.slice(0,Bg)}\u2026`:g,reason:h})}function jo(e){let o={out:[],depth:0};return Au(e,o),o.out}function Wg(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 zl=new Map;function Vv(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(!zl.delete(f))return;p?.removeEventListener("abort",I),h(E)},I=()=>{zg(e,f),g("aborted")};if(zl.set(f,{session:e,finish:g}),e.appendExtension({namespace:fn,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 zg(e,o){try{e.appendExtension({namespace:fn,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=zl.get(o);if(!u||u.session!==e){if(!Jv(e,o))return"unknown";return zg(e,o),"expired"}return e.appendExtension({namespace:fn,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 Jv(e,o){let a=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==fn)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 Vo(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${Wg(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 He(e,o){let a=jo(e);if(!a.at(0))return;let p=Wg(a),f=N.getStore();if(f?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\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`${Vo(a)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let h=await Vv(f,e,p,a,o);if(h==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${h==="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 ks={assign:0,create:0,clone:0,discard:0,update:0};function ea(e,o,a){return e>=o&&e<=a}function Qg(e){return e===8205}function Qv(e){return ea(e,55296,56319)}function Vg(e){return ea(e,127462,127487)}function Xg(e){return ea(e,65024,65039)}function Yg(e){return ea(e,768,879)||ea(e,6832,6911)||ea(e,7616,7679)||ea(e,65056,65071)}function em(e){return e>65535?2:1}function Jg(e,o){while(o<e.length){let a=e.codePointAt(o);if(Yg(a)||Xg(a))o+=em(a);else break}return o}function Vl(e,o){let a=e.codePointAt(o),u=o+em(a);u=Jg(e,u);while(u<e.length-1&&Qg(e.codePointAt(u))){let p=e.codePointAt(u+1);u+=1+em(p),u=Jg(e,u)}if(Vg(a)&&u<e.length&&Vg(e.codePointAt(u)))u+=em(e.codePointAt(u));return u}function Zg(e){return e>=768&&(Qv(e)||Yg(e)||Xg(e)||Qg(e))}function ey(e){let o=0,a=0;while(a<e.length)a=Vl(e,a),o++;return o}function Xv(e,o){let a=0,u=0;while(u<e.length)if(u=Vl(e,u),++a>=o)return!0;return!1}function Yv(e,o){let a=0,u=0;while(u<e.length)if(u=Vl(e,u),++a>o)return!1;return!0}function ty(e,o){if(o===0)return!0;if(e.length<o)return!1;let a=0;while(!0){if(Zg(e.charCodeAt(a)))return Xv(e,o);if(++a>=o)return!0}}function ry(e,o){if(e.length<=o)return!0;let a=0;while(!0){if(Zg(e.charCodeAt(a)))return Yv(e,o);if(++a>o)return!1}}function $e(e){return Array.isArray(e)}function Ur(e){return v(typeof e,"bigint")}function sn(e){return v(typeof e,"boolean")}function Jl(e){if(rr(e)||!Ps(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 Ps(e){return v(typeof e,"function")}function tm(e){return Number.isInteger(e)}function Po(e){return v(e,null)}function Ft(e){return Number.isFinite(e)}function Yo(e){return mt(e)&&!$e(e)}function mt(e){return v(typeof e,"object")&&!Po(e)}function ht(e){return v(typeof e,"string")}function Ql(e){return v(typeof e,"symbol")}function rr(e){return v(e,void 0)}function v(e,o){return e===o}function ta(e,o){return e>o}function Pu(e,o){return e<o}function $s(e,o){return e<=o}function va(e,o){return e>=o}function ny(e,o){if(Ur(e)||Ur(o))return BigInt(e)%BigInt(o)===0n;let a=0.0000000001;if(!Ft(e))return!0;if(tm(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 oy(e){if(!mt(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(Po(o))return!1;return v(typeof o.constructor,"function")&&!(v(o.constructor,globalThis.Object)||v(o.constructor.name,"Object"))}function ra(e){return Ur(e)||sn(e)||Po(e)||Ft(e)||ht(e)||rr(e)}function eM(e){return ey(e)}function sy(e,o){return ry(e,o)}function iy(e,o){return ty(e,o)}function tn(e,o,a){return e.every((u,p)=>p<o||a(u,p))}function Ln(e,o,a){let u=!0;return e.forEach((p,f)=>{if(f>=o&&!a(p,f))u=!1}),u}function Ma(e,o){return e.some((a,u)=>o(a,u))}function ay(e,o){let a=!1;return e.forEach((u,p)=>{if(o(u,p))a=!0}),a}function Xl(e,o){return e.reduce((a,u,p)=>o(u,p)?++a:a,0)}function yt(e,o,a){return v(e.length,0)?a():o(e[0],e.slice(1))}function $u(e){return v(e,"__proto__")||v(e,"constructor")||v(e,"prototype")}function me(e,o){return $u(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function Yl(e){return xe(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function an(e){return Object.entries(e)}function xe(e){return Object.getOwnPropertyNames(e)}function uy(e){return Object.getOwnPropertySymbols(e)}function Zl(e){return Object.values(e)}function tM(e,o){if(!mt(o))return!1;let a=xe(e);return v(a.length,xe(o).length)&&a.every((u)=>Oa(e[u],o[u]))}function rM(e,o){return $e(o)&&v(e.length,o.length)&&e.every((a,u)=>Oa(e[u],o[u]))}function Oa(e,o){return $e(e)?rM(e,o):mt(e)?tM(e,o):v(e,o)}var nM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function oM(e){return nM.test(e)}function $n(e,o){return`(${e} && ${o})`}function Er(e,o){return`(${e} || ${o})`}function Kn(e){return`!(${e})`}function rm(e){return`Array.isArray(${e})`}function cy(e){return`typeof ${e} === "bigint"`}function sM(e){return`typeof ${e} === "boolean"`}function iM(e){return`Number.isInteger(${e})`}function aM(e){return`${e} === null`}function my(e){return`Number.isFinite(${e})`}function py(e){return $n(ly(e),Kn(rm(e)))}function ly(e){return`typeof ${e} === "object" && ${e} !== null`}function dy(e){return`typeof ${e} === "string"`}function uM(e){return`typeof ${e} === "symbol"`}function ed(e){return`${e} === undefined`}function cM(e){return`typeof ${e} === "function"`}function mM(e){return`Guard.IsConstructor(${e})`}function So(e,o){return`${e} === ${o}`}function fy(e,o){return`${e} > ${o}`}function td(e,o){return`${e} < ${o}`}function na(e,o){return`${e} <= ${o}`}function Cu(e,o){return`${e} >= ${o}`}function pM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function lM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function Cs(e,o,a,u){return v(o,"0")?`${e}.every((${a[0]}, ${a[1]}) => (${u}))`:`${e}.every((${a[0]}, ${a[1]}) => (${a[1]} < ${o}) || (${u}))`}function dM(e,o,a){return`${e}.some((${o[0]}, ${o[1]}) => ${a})`}function fM(e,o,a){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${a}) result = true }); return result })(${e})`}function nm(e,o,a){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${a}) ? ++result : result, 0)`}function hy(e){return`Object.entries(${e})`}function oa(e){return`Object.getOwnPropertyNames(${e})`}function sa(e,o){return v(o,'"__proto__"')||v(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function gy(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function hM(e){return`[${e.join(", ")}]`}function Ii(e,o){return`((${e.join(", ")}) => ${o})`}function br(e,o){return`${e}(${o.join(", ")})`}function rd(e,o){return`new ${e}(${o.join(", ")})`}function Et(e,o){return`${e}${oM(o)?`.${o}`:`[${Te(o)}]`}`}function Te(e){if(!ra(e))throw Error("Unsupported Constant");return ht(e)?JSON.stringify(e):`${e}`}function gM(e,o,a){return`(${e} ? ${o} : ${a})`}function om(e){return`{ ${e.join("; ")}; }`}function Qs(e,o){return`const ${e} = ${o}`}function yy(e,o){return`if(${e}) { ${o} }`}function sm(e){return`return ${e}`}function Nn(e){return v(e.length,0)?"true":e.reduce((o,a)=>$n(o,a))}function nd(e){return v(e.length,0)?"false":e.reduce((o,a)=>Er(o,a))}function yM(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function xM(e){return e instanceof Boolean}function IM(e){return e instanceof Number}function EM(e){return e instanceof String}function xy(e){return globalThis.ArrayBuffer.isView(e)}function Iy(e){return e instanceof globalThis.RegExp}function bM(e){return e instanceof globalThis.Date}function SM(e){return e instanceof globalThis.Set}function wM(e){return e instanceof globalThis.Map}var RM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function rs(){return RM}function Ei(e){return rs().immutableTypes?Object.freeze(e):e}function gn(e,o){return ks.assign+=1,Ei({...e,...o})}function kM(e){return e}function AM(e){return me(e,"~kind")||me(e,"~unsafe")}function PM(e){let o={};for(let a of xe(e)){if($u(a))continue;let u=Object.getOwnPropertyDescriptor(e,a);if(u.value=ia(u.value),v(u.enumerable,!0))o[a]=u.value;else Object.defineProperty(o,a,u)}return o}function $M(e){let o={};for(let a of xe(e)){if($u(a))continue;o[a]=ia(e[a])}for(let a of uy(e))o[a]=ia(e[a]);return o}function CM(e){return oy(e)?kM(e):AM(e)?PM(e):$M(e)}function vM(e){return e.map((o)=>ia(o))}function MM(e){return e.slice()}function OM(e){return new RegExp(e.source,e.flags)}function _M(e){return new Map(ia([...e.entries()]))}function LM(e){return new Set(ia([...e.values()]))}function ia(e){return xy(e)?MM(e):Iy(e)?OM(e):wM(e)?_M(e):SM(e)?LM(e):$e(e)?vM(e):mt(e)?CM(e):e}function _a(e){return ks.clone+=1,ia(e)}function NM(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 Ey(e,o){return{...e,...o}}function _t(e,o,a={}){ks.create+=1;let u=Ey(o,a),p=rs().enumerableKind?Ey(u,e):NM(u,e);return Ei(p)}function as(e,o){ks.discard+=1;let a={};for(let u of xe(e)){if(o.includes(u))continue;let p=Object.getOwnPropertyDescriptor(e,u);p.value=_a(p.value),Object.defineProperty(a,u,p)}return Ei(a)}function Tt(e,o,a){ks.update+=1;let u=rs(),p=_a(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 Ei(p)}function Se(e,o){return mt(e)&&me(e,"~kind")&&v(e["~kind"],o)}function Lr(e){return mt(e)}function we(e,o,a){return _t({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:a},{})}function bi(e){return Se(e,"Deferred")}function qM(e){return Tt(e,{"~readonly":!0},{})}function Mu(e,o){return Tt(qM(e),{},o)}function by(e,o,a,u){let p=pe(e,o,a);return Mu(p,u)}function DM(e){return Tt(e,{"~optional":!0},{})}function Ou(e,o){return Tt(DM(e),{},o)}function Sy(e,o,a,u){let p=pe(e,o,a);return Ou(p,u)}function W(e,o){return _t({"~kind":"Array"},{type:"array",items:e},o)}function kt(e){return Se(e,"Array")}function La(e){return as(e,["~kind","type","items"])}function Ms(e,o,a={}){return _t({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},a)}function Jr(e){return Se(e,"Constructor")}function wy(e){return as(e,["~kind","type","parameters","instanceType"])}function Os(e,o,a={}){return _t({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},a)}function Qr(e){return Se(e,"Function")}function Ty(e){return as(e,["~kind","type","parameters","returnType"])}function rn(e,o){return _t({["~kind"]:"Ref"},{$ref:e},o)}function Yt(e){return Se(e,"Ref")}function Si(e,o){return _t({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Na(e){return Se(e,"Generic")}function qa(e){return _t({["~kind"]:"Any"},{},e)}function Nr(e){return Se(e,"Any")}var Ry="(?!)";function sr(e){return _t({"~kind":"Never"},{not:{}},e)}function wo(e){return Se(e,"Never")}function Ls(e,o={}){return we("AddOptional",[e],o)}function aa(e,o={}){return Ou(e,o)}function n(e){return aa(e)}function nn(e){return Lr(e)&&me(e,"~optional")}function ky(e){return xe(e).filter((o)=>!nn(e[o]))}function im(e){return xe(e)}function am(e){return Zl(e)}function l(e,o={}){let a=ky(e),u=a.length>0?{required:a}:{};return _t({"~kind":"Object"},{type:"object",...u,properties:e},o)}function Qe(e){return Se(e,"Object")}function Ay(e){return as(e,["~kind","type","properties","required"])}function Q(e){return _t({["~kind"]:"Unknown"},{},e)}function Xr(e){return Se(e,"Unknown")}function Ns(e,o,a){let u=xe(e).reduce((p,f)=>({...p,[f]:Tt(e[f],{},{$id:f})}),{});return _t({["~kind"]:"Cyclic"},{$defs:u,$ref:o},a)}function cr(e){return Se(e,"Cyclic")}function xr(e){return Tt(e,{["~unsafe"]:null},{})}function um(e){return Yo(e)&&me(e,"~unsafe")&&Po(e["~unsafe"])}function Cn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function _u(...e){let[o,a]=Cn(e,{2:(u,p)=>[u,p,p],1:(u)=>[u,Q(),Q()]});return _t({["~kind"]:"Infer"},{type:"infer",name:o,extends:a},{})}function Yr(e){return Se(e,"Infer")}function ua(e,o,a,u={}){return _t({"~kind":"Dependent"},{if:e,then:o,else:a},u)}function Br(e){return Se(e,"Dependent")}function Py(e){return as(e,["~kind","if","then","else"])}function $y(e){return Yo(e)}function Cy(e){return xe(e).filter((a)=>isNaN(a)).reduce((a,u)=>[...a,e[u]],[])}function vy(e){return ht(e)||Ft(e)}function My(e,o){let a=$y(e)?Cy(e):e;return _t({"~kind":"Enum"},{enum:a},o)}function Zr(e){return Se(e,"Enum")}function qn(e,o={}){return _t({"~kind":"Intersect"},{allOf:e},o)}function We(e){return Se(e,"Intersect")}function Oy(e){return as(e,["~kind","allOf"])}var od=void 0;function FM(){try{return Ly("null")(),!0}catch{return!1}}function _y(){if(rr(od))od=FM();return od&&rs().useAcceleration}function Ly(...e){return new globalThis.Function(...e)}function Gr(){throw Error("Unreachable")}function jM(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 UM(e){return typeof e==="number"}var Hn;(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"})(Hn||(Hn={}));var Da=BigInt("14695981039346656037"),[BM,GM]=[BigInt("1099511628211"),BigInt("18446744073709551616")],KM=Array.from({length:256}).map((e,o)=>BigInt(o)),Fy=new Float64Array(1),jy=new DataView(Fy.buffer),Uy=new Uint8Array(Fy.buffer);function Rn(e){Da=Da^KM[e],Da=Da*BM%GM}function HM(e){Rn(Hn.Array);for(let o of e)wi(o)}function WM(e){Rn(Hn.BigInt),jy.setBigInt64(0,e);for(let o of Uy)Rn(o)}function qy(e){Rn(Hn.Boolean),Rn(e?1:0)}function zM(e){Rn(Hn.Constructor),wi(e.toString())}function VM(e){Rn(Hn.Date),wi(e.getTime())}function JM(e){Rn(Hn.Function),wi(e.toString())}function QM(e){Rn(Hn.Null)}function Dy(e){Rn(Hn.Number),jy.setFloat64(0,e,!0);for(let o of Uy)Rn(o)}function XM(e){Rn(Hn.Object);for(let o of jM(e).sort())wi(o),wi(e[o])}function YM(e){Rn(Hn.RegExp),sd(e.toString())}var ZM=new TextEncoder;function sd(e){Rn(Hn.String);for(let o of ZM.encode(e))Rn(o)}function eO(e){Rn(Hn.Symbol),wi(e.toString())}function tO(e){Rn(Hn.TypeArray);let o=new Uint8Array(e.buffer);for(let a=0;a<o.length;a++)Rn(o[a])}function rO(e){return Rn(Hn.Undefined)}function wi(e){return xy(e)?tO(e):bM(e)?VM(e):Iy(e)?YM(e):xM(e)?qy(e.valueOf()):EM(e)?sd(e.valueOf()):IM(e)?Dy(e.valueOf()):UM(e)?Dy(e):$e(e)?HM(e):sn(e)?qy(e):Ur(e)?WM(e):Jl(e)?zM(e):Po(e)?QM(e):mt(e)?XM(e):ht(e)?sd(e):Ql(e)?eO(e):rr(e)?rO(e):Ps(e)?JM(e):Gr()}function By(e){return Da=BigInt("14695981039346656037"),wi(e),Da}function id(e){return By(e).toString(16).padStart(16,"0")}function Gy(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 nO=Gy;function Ky(){return nO}class cm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,a=Wn(o)?(f)=>this.decode(o["~codec"].decode(f)):this.decode,u=Wn(o)?(f)=>o["~codec"].encode(e(f)):e,p={decode:a,encode:u};return Tt(this.type,{"~codec":p},{})}}class mm{constructor(e){this.type=e}Decode(e){return new cm(this.type,e)}}function pm(e){return new mm(e)}function Wy(e,o){return pm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function zy(e,o){return pm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Wn(e){return Lr(e)&&me(e,"~codec")&&mt(e["~codec"])&&me(e["~codec"],"encode")&&me(e["~codec"],"decode")}function Vy(e){return Fa(e)}function ma(e){return Lr(e)&&me(e,"~immutable")}function qs(e,o={}){return we("AddReadonly",[e],o)}function pa(e,o={}){return Mu(e,o)}function Jy(e){return pa(e)}function la(e){return Lr(e)&&me(e,"~readonly")}function sO(e,o){let a=lm(e)?[...e["~refine"],o]:[o];return Tt(e,{"~refine":a},{})}function Qy(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[p,f,()=>"Refine Error"]});return sO(o,{check:a,error:u})}function iO(e){return Yo(e)&&me(e,"check")&&me(e,"error")&&Ps(e.check)&&Ps(e.error)}function lm(e){return Lr(e)&&me(e,"~refine")&&$e(e["~refine"])&&tn(e["~refine"],0,(o)=>iO(o))}var Xy="-?(?:0|[1-9][0-9]*)n";function Lu(e){return _t({"~kind":"BigInt"},{type:"bigint"},e)}function To(e){return Se(e,"BigInt")}function D(e){return _t({"~kind":"Boolean"},{type:"boolean"},e)}function zn(e){return Se(e,"Boolean")}function Nu(e){return _t({"~kind":"Identifier"},{name:e})}function Yy(e){return Se(e,"Identifier")}var dm="-?(?:0|[1-9][0-9]*)";function x(e){return _t({"~kind":"Integer"},{type:"integer"},e)}function yn(e){return Se(e,"Integer")}class Zy extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function aO(e){return Ur(e)?"bigint":sn(e)?"boolean":Ft(e)?"number":ht(e)?"string":(()=>{throw new Zy(e)})()}function i(e,o){return _t({"~kind":"Literal"},{type:aO(e),const:e},o)}function fm(e){return Ur(e)||sn(e)||Ft(e)||ht(e)}function ex(e){return gt(e)&&Ur(e.const)}function tx(e){return gt(e)&&sn(e.const)}function hm(e){return gt(e)&&Ft(e.const)}function gm(e){return gt(e)&&ht(e.const)}function gt(e){return Se(e,"Literal")}function Dn(e){return _t({"~kind":"Null"},{type:"null"},e)}function Ds(e){return Se(e,"Null")}var ym="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function re(e){return _t({"~kind":"Number"},{type:"number"},e)}function Cr(e){return Se(e,"Number")}function ja(e){return _t({"~kind":"Symbol"},{type:"symbol"},e)}function Fs(e){return Se(e,"Symbol")}function da(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[p,f,f],1:(p)=>[p,Q(),Q()]});return _t({"~kind":"Parameter"},{name:o,extends:a,equals:u},{})}function rx(e){return Se(e,"Parameter")}var xm=".*";function s(e){return _t({"~kind":"String"},{type:"string"},e)}function en(e){return Se(e,"String")}function y(e,o={}){return _t({"~kind":"Union"},{anyOf:e},o)}function ye(e){return Se(e,"Union")}function nx(e){return as(e,["~kind","anyOf"])}function qu(e){let o=ox(e);return v(o.length,2)?o[0]:[]}function uO(e){return!0}function sx(e){return yt(e,(o,a)=>cO(o)?sx(a):!1,()=>!0)}function ix(e){return v(e.length,0)?!1:sx(e)}function cO(e){return ye(e)?ix(e.anyOf):gt(e)?uO(e.const):!1}function Im(e){return ix(e)}function Em(e){return _t({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function ax(e,o,a=[]){return yt(e,(u,p)=>ax(p,o,[...a,`${u}${o}`]),()=>a)}function mO(e,o){return v(e.length,0)?[`${o}`]:ax(e,o)}function ux(e,o,a=[]){return yt(o,(u,p)=>ux(e,p,[...a,...cx(e,u)]),()=>a)}function cx(e,o){return ye(o)?ux(e,o.anyOf):gt(o)?mO(e,o.const):Gr()}function mx(e,o){return yt(o,(a,u)=>mx(cx(e,a),u),()=>e)}function pO(e){return e.map((o)=>i(o))}function lO(e){let o=mx([],e),a=pO(o);return y(a)}function dO(e){return v(e.length,0)?Gr():v(e.length,1)&>(e[0])?e[0]:lO(e)}function ad(e){let o=qu(e);return v(o.length,0)?s():Im(o)?dO(o):Em(e)}function Du(e){let o=ad(e);return lr(o)?s():o}function xo(e,o){let u={[e]:o};return _t({["~kind"]:"Record"},{type:"object",patternProperties:u})}function px(e){return xo(ps,e)}function lx(e){return l({true:e,false:e})}function Kr(e,o={}){let[a,u,p]=[e,e.length,!1];return _t({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:a,minItems:u},o)}function dt(e){return Se(e,"Tuple")}function dx(e){return as(e,["~kind","type","items","minItems","additionalItems"])}function fO(e){return as(e,["~readonly"])}function ud(e,o){return Tt(fO(e),{},o)}function fx(e,o,a,u){let p=pe(e,o,a);return ud(p,u)}function hx(e,o={}){return we("RemoveReadonly",[e],o)}function gx(e,o={}){return ud(e,o)}function hO(e){return as(e,["~optional"])}function cd(e,o){return Tt(hO(e),{},o)}function yx(e,o,a,u){let p=pe(e,o,a);return cd(p,u)}function xx(e,o={}){return we("RemoveOptional",[e],o)}function bm(e,o={}){return cd(e,o)}function md(e){return e.reduceRight((a,u,p)=>({[p]:u,...a}),{})}function Ix(e){let o=md(e.items);return l(o)}function pd(e){return Qe(e)||dt(e)}function gO(e,o){return la(e)?la(o)?!0:!1:!1}function yO(e,o){return nn(e)?nn(o)?!0:!1:!1}function xO(e,o){let a=gO(e,o),u=yO(e,o),p=Mr([e,o]),f=gx(bm(p));return a&&u?pa(aa(f)):a&&!u?pa(f):!a&&u?aa(f):f}function IO(e,o,a){return a in e?a in o?xO(e[a],o[a]):e[a]:(a in o)?o[a]:sr()}function EO(e,o){return[...new Set([...xe(e),...xe(o)])].reduce((p,f)=>({...p,[f]:IO(e,o,f)}),{})}function Ex(e){return Qe(e)?e.properties:dt(e)?md(e.items):{}}function bx(e,o){let a=Ex(e),u=Ex(o),p=EO(a,u);return l(p)}function bO(e,o){let a=Ua(e,o);return v(a,ju)?e:v(a,Uu)?o:v(a,Fu)?o:sr()}function SO(e,o){let a=pd(e),u=pd(o);return a&&u?bx(e,o):a&&!u?e:!a&&u?o:bO(e,o)}function Sx(e,o){return wo(e)?e:Nr(e)?e:Xr(e)?o:wo(o)?o:Nr(o)?o:Xr(o)?e:SO(e,o)}function wO(e,o){return ye(e)||ye(o)}function TO(e,o){let a=Do(e),u=Do(o);return wO(a,u)?Mr([a,u]):Sx(a,u)}function wx(e,o,a=[]){return yt(o,(u,p)=>wx(e,p,[...a,TO(u,e)]),()=>v(a.length,0)?[e]:a)}function Tx(e,o,a=[]){return yt(e,(u,p)=>Tx(p,o,[...a,...Bu([u],o)]),()=>a)}function Bu(e,o=[]){return yt(e,(a,u)=>ye(a)?Bu(u,Tx(a.anyOf,o)):Bu(u,wx(a,o)),()=>o)}function RO(e,o){let a=Mn({},e,o);return Eo(a)?[]:[e]}function Rx(e,o,a=[]){return yt(e,(u,p)=>Rx(p,o,[...a,...RO(u,o)]),()=>a)}function Sm(e,o){let a=Do(e),u=ye(a)?a.anyOf:[a],p=Rx(u,o);return Io(p)}function ds(e,o,a){let u=Mr([e,o]),p=Sm(a,e);return Io([u,p])}function Vn(e,o=[]){return yt(e,(a,u)=>Vn(u,[...o,i(a)]),()=>Io(o))}function Mr(e){let o=Bu(e),a=ld(o);return Io(a)}function Fn(e){let o=Du(e);return Do(o)}function Io(e){let o=ld(e);return Ti(o)}function Do(e){return Br(e)?ds(e.if,e.then,e.else):Zr(e)?Vn(e.enum):We(e)?Mr(e.allOf):lr(e)?Fn(e.pattern):ye(e)?Io(e.anyOf):e}function Ti(e){return v(e.length,1)?e[0]:v(e.length,0)?sr():y(e)}function kx(e,o){let a=Vn(e);return Ri(a,o)}function Ax(e,o){return xo(ki,o)}function Px(e,o){let a=Mr(e);return Ri(a,o)}function $x(e,o){return ht(e)||Ft(e)?l({[e]:o}):v(e,!1)?l({false:o}):v(e,!0)?l({true:o}):l({})}function Cx(e,o){return xo(Ba,o)}function vx(e,o){return me(e,"pattern")&&(ht(e.pattern)||e.pattern instanceof RegExp)?xo(e.pattern.toString(),o):xo(ps,o)}function Mx(e,o){let a=qu(e);return Im(a)?Ri(Fn(e),o):xo(e,o)}function kO(e){return ye(e)?fa(e.anyOf):[e]}function fa(e,o=[]){return yt(e,(a,u)=>fa(u,[...o,...kO(a)]),()=>o)}function AO(e){return e.some((o)=>en(o)||Cr(o)||yn(o))}function PO(e,o){return v(AO(e),!0)?xo(ps,o):void 0}function $O(e,o){return e.reduce((a,u)=>gt(u)&&(ht(u.const)||Ft(u.const))?{...a,[u.const]:o}:a,{})}function CO(e,o){let a=$O(e,o);return l(a)}function Ox(e,o){let a=fa(e),u=PO(a,o);return Lr(u)?u:CO(a,o)}function Ri(e,o){return Nr(e)?px(o):zn(e)?lx(o):Zr(e)?kx(e.enum,o):yn(e)?Ax(e,o):We(e)?Px(e.allOf,o):gt(e)?$x(e.const,o):Cr(e)?Cx(e,o):ye(e)?Ox(e.anyOf,o):en(e)?vx(e,o):lr(e)?Mx(e.pattern,o):l({})}function dd(e,o,a){return pt([e])?Tt(Ri(e,o),{},a):wm(e,o,a)}function _x(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return dd(f,h,p)}var ki=`^${dm}$`,Ba=`^${ym}$`,ps=`^${xm}$`;function wm(e,o,a={}){return we("Record",[e,o],a)}function Ke(e,o,a={}){return dd(e,o,a)}function Lx(e,o){return xo(e,o)}function Tm(e){return v(e,ps)?s():v(e,ki)?x():v(e,Ba)?re():ad(e)}function In(e){return xe(e.patternProperties)[0]}function Ai(e){let o=In(e);return Tm(o)}function hr(e){return e.patternProperties[In(e)]}function nr(e){return Se(e,"Record")}function ha(e){return _t({"~kind":"Rest"},{type:"rest",items:e},{})}function Pi(e){return Se(e,"Rest")}function Rm(e){return _t({["~kind"]:"This"},{$ref:"#"},e)}function km(e){return Se(e,"This")}function Ga(e){return _t({"~kind":"Undefined"},{type:"undefined"},e)}function fs(e){return Se(e,"Undefined")}function Am(e){return _t({"~kind":"Void"},{type:"void"},e)}function Ro(e){return Se(e,"Void")}function MO(e,o){return v(e,"Array")?W(o[0]):v(e,"Capitalize")?$m(o[0]):v(e,"ConstructorParameters")?_m(o[0]):v(e,"Evaluate")?YE(o[0]):v(e,"Exclude")?Lm(o[0],o[1]):v(e,"Extract")?Nm(o[0],o[1]):v(e,"Index")?Wu(o[0],o[1]):v(e,"InstanceType")?qm(o[0]):v(e,"Lowercase")?Cm(o[0]):v(e,"NonNullable")?Dm(o[0]):v(e,"Omit")?Fm(o[0],o[1]):v(e,"Parameters")?jm(o[0]):v(e,"Partial")?Um(o[0]):v(e,"Pick")?Bm(o[0],o[1]):v(e,"Readonly")?Gm(o[0]):v(e,"KeyOf")?zu(o[0]):v(e,"Record")?wm(o[0],o[1]):v(e,"Required")?Km(o[0]):v(e,"ReturnType")?Hm(o[0]):v(e,"Uncapitalize")?vm(o[0]):v(e,"Uppercase")?Mm(o[0]):Hu(rn(e),o)}function ga(){throw Error("Unreachable")}function jx(e,o=[]){return yt(e,(a,u)=>jx(u,[...o,a[1]]),()=>o)}function Xs(e){return v(e.length,3)?[e[0],...jx(e[1])]:[]}function Ux(e){return da(e[0],e[2],e[4])}function Bx(e){return da(e[0],e[2],e[2])}function Gx(e){return da(e[0],Q(),e[2])}function Kx(e){return da(e,Q(),Q())}function Hx(e){return e}function Wx(e){return Xs(e)}function zx(e){return e[1]}function Vx(e){return Xs(e)}function Jx(e){return e[1]}function Qx(e){return MO(e[0],e[1])}function Xx(e){return null}function Yx(e){return s()}function Zx(e){return re()}function eI(e){return D()}function tI(e){return Ga()}function rI(e){return Dn()}function nI(e){return x()}function oI(e){return Lu()}function sI(e){return Q()}function iI(e){return qa()}function aI(e){return l({})}function uI(e){return sr()}function cI(e){return ja()}function mI(e){return Am()}function pI(e){return Rm()}function lI(e){return i(BigInt(e))}function dI(e){return i(v(e,"true"))}function fI(e){return i(parseFloat(e))}function hI(e){return i(e)}function gI(e){return e[1]}function yI(e){return i(e)}function xI(e){return v(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function II(e){return e[1]}function EI(e){return Pm(e)}function bI(e){return v(e.length,6)?ua(e[1],e[3],e[5]):ua(e[1],e[3],Q())}function SI(e){return e.length>0}function wI(e){return e.reduce((o,a)=>v(a.length,3)?[...o,[a[1]]]:[...o,[]],[])}function TI(e){return v(e.length,6)?[e[1],e[3],e[5]]:[]}function RI(e){return $e(e)&&v(e.length,3)?e[1]:e}function kI(e){return v(e.length,2)?e[1]:[]}function Nx(e,o){return o.reduce((a,u)=>{let p=u;return v(p.length,1)?Wu(a,p[0]):v(p.length,0)?W(a):ga()},e)}function qx(e,o){return v(o.length,3)?Om(e,o[0],o[1],o[2]):e}function OO(e,o){return $e(o)&&v(o.length,0)?e:Wm(e,o)}function AI(e){let[o,a,u,p,f]=e;return OO(o?qx(zu(Nx(a,u)),p):qx(Nx(a,u),p),f)}function fd(e,o){return v(o.length,3)?(()=>{let[a,u,p]=o,f=fd(u,p);if(v(a,"&"))return We(f)?qn([e,...f.allOf]):qn([e,f]);if(v(a,"|"))return ye(f)?y([e,...f.anyOf]):y([e,f]);ga()})():e}function PI(e){return e}function $I(e){let[o,a]=e;return fd(o,a)}function CI(e){return e}function vI(e){let[o,a]=e;return fd(o,a)}function MI(e){return XE(e[1])}function OI(e){return e[1]}function _I(e){return Si(e[0],e[2])}function LI(e){return v(e.length,4)?_u(e[1],e[3]):v(e.length,2)?_u(e[1],Q()):ga()}function NI(e){return e}function qI(e){return`${e}`}function DI(e){return e}function FI(e){return e}function jI(e){return yn(e[3])?ki:Cr(e[3])?Ba:Fs(e[3])?ps:en(e[3])?ps:ga()}function UI(e){return e}function BI(e){return e.length>0}function GI(e){return e.length>0}function KI(e){let[o,a,u,p,f]=e;return{[a]:o&&u?qs(Ls(f)):o&&!u?qs(f):!o&&u?Ls(f):f}}function HI(e){return e}function WI(e){return Xs(e)}function zI(e){return e.reduce((o,a)=>me(a,ki)||me(a,Ba)||me(a,ps)?[o[0],gn(o[1],a)]:[gn(o[0],a),o[1]],[{},{}])}function VI(e){return zI(e[1])}function JI(e){let[o,a]=e,u=v(xe(a).length,0)?{}:{patternProperties:a};return l(o,u)}function QI(e){return v(e.length,5)?qs(Ls(e[4])):v(e.length,3)?e[2]:v(e.length,4)?v(e[2],"readonly")?qs(e[3]):Ls(e[3]):ga()}function XI(e){if(!$e(e)||!v(e.length,3))return e;let[o,a,u]=e;return o&&u?qs(Ls(a)):o&&!u?qs(a):!o&&u?Ls(a):a}function YI(e){return v(e.length,2)?ha(e[1]):v(e.length,1)?e[0]:ga()}function ZI(e){return Xs(e)}function eE(e){return Kr(e[1])}function tE(e){return qs(Ls(e[4]))}function rE(e){return qs(e[3])}function nE(e){return Ls(e[3])}function oE(e){return e[2]}function sE(e){return e}function iE(e){return v(e.length,2)?ha(e[1]):v(e.length,1)?e[0]:ga()}function aE(e){return Xs(e)}function uE(e){return Os(e[1],e[4])}function cE(e){return Ms(e[2],e[5])}function Dx(e,o){return v(e,"remove")?hx(o):v(e,"add")?qs(o):o}function mE(e){return v(e.length,2)&&v(e[0],"-")?"remove":v(e.length,2)&&v(e[0],"+")?"add":v(e.length,1)?"add":"none"}function Fx(e,o){return v(e,"remove")?xx(o):v(e,"add")?Ls(o):o}function pE(e){return v(e.length,2)&&v(e[0],"-")?"remove":v(e.length,2)&&v(e[0],"+")?"add":v(e.length,1)?"add":"none"}function lE(e){return v(e.length,2)?[e[1]]:[]}function dE(e){return $e(e[6])&&v(e[6].length,1)?Gu(Nu(e[3]),e[5],e[6][0],Dx(e[1],Fx(e[8],e[10]))):Gu(Nu(e[3]),e[5],rn(e[3]),Dx(e[1],Fx(e[8],e[10])))}function fE(e){return rn(e)}function hE(e){return BigInt(e)}function gE(e){return parseFloat(e)}function yE(e){return v(e,"true")}function xE(e){return e}function IE(e){return null}function EE(e){return}function bE(e){return{[e[0]]:e[2]}}function SE(e){return Xs(e)}function _O(e){return e.reduce((o,a)=>gn(o,a),{})}function wE(e){return _O(e[1])}function TE(e){return Xs(e)}function RE(e){return e[1]}function kE(e){return e}function AE(e){return Lu()}function PE(e){return s()}function $E(e){return re()}function CE(e){return x()}function vE(e){return sr()}function ME(e){return i(e)}function OE(e){return e}function _E(e){return y(e[1])}function LE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function NE(e){return[e[0],...e[1]]}function qE(e){return e}function DE(e){return e[1]}function FE(e){return Xs(e)}function jE(e){return v(e.length,2)?e[1]:[]}function UE(e){let o=e[2],a=e[3],[u,p]=e[4],f=v(xe(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Si(o,Ku(a,u,f))}}function BE(e){let o=e[2],[a,u]=e[3],p=v(xe(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Ku(o,a,p)}}function GE(e){return{[e[1]]:Si(e[2],e[4])}}function KE(e){return{[e[1]]:e[3]}}function HE(e){return null}function WE(e){return e}function zE(e){return Xs(e)}function VE(e){return e[1]}function JE(e){let[o,a]=[e[0],e[1]];return ZE(gn(o,zI(a)[0]))}function QE(e){return e}function Vu(e){return v(e.length,2)}function At(e,o,a){return Vu(e)?o(e[0],e[1]):a()}function qO(e,o){return v(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Dr(e,o){for(let a=0;a<e.length;a++){let u=qO(e[a],o);if(Vu(u))return u}return[]}function hd(e,o){return Array.from({length:o-e+1},(a,u)=>String.fromCharCode(e+u))}var eb=[...hd(97,122),...hd(65,90)],gd="0",yd=hd(49,57),Ka=[gd,...yd],tb=" ",Ha=`
|
|
15
|
-
`;var Ci="_",zm=".",rb="$",Vm="-";var nb="//",ob="/*",FO="*/";function sb(e){let o=e.indexOf(FO);return v(o,-1)?"":e.slice(o+2)}function ib(e){let o=e.indexOf(Ha);return v(o,-1)?"":e.slice(o)}function jO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Jm(e){let o=jO(e);return o.startsWith(ob)?Jm(sb(o.slice(2))):o.startsWith(nb)?Jm(ib(o.slice(2))):o}function kn(e){let o=e.trimStart();return o.startsWith(ob)?kn(sb(o.slice(2))):o.startsWith(nb)?kn(ib(o.slice(2))):o}function Qm(e,o){return At(Dr([e],o),(a,u)=>[a,u],()=>["",o])}function UO(e,o){return e.includes(o)}function Wa(e,o,a,u=""){return At(Dr(e,a),(p,f)=>UO(o,p)?Wa(e,o,f,u):Wa(e,o,f,`${u}${p}`),()=>[u,a])}function BO(e){return Dr(yd,e)}var GO=[...Ka,Ci];function KO(e){return Wa(GO,[Ci],e)}function HO(e){return At(Dr([gd],e),(o,a)=>[o,a],()=>At(BO(e),(o,a)=>At(KO(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[]))}function Xm(e){return HO(kn(e))}function WO(e){return Qm(Vm,e)}function zO(e){return At(WO(e),(o,a)=>At(Xm(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function ab(e){return zO(kn(e))}function VO(e){return At(ab(e),(o,a)=>At(Dr(["n"],a),(u,p)=>[`${o}`,p],()=>[]),()=>[])}function xd(e){return VO(e)}function Id(e,o){return Dr([e],o)}function B(e,o){return v(e,"")?["",o]:e.startsWith(Ha)?Id(e,Jm(o)):e.startsWith(tb)?Id(e,o):Id(e,kn(o))}var ub=[...eb,Ci,rb];function JO(e){return Dr(ub,e)}var QO=[...ub,...Ka];function cb(e,o=""){return At(Dr(QO,e),(a,u)=>cb(u,`${o}${a}`),()=>[o,e])}function XO(e){return At(JO(e),(o,a)=>At(cb(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Hr(e){return XO(kn(e))}var YO=[...Ka,Ci];function ZO(e){return Vu(Dr([zm],e))}function mb(e){return At(Wa(YO,[Ci],e),(o,a)=>v(o,"")?[]:[o,a],()=>[])}function e_(e){return At(Dr([zm],e),(o,a)=>At(mb(a),(u,p)=>[`0${o}${u}`,p],()=>[]),()=>[])}function t_(e){return At(Xm(e),(o,a)=>At(Dr([zm],a),(u,p)=>At(mb(p),(f,h)=>[`${o}${u}${f}`,h],()=>[`${o}`,p]),()=>[`${o}`,a]),()=>[])}function r_(e){return ZO(e)?e_(e):t_(e)}function pb(e){return r_(kn(e))}function n_(e){return Qm(Vm,e)}function o_(e){return At(n_(e),(o,a)=>At(pb(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Ym(e){return o_(kn(e))}function s_(e){return v(e,"")?[]:[e.slice(0,1),e.slice(1)]}function lb(e,o){return yt(e,(a,u)=>o.startsWith(a)?!0:lb(u,o),()=>!1)}function vi(e,o,a=""){return At(s_(o),(u,p)=>lb(e,o)?[a,o]:vi(e,p,`${a}${u}`),()=>[])}function i_(e,o,a){return At(Dr([e],a),(u,p)=>At(vi([o],p),(f,h)=>At(Dr([o],h),(g,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function a_(e,o,a){return At(Dr([e],a),(u,p)=>At(vi([Ha,o],p),(f,h)=>At(Dr([o],h),(g,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function db(e,o,a,u){return a?i_(e,o,kn(u)):a_(e,o,kn(u))}function u_(e,o){return Dr(e,o)}function c_(e,o){return db(e,e,!1,o)}function m_(e,o){return At(u_(e,o),(a,u)=>c_(a,`${a}${u}`),()=>[])}function Zm(e,o){return m_(e,kn(o))}function fb(e,o){return At(vi(e,o),(a,u)=>v(a,"")?[]:[a,u],()=>[])}var w=(e,o,a=()=>[])=>e.length===2?o(e):a(),l_=(e)=>w(w(Hr(e),([o,a])=>w(B("extends",a),([u,p])=>w(Nt(p),([f,h])=>w(B("=",h),([g,I])=>w(Nt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[Ux(o),a]),d_=(e)=>w(w(Hr(e),([o,a])=>w(B("extends",a),([u,p])=>w(Nt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Bx(o),a]),f_=(e)=>w(w(Hr(e),([o,a])=>w(B("=",a),([u,p])=>w(Nt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Gx(o),a]),h_=(e)=>w(Hr(e),([o,a])=>[Kx(o),a]),yb=(e)=>w(w(l_(e),([o,a])=>[o,a],()=>w(d_(e),([o,a])=>[o,a],()=>w(f_(e),([o,a])=>[o,a],()=>w(h_(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Hx(o),a]),xb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(yb(u),([p,f])=>[[a,p],f])),([a,u])=>xb(u,[...o,a]),()=>[o,e]),g_=(e)=>w(w(w(yb(e),([o,a])=>w(xb(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])=>[Wx(o),a]),Sd=(e)=>w(w(B("<",e),([o,a])=>w(g_(a),([u,p])=>w(B(">",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[zx(o),a]),Ib=(e,o=[])=>w(w(B(",",e),([a,u])=>w(Nt(u),([p,f])=>[[a,p],f])),([a,u])=>Ib(u,[...o,a]),()=>[o,e]),y_=(e)=>w(w(w(Nt(e),([o,a])=>w(Ib(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])=>[Vx(o),a]),x_=(e)=>w(w(B("<",e),([o,a])=>w(y_(a),([u,p])=>w(B(">",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Jx(o),a]),I_=(e)=>w(w(Hr(e),([o,a])=>w(x_(a),([u,p])=>[[o,u],p])),([o,a])=>[Qx(o),a]),Eb=(e)=>w(w(w(B(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Xx(o),a]),bb=(e)=>w(B("string",e),([o,a])=>[Yx(o),a]),Sb=(e)=>w(B("number",e),([o,a])=>[Zx(o),a]),E_=(e)=>w(B("boolean",e),([o,a])=>[eI(o),a]),b_=(e)=>w(B("undefined",e),([o,a])=>[tI(o),a]),S_=(e)=>w(B("null",e),([o,a])=>[rI(o),a]),wb=(e)=>w(B("integer",e),([o,a])=>[nI(o),a]),w_=(e)=>w(B("bigint",e),([o,a])=>[oI(o),a]),T_=(e)=>w(B("unknown",e),([o,a])=>[sI(o),a]),R_=(e)=>w(B("any",e),([o,a])=>[iI(o),a]),k_=(e)=>w(B("object",e),([o,a])=>[aI(o),a]),A_=(e)=>w(B("never",e),([o,a])=>[uI(o),a]),Tb=(e)=>w(B("symbol",e),([o,a])=>[cI(o),a]),P_=(e)=>w(B("void",e),([o,a])=>[mI(o),a]),$_=(e)=>w(B("this",e),([o,a])=>[pI(o),a]),C_=(e)=>w(w(B("${",e),([o,a])=>w(Nt(a),([u,p])=>w(B("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[gI(o),a]),Ed=(e)=>w(vi(["${","`"],e),([o,a])=>[yI(o),a]),Rb=(e)=>w(w(w(Ed(e),([o,a])=>w(C_(a),([u,p])=>w(Rb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(w(Ed(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(Ed(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[xI(o),a]),wd=(e)=>w(w(B("`",e),([o,a])=>w(Rb(a),([u,p])=>w(B("`",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[II(o),a]),v_=(e)=>w(wd(e),([o,a])=>[EI(o),a]),M_=(e)=>w(w(w(B("if",e),([o,a])=>w(Nt(a),([u,p])=>w(B("then",p),([f,h])=>w(Nt(h),([g,I])=>w(B("else",I),([E,S])=>w(Nt(S),([k,A])=>[[o,u,f,g,E,k],A])))))),([o,a])=>[o,a],()=>w(w(B("if",e),([o,a])=>w(Nt(a),([u,p])=>w(B("then",p),([f,h])=>w(Nt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>[])),([o,a])=>[bI(o),a]),O_=(e)=>w(xd(e),([o,a])=>[lI(o),a]),__=(e)=>w(w(B("true",e),([o,a])=>[o,a],()=>w(B("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[dI(o),a]),L_=(e)=>w(Ym(e),([o,a])=>[fI(o),a]),N_=(e)=>w(Zm(["'",'"'],e),([o,a])=>[hI(o),a]),q_=(e)=>w(w(w(B("keyof",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[SI(o),a]),kb=(e,o=[])=>w(w(w(B("[",e),([a,u])=>w(Nt(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])=>kb(u,[...o,a]),()=>[o,e]),D_=(e)=>w(kb(e),([o,a])=>[wI(o),a]),F_=(e)=>w(w(w(B("extends",e),([o,a])=>w(Nt(a),([u,p])=>w(B("?",p),([f,h])=>w(Nt(h),([g,I])=>w(B(":",I),([E,S])=>w(Nt(S),([k,A])=>[[o,u,f,g,E,k],A])))))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[TI(o),a]),j_=(e)=>w(w(w(B("(",e),([o,a])=>w(Nt(a),([u,p])=>w(B(")",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(bb(e),([o,a])=>[o,a],()=>w(Sb(e),([o,a])=>[o,a],()=>w(E_(e),([o,a])=>[o,a],()=>w(b_(e),([o,a])=>[o,a],()=>w(S_(e),([o,a])=>[o,a],()=>w(wb(e),([o,a])=>[o,a],()=>w(w_(e),([o,a])=>[o,a],()=>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],()=>w(Tb(e),([o,a])=>[o,a],()=>w(P_(e),([o,a])=>[o,a],()=>w($_(e),([o,a])=>[o,a],()=>w(O_(e),([o,a])=>[o,a],()=>w(__(e),([o,a])=>[o,a],()=>w(L_(e),([o,a])=>[o,a],()=>w(N_(e),([o,a])=>[o,a],()=>w(v_(e),([o,a])=>[o,a],()=>w(M_(e),([o,a])=>[o,a],()=>w(X_(e),([o,a])=>[o,a],()=>w(eL(e),([o,a])=>[o,a],()=>w(iL(e),([o,a])=>[o,a],()=>w(sL(e),([o,a])=>[o,a],()=>w(mL(e),([o,a])=>[o,a],()=>w(I_(e),([o,a])=>[o,a],()=>w(pL(e),([o,a])=>[o,a],()=>[])))))))))))))))))))))))))))),([o,a])=>[RI(o),a]),U_=(e)=>w(w(w(B("with",e),([o,a])=>w(Gb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kI(o),a]),Ab=(e)=>w(w(q_(e),([o,a])=>w(j_(a),([u,p])=>w(D_(p),([f,h])=>w(F_(h),([g,I])=>w(U_(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[AI(o),a]),Pb=(e)=>w(w(w(B("&",e),([o,a])=>w(Ab(a),([u,p])=>w(Pb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[PI(o),a]),$b=(e)=>w(w(Ab(e),([o,a])=>w(Pb(a),([u,p])=>[[o,u],p])),([o,a])=>[$I(o),a]),Cb=(e)=>w(w(w(B("|",e),([o,a])=>w($b(a),([u,p])=>w(Cb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[CI(o),a]),ep=(e)=>w(w($b(e),([o,a])=>w(Cb(a),([u,p])=>[[o,u],p])),([o,a])=>[vI(o),a]),B_=(e)=>w(w(B("readonly",e),([o,a])=>w(ep(a),([u,p])=>[[o,u],p])),([o,a])=>[MI(o),a]),G_=(e)=>w(w(B("|",e),([o,a])=>w(ep(a),([u,p])=>[[o,u],p])),([o,a])=>[OI(o),a]),K_=(e)=>w(w(Sd(e),([o,a])=>w(B("=",a),([u,p])=>w(Nt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[_I(o),a]),H_=(e)=>w(w(w(B("infer",e),([o,a])=>w(Hr(a),([u,p])=>w(B("extends",p),([f,h])=>w(ep(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>w(w(B("infer",e),([o,a])=>w(Hr(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>[])),([o,a])=>[LI(o),a]),Nt=(e)=>w(w(H_(e),([o,a])=>[o,a],()=>w(G_(e),([o,a])=>[o,a],()=>w(B_(e),([o,a])=>[o,a],()=>w(ep(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[NI(o),a]),W_=(e)=>w(Ym(e),([o,a])=>[qI(o),a]),z_=(e)=>w(Hr(e),([o,a])=>[DI(o),a]),V_=(e)=>w(Zm(["'",'"'],e),([o,a])=>[FI(o),a]),J_=(e)=>w(w(B("[",e),([o,a])=>w(Hr(a),([u,p])=>w(B(":",p),([f,h])=>w(w(wb(h),([g,I])=>[g,I],()=>w(Sb(h),([g,I])=>[g,I],()=>w(bb(h),([g,I])=>[g,I],()=>w(Tb(h),([g,I])=>[g,I],()=>[])))),([g,I])=>w(B("]",I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[jI(o),a]),vb=(e)=>w(w(W_(e),([o,a])=>[o,a],()=>w(z_(e),([o,a])=>[o,a],()=>w(V_(e),([o,a])=>[o,a],()=>w(J_(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[UI(o),a]),Mb=(e)=>w(w(w(B("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[BI(o),a]),Ob=(e)=>w(w(w(B("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[GI(o),a]),_b=(e)=>w(w(Mb(e),([o,a])=>w(vb(a),([u,p])=>w(Ob(p),([f,h])=>w(B(":",h),([g,I])=>w(Nt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[KI(o),a]),tp=(e)=>w(w(w(B(",",e),([o,a])=>w(B(`
|
|
16
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(B(";",e),([o,a])=>w(B(`
|
|
17
|
-
`,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(`
|
|
18
|
-
`,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))))),([o,a])=>[HI(o),a]),Lb=(e,o=[])=>w(w(tp(e),([a,u])=>w(_b(u),([p,f])=>[[a,p],f])),([a,u])=>Lb(u,[...o,a]),()=>[o,e]),Q_=(e)=>w(w(w(_b(e),([o,a])=>w(Lb(a),([u,p])=>w(w(tp(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[WI(o),a]),Td=(e)=>w(w(B("{",e),([o,a])=>w(Q_(a),([u,p])=>w(B("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[VI(o),a]),X_=(e)=>w(Td(e),([o,a])=>[JI(o),a]),Y_=(e)=>w(w(w(Hr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(B("readonly",h),([g,I])=>w(Nt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[o,a],()=>w(w(Hr(e),([o,a])=>w(B(":",a),([u,p])=>w(B("readonly",p),([f,h])=>w(Nt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>w(w(Hr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(Nt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[o,a],()=>w(w(Hr(e),([o,a])=>w(B(":",a),([u,p])=>w(Nt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>[])))),([o,a])=>[QI(o),a]),hb=(e)=>w(w(Y_(e),([o,a])=>[o,a],()=>w(w(Mb(e),([o,a])=>w(Nt(a),([u,p])=>w(Ob(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>[])),([o,a])=>[XI(o),a]),Nb=(e)=>w(w(w(B("...",e),([o,a])=>w(hb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(hb(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[YI(o),a]),qb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(Nb(u),([p,f])=>[[a,p],f])),([a,u])=>qb(u,[...o,a]),()=>[o,e]),Z_=(e)=>w(w(w(Nb(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])=>[ZI(o),a]),eL=(e)=>w(w(B("[",e),([o,a])=>w(Z_(a),([u,p])=>w(B("]",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[eE(o),a]),tL=(e)=>w(w(Hr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(B("readonly",h),([g,I])=>w(Nt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[tE(o),a]),rL=(e)=>w(w(Hr(e),([o,a])=>w(B(":",a),([u,p])=>w(B("readonly",p),([f,h])=>w(Nt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[rE(o),a]),nL=(e)=>w(w(Hr(e),([o,a])=>w(B("?",a),([u,p])=>w(B(":",p),([f,h])=>w(Nt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[nE(o),a]),oL=(e)=>w(w(Hr(e),([o,a])=>w(B(":",a),([u,p])=>w(Nt(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[oE(o),a]),gb=(e)=>w(w(tL(e),([o,a])=>[o,a],()=>w(rL(e),([o,a])=>[o,a],()=>w(nL(e),([o,a])=>[o,a],()=>w(oL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[sE(o),a]),Db=(e)=>w(w(w(B("...",e),([o,a])=>w(gb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(gb(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[iE(o),a]),Fb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(Db(u),([p,f])=>[[a,p],f])),([a,u])=>Fb(u,[...o,a]),()=>[o,e]),jb=(e)=>w(w(w(Db(e),([o,a])=>w(Fb(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])=>[aE(o),a]),sL=(e)=>w(w(B("(",e),([o,a])=>w(jb(a),([u,p])=>w(B(")",p),([f,h])=>w(B("=>",h),([g,I])=>w(Nt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[uE(o),a]),iL=(e)=>w(w(B("new",e),([o,a])=>w(B("(",a),([u,p])=>w(jb(p),([f,h])=>w(B(")",h),([g,I])=>w(B("=>",I),([E,S])=>w(Nt(S),([k,A])=>[[o,u,f,g,E,k],A])))))),([o,a])=>[cE(o),a]),aL=(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])=>[mE(o),a]),uL=(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])=>[pE(o),a]),cL=(e)=>w(w(w(B("as",e),([o,a])=>w(Nt(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[lE(o),a]),mL=(e)=>w(w(B("{",e),([o,a])=>w(aL(a),([u,p])=>w(B("[",p),([f,h])=>w(Hr(h),([g,I])=>w(B("in",I),([E,S])=>w(Nt(S),([k,A])=>w(cL(A),([P,C])=>w(B("]",C),([M,V])=>w(uL(V),([_,J])=>w(B(":",J),([j,Y])=>w(Nt(Y),([te,L])=>w(Eb(L),([se,he])=>w(B("}",he),([Me,ze])=>[[o,u,f,g,E,k,P,M,_,j,te,se,Me],ze]))))))))))))),([o,a])=>[dE(o),a]),pL=(e)=>w(Hr(e),([o,a])=>[fE(o),a]),lL=(e)=>w(xd(e),([o,a])=>[hE(o),a]),dL=(e)=>w(Ym(e),([o,a])=>[gE(o),a]),fL=(e)=>w(w(B("true",e),([o,a])=>[o,a],()=>w(B("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[yE(o),a]),hL=(e)=>w(Zm(['"',"'"],e),([o,a])=>[xE(o),a]),gL=(e)=>w(B("null",e),([o,a])=>[IE(o),a]),yL=(e)=>w(B("undefined",e),([o,a])=>[EE(o),a]),Ub=(e)=>w(w(vb(e),([o,a])=>w(B(":",a),([u,p])=>w(Rd(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[bE(o),a]),Bb=(e,o=[])=>w(w(tp(e),([a,u])=>w(Ub(u),([p,f])=>[[a,p],f])),([a,u])=>Bb(u,[...o,a]),()=>[o,e]),xL=(e)=>w(w(w(Ub(e),([o,a])=>w(Bb(a),([u,p])=>w(w(tp(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[SE(o),a]),Gb=(e)=>w(w(B("{",e),([o,a])=>w(xL(a),([u,p])=>w(B("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[wE(o),a]),Kb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(Rd(u),([p,f])=>[[a,p],f])),([a,u])=>Kb(u,[...o,a]),()=>[o,e]),IL=(e)=>w(w(w(Rd(e),([o,a])=>w(Kb(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])=>[TE(o),a]),EL=(e)=>w(w(B("[",e),([o,a])=>w(IL(a),([u,p])=>w(B("]",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[RE(o),a]),Rd=(e)=>w(w(lL(e),([o,a])=>[o,a],()=>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],()=>w(yL(e),([o,a])=>[o,a],()=>w(Gb(e),([o,a])=>[o,a],()=>w(EL(e),([o,a])=>[o,a],()=>[])))))))),([o,a])=>[kE(o),a]),bL=(e)=>w(B("-?(?:0|[1-9][0-9]*)n",e),([o,a])=>[AE(o),a]),SL=(e)=>w(B(".*",e),([o,a])=>[PE(o),a]),wL=(e)=>w(B("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,a])=>[$E(o),a]),TL=(e)=>w(B("-?(?:0|[1-9][0-9]*)",e),([o,a])=>[CE(o),a]),RL=(e)=>w(B("(?!)",e),([o,a])=>[vE(o),a]),kL=(e)=>w(fb(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,a])=>[ME(o),a]),AL=(e)=>w(w(bL(e),([o,a])=>[o,a],()=>w(SL(e),([o,a])=>[o,a],()=>w(wL(e),([o,a])=>[o,a],()=>w(TL(e),([o,a])=>[o,a],()=>w(RL(e),([o,a])=>[o,a],()=>w(PL(e),([o,a])=>[o,a],()=>w(kL(e),([o,a])=>[o,a],()=>[]))))))),([o,a])=>[OE(o),a]),PL=(e)=>w(w(B("(",e),([o,a])=>w(kd(a),([u,p])=>w(B(")",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[_E(o),a]),Hb=(e)=>w(w(w(bd(e),([o,a])=>w(B("|",a),([u,p])=>w(Hb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(w(bd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[]))),([o,a])=>[LE(o),a]),bd=(e)=>w(w(AL(e),([o,a])=>w(kd(a),([u,p])=>[[o,u],p])),([o,a])=>[NE(o),a]),kd=(e)=>w(w(Hb(e),([o,a])=>[o,a],()=>w(bd(e),([o,a])=>[o,a],()=>[])),([o,a])=>[qE(o),a]),ox=(e)=>w(w(B("^",e),([o,a])=>w(kd(a),([u,p])=>w(B("$",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[DE(o),a]),Wb=(e,o=[])=>w(w(B(",",e),([a,u])=>w(Nt(u),([p,f])=>[[a,p],f])),([a,u])=>Wb(u,[...o,a]),()=>[o,e]),$L=(e)=>w(w(w(Nt(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])=>[FE(o),a]),zb=(e)=>w(w(w(B("extends",e),([o,a])=>w($L(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[jE(o),a]),CL=(e)=>w(w(B("interface",e),([o,a])=>w(Hr(a),([u,p])=>w(Sd(p),([f,h])=>w(zb(h),([g,I])=>w(Td(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[UE(o),a]),vL=(e)=>w(w(B("interface",e),([o,a])=>w(Hr(a),([u,p])=>w(zb(p),([f,h])=>w(Td(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[BE(o),a]),ML=(e)=>w(w(B("type",e),([o,a])=>w(Hr(a),([u,p])=>w(Sd(p),([f,h])=>w(B("=",h),([g,I])=>w(Nt(I),([E,S])=>[[o,u,f,g,E],S]))))),([o,a])=>[GE(o),a]),OL=(e)=>w(w(B("type",e),([o,a])=>w(Hr(a),([u,p])=>w(B("=",p),([f,h])=>w(Nt(h),([g,I])=>[[o,u,f,g],I])))),([o,a])=>[KE(o),a]),_L=(e)=>w(w(w(B("export",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[HE(o),a]),Vb=(e)=>w(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(`
|
|
20
|
-
`,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[WE(o),a]),Jb=(e,o=[])=>w(w(Vb(e),([a,u])=>w(Ad(u),([p,f])=>[[a,p],f])),([a,u])=>Jb(u,[...o,a]),()=>[o,e]),LL=(e)=>w(w(w(Ad(e),([o,a])=>w(Jb(a),([u,p])=>w(w(Vb(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[zE(o),a]),Ad=(e)=>w(w(_L(e),([o,a])=>w(w(CL(a),([u,p])=>[u,p],()=>w(vL(a),([u,p])=>[u,p],()=>w(ML(a),([u,p])=>[u,p],()=>w(OL(a),([u,p])=>[u,p],()=>[])))),([u,p])=>w(Eb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[VE(o),a]),NL=(e)=>w(w(Ad(e),([o,a])=>w(LL(a),([u,p])=>[[o,u],p])),([o,a])=>[JE(o),a]),Qb=(e)=>w(w(NL(e),([o,a])=>[o,a],()=>w(K_(e),([o,a])=>[o,a],()=>w(Nt(e),([o,a])=>[o,a],()=>[]))),([o,a])=>[QE(o),a]);function Xb(e){let o=wd(`\`${e}\``);return v(o.length,2)?o[0]:Gr()}function DL(e){return e.join("|")}function FL(e){return e.slice(1,e.length-1)}function jL(e,o,a){return Mi(o,`${a}${e}`)}function UL(e,o){return Mi(e,`${o}${Xy}`)}function BL(e,o){return Mi(e,`${o}${dm}`)}function GL(e,o){return Mi(e,`${o}${ym}`)}function KL(e,o){return Ju(y([i("false"),i("true")]),e,o)}function HL(e,o){return Mi(e,`${o}${xm}`)}function WL(e,o,a){return Mi(o,`${a}${FL(e)}`)}function zL(e,o,a){let u=Qu(e,{});return Ju(u,o,a)}function VL(e,o,a){let u=Vn(e);return Ju(u,o,a)}function Yb(e,o,a,u=[]){return yt(e,(p,f)=>Yb(f,o,a,[...u,Ju(p,[],"")]),()=>Mi(o,`${a}(${DL(u)})`))}function Ju(e,o,a){return Zr(e)?VL(e.enum,o,a):yn(e)?BL(o,a):gt(e)?jL(e.const,o,a):To(e)?UL(o,a):zn(e)?KL(o,a):Cr(e)?GL(o,a):en(e)?HL(o,a):lr(e)?WL(e.pattern,o,a):eS(e)?zL(e.parameters[0],o,a):ye(e)?Yb(e.anyOf,o,a):Ry}function Mi(e,o){return yt(e,(a,u)=>Ju(a,u,o),()=>o)}function JL(e){return`^${Mi(e,"")}$`}function Zb(e){let o=JL(e);return Em(o)}function Qu(e,o){return pt(e)?Tt(Zb(e),{},o):Pm(e,o)}function tS(e,o,a,u){let p=Co(e,o,a);return Qu(p,u)}function Pm(e,o={}){return we("TemplateLiteral",[e],o)}function eS(e){return Lr(e)&&me(e,"action")&&v(e.action,"TemplateLiteral")}function rS(e){return Qu(e,{})}function QL(e){let o=Xb(e);return rS(o)}function nS(e,o={}){let a=ht(e)?QL(e):rS(e);return Tt(a,{},o)}function lr(e){return Se(e,"TemplateLiteral")}function Pd(e){return _t({["~kind"]:"ExtendsUnion"},{inferred:e})}function $d(e){return mt(e)&&me(e,"~kind")&&me(e,"inferred")&&v(e["~kind"],"ExtendsUnion")&&mt(e.inferred)}function Ee(e){return _t({["~kind"]:"ExtendsTrue"},{inferred:e})}function Cd(e){return mt(e)&&me(e,"~kind")&&me(e,"inferred")&&v(e["~kind"],"ExtendsTrue")&&mt(e.inferred)}function ot(){return _t({["~kind"]:"ExtendsFalse"},{})}function vd(e){return mt(e)&&me(e,"~kind")&&v(e["~kind"],"ExtendsFalse")}function Eo(e){return $d(e)||Cd(e)}function Sr(e,o,a){return Eo(e)?o(e.inferred):a()}function XL(e,o,a,u){return Sr(Pt(e,a,u),(p)=>Ee(gn(gn(e,p),{[o]:a})),()=>ot())}function YL(e,o){return Ee(e)}function ZL(e,o,a,u,p){return Sr(Pt(e,o,a),(f)=>Sr(Pt(f,o,u),(h)=>Ee(h),()=>ot()),()=>Sr(Pt(e,o,p),(f)=>Ee(f),()=>ot()))}function eN(e,o,a){let u=Vn(a);return Pt(e,o,u)}function oS(e,o,a){return yt(a,(u,p)=>Sr(Pt(e,o,u),(f)=>oS(f,o,p),()=>ot()),()=>Ee(e))}function tN(e,o,a){let u=Fn(a);return Pt(e,o,u)}function sS(e,o,a){return yt(a,(u,p)=>Sr(Pt(e,o,u),(f)=>Ee(f),()=>sS(e,o,p)),()=>ot())}function Ht(e,o,a){return Nr(a)?YL(e,o):Br(a)?ZL(e,o,a.if,a.then,a.else):Zr(a)?eN(e,o,a.enum):Yr(a)?XL(e,a.name,o,a.extends):We(a)?oS(e,o,a.allOf):lr(a)?tN(e,o,a.pattern):ye(a)?sS(e,o,a.anyOf):Xr(a)?Ee(e):ot()}function iS(e,o,a){return Yr(a)?Ht(e,o,a):Nr(a)?Ee(e):Xr(a)?Ee(e):Pd(e)}function rN(e,o){let a=ma(e),u=ma(o);return a&&u?!0:!a&&u?!0:a&&!u?!1:!0}function aS(e,o,a,u){return kt(u)?rN(o,u)?Pt(e,a,u.items):ot():Ht(e,o,u)}function uS(e,o,a){return To(a)?Ee(e):Ht(e,o,a)}function cS(e,o,a){return zn(a)?Ee(e):Ht(e,o,a)}function nN(e,o,a,u,p){let f=Yr(u)?o:u,h=Yr(u)?u:o,g=nn(o),I=nn(u);return!g&&I?ot():Sr(Pt(e,f,h),(E)=>Xu(E,a,p),()=>ot())}function oN(e,o,a,u){return yt(u,(p,f)=>nN(e,o,a,p,f),()=>nn(o)?Ee(e):ot())}function sN(e,o,a){return yt(o,(u,p)=>oN(e,u,p,a),()=>Ee(e))}function Xu(e,o,a){return sN(e,o,a)}function rp(e,o,a){return Ro(a)?Ee(e):Pt(e,o,a)}function mS(e,o,a,u){return Nr(u)?Ee(e):Xr(u)?Ee(e):Jr(u)?Sr(Xu(e,o,u.parameters),(p)=>rp(p,a,u.instanceType),()=>ot()):ot()}function pS(e,o,a,u,p){return Sr(Pt(e,o,p),()=>Pt(e,a,p),()=>Pt(e,u,p))}function lS(e,o,a){let u=Vn(o);return Pt(e,u,a)}function dS(e,o,a,u){return Nr(u)?Ee(e):Xr(u)?Ee(e):Qr(u)?Sr(Xu(e,o,u.parameters),(p)=>rp(p,a,u.returnType),()=>ot()):ot()}function fS(e,o,a){return yn(a)?Ee(e):Cr(a)?Ee(e):Ht(e,o,a)}function hS(e,o,a){let u=Mr(o);return Pt(e,u,a)}function np(e,o,a){return o===a?Ee(e):ot()}function iN(e,o,a){return gt(a)?np(e,o,a.const):To(a)?Ee(e):Ht(e,i(o),a)}function aN(e,o,a){return gt(a)?np(e,o,a.const):zn(a)?Ee(e):Ht(e,i(o),a)}function uN(e,o,a){return gt(a)?np(e,o,a.const):Cr(a)?Ee(e):Ht(e,i(o),a)}function cN(e,o,a){return gt(a)?np(e,o,a.const):en(a)?Ee(e):Ht(e,i(o),a)}function gS(e,o,a){return Ur(o.const)?iN(e,o.const,a):sn(o.const)?aN(e,o.const,a):Ft(o.const)?uN(e,o.const,a):ht(o.const)?cN(e,o.const,a):Gr()}function yS(e,o,a){return Yr(a)?Ht(e,o,a):Ee(e)}function xS(e,o,a){return Ds(a)?Ee(e):Ht(e,o,a)}function IS(e,o,a){return Cr(a)?Ee(e):Ht(e,o,a)}function mN(e,o,a){return nn(o)?nn(a)?Ee(e):ot():Ee(e)}function pN(e,o,a){return Yr(a)&&wo(a.extends)?ot():Sr(Pt(e,o,a),(u)=>mN(u,o,a),()=>ot())}function lN(e,o){return e.reduce((a,u)=>(u in o)?Eo(o[u])?{...a,...o[u].inferred}:Gr():Gr(),{})}function dN(e,o,a){let u={};for(let h of xe(a))u[h]=h in o?pN({},o[h],a[h]):nn(a[h])?Yr(a[h])?Ee(gn(e,{[a[h].name]:a[h].extends})):Ee(e):ot();let p=Zl(u).every((h)=>Eo(h)),f=p?lN(xe(u),u):{};return p?Ee(f):ot()}function fN(e,o,a){let u=dN(e,o,a);return Eo(u)?Ee(gn(e,u.inferred)):ot()}function hN(e,o,a){return fN(e,o,a)}function gN(e,o){return xe(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 ES(e,o,a,u){return yt(o,(p,f)=>Sr(Pt({},e[p],a),(h)=>ES(e,f,a,gN(u,h)),()=>ot()),()=>Ee(u))}function yN(e,o,a,u){let p=xe(o);return ES(o,p,u,e)}function bS(e,o,a){return nr(a)?yN(e,o,In(a),hr(a)):Qe(a)?hN(e,o,a.properties):Ht(e,l(o),a)}function xN(e,o){return v(xe(o).length,0)?Ee(e):ot()}function IN(e,o,a,u,p){return Pt(e,a,p)}function SS(e,o,a,u){return nr(u)?IN(e,Tm(o),a,Tm(In(u)),hr(u)):Qe(u)?xN(e,u.properties):Nr(u)?Ee(e):Xr(u)?Ee(e):ot()}function wS(e,o,a){return en(a)?Ee(e):Ht(e,o,a)}function TS(e,o,a){return Fs(a)?Ee(e):Ht(e,o,a)}function RS(e,o,a){let u=Fn(o);return Pt(e,u,a)}function Md(e,o){return _t({"~kind":"Inferrable"},{name:e,type:o},{})}function Yu(e){return mt(e)&&me(e,"~kind")&&me(e,"name")&&me(e,"type")&&v(e["~kind"],"Inferrable")&&ht(e.name)&&mt(e.type)}function Od(e){return Pi(e)?Yr(e.items)?kt(e.items.extends)?Md(e.items.name,e.items.extends.items):Xr(e.items.extends)?Md(e.items.name,e.items.extends):void 0:Gr():void 0}function op(e){return Yr(e)?Md(e.name,e.extends):void 0}function _d(e,o,a=[]){return yt(e,(u,p)=>Sr(Pt({},u,o),()=>_d(p,o,[...a,u]),()=>{return}),()=>a)}function kS(e,o,a,u){let p=_d(a,u);return $e(p)?Ee(gn(e,{[o]:Kr(p)})):ot()}function sp(e,o,a,u){let p=_d(a,u);return $e(p)?Ee(gn(e,{[o]:y(p)})):ot()}function EN(e){return[...e].reverse()}function Ld(e,o){return o?EN(e):e}function bN(e){let o=e.length>0?e[0]:void 0,a=Lr(o)?Od(o):void 0;return Lr(a)}function SN(e,o,a,u,p,f){return Sr(Pt(e,a,p),(h)=>AS(h,o,u,f),()=>ot())}function wN(e,o,a,u,p){let f=Od(u);return Yu(f)?kS(e,f.name,Ld(a,o),f.type):yt(a,(h,g)=>SN(e,o,h,g,u,p),()=>ot())}function TN(e,o,a,u){return yt(u,(p,f)=>wN(e,o,a,p,f),()=>v(a.length,0)?Ee(e):ot())}function AS(e,o,a,u){return TN(e,o,a,u)}function RN(e,o,a){let u=Oi(e,gr([],[]),a),p=bN(u);return AS(e,p,Ld(o,p),Ld(u,p))}function PS(e,o,a){let u=op(a);return Yu(u)?sp(e,u.name,o,u.type):yt(o,(p,f)=>Sr(Pt(e,p,a),(h)=>PS(h,f,a),()=>ot()),()=>Ee(e))}function $S(e,o,a){let u=Oi(e,gr([],[]),o);return dt(a)?RN(e,u,a.items):kt(a)?PS(e,u,a.items):Ht(e,Kr(u),a)}function CS(e,o,a){return Ro(a)?Ee(e):fs(a)?Ee(e):Ht(e,o,a)}function vS(e,o,a){return yt(a,(u,p)=>Sr(Pt(e,o,u),(f)=>Ee(f),()=>vS(e,o,p)),()=>ot())}function Nd(e,o,a){return yt(o,(u,p)=>Sr(vS(e,u,a),(f)=>Nd(f,p,a),()=>ot()),()=>Ee(e))}function MS(e,o,a){let u=op(a);return Yu(u)?sp(e,u.name,o,u.type):ye(a)?Nd(e,o,a.anyOf):Nd(e,o,[a])}function OS(e,o,a){return Yr(a)?Ht(e,o,a):Nr(a)?Ee(e):Xr(a)?Ee(e):ot()}function _S(e,o,a){return Ro(a)?Ee(e):Ht(e,o,a)}function Pt(e,o,a){return Nr(o)?iS(e,o,a):kt(o)?aS(e,o,o.items,a):To(o)?uS(e,o,a):zn(o)?cS(e,o,a):Jr(o)?mS(e,o.parameters,o.instanceType,a):Br(o)?pS(e,o.if,o.then,o.else,a):Zr(o)?lS(e,o.enum,a):Qr(o)?dS(e,o.parameters,o.returnType,a):yn(o)?fS(e,o,a):We(o)?hS(e,o.allOf,a):gt(o)?gS(e,o,a):wo(o)?yS(e,o,a):Ds(o)?xS(e,o,a):Cr(o)?IS(e,o,a):Qe(o)?bS(e,o.properties,a):nr(o)?SS(e,In(o),hr(o),a):en(o)?wS(e,o,a):Fs(o)?TS(e,o,a):lr(o)?RS(e,o.pattern,a):dt(o)?$S(e,o.items,a):fs(o)?CS(e,o,a):ye(o)?MS(e,o.anyOf,a):Xr(o)?OS(e,o,a):Ro(o)?_S(e,o,a):ot()}function kN(e,o){return Mr([...e,l(o)])}function qd(e,o,a){return pt(e)?Tt(kN(e,o),{},a):Ku(e,o,a)}function LS(e,o,a,u,p){let f=Co(e,o,a),h=Zu(e,o,u);return qd(f,h,p)}function Ku(e,o,a={}){return we("Interface",[e,o],a)}function za(e){return Lr(e)&&me(e,"action")&&v(e.action,"Interface")}function NS(e,o,a={}){return qd(e,o,a)}function AN(e,o,a){return e.includes(a)?!0:ec([...e,a],o,o[a])}function qS(e,o,a){let u=am(a);return ya(e,o,u)}function ya(e,o,a){return yt(a,(u,p)=>ec(e,o,u)?!0:ya(e,o,p),()=>!1)}function ec(e,o,a){return Yt(a)?AN(e,o,a.$ref):kt(a)?ec(e,o,a.items):Jr(a)?ya(e,o,[...a.parameters,a.instanceType]):Qr(a)?ya(e,o,[...a.parameters,a.returnType]):za(a)?qS(e,o,a.parameters[1]):We(a)?ya(e,o,a.allOf):Qe(a)?qS(e,o,a.properties):ye(a)?ya(e,o,a.anyOf):dt(a)?ya(e,o,a.items):nr(a)?ec(e,o,hr(a)):!1}function DS(e,o,a){return ec(e,o,a)}function PN(e,o){return o.reduce((a,u)=>DS([u],e,e[u])?[...a,u]:a,[])}function FS(e){let o=im(e);return PN(e,o)}function $N(e,o,a){return a.includes(o)?a:(o in e)?tc(e,e[o],[...a,o]):Gr()}function jS(e,o,a){let u=am(o);return Va(e,u,a)}function Va(e,o,a){return o.reduce((u,p)=>tc(e,p,u),a)}function tc(e,o,a){return Yt(o)?$N(e,o.$ref,a):kt(o)?tc(e,o.items,a):Jr(o)?Va(e,[...o.parameters,o.instanceType],a):Qr(o)?Va(e,[...o.parameters,o.returnType],a):za(o)?jS(e,o.parameters[1],a):We(o)?Va(e,o.allOf,a):Qe(o)?jS(e,o.properties,a):ye(o)?Va(e,o.anyOf,a):dt(o)?Va(e,o.items,a):nr(o)?tc(e,hr(o),a):a}function US(e,o,a){return tc(e,a,[o])}function CN(e){return qa()}function vN(e){return xe(e).reduce((o,a)=>({...o,[a]:xa(e[a])}),{})}function rc(e){return e.reduce((o,a)=>[...o,xa(a)],[])}function xa(e){return Yt(e)?CN(e.$ref):kt(e)?W(xa(e.items),La(e)):Jr(e)?Ms(rc(e.parameters),xa(e.instanceType)):Qr(e)?Os(rc(e.parameters),xa(e.returnType)):We(e)?qn(rc(e.allOf)):Qe(e)?l(vN(e.properties)):nr(e)?Ke(Ai(e),xa(hr(e))):ye(e)?y(rc(e.anyOf)):dt(e)?Kr(rc(e.items)):e}function MN(e,o){return o in e?xa(e[o]):Q()}function BS(e){return MN(e.$defs,e.$ref)}function ON(e,o,a){let u=Co(e,gr([],[]),o),p=Zu({},gr([],[]),a);return Mr([...u,l(p)])}function _N(e,o){return xe(e).filter((u)=>o.includes(u)).reduce((u,p)=>{let f=e[p],h=za(f)?ON(e,f.parameters[0],f.parameters[1]):f;return{...u,[p]:h}},{})}function GS(e,o,a){let u=US(e,o,a),p=_N(e,u);return Ns(p,o)}function KS(e,o){return o in e?Yt(e[o])?KS(e,e[o].$ref):e[o]:sr()}function js(e,o){return KS(e,o)}function HS(e){return cr(e)?BS(e):um(e)?Q():e}function Mn(e,o,a){let u=HS(o),p=HS(a);return Pt(e,u,p)}var Fu=0,nc=1,ju=2,Uu=3;function Ua(e,o){let a=[Mn({},e,o),Mn({},o,e)];return Eo(a[0])&&Eo(a[1])?Fu:Eo(a[0])&&vd(a[1])?ju:vd(a[0])&&Eo(a[1])?Uu:nc}function Dd(e,o,a=[],u=o){return yt(o,(p,f)=>{let h=Ua(e,p);return v(h,ju)||v(h,Fu)?u:v(h,nc)?Dd(e,f,[...a,p],u):Dd(e,f,a,u)},()=>[...a,e])}function LN(e,o,a){let u=Do(e);return Nr(u)?[u]:Xr(u)?[u]:wo(u)?ip(o,a):Qe(u)?ip(o,[...a,u]):ip(o,Dd(u,a))}function ip(e,o=[]){return yt(e,(a,u)=>LN(a,u,o),()=>o)}function ld(e){let o=ip(e);return fa(o)}function Fd(e,o){return Tt(Do(e),{},o)}function WS(e,o,a,u){let p=pe(e,o,a);return Fd(p,u)}function oc(e,o=[]){return bi(e)&&v(e.action,"Conditional")?Yt(e.parameters[0])?oc(e.parameters[2],oc(e.parameters[3],[...o,e.parameters[0].$ref])):oc(e.parameters[2],oc(e.parameters[3],o)):bi(e)&&v(e.action,"Mapped")?bi(e.parameters[1])&&v(e.parameters[1].action,"KeyOf")&&Yt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function NN(e,o){return e.reduce((a,u)=>[...a,o.includes(u.name)],[])}function JS(e,o,a=[]){return yt(e,(u,p)=>yt(o,(f,h)=>JS(p,h,[...a,[f,u]]),()=>a),()=>a)}function qN(e){return lr(e)?Fn(e.pattern):Zr(e)?Vn(e.enum):e}function DN(e){let o=qN(e);return ye(o)?[...o.anyOf]:[o]}function FN(e,o){return e.reduce((a,u)=>[...a,[...u,o]],[])}function zS(e,o){return o.reduce((a,u)=>[...a,...FN(e,u)],[])}function VS(e){return e.reduce((o,a)=>v(a[0],!0)?zS(o,DN(a[1])):zS(o,[a[1]]),[[]])}function QS(e,o,a){let u=oc(a),p=NN(e,u),f=JS(o,p);return bi(a)&&v(a.action,"Conditional")?VS(f):bi(a)&&v(a.action,"Mapped")?VS(f):[o]}function jN(){return["(not-resolvable)",sr()]}function UN(){return["(not-generic)",sr()]}function BN(e,o,a){return[e,Si(o,a)]}function GN(e,o,a){return o in e?XS(e,o,e[o],a):jN()}function XS(e,o,a,u){return Na(a)?BN(o,a.parameters,a.expression):Yt(a)?GN(e,a.$ref,u):UN()}function YS(e,o,a){return XS(e,"(anonymous)",o,a)}function KN(e,o,a){if(Yr(o)||Ja(o)||Eo(Mn({},o,a)))return;let u={parameter:e,expect:a,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function ZS(e,o,a,u,p){let f=pe(e,o,p);return KN(a,f,u),gn(e,{[a]:f})}function HN(e,o,a,u,p){let f=pe(e,o,a.extends),h=pe(e,o,a.equals);return yt(p,(g,I)=>jd(ZS(e,o,a.name,f,g),o,u,I),()=>jd(ZS(e,o,a.name,f,h),o,u,[]))}function jd(e,o,a,u){return yt(a,(p,f)=>HN(e,o,p,f,u),()=>e)}function ew(e,o,a,u){return jd(e,o,a,u)}var Ud=0,Bd=0;function WN(){if(Pu(Bd,rs().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function zN(){WN(),Bd++,Ud++}function VN(){if(Ud--,v(Ud,0))Bd=0}function JN(e){return ta(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function QN(e,o){return v(JN(e),o)}function XN(e,o,a,u,p,f){zN();try{let h=ew(e,o,u,f),g=pe(h,gr([...o.callstack,a.$ref],o.visited),p);return pe(h,gr([],[]),g)}finally{VN()}}function YN(e,o,a,u,p,f){return f.reduce((h,g)=>{let I=XN(e,o,a,u,p,g);return[...h,I]},[])}function ZN(e,o,a,u,p,f){let h=QS(u,f,p),g=YN(e,o,a,u,p,h);return v(g.length,1)?g[0]:Io(g)}function ap(e,o,a,u){let p=Co(e,o,u),f=YS(e,a,u),h=f[0],g=f[1];return Na(g)?QN(o,h)?Hu(rn(h),p):ZN(e,o,rn(h),g.parameters,g.expression,p):Hu(a,p)}function Hu(e,o){return _t({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function tw(e,o){return ap({},gr([],[]),e,o)}function Ja(e){return Se(e,"Call")}function eq(e){return as(e,["~immutable"])}function rw(e,o){return Tt(eq(e),{},o)}function nw(e,o,a,u){let p=pe(e,o,a);return rw(p,u)}function ow(e,o){return e(o)}function sw(e,o){return ht(o)?i(ow(e,o)):i(o)}function iw(e,o){let a=Fn(o);return Ys(e,a)}function aw(e,o){let a=o.map((u)=>Ys(e,u));return y(a)}function Ys(e,o){return gt(o)?sw(e,o.const):lr(o)?iw(e,o.pattern):ye(o)?aw(e,o.anyOf):o}function $m(e,o={}){return we("Capitalize",[e],o)}function uw(e,o={}){return Gd(e,o)}function Cm(e,o={}){return we("Lowercase",[e],o)}function cw(e,o={}){return Kd(e,o)}function vm(e,o={}){return we("Uncapitalize",[e],o)}function mw(e,o={}){return Hd(e,o)}function Mm(e,o={}){return we("Uppercase",[e],o)}function pw(e,o={}){return Wd(e,o)}var tq=(e)=>e[0].toUpperCase()+e.slice(1),rq=(e)=>e.toLowerCase(),nq=(e)=>e[0].toLowerCase()+e.slice(1),oq=(e)=>e.toUpperCase();function Gd(e,o){return pt([e])?Tt(Ys(tq,e),{},o):$m(e,o)}function Kd(e,o){return pt([e])?Tt(Ys(rq,e),{},o):Cm(e,o)}function Hd(e,o){return pt([e])?Tt(Ys(nq,e),{},o):vm(e,o)}function Wd(e,o){return pt([e])?Tt(Ys(oq,e),{},o):Mm(e,o)}function lw(e,o,a,u){let p=pe(e,o,a);return Gd(p,u)}function dw(e,o,a,u){let p=pe(e,o,a);return Kd(p,u)}function fw(e,o,a,u){let p=pe(e,o,a);return Hd(p,u)}function hw(e,o,a,u){let p=pe(e,o,a);return Wd(p,u)}function Om(e,o,a,u,p={}){return we("Conditional",[e,o,a,u],p)}function gw(e,o,a,u,p={}){return zd({},gr([],[]),e,o,a,u,p)}function sq(e,o,a,u,p,f){let h=Mn(e,a,u);return $d(h)?y([pe(h.inferred,o,p),pe(e,o,f)]):Cd(h)?pe(h.inferred,o,p):pe(e,o,f)}function zd(e,o,a,u,p,f,h){return pt([a,u])?Tt(sq(e,o,a,u,p,f),{},h):Om(a,u,p,f,h)}function yw(e,o,a,u,p,f,h){let g=pe(e,o,a),I=pe(e,o,u);return zd(e,o,g,I,p,f,h)}function _m(e,o={}){return we("ConstructorParameters",[e],o)}function xw(e,o={}){return Vd(e,o)}function iq(e){let o=Jr(e)?e.parameters:[],a=Oi({},gr([],[]),o);return Kr(a)}function Vd(e,o){return pt([e])?Tt(iq(e),{},o):_m(e,o)}function Iw(e,o,a,u){let p=pe(e,o,a);return Vd(p,u)}function Lm(e,o,a={}){return we("Exclude",[e,o],a)}function Ew(e,o,a={}){return sc(e,o,a)}function sc(e,o,a){return pt([e,o])?Tt(Sm(e,o),{},a):Lm(e,o,a)}function bw(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return sc(f,h,p)}function Nm(e,o,a={}){return we("Extract",[e,o],a)}function Sw(e,o,a={}){return Jd(e,o,a)}function aq(e,o){let a=Mn({},e,o);return Eo(a)?[e]:[]}function ww(e,o,a=[]){return yt(e,(u,p)=>ww(p,o,[...a,...aq(u,o)]),()=>a)}function Tw(e,o){let a=Do(e),u=ye(a)?a.anyOf:[a],p=ww(u,o);return Io(p)}function Jd(e,o,a){return pt([e,o])?Tt(Tw(e,o),{},a):Nm(e,o,a)}function Rw(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return Jd(f,h,p)}function uq(e){return e.reduce((o,a)=>fm(a)?[...o,i(a)]:o,[])}function Qa(e){let o=uq(e);return y(o)}function Wu(e,o,a={}){return we("Index",[e,o],a)}function kw(e,o,a={}){let u=$e(o)?Qa(o):o;return Qd(e,u,a)}function Aw(e,o){let a=js(e,o);return vo(a)}function Pw(e,o,a){let u=ds(e,o,a);return vo(u)}function cq(e,o){let a=xe(e).filter((S)=>!me(o,S)),u=xe(o).filter((S)=>!me(e,S)),p=xe(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]:Mr([e[k],o[k]])}),{}),I=gn(f,h);return gn(I,g)}function $w(e){return e.reduce((o,a)=>cq(o,vo(a)),{})}function Cw(e){return e}function vw(e){let o=Ix(Kr(e));return vo(o)}function mq(e,o){return xe(e).filter((p)=>(p in o)).reduce((p,f)=>({...p,[f]:Io([e[f],o[f]])}),{})}function Mw(e,o){return yt(e,(a,u)=>Mw(u,mq(o,vo(a))),()=>o)}function Ow(e){return yt(e,(o,a)=>Mw(a,vo(o)),()=>Gr())}function vo(e){return cr(e)?Aw(e.$defs,e.$ref):Br(e)?Pw(e.if,e.then,e.else):We(e)?$w(e.allOf):ye(e)?Ow(e.anyOf):dt(e)?vw(e.items):Qe(e)?Cw(e.properties):{}}function Xa(e){let o=vo(e);return l(o)}var pq=new RegExp("^(?:0|[1-9][0-9]*)$");function Ya(e){let o=`${e}`;return pq.test(o)?parseInt(o):e}function lq(e){return i(Ya(e))}function _w(e){return e.map((o)=>Lw(o))}function Lw(e){return We(e)?qn(_w(e.allOf)):ye(e)?y(_w(e.anyOf)):gt(e)?lq(e.const):e}function Nw(e,o){let a=Lw(o),u=Mn({},a,re());return Eo(u)?e:gt(o)&&v(o.const,"length")?re():sr()}function qw(e,o){let a=js(e,o);return ko(a)}function Dw(e,o,a){let u=ds(e,o,a);return ko(u)}function Fw(e){let o=Vn(e);return ko(o)}function jw(e){let o=Mr(e);return ko(o)}function Uw(e){return[`${e}`]}function Bw(e){let o=Fn(e);return ko(o)}function Gw(e){return e.reduce((o,a)=>[...o,...ko(a)],[])}function ko(e){return cr(e)?qw(e.$defs,e.$ref):Br(e)?Dw(e.if,e.then,e.else):Zr(e)?Fw(e.enum):We(e)?jw(e.allOf):gt(e)?Uw(e.const):lr(e)?Bw(e.pattern):ye(e)?Gw(e.anyOf):[]}function Za(e){return ko(e)}function ic(e,o){return o.map((a)=>ac(e,a))}function ac(e,o){return kt(o)?W(ac(e,o.items)):Jr(o)?Ms(ic(e,o.parameters),ac(e,o.instanceType)):Qr(o)?Os(ic(e,o.parameters),ac(e,o.returnType)):dt(o)?Kr(ic(e,o.items)):ye(o)?y(ic(e,o.anyOf)):We(o)?qn(ic(e,o.allOf)):km(o)?l(e):o}function Kw(e,o){return ac(e,o)}function dq(e,o){let a=o in e?e[o]:sr();return Kw(e,a)}function Hw(e,o){return o.reduce((a,u)=>[...a,dq(e,u)],[])}function fq(e,o){let a=Za(o),u=Hw(e,a);return Io(u)}var hq=new RegExp(ki);function gq(e){return e.filter((a)=>hq.test(a))}function yq(e){let o=im(e),a=gq(o),u=Hw(e,a);return Io(u)}function Ww(e,o){return Cr(o)?yq(e):fq(e,o)}function xq(e){return i(Ya(e))}function zw(e){return e.map((o)=>Xd(o))}function Xd(e){return We(e)?qn(zw(e.allOf)):ye(e)?y(zw(e.anyOf)):gt(e)?xq(e.const):e}function Iq(e,o){return e.reduceRight((a,u,p)=>{let f=Mn({},i(p),o);return Eo(f)?[u,...a]:a},[])}function Eq(e,o){let a=Xd(o),u=Iq(e,a);return Ti(u)}function bq(e){return Ti(e)}function Vw(e,o){return gt(o)&&v(o.const,"length")?i(e.length):Cr(o)||yn(o)?bq(e):Eq(e,o)}function Jw(e,o){return kt(e)?Nw(e.items,o):Qe(e)?Ww(e.properties,o):dt(e)?Vw(e.items,o):sr()}function Sq(e){return cr(e)||Br(e)||We(e)||ye(e)?Xa(e):e}function Qd(e,o,a){return pt([e,o])?Tt(Jw(Sq(e),o),{},a):Wu(e,o,a)}function Qw(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return Qd(f,h,p)}function qm(e,o={}){return we("InstanceType",[e],o)}function Xw(e,o={}){return Yd(e,o)}function wq(e){return Jr(e)?e.instanceType:sr()}function Yd(e,o){return pt([e])?Tt(wq(e),{},o):qm(e,o)}function Yw(e,o,a,u={}){let p=pe(e,o,a);return Yd(p,u)}function zu(e,o={}){return we("KeyOf",[e],o)}function Zw(e,o={}){return Zd(e,o)}function eT(){return y([re(),s(),ja()])}function tT(e){return re()}function Tq(e){return e.reduce((a,u)=>fm(u)?[...a,i(Ya(u))]:Gr(),[])}function rT(e){let o=xe(e),a=Tq(o);return Ti(a)}function nT(e){return Ai(e)}function oT(e){let o=e.map((a,u)=>i(u));return Ti(o)}function sT(e){return Nr(e)?eT():kt(e)?tT(e.items):Qe(e)?rT(e.properties):nr(e)?nT(e):dt(e)?oT(e.items):sr()}function Rq(e){return cr(e)||Br(e)||We(e)||ye(e)?Xa(e):e}function Zd(e,o){return pt([e])?Tt(sT(Rq(e)),{},o):zu(e,o)}function iT(e,o,a,u){let p=pe(e,o,a);return Zd(p,u)}function Gu(e,o,a,u,p={}){return we("Mapped",[e,o,a,u],p)}function aT(e,o,a,u,p={}){return ef({},gr([],[]),e,o,a,u,p)}function kq(e){let o=Fn(e);return up(o)}function Aq(e){return e.reduce((o,a)=>[...o,...up(a)],[])}function Pq(e){let o=Vn(e);return up(o)}function $q(e){return Ft(e)?[i(`${e}`)]:[i(e)]}function up(e){return Zr(e)?Pq(e.enum):gt(e)?$q(e.const):lr(e)?kq(e.pattern):ye(e)?Aq(e.anyOf):[e]}function uT(e){return up(e)}function Cq(e){return lr(e)?Fn(e.pattern):e}function vq(e,o,a,u,p,f){let h=gn(e,{[a.name]:u}),g=pe(h,o,p),I=Cq(g),E=pe(h,o,f);return hm(I)||gm(I)?{[I.const]:E}:{}}function Mq(e,o,a,u,p,f){return u.reduce((h,g)=>[...h,vq(e,o,a,g,p,f)],[])}function Oq(e){return e.reduce((o,a)=>[...o,l(a)],[])}function cT(e,o,a,u,p,f){let h=uT(u),g=Mq(e,o,a,h,p,f),I=Oq(g);return Mr(I)}function ef(e,o,a,u,p,f,h){return pt([u])?Tt(cT(e,o,a,u,p,f),{},h):Gu(a,u,p,f,h)}function mT(e,o,a,u,p,f,h){let g=pe(e,o,u);return ef(e,o,a,g,p,f,h)}function _q(e,o,a){let u=gn(e,o);return xe(o).filter((f)=>a.includes(f)).reduce((f,h)=>({...f,[h]:GS(u,h,o[h])}),{})}function Lq(e,o,a){let u=gn(e,o);return xe(o).filter((f)=>!a.includes(f)).reduce((f,h)=>({...f,[h]:pe(u,gr([],[]),o[h])}),{})}function Nq(e,o,a){let u=FS(o),p=_q(e,o,u),f=Lq(e,o,u),h={...p,...f};return Tt(h,{},a)}function cp(e,o,a,u){return Nq(e,a,u)}function Dm(e,o={}){return we("NonNullable",[e],o)}function pT(e,o={}){return tf(e,o)}function qq(e){let o=y([Dn(),Ga()]);return sc(e,o,{})}function tf(e,o){return pt([e])?Tt(qq(e),{},o):Dm(e,o)}function lT(e,o,a,u){let p=pe(e,o,a);return tf(p,u)}function Fm(e,o,a={}){return we("Omit",[e,o],a)}function dT(e,o,a={}){let u=$e(o)?Qa(o):o;return rf(e,u,a)}function mp(e){let o=Xa(e);return Qe(o)?o.properties:Gr()}function Dq(e,o){return xe(e).reduce((u,p)=>o.includes(p)?u:{...u,[p]:e[p]},{})}function fT(e,o){let a=mp(e),u=Za(o),p=Dq(a,u);return l(p)}function rf(e,o,a){return pt([e,o])?Tt(fT(e,o),{},a):Fm(e,o,a)}function hT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return rf(f,h,p)}function jm(e,o={}){return we("Parameters",[e],o)}function gT(e,o={}){return nf(e,o)}function Fq(e){let o=Qr(e)?e.parameters:[],a=Oi({},gr([],[]),o);return Kr(a)}function nf(e,o){return pt([e])?Tt(Fq(e),{},o):jm(e,o)}function yT(e,o,a,u){let p=pe(e,o,a);return nf(p,u)}function Um(e,o={}){return we("Partial",[e],o)}function xT(e,o={}){return of(e,o)}function IT(e,o){let a=js(e,o),u=Us(a);return Ns(gn(e,{[o]:u}),o)}function ET(e,o,a){let u=ds(e,o,a);return Us(u)}function bT(e){let o=Mr(e);return Us(o)}function ST(e){let o=e.map((a)=>Us(a));return y(o)}function wT(e){let o=xe(e).reduce((u,p)=>({...u,[p]:aa(e[p])}),{});return l(o)}function Us(e){return cr(e)?IT(e.$defs,e.$ref):Br(e)?ET(e.if,e.then,e.else):We(e)?bT(e.allOf):ye(e)?ST(e.anyOf):Qe(e)?wT(e.properties):l({})}function of(e,o){return pt([e])?Tt(Us(e),{},o):Um(e,o)}function TT(e,o,a,u){let p=pe(e,o,a);return of(p,u)}function Bm(e,o,a={}){return we("Pick",[e,o],a)}function RT(e,o,a={}){let u=$e(o)?Qa(o):o;return sf(e,u,a)}function jq(e,o){return xe(e).reduce((u,p)=>o.includes(p)?gn(u,{[p]:e[p]}):u,{})}function kT(e,o){let a=mp(e),u=Za(o),p=jq(a,u);return l(p)}function sf(e,o,a){return pt([e,o])?Tt(kT(e,o),{},a):Bm(e,o,a)}function AT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return sf(f,h,p)}function Gm(e,o={}){return we("ReadonlyObject",[e],o)}function af(e,o={}){return uf(e,o)}var PT=af;function $T(e){return Fa(W(e))}function CT(e,o){let a=js(e,o),u=Bs(a);return Ns(gn(e,{[o]:u}),o)}function vT(e,o,a){let u=ds(e,o,a);return Bs(u)}function MT(e){let o=Mr(e);return Bs(o)}function OT(e){let o=xe(e).reduce((u,p)=>({...u,[p]:pa(e[p])}),{});return l(o)}function _T(e){return Fa(Kr(e))}function LT(e){let o=e.map((a)=>Bs(a));return y(o)}function Bs(e){return kt(e)?$T(e.items):cr(e)?CT(e.$defs,e.$ref):Br(e)?vT(e.if,e.then,e.else):We(e)?MT(e.allOf):Qe(e)?OT(e.properties):dt(e)?_T(e.items):ye(e)?LT(e.anyOf):e}function uf(e,o){return pt([e])?Tt(Bs(e),{},o):Gm(e)}function NT(e,o,a,u){let p=pe(e,o,a);return uf(p,u)}function qT(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 DT(e,o){let a=js(e,o),u=Gs(a);return Ns(gn(e,{[o]:u}),o)}function FT(e,o,a){let u=ds(e,o,a);return Gs(u)}function jT(e){let o=Mr(e);return Gs(o)}function UT(e){let o=e.map((a)=>Gs(a));return y(o)}function BT(e){let o=xe(e).reduce((u,p)=>({...u,[p]:bm(e[p])}),{});return l(o)}function Gs(e){return cr(e)?DT(e.$defs,e.$ref):Br(e)?FT(e.if,e.then,e.else):We(e)?jT(e.allOf):ye(e)?UT(e.anyOf):Qe(e)?BT(e.properties):l({})}function Km(e,o={}){return we("Required",[e],o)}function GT(e,o={}){return cf(e,o)}function cf(e,o){return pt([e])?Tt(Gs(e),{},o):Km(e,o)}function KT(e,o,a,u){let p=pe(e,o,a);return cf(p,u)}function Hm(e,o={}){return we("ReturnType",[e],o)}function HT(e,o={}){return mf(e,o)}function Uq(e){return Qr(e)?e.returnType:sr()}function mf(e,o){return pt([e])?Tt(Uq(e),{},o):Hm(e,o)}function WT(e,o,a,u={}){let p=pe(e,o,a);return mf(p,u)}function Wm(e,o){return we("With",[e,o],{})}function pp(e,o){return pf(e,o)}function pf(e,o){return pt([e])?Tt(e,{},o):Wm(e,o)}function zT(e,o,a,u){let p=pe(e,o,a);return pf(p,u)}function Bq(e){return Pi(e)?dt(e.items)?lf(e.items.items):Yr(e.items)?[e]:Yt(e.items)?[e]:[sr()]:[e]}function lf(e){return e.reduce((a,u)=>[...a,...Bq(u)],[])}function gr(e,o){return{callstack:e,visited:o}}function pt(e){return yt(e,(o,a)=>Yt(o)?!1:pt(a),()=>!0)}function Zu(e,o,a){return xe(a).reduce((u,p)=>({...u,[p]:pe(e,o,a[p])}),{})}function Oi(e,o,a){let u=Co(e,o,a);return lf(u)}function Co(e,o,a){return a.map((u)=>pe(e,o,u))}function Gq(e,o){let a=nn(e)?Ou(o,{}):o,u=la(e)?Mu(a,{}):a;return ma(e)?uc(u,{}):u}function Kq(e,o,a,u,p){return v(a,"AddImmutable")?VT(e,o,u[0],p):v(a,"RemoveImmutable")?nw(e,o,u[0],p):v(a,"AddReadonly")?by(e,o,u[0],p):v(a,"RemoveReadonly")?fx(e,o,u[0],p):v(a,"AddOptional")?Sy(e,o,u[0],p):v(a,"RemoveOptional")?yx(e,o,u[0],p):v(a,"Capitalize")?lw(e,o,u[0],p):v(a,"Conditional")?yw(e,o,u[0],u[1],u[2],u[3],p):v(a,"ConstructorParameters")?Iw(e,o,u[0],p):v(a,"Evaluate")?WS(e,o,u[0],p):v(a,"Exclude")?bw(e,o,u[0],u[1],p):v(a,"Extract")?Rw(e,o,u[0],u[1],p):v(a,"Index")?Qw(e,o,u[0],u[1],p):v(a,"InstanceType")?Yw(e,o,u[0],p):v(a,"Interface")?LS(e,o,u[0],u[1],p):v(a,"KeyOf")?iT(e,o,u[0],p):v(a,"Lowercase")?dw(e,o,u[0],p):v(a,"Mapped")?mT(e,o,u[0],u[1],u[2],u[3],p):v(a,"Module")?cp(e,o,u[0],p):v(a,"NonNullable")?lT(e,o,u[0],p):v(a,"Pick")?AT(e,o,u[0],u[1],p):v(a,"Parameters")?yT(e,o,u[0],p):v(a,"Partial")?TT(e,o,u[0],p):v(a,"Omit")?hT(e,o,u[0],u[1],p):v(a,"ReadonlyObject")?NT(e,o,u[0],p):v(a,"Record")?_x(e,o,u[0],u[1],p):v(a,"Required")?KT(e,o,u[0],p):v(a,"ReturnType")?WT(e,o,u[0],p):v(a,"TemplateLiteral")?tS(e,o,u[0],p):v(a,"Uncapitalize")?fw(e,o,u[0],p):v(a,"Uppercase")?hw(e,o,u[0],p):v(a,"With")?zT(e,o,u[0],u[1]):we(a,u,p)}function Hq(e,o,a){let u=Yt(a)?qT(e,o,a,a.$ref):kt(a)?W(pe(e,o,a.items),La(a)):Ja(a)?ap(e,o,a.target,a.arguments):Jr(a)?Ms(Co(e,o,a.parameters),pe(e,o,a.instanceType),wy(a)):Qr(a)?Os(Co(e,o,a.parameters),pe(e,o,a.returnType),Ty(a)):Br(a)?ua(pe(e,o,a.if),pe(e,o,a.then),pe(e,o,a.else),Py(a)):We(a)?qn(Co(e,o,a.allOf),Oy(a)):Qe(a)?l(Zu(e,o,a.properties),Ay(a)):nr(a)?Lx(In(a),pe(e,o,hr(a))):Pi(a)?ha(pe(e,o,a.items)):dt(a)?Kr(Oi(e,o,a.items),dx(a)):ye(a)?y(Co(e,o,a.anyOf),nx(a)):a;return Gq(a,u)}function pe(e,o,a){return bi(a)?Kq(e,o,a.action,a.parameters,a.options):Hq(e,o,a)}function Fo(e,o){return pe(e,gr([],[]),o)}function Wq(e){return Tt(e,{"~immutable":!0},{})}function uc(e,o){return Tt(Wq(e),{},o)}function VT(e,o,a,u){let p=pe(e,o,a);return uc(p,u)}function XE(e,o={}){return we("AddImmutable",[e],o)}function Fa(e,o={}){return uc(e,o)}function YE(e,o={}){return we("Evaluate",[e],o)}function On(e,o={}){return Fd(e,o)}function ZE(e,o={}){return we("Module",[e],o)}function JT(e,o={}){return cp({},gr([],[]),e,o)}function zq(e,o){let a=Ua(e,o);return v(a,Uu)?1:v(a,nc)?1:0}function QT(e,o,a=[]){return yt(o,(u,p)=>v(zq(e,u),1)?QT(e,p,[...a,u]):[...a,e,...o],()=>[...a,e])}function XT(e,o=[]){return yt(e,(a,u)=>XT(u,QT(a,o)),()=>o)}function YT(e){return XT(e)}function ZT(...e){let[o,a,u]=Cn(e,{2:(h,g)=>ht(h)?[{},h,g]:[h,g,{}],3:(h,g,I)=>[h,g,I],1:(h)=>[{},h,{}]}),p=Qb(a),f=$e(p)&&v(p.length,2)?pe(o,gr([],[]),p[0]):sr();return Tt(f,{},u)}function Vq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function Jq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Qq(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 Xq(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 cc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function eu(e){cc(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 ff(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var Yq=ff(z(""));function hf(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)=>hf(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)&&hf(p,a[u]))}class eR{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:Xq(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=eu(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:Vq(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=eu(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=eu(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:Jq(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=eu(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=eu(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let a=ff(o.arguments),u=a===Yq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":a}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Qq(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(ff(a)!==o.snapshotArguments){let p=z(o.snapshotArguments);if(!hf(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=eu(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(cc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){cc(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 df(e,o,a,u,p){if(cc(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 Ia(e,o,a,u,p){cc(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 Zq(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`);df(o,u,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:f}=Ia(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}=Ia(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`);df(o,u,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:f}=Ia(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}=Ia(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`);df(o,u,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:f,state:h}=Ia(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}=Ia(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}=Ia(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 tR=[/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],eD=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,tD=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Ea(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!tD.some((u)=>u.test(e.errorMessage))){if(tR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&eD.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 rD(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function nD(){return[...tR]}function rR(e){return new RegExp(e.join("|"),"i")}var oD=rR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),sD=rR(["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"]),nR=60000;function oR(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??nR)}class lp extends Error{constructor(){super("Aborted")}}function iD(e,o){return new Promise((a,u)=>{if(o?.aborted){u(new lp);return}let p=setTimeout(a,e);o?.addEventListener("abort",()=>{clearTimeout(p),u(new lp)},{once:!0})})}async function aD(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||!sR(g)){if(h)await u?.onRetryFinished?.(!1,h.attempt,g.errorMessage);return g}f++,h={attempt:f,errorMessage:g.errorMessage||"Unknown error"};let I=oR(o,f);await u?.onRetryScheduled?.(f,p,I,h.errorMessage);try{await iD(I,a)}catch(E){if(await u?.onRetryFinished?.(!1,f,h.errorMessage),E instanceof lp){let{errorMessage:S,...k}=g;return{...k,stopReason:"aborted"}}throw E}await u?.onRetryAttemptStart?.()}}function sR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(oD.test(o))return!1;return sD.test(o)}function uD(e,o){return xr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function mc(e){return me(e,"~refine")&&$e(e["~refine"])&&tn(e["~refine"],0,(o)=>mt(o)&&me(o,"check")&&me(o,"error")&&Ps(o.check)&&Ps(o.error))}function bn(e){return mt(e)&&!$e(e)}function Zs(e){return sn(e)}function Ze(e){return bn(e)||Zs(e)}function tu(e){return me(e,"additionalItems")&&Ze(e.additionalItems)}function Uo(e){return me(e,"additionalProperties")&&Ze(e.additionalProperties)}function pc(e){return me(e,"allOf")&&$e(e.allOf)&&e.allOf.every((o)=>Ze(o))}function lc(e){return me(e,"$anchor")&&ht(e.$anchor)}function dc(e){return me(e,"anyOf")&&$e(e.anyOf)&&e.anyOf.every((o)=>Ze(o))}function dp(e){return me(e,"const")}function Ks(e){return me(e,"contains")&&Ze(e.contains)}function Mo(e){return me(e,"default")}function fc(e){return me(e,"dependencies")&&mt(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ze(o)||$e(o)&&o.every((a)=>ht(a)))}function hc(e){return me(e,"dependentRequired")&&mt(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>$e(o)&&o.every((a)=>ht(a)))}function ru(e){return me(e,"dependentSchemas")&&mt(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ze(o))}function ti(e){return me(e,"$dynamicAnchor")&&ht(e.$dynamicAnchor)}function gc(e){return me(e,"$dynamicRef")&&ht(e.$dynamicRef)}function yc(e){return me(e,"else")&&Ze(e.else)}function fp(e){return me(e,"enum")&&$e(e.enum)}function xc(e){return me(e,"exclusiveMaximum")&&(Ft(e.exclusiveMaximum)||Ur(e.exclusiveMaximum))}function hs(e){return me(e,"exclusiveMinimum")&&(Ft(e.exclusiveMinimum)||Ur(e.exclusiveMinimum))}function ba(e){return me(e,"format")&&ht(e.format)}function Oo(e){return me(e,"$id")&&ht(e.$id)}function Ic(e){return me(e,"if")&&Ze(e.if)}function ai(e){return me(e,"items")&&(Ze(e.items)||$e(e.items)&&e.items.every((o)=>Ze(o)))}function Ec(e){return ai(e)&&$e(e.items)}function bc(e){return me(e,"maximum")&&(Ft(e.maximum)||Ur(e.maximum))}function Sc(e){return me(e,"maxContains")&&Ft(e.maxContains)}function nu(e){return me(e,"maxItems")&&Ft(e.maxItems)}function wc(e){return me(e,"maxLength")&&Ft(e.maxLength)}function Tc(e){return me(e,"maxProperties")&&Ft(e.maxProperties)}function gs(e){return me(e,"minimum")&&(Ft(e.minimum)||Ur(e.minimum))}function ui(e){return me(e,"minContains")&&Ft(e.minContains)}function _i(e){return me(e,"minItems")&&Ft(e.minItems)}function Sa(e){return me(e,"minLength")&&Ft(e.minLength)}function wa(e){return me(e,"minProperties")&&Ft(e.minProperties)}function Rc(e){return me(e,"multipleOf")&&(Ft(e.multipleOf)||Ur(e.multipleOf))}function kc(e){return me(e,"not")&&Ze(e.not)}function Ac(e){return me(e,"oneOf")&&$e(e.oneOf)&&e.oneOf.every((o)=>Ze(o))}function Ta(e){return me(e,"pattern")&&(ht(e.pattern)||e.pattern instanceof RegExp)}function ci(e){return me(e,"patternProperties")&&mt(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ze(o))}function ys(e){return me(e,"prefixItems")&&$e(e.prefixItems)&&e.prefixItems.every((o)=>Ze(o))}function mi(e){return me(e,"properties")&&mt(e.properties)&&Object.values(e.properties).every((o)=>Ze(o))}function ou(e){return me(e,"propertyNames")&&(mt(e.propertyNames)||Ze(e.propertyNames))}function cD(e){return me(e,"$recursiveAnchor")&&sn(e.$recursiveAnchor)}function Pc(e){return cD(e)&&v(e.$recursiveAnchor,!0)}function $c(e){return me(e,"$recursiveRef")&&ht(e.$recursiveRef)}function Cc(e){return me(e,"$ref")&&ht(e.$ref)}function Is(e){return me(e,"required")&&$e(e.required)&&e.required.every((o)=>ht(o))}function vc(e){return me(e,"then")&&Ze(e.then)}function Mc(e){return me(e,"type")&&(ht(e.type)||$e(e.type)&&e.type.every((o)=>ht(o)))}function Li(e){return me(e,"uniqueItems")&&sn(e.uniqueItems)}function Ni(e){return me(e,"unevaluatedItems")&&Ze(e.unevaluatedItems)}function Ki(e){return me(e,"unevaluatedProperties")&&Ze(e.unevaluatedProperties)}function mD(e){return Ni(e)||Ki(e)||Ma(xe(e),(o)=>hp(e[o]))}function pD(e){return Ma(e,(o)=>hp(o))}function hp(e){return $e(e)?pD(e):mt(e)?mD(e):!1}function iR(e,o){return hp(o)||Ma(xe(e),(a)=>hp(e[a]))}class gf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return br(Et("context","Push"),[])}Pop(){return br(Et("context","Pop"),[])}AddIndex(e){return br(Et("context","AddIndex"),[e])}AddKey(e){return br(Et("context","AddKey"),[e])}Merge(e){return br(Et("context","Merge"),[e])}}class Un{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 Bn extends Un{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=rs().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var gp={identifier:"External",variables:[]};function Bo(e){let o=`External[${gp.variables.length}]`;return gp.variables.push(e),o}function aR(){gp.variables=[]}function uR(){return{...gp}}function cR(e,o,a,u){let p=Bo(a["~refine"].map((f)=>f));return Cs(p,Te(0),["refinement","_"],br(Et("refinement","check"),[u]))}function mR(e,o,a,u){return tn(a["~refine"],0,(p,f)=>p.check(u))}function pR(e,o,a,u,p,f){return Ln(p["~refine"],0,(h,g)=>h.check(f)||o.AddError({keyword:"~refine",schemaPath:a,instancePath:u,params:{index:g,message:h.error(f)}}))}var lD=0;function ir(){return`var_${lD++}`}function yf(e){return ai(e)&&$e(e.items)}function dD(e,o,a,u){let[p,f]=[ir(),ir()],h=Qn(e,o,a.additionalItems,p),g=td(f,Te(a.items.length)),I=o.AddIndex(f);return Cs(u,Te(0),[p,f],Er(g,$n(h,I)))}function fD(e,o,a,u){let[p,f]=[ir(),ir()],h=Qn(e,o,a.additionalItems,p),g=td(f,Te(a.items.length));return Cs(u,Te(0),[p,f],Er(g,h))}function lR(e,o,a,u){if(!yf(a))return Te(!0);return o.UseUnevaluated()?dD(e,o,a,u):fD(e,o,a,u)}function dR(e,o,a,u){if(!yf(a))return!0;return tn(u,0,(f,h)=>Pu(h,a.items.length)||_o(e,o,a.additionalItems,f)&&o.AddIndex(h))}function fR(e,o,a,u,p,f){if(!yf(p))return!0;return tn(f,0,(g,I)=>{let E=`${a}/additionalItems`,S=`${u}/${I}`;return Pu(I,p.items.length)||Lo(e,o,E,S,p.additionalItems,g)&&o.AddIndex(I)})}function Es(e){return new RegExp(e,"u")}function hD(e,o){return!e.UseUnevaluated()&&(v(o,!0)||mt(o)&&v(xe(o).length,0))}function gD(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function xf(e){let o=[];if(ci(e))o.push(...xe(e.patternProperties));if(mi(e))o.push(...xe(e.properties).map(gD));return v(o.length,0)?"(?!)":`(${o.join("|")})`}function yD(e,o,a){return Is(o)&&mi(o)&&!ci(o)&&v(o.additionalProperties,!1)&&v(xe(o.properties).length,o.required.length)}function xD(e,o,a){return So(Et(br(Et("Object","getOwnPropertyNames"),[a]),"length"),Te(o.required.length))}function ID(e,o,a,u){let[p,f]=[ir(),ir()],h=Bo(Es(xf(a))),g=Qn(e,o,a.additionalProperties,`${u}[${p}]`),I=br(Et(h,"test"),[p]),E=o.AddKey(p),S=o.UseUnevaluated()?Er(I,$n(g,E)):Er(I,g);return Cs(oa(u),Te(0),[p,f],S)}function hR(e,o,a,u){if(hD(o,a.additionalProperties))return Te(!0);return yD(o,a,u)?xD(o,a,u):ID(e,o,a,u)}function gR(e,o,a,u){let p=Es(xf(a));return tn(xe(u),0,(h,g)=>p.test(h)||_o(e,o,a.additionalProperties,u[h])&&o.AddKey(h))}function yR(e,o,a,u,p,f){let h=Es(xf(p)),g=[];return Ln(xe(f),0,(E,S)=>{let k=`${a}/additionalProperties`,A=`${u}/${E}`,P=h.test(E)||Lo(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 Hi(e,o,a,u,p){let f=Qs("results","[]"),h=a.map((S,k)=>Qs(`context_${k}`,rd("CheckContext",[]))),g=a.map((S,k)=>Qs(`condition_${k}`,br(Ii(["context"],Bt(e,o,S,u)),[`context_${k}`]))),I=a.map((S,k)=>yy(`condition_${k}`,br(Et("results","push"),[`context_${k}`]))),E=sm($n(p,o.Merge("results")));return br(Ii([],om([f,...h,...g,...I,E])),[])}function ED(e,o,a,u){return Hi(e,o,a.allOf,u,So(Et("results","length"),Te(a.allOf.length)))}function bD(e,o,a,u){return Nn(a.allOf.map((p)=>Bt(e,o,p,u)))}function xR(e,o,a,u){return o.UseUnevaluated()?ED(e,o,a,u):bD(e,o,a,u)}function IR(e,o,a,u){let p=a.allOf.reduce((f,h)=>{let g=new Un;return $t(e,g,h,u)?[...f,g]:f},[]);return v(p.length,a.allOf.length)&&o.Merge(p)}function ER(e,o,a,u,p,f){let h=[],g=p.allOf.reduce((E,S,k)=>{let A=`${a}/allOf/${k}`,P=new Bn,C=dr(e,P,A,u,S,f);if(!C)h.push(P);return C?[...E,P]:E},[]),I=v(g.length,p.allOf.length)&&o.Merge(g);if(!I)h.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I}function SD(e,o,a,u){return Hi(e,o,a.anyOf,u,fy(Et("results","length"),Te(0)))}function wD(e,o,a,u){return nd(a.anyOf.map((p)=>Bt(e,o,p,u)))}function bR(e,o,a,u){return o.UseUnevaluated()?SD(e,o,a,u):wD(e,o,a,u)}function SR(e,o,a,u){let p=a.anyOf.reduce((f,h)=>{let g=new Un;return $t(e,g,h,u)?[...f,g]:f},[]);return ta(p.length,0)&&o.Merge(p)}function wR(e,o,a,u,p,f){let h=[],g=p.anyOf.reduce((E,S,k)=>{let A=new Bn,P=`${a}/anyOf/${k}`,C=dr(e,A,P,u,S,f);if(!C)h.push(A);return C?[...E,A]:E},[]),I=ta(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 TR(e,o,a,u){return a?Te(!0):Te(!1)}function If(e,o,a,u){return a}function RR(e,o,a,u,p,f){return If(e,o,p,f)||o.AddError({keyword:"boolean",schemaPath:a,instancePath:u,params:{}})}function kR(e,o,a,u){return ra(a.const)?So(u,Te(a.const)):gy(u,Bo(a.const))}function Ef(e,o,a,u){return ra(a.const)?v(u,a.const):Oa(u,a.const)}function AR(e,o,a,u,p,f){return Ef(e,o,p,f)||o.AddError({keyword:"const",schemaPath:a,instancePath:u,params:{allowedValue:p.const}})}function PR(e){return!(ui(e)&&v(e.minContains,0))}function TD(e,o,a,u){let[p,f]=[ir(),ir()],h=Kn(So(Et(u,"length"),Te(0))),g=fM(u,[p,f],$n(Bt(e,o,a.contains,p),o.AddIndex(f)));return $n(h,g)}function RD(e,o,a,u){let[p]=[ir()],f=Kn(So(Et(u,"length"),Te(0))),h=dM(u,[p,"_"],Bt(e,o,a.contains,p));return $n(f,h)}function $R(e,o,a,u){if(!PR(a))return Te(!0);return o.UseUnevaluated()?TD(e,o,a,u):RD(e,o,a,u)}function bf(e,o,a,u){if(!PR(a))return!0;return!v(u.length,0)&&ay(u,(p,f)=>$t(e,o,a.contains,p)&&o.AddIndex(f))}function CR(e,o,a,u,p,f){return bf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:1}})}function vR(e,o,a,u){let p=So(Et(oa(u),"length"),Te(0)),f=Nn(an(a.dependencies).map(([h,g])=>{let I=Kn(sa(u,Te(h))),E=Bt(e,o,g,u),S=(k)=>Nn(k.map((A)=>sa(u,Te(A))));return Er(I,$e(g)?S(g):E)}));return Er(p,f)}function MR(e,o,a,u){let p=v(xe(u).length,0),f=tn(an(a.dependencies),0,([h,g])=>!me(u,h)||($e(g)?g.every((I)=>me(u,I)):$t(e,o,g,u)));return p||f}function OR(e,o,a,u,p,f){let h=v(xe(f).length,0),g=Ln(an(p.dependencies),0,([I,E])=>{let S=`${a}/dependencies/${I}`;return!me(f,I)||($e(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 _R(e,o,a,u){let p=So(Et(oa(u),"length"),Te(0)),f=Nn(an(a.dependentRequired).map(([h,g])=>{let I=Kn(sa(u,Te(h))),E=Nn(g.map((S)=>sa(u,Te(S))));return Er(I,E)}));return Er(p,f)}function LR(e,o,a,u){let p=v(xe(u).length,0),f=tn(an(a.dependentRequired),0,([h,g])=>!me(u,h)||g.every((I)=>me(u,I)));return p||f}function NR(e,o,a,u,p,f){let h=v(xe(f).length,0),g=Ln(an(p.dependentRequired),0,([I,E])=>!me(f,I)||Ln(E,0,(S)=>me(f,S)||o.AddError({keyword:"dependentRequired",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})));return h||g}function qR(e,o,a,u){let p=So(Et(oa(u),"length"),Te(0)),f=Nn(an(a.dependentSchemas).map(([h,g])=>{let I=Kn(sa(u,Te(h))),E=Bt(e,o,g,u);return Er(I,E)}));return Er(p,f)}function DR(e,o,a,u){let p=v(xe(u).length,0),f=tn(an(a.dependentSchemas),0,([h,g])=>!me(u,h)||$t(e,o,g,u));return p||f}function FR(e,o,a,u,p,f){let h=v(xe(f).length,0),g=Ln(an(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 jR(e,o,a,u){let p=e.DynamicRef(a)??!1;return pi(e,o,p,u)}function UR(e,o,a,u){let p=e.DynamicRef(a)??!1;return Ze(p)&&$t(e,o,p,u)}function BR(e,o,a,u,p,f){let h=e.DynamicRef(p)??!1;return Ze(h)&&dr(e,o,"#",u,h,f)}function GR(e,o,a,u){return nd(a.enum.map((p)=>{if(ra(p))return So(u,Te(p));let f=Bo(p);return gy(u,f)}))}function wf(e,o,a,u){return Ma(a.enum,(p)=>ra(p)?v(u,p):Oa(u,p))}function KR(e,o,a,u,p,f){return wf(e,o,p,f)||o.AddError({keyword:"enum",schemaPath:a,instancePath:u,params:{allowedValues:p.enum}})}function HR(e,o,a,u){return td(u,Te(a.exclusiveMaximum))}function Tf(e,o,a,u){return Pu(u,a.exclusiveMaximum)}function WR(e,o,a,u,p,f){return Tf(e,o,p,f)||o.AddError({keyword:"exclusiveMaximum",schemaPath:a,instancePath:u,params:{comparison:"<",limit:p.exclusiveMaximum}})}function zR(e,o,a,u){return fy(u,Te(a.exclusiveMinimum))}function Rf(e,o,a,u){return ta(u,a.exclusiveMinimum)}function VR(e,o,a,u,p,f){return Rf(e,o,p,f)||o.AddError({keyword:"exclusiveMinimum",schemaPath:a,instancePath:u,params:{comparison:">",limit:p.exclusiveMinimum}})}var kD=[0,31,28,31,30,31,30,31,31,30,31,30,31],AD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function PD(e){return e%4===0&&(e%100!==0||e%400===0)}function iu(e){let o=AD.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&&PD(a)?29:kD[u])}var $D=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function au(e,o=!0){let a=$D.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 yp(e){let o=e.split(/T/i);return o.length===2&&iu(o[0])&&au(o[1])}var CD=/^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 xp(e){return CD.test(e)}var vD=/^(?:[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 Ip(e){return vD.test(e)}var JR=/^(?!-).*(?<!-)$/,QR=/^(?!..--)/,XR=/^[a-zA-Z0-9-]*$/;var uu=/[^\p{ASCII}]/u;var MD=/[0-9]/,YR=/[\u{0660}-\u{0669}]/u,OD=/[\u{06f0}-\u{06f9}]/u,_D=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,LD=/[\u{002d}\u{002b}]/u,kf=/\p{Mn}/u,ND=/\p{Mc}/u;var ZR=/[\p{Mn}\p{Mc}\p{Me}]/u,Af=/\p{L}/u,qD=/\p{Nd}/u,ek=/\p{Script=Greek}/u,Ep=/\p{Script=Hebrew}/u,tk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,rk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Pf=/[\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,nk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,DD=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,FD=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,ok=new RegExp([MD,OD].map((e)=>e.source).join("|"),"u"),sk=new RegExp([Af,LD,_D,qD,kf,ND,DD,FD].map((e)=>e.source).join("|"),"u");function ik(e){return JR.test(e)&&QR.test(e)&&XR.test(e)}var bs=36,_c=1,Lc=26,UD=38,BD=700,uk=72,ck=128;function $f(){throw null}function bp(e){return e.toLowerCase().startsWith("xn--")}function mk(e,o,a){e=a?Math.floor(e/BD):e>>1,e+=Math.floor(e/o);let u=0;while(e>(bs-_c)*Lc>>1)e=Math.floor(e/(bs-_c)),u+=bs;return u+Math.floor((bs-_c+1)*e/(e+UD))}function Sp(e){let o=[],a=ck,u=0,p=uk,f=e.lastIndexOf("-");if(f>0)for(let g=0;g<f;g++){let I=e.charCodeAt(g);if(I>=128)$f();o.push(I)}let h=f<0?0:f+1;while(h<e.length){let g=u,I=1,E=bs;while(!0){if(h>=e.length)$f();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 $f();u+=A*I;let P=E<=p?_c:E>=p+Lc?Lc:E-p;if(A<P)break;I*=bs-P,E+=bs}let S=o.length+1;p=mk(u-g,S,g===0),a+=Math.floor(u/S),u%=S,o.splice(u,0,a),u++}return String.fromCodePoint(...o)}function ak(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var GD=new RegExp(uu.source,"gu");function pk(e){let o=e.replace(GD,""),a=o.length,u=a>0?[o,"-"]:[],p=Array.from(e,(E)=>E.codePointAt(0)),f=ck,h=0,g=uk,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=bs;;A+=bs){let P=A<=g?_c:A>=g+Lc?Lc:A-g;if(k<P)break;let C=P+(k-P)%(bs-P);u.push(ak(C)),k=Math.floor((k-P)/(bs-P))}u.push(ak(k)),g=mk(h,I+1,I===a),h=0,I++}}h++,f++}return u.join("")}var KD=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,lk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,HD=/^(?:R|AL|AN)$/;function dk(e){if(bp(e))try{return wp(Sp(e.slice(4).toLowerCase()))}catch{return!1}return wp(e)}function fk(e){let o=String.fromCodePoint(e);return ok.test(o)?"EN":YR.test(o)?"AN":kf.test(o)?"NSM":Ep.test(o)?"R":rk.test(o)?"AL":Af.test(o)?"L":"ON"}function wp(e){for(let o of e)if(HD.test(fk(o.codePointAt(0))))return!0;return!1}function Tp(e){let o=!1,a=lk,u=!1,p=!1,f=!0;for(let h of e){let g=fk(h.codePointAt(0));if(f){if(g!=="L"&&g!=="R"&&g!=="AL")return!1;o=g==="R"||g==="AL",a=o?KD:lk,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 WD(e){return uu.test(e)&&pk(e).length+4>63}function zD(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Rp(e){if(WD(e))return!1;if(wp(e)&&!Tp(e))return!1;let o=[...e],a=o.map((f)=>f.codePointAt(0)),u=a.length;if(zD(o))return!1;if(ZR.test(o[0]))return!1;let p=!1;for(let f=0;f<u;f++){let h=a[f],g=o[f];if(nk.test(g))return!1;if(!sk.test(g))return!1;if(tk.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||!ek.test(o[f+1]))return!1;break;case 1523:case 1524:if(!I||!Ep.test(o[f-1]))return!1;break;case 8204:if(!I||I<128&&!Pf.test(o[f-1]))return!1;break;case 8205:if(!I||!Pf.test(o[f-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function kp(e){if(!bp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let a=Sp(o);if(!uu.test(a))return!1;return Rp(a)}catch{return!1}}function VD(e){return e.length>0&&e.length<=63}function JD(e){return VD(e)&&(kp(e)||ik(e))}function xk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>JD(o))}function QD(e){return e.length>0&&e.length<=63}function XD(e){return QD(e)&&(kp(e)||Rp(e))}function YD(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 Ik(e){if(e.length===0||e.includes(" "))return!1;let o=YD(e);if(o.length>253)return!1;let a=o.split("."),u=a.some((p)=>dk(p));return a.every((p)=>XD(p)&&(!u||Tp(p)))}function Ap(e){return xk(e)}var ZD=/^(?:[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 Pp(e){return ZD.test(e.normalize("NFC"))}function $p(e){return Ik(e)}var eF=/^(?:(?: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 Cp(e){return eF.test(e)}var tF=/^(?:(?:(?:[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 vp(e){return tF.test(e)}var rF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,nF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Mp(e){return!rF.test(e)&&!nF.test(e)&&URL.canParse(e,"http://example.com")}var oF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,sF=/[\x00-\x20<>\^`{|}\\]/,iF=/%(?![0-9a-fA-F]{2})/;function aF(e){return e.length<2048?e.replace(oF,"[::1]"):e}function Op(e){if(sF.test(e))return!1;if(iF.test(e))return!1;return URL.canParse(aF(e))}var uF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function _p(e){return uF.test(e)}var cF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Lp(e){return cF.test(e)}function Np(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var mF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function qp(e){return mF.test(e)}var pF=/^(?:[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 Dp(e){return pF.test(e)}var lF=/^(?:(?:[^\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 Fp(e){return lF.test(e)}var dF=/^[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 jp(e){return dF.test(e)}function Up(e){return URL.canParse(e)}var fF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Bp(e){return fF.test(e)}var wr=new Map;function bk(){wr.clear()}function hF(){return[...wr.entries()]}function gF(e,o){wr.set(e,o)}function yF(e){return wr.has(e)}function xF(e){return wr.get(e)}function Sk(e,o){return wr.get(e)?.(o)??!0}function wk(){bk(),wr.set("date-time",yp),wr.set("date",iu),wr.set("duration",xp),wr.set("email",Ip),wr.set("hostname",Ap),wr.set("idn-email",Pp),wr.set("idn-hostname",$p),wr.set("ipv4",Cp),wr.set("ipv6",vp),wr.set("iri-reference",Mp),wr.set("iri",Op),wr.set("json-pointer-uri-fragment",_p),wr.set("json-pointer",Lp),wr.set("regex",Np),wr.set("relative-json-pointer",qp),wr.set("time",au),wr.set("uri-reference",Dp),wr.set("uri-template",Fp),wr.set("uri",jp),wr.set("url",Up),wr.set("uuid",Bp)}wk();function Tk(e,o,a,u){return br(Et("Format","Test"),[Te(a.format),u])}function vf(e,o,a,u){return Sk(a.format,u)}function Rk(e,o,a,u,p,f){return vf(e,o,p,f)||o.AddError({keyword:"format",schemaPath:a,instancePath:u,params:{format:p.format}})}function kk(e,o,a,u){let p=vc(a)?a.then:!0,f=yc(a)?a.else:!0;return gM(Bt(e,o,a.if,u),Bt(e,o,p,u),Bt(e,o,f,u))}function Ak(e,o,a,u){let p=vc(a)?a.then:!0,f=yc(a)?a.else:!0;return $t(e,o,a.if,u)?$t(e,o,p,u):$t(e,o,f,u)}function Pk(e,o,a,u,p,f){let h=vc(p)?p.then:!0,g=yc(p)?p.else:!0,I=new Bn,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 IF(e,o,a,u){return Nn(a.items.map((p,f)=>{let h=na(Et(u,"length"),Te(f)),g=Qn(e,o,p,`${u}[${f}]`),I=o.AddIndex(Te(f));return Er(h,$n(g,I))}))}function EF(e,o,a,u){return Nn(a.items.map((p,f)=>{let h=na(Et(u,"length"),Te(f)),g=Qn(e,o,p,`${u}[${f}]`);return Er(h,g)}))}function bF(e,o,a,u){return o.UseUnevaluated()?IF(e,o,a,u):EF(e,o,a,u)}function SF(e,o,a,u){return tn(a.items,0,(p,f)=>$s(u.length,f)||_o(e,o,p,u[f])&&o.AddIndex(f))}function wF(e,o,a,u,p,f){return Ln(p.items,0,(h,g)=>{let I=`${a}/items/${g}`,E=`${u}/${g}`;return $s(f.length,g)||Lo(e,o,I,E,h,f[g])&&o.AddIndex(g)})}function TF(e,o,a,u){let p=ys(a)?a.prefixItems.length:0,f=Qn(e,o,a.items,"element"),h=o.AddIndex("index");return Cs(u,Te(p),["element","index"],$n(f,h))}function RF(e,o,a,u){let p=ys(a)?a.prefixItems.length:0,f=Qn(e,o,a.items,"element");return Cs(u,Te(p),["element","index"],f)}function kF(e,o,a,u){return o.UseUnevaluated()?TF(e,o,a,u):RF(e,o,a,u)}function AF(e,o,a,u){let p=ys(a)?a.prefixItems.length:0;return tn(u,p,(f,h)=>_o(e,o,a.items,f)&&o.AddIndex(h))}function PF(e,o,a,u,p,f){let h=ys(p)?p.prefixItems.length:0;return Ln(f,h,(g,I)=>{let E=`${a}/items`,S=`${u}/${I}`;return Lo(e,o,E,S,p.items,g)&&o.AddIndex(I)})}function $k(e,o,a,u){return Ec(a)?bF(e,o,a,u):kF(e,o,a,u)}function Ck(e,o,a,u){return Ec(a)?SF(e,o,a,u):AF(e,o,a,u)}function vk(e,o,a,u,p,f){return Ec(p)?wF(e,o,a,u,p,f):PF(e,o,a,u,p,f)}function Mk(e){return Ks(e)}function Ok(e,o,a,u){if(!Mk(a))return Te(!0);let[p]=[ir()],f=nm(u,[p,"_"],Bt(e,o,a.contains,p));return na(f,Te(a.maxContains))}function Mf(e,o,a,u){if(!Mk(a))return!0;let p=Xl(u,(f)=>$t(e,o,a.contains,f));return $s(p,a.maxContains)}function _k(e,o,a,u,p,f){let h=ui(p)?p.minContains:1;return Mf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:h,maxContains:p.maxContains}})}function Lk(e,o,a,u){return na(u,Te(a.maximum))}function Of(e,o,a,u){return $s(u,a.maximum)}function Nk(e,o,a,u,p,f){return Of(e,o,p,f)||o.AddError({keyword:"maximum",schemaPath:a,instancePath:u,params:{comparison:"<=",limit:p.maximum}})}function qk(e,o,a,u){return na(Et(u,"length"),Te(a.maxItems))}function _f(e,o,a,u){return $s(u.length,a.maxItems)}function Dk(e,o,a,u,p,f){return _f(e,o,p,f)||o.AddError({keyword:"maxItems",schemaPath:a,instancePath:u,params:{limit:p.maxItems}})}function Fk(e,o,a,u){return lM(u,Te(a.maxLength))}function Lf(e,o,a,u){return sy(u,a.maxLength)}function jk(e,o,a,u,p,f){return Lf(e,o,p,f)||o.AddError({keyword:"maxLength",schemaPath:a,instancePath:u,params:{limit:p.maxLength}})}function Uk(e,o,a,u){return na(Et(oa(u),"length"),Te(a.maxProperties))}function Nf(e,o,a,u){return $s(xe(u).length,a.maxProperties)}function Bk(e,o,a,u,p,f){return Nf(e,o,p,f)||o.AddError({keyword:"maxProperties",schemaPath:a,instancePath:u,params:{limit:p.maxProperties}})}function Gk(e){return Ks(e)}function $F(e,o,a,u){let[p,f]=[ir(),ir()],h=nm(u,[p,f],$n(Bt(e,o,a.contains,p),o.AddIndex(f)));return Cu(h,Te(a.minContains))}function CF(e,o,a,u){let[p]=[ir()],f=nm(u,[p,"_"],Bt(e,o,a.contains,p));return Cu(f,Te(a.minContains))}function Kk(e,o,a,u){if(!Gk(a))return Te(!0);return o.UseUnevaluated()?$F(e,o,a,u):CF(e,o,a,u)}function qf(e,o,a,u){if(!Gk(a))return!0;let p=Xl(u,(f,h)=>$t(e,o,a.contains,f)&&o.AddIndex(h));return va(p,a.minContains)}function Hk(e,o,a,u,p,f){return qf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:p.minContains}})}function Wk(e,o,a,u){return Cu(u,Te(a.minimum))}function Df(e,o,a,u){return va(u,a.minimum)}function zk(e,o,a,u,p,f){return Df(e,o,p,f)||o.AddError({keyword:"minimum",schemaPath:a,instancePath:u,params:{comparison:">=",limit:p.minimum}})}function Vk(e,o,a,u){return Cu(Et(u,"length"),Te(a.minItems))}function Ff(e,o,a,u){return va(u.length,a.minItems)}function Jk(e,o,a,u,p,f){return Ff(e,o,p,f)||o.AddError({keyword:"minItems",schemaPath:a,instancePath:u,params:{limit:p.minItems}})}function Qk(e,o,a,u){return pM(u,Te(a.minLength))}function jf(e,o,a,u){return iy(u,a.minLength)}function Xk(e,o,a,u,p,f){return jf(e,o,p,f)||o.AddError({keyword:"minLength",schemaPath:a,instancePath:u,params:{limit:p.minLength}})}function Yk(e,o,a,u){return Cu(Et(oa(u),"length"),Te(a.minProperties))}function Uf(e,o,a,u){return va(xe(u).length,a.minProperties)}function Zk(e,o,a,u,p,f){return Uf(e,o,p,f)||o.AddError({keyword:"minProperties",schemaPath:a,instancePath:u,params:{limit:p.minProperties}})}function eA(e,o,a,u){return yM(u,Te(a.multipleOf))}function Bf(e,o,a,u){return ny(u,a.multipleOf)}function tA(e,o,a,u,p,f){return Bf(e,o,p,f)||o.AddError({keyword:"multipleOf",schemaPath:a,instancePath:u,params:{multipleOf:p.multipleOf}})}function vF(e,o,a,u){return Hi(e,o,[a.not],u,Kn(So(Et("results","length"),Te(1))))}function MF(e,o,a,u){return Kn(Bt(e,o,a.not,u))}function rA(e,o,a,u){return o.UseUnevaluated()?vF(e,o,a,u):MF(e,o,a,u)}function Gf(e,o,a,u){let p=new Un;return!$t(e,p,a.not,u)&&o.Merge([p])}function nA(e,o,a,u,p,f){return Gf(e,o,p,f)||o.AddError({keyword:"not",schemaPath:a,instancePath:u,params:{}})}function OF(e,o,a,u){return Hi(e,o,a.oneOf,u,So(Et("results","length"),Te(1)))}function _F(e,o,a,u){let[p]=[ir()],f=hM(a.oneOf.map((g)=>Bt(e,o,g,u))),h=nm(f,[p,"_"],So(p,Te(!0)));return So(h,Te(1))}function oA(e,o,a,u){return o.UseUnevaluated()?OF(e,o,a,u):_F(e,o,a,u)}function sA(e,o,a,u){let p=a.oneOf.reduce((f,h)=>{let g=new Un;return $t(e,g,h,u)?[...f,g]:f},[]);return v(p.length,1)&&o.Merge(p)}function iA(e,o,a,u,p,f){let h=[],g=[],I=p.oneOf.reduce((S,k,A)=>{let P=new Bn,C=`${a}/oneOf/${A}`,M=dr(e,P,C,u,k,f);if(M)g.push(A);if(!M)h.push(P);return M?[...S,P]:S},[]),E=v(I.length,1)&&o.Merge(I);if(!E&&v(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 aA(e,o,a,u){let p=Bo(ht(a.pattern)?Es(a.pattern):a.pattern);return br(Et(p,"test"),[u])}function Kf(e,o,a,u){return(ht(a.pattern)?Es(a.pattern):a.pattern).test(u)}function uA(e,o,a,u,p,f){return Kf(e,o,p,f)||o.AddError({keyword:"pattern",schemaPath:a,instancePath:u,params:{pattern:p.pattern}})}function cA(e,o,a,u){return Nn(an(a.patternProperties).map(([p,f])=>{let[h,g]=[ir(),ir()],I=Bo(Es(p)),E=Kn(br(Et(I,"test"),[h])),S=Qn(e,o,f,g),k=o.AddKey(h),A=o.UseUnevaluated()?Er(E,$n(S,k)):Er(E,S);return Cs(hy(u),Te(0),[`[${h}, ${g}]`,"_"],A)}))}function mA(e,o,a,u){return tn(an(a.patternProperties),0,([p,f])=>{let h=Es(p);return tn(an(u),0,([g,I])=>!h.test(g)||_o(e,o,f,I)&&o.AddKey(g))})}function pA(e,o,a,u,p,f){return Ln(an(p.patternProperties),0,([h,g])=>{let I=`${a}/patternProperties/${h}`,E=Es(h);return Ln(an(f),0,([S,k])=>{let A=`${u}/${S}`;return!E.test(S)||Lo(e,o,I,A,g,k)&&o.AddKey(S)})})}function lA(e,o,a,u){return Nn(a.prefixItems.map((p,f)=>{let h=na(Et(u,"length"),Te(f)),g=Qn(e,o,p,`${u}[${f}]`),I=o.AddIndex(Te(f)),E=o.UseUnevaluated()?$n(g,I):g;return Er(h,E)}))}function dA(e,o,a,u){return v(u.length,0)||tn(a.prefixItems,0,(p,f)=>$s(u.length,f)||_o(e,o,p,u[f])&&o.AddIndex(f))}function fA(e,o,a,u,p,f){return v(f.length,0)||Ln(p.prefixItems,0,(h,g)=>{let I=`${a}/prefixItems/${g}`,E=`${u}/${g}`;return $s(f.length,g)||Lo(e,o,I,E,h,f[g])&&o.AddIndex(g)})}function Gp(e,o){return e.includes(o)||rs().exactOptionalPropertyTypes}function hA(e,o){return ed(Et(e,o))}function Hf(e,o){return rr(e[o])}function gA(e,o,a,u){let p=Is(a)?a.required:[],f=an(a.properties).map(([h,g])=>{let I=Kn(sa(u,Te(h))),E=Qn(e,o,g,Et(u,h)),S=o.AddKey(Te(h)),k=o.UseUnevaluated()?$n(E,S):E,A=p.includes(h)?k:Er(I,k);return Gp(p,h)?A:Er(hA(u,h),A)});return Nn(f)}function yA(e,o,a,u){let p=Is(a)?a.required:[];return tn(an(a.properties),0,([h,g])=>{let I=!me(u,h)||_o(e,o,g,u[h])&&o.AddKey(h);return Gp(p,h)?I:Hf(u,h)||I})}function xA(e,o,a,u,p,f){let h=Is(p)?p.required:[];return Ln(an(p.properties),0,([I,E])=>{let S=`${a}/properties/${I}`,k=`${u}/${I}`,A=()=>!me(f,I)||Lo(e,o,S,k,E,f[I])&&o.AddKey(I);return Gp(h,I)?A():Hf(f,I)||A()})}function IA(e,o,a,u){let[p,f]=[ir(),ir()];return Cs(oa(u),Te(0),[p,f],Bt(e,o,a.propertyNames,p))}function EA(e,o,a,u){return tn(xe(u),0,(p,f)=>$t(e,o,a.propertyNames,p))}function bA(e,o,a,u,p,f){let h=[];return Ln(xe(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 SA(e,o,a,u){let p=e.RecursiveRef(a)??!1;return pi(e,o,p,u)}function wA(e,o,a,u){let p=e.RecursiveRef(a)??!1;return Ze(p)&&$t(e,o,p,u)}function TA(e,o,a,u,p,f){let h=e.RecursiveRef(p)??!1;return Ze(h)&&dr(e,o,"#",u,h,f)}function LF(e,o,a,u){let p=Ii(["context","value"],pi(e,o,a,"value")),f=Ii(["context","value"],om([Qs("nextContext",rd("CheckContext",[])),Qs("result",br(p,["nextContext","value"])),yy("result",o.Merge("[nextContext]")),sm("result")]));return br(f,["context",u])}function NF(e,o,a,u){return pi(e,o,a,u)}function RA(e,o,a,u){let p=e.Ref(a)??!1;return o.UseUnevaluated()?LF(e,o,p,u):NF(e,o,p,u)}function kA(e,o,a,u){let p=e.Ref(a)??!1,f=new Un,h=Ze(p)&&$t(e,f,p,u);if(h)o.Merge([f]);return h}function AA(e,o,a,u,p,f){let h=e.Ref(p)??!1,g=new Bn,I=Ze(h)&&dr(e,g,"#",u,h,f);if(I)o.Merge([g]);if(!I)g.GetErrors().forEach((E)=>o.AddError(E));return I}function PA(e,o,a,u){return Nn(a.required.map((p)=>sa(u,Te(p))))}function $A(e,o,a,u){return tn(a.required,0,(p)=>me(u,p))}function CA(e,o,a,u,p,f){let h=[];return Ln(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 vA(e,o,a,u){return v(a,"object")?py(u):v(a,"array")?rm(u):v(a,"boolean")?sM(u):v(a,"integer")?iM(u):v(a,"number")?my(u):v(a,"null")?aM(u):v(a,"string")?dy(u):v(a,"bigint")?cy(u):v(a,"constructor")?mM(u):v(a,"function")?cM(u):v(a,"symbol")?uM(u):v(a,"undefined")?ed(u):v(a,"void")?ed(u):Te(!0)}function Wf(e,o,a,u,p){return v(a,"object")?Yo(p):v(a,"array")?$e(p):v(a,"boolean")?sn(p):v(a,"integer")?tm(p):v(a,"number")?Ft(p):v(a,"null")?Po(p):v(a,"string")?ht(p):v(a,"bigint")?Ur(p):v(a,"constructor")?Jl(p):v(a,"function")?Ps(p):v(a,"symbol")?Ql(p):v(a,"undefined")?rr(p):v(a,"void")?rr(p):!0}function qF(e,o,a,u){return nd(a.map((p)=>vA(e,o,p,u)))}function MA(e,o,a,u,p){return Ma(a,(f)=>Wf(e,o,f,u,p))}function OA(e,o,a,u){return $e(a.type)?qF(e,o,a.type,u):vA(e,o,a.type,u)}function _A(e,o,a,u){return $e(a.type)?MA(e,o,a.type,a,u):Wf(e,o,a.type,a,u)}function LA(e,o,a,u,p,f){return($e(p.type)?MA(e,o,p.type,p,f):Wf(e,o,p.type,p,f))||o.AddError({keyword:"type",schemaPath:a,instancePath:u,params:{type:p.type}})}function NA(e,o,a,u){let[p,f]=[ir(),ir()],h=br(Et("context","GetIndices"),[]),g=br(Et("indices","has"),[p]),I=Bt(e,o,a.unevaluatedItems,f),E=br(Et("context","AddIndex"),[p]),S=Cs(u,Te(0),[f,p],$n(Er(g,I),E));return br(Ii(["context"],om([Qs("indices",h),sm(S)])),["context"])}function qA(e,o,a,u){let p=o.GetIndices();return tn(u,0,(f,h)=>(p.has(h)||$t(e,o,a.unevaluatedItems,f))&&o.AddIndex(h))}function DA(e,o,a,u,p,f){let h=o.GetIndices(),g=[];return Ln(f,0,(E,S)=>{let k=new Bn,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 FA(e,o,a,u){let[p,f]=[ir(),ir()],h=br(Et("context","GetKeys"),[]),g=br(Et("keys","has"),[p]),I=br(Et("context","AddKey"),[p]),E=Bt(e,o,a.unevaluatedProperties,f),S=Cs(hy(u),Te(0),[`[${p}, ${f}]`,"_"],Er(g,$n(E,I)));return br(Ii(["context"],om([Qs("keys",h),sm(S)])),["context"])}function jA(e,o,a,u){let p=o.GetKeys();return tn(an(u),0,([f,h])=>p.has(f)||$t(e,o,a.unevaluatedProperties,h)&&o.AddKey(f))}function UA(e,o,a,u,p,f){let h=o.GetKeys(),g=[];return Ln(an(f),0,([E,S])=>{let k=new Bn,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 zf(e){return!v(e.uniqueItems,!1)}function BA(e,o,a,u){if(!zf(a))return Te(!0);let p=Et(rd("Set",[br(Et(u,"map"),[Et("Hashing","Hash")])]),"size"),f=Et(u,"length");return So(p,f)}function GA(e,o,a,u){if(!zf(a))return!0;let p=new Set(u.map(id)).size,f=u.length;return v(p,f)}function KA(e,o,a,u,p,f){if(!zf(p))return!0;let h=new Set,g=f.reduce((E,S,k)=>{let A=id(S);if(h.has(A))return[...E,k];return h.add(A),E},[]);return v(g.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:a,instancePath:u,params:{duplicateItems:g}})}function Nc(e,o){return Mc(e)&&($e(e.type)&&ta(e.type.length,0)&&tn(e.type,0,(a)=>v(a,o))||v(e.type,o))}function DF(e){return Nc(e,"object")}function FF(e){return bn(e)&&(Uo(e)||fc(e)||hc(e)||ru(e)||mi(e)||ci(e)||ou(e)||wa(e)||Tc(e)||Is(e)||Ki(e))}function jF(e){return Nc(e,"array")}function UF(e){return bn(e)&&(tu(e)||ai(e)||Ks(e)||Sc(e)||nu(e)||ui(e)||_i(e)||ys(e)||Ni(e)||Li(e))}function BF(e){return Nc(e,"string")}function GF(e){return bn(e)&&(Sa(e)||wc(e)||ba(e)||Ta(e))}function KF(e){return Nc(e,"number")||Nc(e,"bigint")}function HF(e){return bn(e)&&(gs(e)||bc(e)||xc(e)||hs(e)||Rc(e))}function Qn(e,o,a,u){return o.UseUnevaluated()?$n($n(o.Push(),Bt(e,o,a,u)),o.Pop()):Bt(e,o,a,u)}function Bt(e,o,a,u){e.Push(a);let p=[];if(Zs(a))return TR(e,o,a,u);if(Mc(a))p.push(OA(e,o,a,u));if(FF(a)){let h=[];if(Is(a))h.push(PA(e,o,a,u));if(Uo(a))h.push(hR(e,o,a,u));if(fc(a))h.push(vR(e,o,a,u));if(hc(a))h.push(_R(e,o,a,u));if(ru(a))h.push(qR(e,o,a,u));if(ci(a))h.push(cA(e,o,a,u));if(mi(a))h.push(gA(e,o,a,u));if(ou(a))h.push(IA(e,o,a,u));if(wa(a))h.push(Yk(e,o,a,u));if(Tc(a))h.push(Uk(e,o,a,u));let g=Nn(h),I=Er(Kn(py(u)),g);p.push(DF(a)?g:I)}if(UF(a)){let h=[];if(tu(a))h.push(lR(e,o,a,u));if(Ks(a))h.push($R(e,o,a,u));if(ai(a))h.push($k(e,o,a,u));if(Sc(a))h.push(Ok(e,o,a,u));if(nu(a))h.push(qk(e,o,a,u));if(ui(a))h.push(Kk(e,o,a,u));if(_i(a))h.push(Vk(e,o,a,u));if(ys(a))h.push(lA(e,o,a,u));if(Li(a))h.push(BA(e,o,a,u));let g=Nn(h),I=Er(Kn(rm(u)),g);p.push(jF(a)?g:I)}if(GF(a)){let h=[];if(wc(a))h.push(Fk(e,o,a,u));if(Sa(a))h.push(Qk(e,o,a,u));if(ba(a))h.push(Tk(e,o,a,u));if(Ta(a))h.push(aA(e,o,a,u));let g=Nn(h),I=Er(Kn(dy(u)),g);p.push(BF(a)?g:I)}if(HF(a)){let h=[];if(xc(a))h.push(HR(e,o,a,u));if(hs(a))h.push(zR(e,o,a,u));if(bc(a))h.push(Lk(e,o,a,u));if(gs(a))h.push(Wk(e,o,a,u));if(Rc(a))h.push(eA(e,o,a,u));let g=Nn(h),I=Er(Kn(Er(my(u),cy(u))),g);p.push(KF(a)?g:I)}if(Cc(a))p.push(RA(e,o,a,u));if($c(a))p.push(SA(e,o,a,u));if(gc(a))p.push(jR(e,o,a,u));if(dp(a))p.push(kR(e,o,a,u));if(fp(a))p.push(GR(e,o,a,u));if(Ic(a))p.push(kk(e,o,a,u));if(kc(a))p.push(rA(e,o,a,u));if(pc(a))p.push(xR(e,o,a,u));if(dc(a))p.push(bR(e,o,a,u));if(Ac(a))p.push(oA(e,o,a,u));if(Ni(a))p.push(Er(Kn(rm(u)),NA(e,o,a,u)));if(Ki(a))p.push(Er(Kn(ly(u)),FA(e,o,a,u)));if(mc(a))p.push(cR(e,o,a,u));let f=Nn(p);return e.Pop(a),f}function _o(e,o,a,u){return o.Push()&&$t(e,o,a,u)&&o.Pop()}function $t(e,o,a,u){e.Push(a);let p=Zs(a)?If(e,o,a,u):(!Mc(a)||_A(e,o,a,u))&&(!(mt(u)&&!$e(u))||(!Is(a)||$A(e,o,a,u))&&(!Uo(a)||gR(e,o,a,u))&&(!fc(a)||MR(e,o,a,u))&&(!hc(a)||LR(e,o,a,u))&&(!ru(a)||DR(e,o,a,u))&&(!ci(a)||mA(e,o,a,u))&&(!mi(a)||yA(e,o,a,u))&&(!ou(a)||EA(e,o,a,u))&&(!wa(a)||Uf(e,o,a,u))&&(!Tc(a)||Nf(e,o,a,u)))&&(!$e(u)||(!tu(a)||dR(e,o,a,u))&&(!Ks(a)||bf(e,o,a,u))&&(!ai(a)||Ck(e,o,a,u))&&(!Sc(a)||Mf(e,o,a,u))&&(!nu(a)||_f(e,o,a,u))&&(!ui(a)||qf(e,o,a,u))&&(!_i(a)||Ff(e,o,a,u))&&(!ys(a)||dA(e,o,a,u))&&(!Li(a)||GA(e,o,a,u)))&&(!ht(u)||(!wc(a)||Lf(e,o,a,u))&&(!Sa(a)||jf(e,o,a,u))&&(!ba(a)||vf(e,o,a,u))&&(!Ta(a)||Kf(e,o,a,u)))&&(!(Ft(u)||Ur(u))||(!xc(a)||Tf(e,o,a,u))&&(!hs(a)||Rf(e,o,a,u))&&(!bc(a)||Of(e,o,a,u))&&(!gs(a)||Df(e,o,a,u))&&(!Rc(a)||Bf(e,o,a,u)))&&(!Cc(a)||kA(e,o,a,u))&&(!$c(a)||wA(e,o,a,u))&&(!gc(a)||UR(e,o,a,u))&&(!dp(a)||Ef(e,o,a,u))&&(!fp(a)||wf(e,o,a,u))&&(!Ic(a)||Ak(e,o,a,u))&&(!kc(a)||Gf(e,o,a,u))&&(!pc(a)||IR(e,o,a,u))&&(!dc(a)||SR(e,o,a,u))&&(!Ac(a)||sA(e,o,a,u))&&(!Ni(a)||(!$e(u)||qA(e,o,a,u)))&&(!Ki(a)||(!mt(u)||jA(e,o,a,u)))&&(!mc(a)||mR(e,o,a,u));return e.Pop(a),p}function Lo(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=Zs(p)?RR(e,o,a,u,p,f):!!(+(!Mc(p)||LA(e,o,a,u,p,f))&+(!(mt(f)&&!$e(f))||!!(+(!Is(p)||CA(e,o,a,u,p,f))&+(!Uo(p)||yR(e,o,a,u,p,f))&+(!fc(p)||OR(e,o,a,u,p,f))&+(!hc(p)||NR(e,o,a,u,p,f))&+(!ru(p)||FR(e,o,a,u,p,f))&+(!ci(p)||pA(e,o,a,u,p,f))&+(!mi(p)||xA(e,o,a,u,p,f))&+(!ou(p)||bA(e,o,a,u,p,f))&+(!wa(p)||Zk(e,o,a,u,p,f))&+(!Tc(p)||Bk(e,o,a,u,p,f))))&+(!$e(f)||!!(+(!tu(p)||fR(e,o,a,u,p,f))&+(!Ks(p)||CR(e,o,a,u,p,f))&+(!ai(p)||vk(e,o,a,u,p,f))&+(!Sc(p)||_k(e,o,a,u,p,f))&+(!nu(p)||Dk(e,o,a,u,p,f))&+(!ui(p)||Hk(e,o,a,u,p,f))&+(!_i(p)||Jk(e,o,a,u,p,f))&+(!ys(p)||fA(e,o,a,u,p,f))&+(!Li(p)||KA(e,o,a,u,p,f))))&+(!ht(f)||!!(+(!wc(p)||jk(e,o,a,u,p,f))&+(!Sa(p)||Xk(e,o,a,u,p,f))&+(!ba(p)||Rk(e,o,a,u,p,f))&+(!Ta(p)||uA(e,o,a,u,p,f))))&+(!(Ft(f)||Ur(f))||!!(+(!xc(p)||WR(e,o,a,u,p,f))&+(!hs(p)||VR(e,o,a,u,p,f))&+(!bc(p)||Nk(e,o,a,u,p,f))&+(!gs(p)||zk(e,o,a,u,p,f))&+(!Rc(p)||tA(e,o,a,u,p,f))))&+(!Cc(p)||AA(e,o,a,u,p,f))&+(!$c(p)||TA(e,o,a,u,p,f))&+(!gc(p)||BR(e,o,a,u,p,f))&+(!dp(p)||AR(e,o,a,u,p,f))&+(!fp(p)||KR(e,o,a,u,p,f))&+(!Ic(p)||Pk(e,o,a,u,p,f))&+(!kc(p)||nA(e,o,a,u,p,f))&+(!pc(p)||ER(e,o,a,u,p,f))&+(!dc(p)||wR(e,o,a,u,p,f))&+(!Ac(p)||iA(e,o,a,u,p,f))&+(!Ni(p)||(!$e(f)||DA(e,o,a,u,p,f)))&+(!Ki(p)||(!mt(f)||UA(e,o,a,u,p,f))))&&(!mc(p)||pR(e,o,a,u,p,f));return e.Pop(p),h}var HA=[0],Kp=new Map,qc=new Map;function WF(){return`${HA[0]++}`}function zF(e,o){if(!Kp.has(e))Kp.set(e,new Map);let a=Kp.get(e);if(a.has(o))return a.get(o);let u=WF();return a.set(o,u),u}function VF(e,o,a,u){return e.UseUnevaluated()?br(`check_${a}`,["context",u]):br(`check_${a}`,[u])}function JF(e,o,a,u){let p=Bt(e,o,a,"value");return o.UseUnevaluated()?Qs(`check_${u}`,Ii(["context","value"],p)):Qs(`check_${u}`,Ii(["value"],p))}function WA(){HA[0]=0,Kp.clear(),qc.clear()}function zA(){return[...qc.values()]}function pi(e,o,a,u){let p=zF(a,e.LexicalBaseURL()),f=VF(o,a,p,u);if(qc.has(p))return f;return qc.set(p,""),qc.set(p,JF(e,o,a,p)),f}function QF(e,o){return mt(o)&&!$u(e)?o[e]:void 0}function XF(e,o){return e.reduce((a,u)=>QF(u,a),o)}function YF(e){if(v(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 ZF(e,o){let a=YF(o);return XF(a,e)}var Wp="https://json-schema.org";function JA(e,o){if(mt(e)&&ti(e)&&v(e.$dynamicAnchor,o))return e;if(mt(e))for(let a of xe(e)){let u=JA(e[a],o);if(u)return u}return}function Vf(e,o,a){if(v(e,a))return o.href;let u=bn(e)&&Oo(e)?new URL(e.$id,o.href):o;if($e(e))for(let p of e){let f=Vf(p,u,a);if(!rr(f))return f}else if(mt(e))for(let p of xe(e)){let f=Vf(e[p],u,a);if(!rr(f))return f}return}function e1(e,o,a){if(v(e.$id,a.hash))return e;let u=new URL(a.href,o.href);if(v(o.pathname,u.pathname))return a.hash.startsWith("#")?QA(e,a):e;return}function t1(e,o,a){let u=new URL(`#${e.$anchor}`,o.href),p=new URL(a.href,o.href);return v(u.href,p.href)?e:void 0}function r1(e,o,a){let u=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(a.href,o.href);return v(u.href,p.href)?e:void 0}function QA(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 ZF(e,a)}function n1(e,o,a){if(Oo(e)){let u=e1(e,o,a);if(!rr(u))return u}if(lc(e)){let u=t1(e,o,a);if(!rr(u))return u}if(ti(e)){let u=r1(e,o,a);if(!rr(u))return u}return QA(e,a)}function o1(e,o,a){return e.reduce((u,p)=>{let f=zp(p,o,a);return!rr(f)?f:u},void 0)}function s1(e){return v(e,"const")||v(e,"enum")}function i1(e,o,a){return xe(e).reduce((u,p)=>{if(s1(p))return u;let f=zp(e[p],o,a);return!rr(f)?f:u},void 0)}function zp(e,o,a){let u=bn(e)&&Oo(e)?new URL(e.$id,o.href):o;if(bn(e)){let p=n1(e,u,a);if(!rr(p))return p}if($e(e))return o1(e,u,a);if(mt(e))return i1(e,u,a);return}function a1(e,o,a){return Vf(e,new URL(o||".",Wp),a)}function u1(e,o,a,u){let p=Vp(e,o,a,u,!1);return bn(p)&&Oo(p)?p:void 0}function VA(e){return e.href.split("#")[0]}function c1(e,o){return me(e,o)?e[o]:void 0}function m1(e,o,a){return zp(e,o,a)}function p1(e,o,a){let u=VA(a);if(v(u,VA(o)))return;if(!me(e,u))return;let p=e[u],f=bn(p)&&Oo(p)?new URL(p.$id,u):new URL(u);return v(a.hash,"")?p:zp(p,f,a)}function l1(e,o,a,u,p){if(!u.$ref.startsWith("#"))return;if(me(e,"$schema"))return;let f=a1(o,a,p);if(rr(f)||v(f,a))return;return{target:p,base:f,root:o}}function d1(e,o,a){let u=e[o];if(!bn(u))return;return{target:a,base:o,root:u}}function f1(e,o,a,u,p){let f=p?d1(e.context,u,a):void 0;if(!rr(f))return f;return l1(e.root,e.lexicalSchema,e.referenceBase,o,a)}function h1(e,o,a,u,p,f){if(Oo(p))return;let h=u1(e,o,a,u);if(!h||f.includes(h))return;return{target:p,resource:h}}function Vp(e,o,a,u,p=!0){let f=new URL(a||".",Wp),h=p&&Oo(o)?new URL(o.$id,f):f,g=new URL(u,h.href);return c1(e,u)??m1(o,h,g)??p1(e,h,g)}function g1(e,o,a,u,p,f){let h=new URL(a||".",Wp),g=p.$dynamicRef.startsWith("#")?u:o,I=Vp(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((C)=>v(C.$dynamicAnchor,A))??JA(o,A)}return}if(!bn(I)||!ti(I))return I;if(new URL(p.$dynamicRef,h).hash.startsWith("#/"))return I;return f.find((k)=>v(k.$dynamicAnchor,I.$dynamicAnchor))??I}function y1(e,o){let a=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:a,p=Vp(e.context,u,e.referenceBase,o.$ref,!1);if(!p||!bn(p))return{schema:p};let f=new URL(o.$ref,e.referenceBase).href.split("#")[0],h=!v(f,e.resourceBase),g=f1(e,o,p,f,h),I=h?h1(e.context,e.root,e.referenceBase,f,p,e.ids):void 0;return{schema:p,retrievedResource:g,resolvedResource:I}}function x1(e,o){let a=Pc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Vp(e.context,a,e.lexicalBase,o.$recursiveRef,!1)}function I1(e,o){return g1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var Fr=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)},Rr,Qp,rP,Yf,Jp,XA,YA,ZA,eP,Qf,Xf,Zf,eh,tP,nP;class Vi{constructor(e,o){Rr.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 Fr(this,Rr,"m",Yf).call(this,this.ids)}Push(e){if(!bn(e))return;if(Oo(e))Fr(this,Rr,"m",Zf).call(this,e);if(lc(e))this.anchors.push(e);if(Pc(e))this.recursiveAnchors.push(e);if(ti(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(!bn(e))return;if(Oo(e))Fr(this,Rr,"m",eh).call(this,e);if(lc(e))this.anchors.pop();if(Pc(e))this.recursiveAnchors.pop();if(ti(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Fr(this,Rr,"m",nP).call(this,e)}Ref(e){let o=y1(Fr(this,Rr,"m",Qp).call(this),e);return Fr(this,Rr,"m",rP).call(this,o),o.schema}RecursiveRef(e){let o=x1(Fr(this,Rr,"m",Qp).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=I1(Fr(this,Rr,"m",Qp).call(this),e);if(o)this.pendingResource=!0;return o}}Rr=new WeakSet,Qp=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Fr(this,Rr,"m",YA).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Fr(this,Rr,"m",XA).call(this),resourceBase:Fr(this,Rr,"m",Jp).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},rP=function(o){if(!rr(o.schema))this.pendingResource=!0;if(!rr(o.resolvedResource))Fr(this,Rr,"m",tP).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})},Yf=function(o){let a=this.retrievedFrames[this.retrievedFrames.length-1],u=a?new URL(a.base):new URL(Wp);return(a?o.slice(a.idDepth):o).reduce((f,h)=>new URL(h.$id,f),u).href},Jp=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return Fr(this,Rr,"m",Yf).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((a,u)=>new URL(u.$id,a),new URL(o.base)).href},XA=function(){if(this.retrievedFrames.length>0)return Fr(this,Rr,"m",Jp).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 Fr(this,Rr,"m",Jp).call(this)},YA=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},ZA=function(o){o.forEach((a)=>Fr(this,Rr,"m",Qf).call(this,a,!1))},eP=function(o){o.forEach((a)=>Fr(this,Rr,"m",Xf).call(this,a,!1))},Qf=function e(o,a=!0){if(Zs(o))return;if($e(o))return Fr(this,Rr,"m",ZA).call(this,o);if(!bn(o))return;let u=o;if(!a&&Oo(u))return;if(!a&&ti(u))this.dynamicAnchors.push(u);for(let p of xe(u))Fr(this,Rr,"m",e).call(this,u[p],!1)},Xf=function e(o,a=!0){if(Zs(o))return;if($e(o))return Fr(this,Rr,"m",eP).call(this,o);if(!bn(o))return;let u=o;if(!a&&Oo(u))return;if(!a&&ti(u))this.dynamicAnchors.pop();for(let p of xe(u))Fr(this,Rr,"m",e).call(this,u[p],!1)},Zf=function(o){this.ids.push(o);let a=this.pendingResource;if(this.pendingResource=!1,a)this.resourceIds.push(o);Fr(this,Rr,"m",Qf).call(this,o,!0)},eh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&v(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();Fr(this,Rr,"m",Xf).call(this,o,!0)},tP=function(o,a){Fr(this,Rr,"m",Zf).call(this,a),this.resolvedResources.set(o,a)},nP=function(o){if(!this.resolvedResources.has(o))return;let a=this.resolvedResources.get(o);Fr(this,Rr,"m",eh).call(this,a),this.resolvedResources.delete(o)};function E1(e){let o=e.Functions().join(`;
|
|
21
|
-
`),a=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${a.join("; ")} }`}function b1(e,o){return Ly("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Un,O,cu,ca,e.External().variables)}function S1(e){let o=new Vi(e.Context(),e.Schema()),a=new Un;return(u)=>$t(o,a,e.Schema(),u)}function w1(e,o){return _y()?b1(e,o):S1(e)}class oP{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 sP{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=E1(this),o=w1(this,e);return new oP(_y(),e,o)}}function Xp(...e){let[o,a]=Cn(e,{2:(I,E)=>[I,E],1:(I)=>[{},I]});aR(),WA();let u=new Vi(o,a),p=new gf(iR(o,a)),f=pi(u,p,a,"value"),h=zA(),g=uR();return new sP(o,a,g,h,f,p.UseUnevaluated())}function Yp(...e){let[o,a,u]=Cn(e,{3:(S,k,A)=>[S,k,A],2:(S,k)=>[{},S,k]}),p=new Vi(o,a),f=new Bn,h=dr(p,f,"#","",a,u),g=f.GetErrors(),I=Ky(),E=g.map((S)=>({...S,message:I(S)}));return[h,E]}function rh(...e){let[o,a,u]=Cn(e,{3:(h,g,I)=>[h,g,I],2:(h,g)=>[{},h,g]}),p=new Vi(o,a),f=new Un;return $t(p,f,a,u)}function mr(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return rh(o,a,u)}function Hs(...e){let[o,a,u]=Cn(e,{3:(h,g,I)=>[h,g,I],2:(h,g)=>[{},h,g]}),[p,f]=Yp(o,a,u);return f}class Ra 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 iP(e,o,a){if(!$e(a))return a;return a.map((u)=>wn(e,o.items,u))}function aP(e,o,a){return wn({...e,...o.$defs},rn(o.$ref),a)}function k1(e,o){let a=me(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Fo(e,o),p=On(u);return Qe(p)?pp(p,a):p}function uP(e,o,a){let u=k1(e,o);return wn(e,u,a)}function Zp(e){return me(e,"additionalProperties")?e.additionalProperties:void 0}function cP(e,o,a){if(!mt(a)||$e(a))return a;let u=Zp(o);for(let p of xe(a)){if(me(o.properties,p)){a[p]=wn(e,o.properties[p],a[p]);continue}if(sn(u)&&v(u,!0)||Lr(u)&&mr(e,u,a[p])){a[p]=wn(e,u,a[p]);continue}delete a[p]}return a}function mP(e,o,a){if(!mt(a))return a;let u=Zp(o),[p,f]=[new RegExp(In(o)),hr(o)];for(let h of xe(a)){if(p.test(h)){a[h]=wn(e,f,a[h]);continue}if(sn(u)&&v(u,!0)||Lr(u)&&mr(e,u,a[h])){a[h]=wn(e,u,a[h]);continue}delete a[h]}return a}function pP(e,o,a){return me(e,o.$ref)?wn(e,e[o.$ref],a):a}function lP(e,o,a){if(!$e(a))return a;let u=Math.min(a.length,o.items.length);for(let p=0;p<u;p++)a[p]=wn(e,o.items[p],a[p]);return ta(a.length,u)?a.slice(0,u):a}function Wr(e){return _a(e)}function dP(e,o,a){for(let u of o.anyOf){let p=wn(e,u,Wr(a));if(mr(e,u,p))return p}return a}function wn(e,o,a){return kt(o)?iP(e,o,a):cr(o)?aP(e,o,a):We(o)?uP(e,o,a):Qe(o)?cP(e,o,a):nr(o)?mP(e,o,a):Yt(o)?pP(e,o,a):dt(o)?lP(e,o,a):ye(o)?dP(e,o,a):a}function A1(e,o){for(let a of xe(e)){if(me(o,a))continue;o[a]=e[a]}return o}function P1(e){let o={};for(let a of xe(e))o[a]=Dc(e[a]);return o}function $1(e){return nh(YT(e))}function nh(e){return e.map((o)=>Dc(o))}function Dc(e){let o=kt(e)?W(Dc(e.items),La(e)):We(e)?qn(nh(e.allOf)):ye(e)?y($1(e.anyOf)):Qe(e)?l(P1(e.properties)):nr(e)?Ke(Ai(e),Dc(hr(e))):dt(e)?Kr(nh(e.items)):e;return A1(e,o)}function mu(e){return Dc(e)}function Go(...e){let[o,a,u]=Cn(e,{3:(f,h,g)=>[f,h,g],2:(f,h)=>[{},f,h]}),p=rs().unionPrioritySort?mu(a):a;return wn(o,p,u)}function Ao(e){return mt(e)&&me(e,"value")}function je(e){return{value:e}}function kr(){return}function C1(e){return $e(e)?je(e):je([e])}function v1(e){return v(e,!0)?je(BigInt(1)):je(BigInt(0))}var M1=/^-?(0|[1-9]\d*)n$/,O1=/^-?(0|[1-9]\d*)\.\d+$/,_1=/^-?(0|[1-9]\d*)$/;function L1(e){return M1.test(e)}function N1(e){return O1.test(e)}function q1(e){return _1.test(e)}function D1(e){let o=e.toLowerCase();return L1(e)?je(BigInt(e.slice(0,e.length-1))):N1(e)?je(BigInt(e.split(".")[0])):q1(e)?je(BigInt(e)):v(o,"false")?je(BigInt(0)):v(o,"true")?je(BigInt(1)):kr()}function el(e){return Ur(e)?je(e):sn(e)?v1(e):Ft(e)?je(BigInt(Math.trunc(e))):Po(e)?je(BigInt(0)):ht(e)?D1(e):rr(e)?je(BigInt(0)):kr()}function F1(e){return v(e,BigInt(0))?je(!1):v(e,BigInt(1))?je(!0):kr()}function j1(e){return v(e,0)?je(!1):v(e,1)?je(!0):kr()}function U1(e){return v(e.toLowerCase(),"false")?je(!1):v(e.toLowerCase(),"true")?je(!0):v(e,"0")?je(!1):v(e,"1")?je(!0):kr()}function fP(e){return Ur(e)?F1(e):sn(e)?je(e):Ft(e)?j1(e):Po(e)?je(!1):ht(e)?U1(e):rr(e)?je(!1):kr()}function B1(e){return v(e,BigInt(0))?je(null):kr()}function G1(e){return v(e,!1)?je(null):kr()}function K1(e){return v(e,0)?je(null):kr()}function H1(e){let o=e.toLowerCase();return v(o,"undefined")||v(o,"null")||v(e,"")||v(e,"0")?je(null):kr()}function W1(e){return Ur(e)?B1(e):sn(e)?G1(e):Ft(e)?K1(e):Po(e)?je(null):ht(e)?H1(e):rr(e)?je(null):kr()}var hP=BigInt(Number.MAX_SAFE_INTEGER),gP=BigInt(Number.MIN_SAFE_INTEGER);function z1(e){return e<=hP&&e>=gP?je(Number(e)):kr()}function V1(e){return je(e?1:0)}function J1(e){let o=+e;if(Ft(o))return je(o);let a=e.toLowerCase();if(v(a,"false"))return je(0);if(v(a,"true"))return je(1);let u=el(e);if(Ao(u))return u.value<=hP&&u.value>=gP?je(Number(u.value)):kr();return kr()}function oh(e){return Ur(e)?z1(e):sn(e)?V1(e):Ft(e)?je(e):Po(e)?je(0):ht(e)?J1(e):rr(e)?je(0):kr()}function yP(e){return Ur(e)?je(e.toString()):sn(e)?je(e.toString()):Ft(e)?je(e.toString()):Po(e)?je("null"):ht(e)?je(e):rr(e)?je(""):kr()}function Q1(e){return v(e,BigInt(0))?je(void 0):kr()}function X1(e){return v(e,!1)?je(void 0):kr()}function Y1(e){return v(e,0)?je(void 0):kr()}function Z1(e){let o=e.toLowerCase();return v(o,"undefined")||v(o,"null")||v(e,"")||v(e,"0")?je(void 0):kr()}function xP(e){return Ur(e)?Q1(e):sn(e)?X1(e):Ft(e)?Y1(e):Po(e)?je(void 0):ht(e)?Z1(e):rr(e)?je(e):kr()}function IP(e,o,a){return C1(a).value.map((p)=>zr(e,o.items,p))}function EP(e,o,a){let u=el(a);return Ao(u)?u.value:a}function bP(e,o,a){let u=fP(a);return Ao(u)?u.value:a}function SP(e,o,a){return zr({...e,...o.$defs},rn(o.$ref),a)}function wP(e,o,a){return zr(e,On(o),a)}function TP(e,o,a){let u=oh(a);return Ao(u)?Math.trunc(u.value):a}function RP(e,o,a){let u=Fo(e,o),p=On(u);return zr(e,p,a)}function ej(e,o,a){let u=el(a);return Ao(u)&&v(o.const,u.value)?u.value:a}function tj(e,o,a){let u=fP(a);return Ao(u)&&v(o.const,u.value)?u.value:a}function rj(e,o,a){let u=oh(a);return Ao(u)&&v(o.const,u.value)?u.value:a}function nj(e,o,a){let u=yP(a);return Ao(u)&&v(o.const,u.value)?u.value:a}function kP(e,o,a){if(v(o.const,a))return a;return ex(o)?ej(e,o,a):tx(o)?tj(e,o,a):hm(o)?rj(e,o,a):gm(o)?nj(e,o,a):Gr()}function AP(e,o,a){let u=W1(a);return Ao(u)?u.value:a}function PP(e,o,a){let u=oh(a);return Ao(u)?u.value:a}function tl(e,o,a,u){let p=xe(u);for(let[f,h]of o)for(let g of p)if(!f.test(g))u[g]=zr(e,a,u[g]);return u}function Fc(e,o,a){return nn(e)&&rr(a[o])}function oj(e,o,a){let u=Yl(o.properties),p=xe(a);for(let[f,h]of u)for(let g of p){if(!f.test(g)||Fc(h,g,a))continue;a[g]=zr(e,h,a[g])}return me(o,"additionalProperties")&&mt(o.additionalProperties)?tl(e,u,o.additionalProperties,a):a}function $P(e,o,a){return Yo(a)?oj(e,o,a):a}function sj(e,o,a){let u=Yl(o.patternProperties),p=xe(a);for(let[f,h]of u)for(let g of p)if(f.test(g))a[g]=zr(e,h,a[g]);return me(o,"additionalProperties")&&mt(o.additionalProperties)?tl(e,u,o.additionalProperties,a):a}function CP(e,o,a){return Yo(a)?sj(e,o,a):a}function vP(e,o,a){return me(e,o.$ref)?zr(e,e[o.$ref],a):a}function MP(e,o,a){let u=yP(a);return Ao(u)?u.value:a}function OP(e,o,a){return zr(e,On(o),a)}function _P(e,o,a){if(!$e(a))return a;for(let u=0;u<Math.min(o.items.length,a.length);u++)a[u]=zr(e,o.items[u],a[u]);return a}function LP(e,o,a){let u=xP(a);return Ao(u)?u.value:a}function NP(e,o,a){if(o.anyOf.some((h)=>mr(e,h,a)))return a;let f=o.anyOf.map((h)=>zr(e,h,Wr(a))).find((h)=>mr(e,o,h));return rr(f)?a:f}function qP(e,o,a){let u=xP(a);return Ao(u)?void 0:a}function zr(e,o,a){return kt(o)?IP(e,o,a):To(o)?EP(e,o,a):zn(o)?bP(e,o,a):cr(o)?SP(e,o,a):Zr(o)?wP(e,o,a):yn(o)?TP(e,o,a):We(o)?RP(e,o,a):gt(o)?kP(e,o,a):Ds(o)?AP(e,o,a):Cr(o)?PP(e,o,a):Qe(o)?$P(e,o,a):nr(o)?CP(e,o,a):Yt(o)?vP(e,o,a):en(o)?MP(e,o,a):lr(o)?OP(e,o,a):dt(o)?_P(e,o,a):fs(o)?LP(e,o,a):ye(o)?NP(e,o,a):Ro(o)?qP(e,o,a):a}function Ts(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return zr(o,a,u)}function DP(e,o,a){if(!$e(a))return a;for(let u=0;u<a.length;u++)a[u]=Tn(e,o.items,a[u]);return a}function FP(e,o,a){return Tn({...e,...o.$defs},rn(o.$ref),a)}function jP(e,o){if(!rr(o))return o;return Ps(e.default)?e.default():Wr(e.default)}function UP(e,o,a){let u=Fo(e,o),p=On(u);return Tn(e,p,a)}function BP(e,o,a){if(!mt(a))return a;let u=xe(o.properties);for(let p of u){let f=Tn(e,o.properties[p],a[p]);if(rr(f)&&(nn(o.properties[p])||!me(o.properties[p],"default")))continue;a[p]=f}if(!Uo(o)||sn(o.additionalProperties))return a;for(let p of xe(a)){if(u.includes(p))continue;a[p]=Tn(e,o.additionalProperties,a[p])}return a}function GP(e,o,a){if(!mt(a))return a;let[u,p]=[new RegExp(In(o)),hr(o)];for(let f of xe(a)){if(!(u.test(f)&&Mo(p)))continue;a[f]=Tn(e,p,a[f])}if(!Uo(o))return a;for(let f of xe(a)){if(u.test(f))continue;a[f]=Tn(e,o.additionalProperties,a[f])}return a}function KP(e,o,a){return me(e,o.$ref)?Tn(e,e[o.$ref],a):a}function HP(e,o,a){if(!$e(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]=Tn(e,u[f],a[f]);return a}function WP(e,o,a){for(let u of o.anyOf){let p=Tn(e,u,Wr(a));if(mr(e,u,p))return p}return a}function Tn(e,o,a){let u=Mo(o)?jP(o,a):a;return kt(o)?DP(e,o,u):cr(o)?FP(e,o,u):We(o)?UP(e,o,u):Qe(o)?BP(e,o,u):nr(o)?GP(e,o,u):Yt(o)?KP(e,o,u):dt(o)?HP(e,o,u):ye(o)?WP(e,o,u):u}function li(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return Tn(o,a,u)}function pu(e){return(...o)=>{let[a,u,p]=Cn(o,{3:(f,h,g)=>[f,h,g],2:(f,h)=>[{},f,h]});return e.reduce((f,h)=>h(a,u,f),p)}}function ij(e,o,a){return o["~codec"].decode(a)}function aj(e,o,a){return o["~codec"].encode(a)}function $r(e,o,a,u){if(!Wn(a))return u;return v(e,"Decode")?ij(o,a,u):aj(o,a,u)}function uj(e,o,a,u){if(!$e(u))return u;for(let p=0;p<u.length;p++)u[p]=Or(e,o,a.items,u[p]);return $r(e,o,a,u)}function cj(e,o,a,u){let p=$r(e,o,a,u);if(!$e(p))return p;for(let f=0;f<p.length;f++)p[f]=Or(e,o,a.items,p[f]);return p}function zP(e,o,a,u){return v(e,"Decode")?uj(e,o,a,u):cj(e,o,a,u)}function VP(e,o,a,u){return u=Or(e,{...o,...a.$defs},rn(a.$ref),u),$r(e,o,a,u)}function JP(e){return e.reduce((o,a)=>({...o,...a}),{})}function QP(e,o){for(let a of o)if(!Oa(e,a))return a;return e}function mj(e,o,a,u){if(v(a.allOf.length,0))return $r(e,o,a,u);let p=a.allOf.map((g)=>Or(e,o,g,Go(g,Wr(u)))),h=p.every((g)=>mt(g))?JP(p):QP(u,p);return $r(e,o,a,h)}function pj(e,o,a,u){if(v(a.allOf.length,0))return $r(e,o,a,u);let p=$r(e,o,a,u),f=a.allOf.map((g)=>Or(e,o,g,Go(g,Wr(p))));if(f.every((g)=>mt(g)))return JP(f);return QP(p,f)}function XP(e,o,a,u){return v(e,"Decode")?mj(e,o,a,u):pj(e,o,a,u)}function lj(e,o,a,u){if(!Yo(u))return u;for(let p of xe(a.properties)){if(!me(u,p)||Fc(a.properties[p],p,u))continue;u[p]=Or(e,o,a.properties[p],u[p])}return $r(e,o,a,u)}function dj(e,o,a,u){let p=$r(e,o,a,u);if(!Yo(p))return p;for(let f of xe(a.properties)){if(!me(p,f)||Fc(a.properties[f],f,p))continue;p[f]=Or(e,o,a.properties[f],p[f])}return p}function YP(e,o,a,u){return v(e,"Decode")?lj(e,o,a,u):dj(e,o,a,u)}function fj(e,o,a,u){if(!Yo(u))return u;let p=new RegExp(In(a));for(let f of xe(u)){if(!p.test(f))continue;u[f]=Or(e,o,hr(a),u[f])}return $r(e,o,a,u)}function hj(e,o,a,u){let p=$r(e,o,a,u);if(!Yo(p))return p;let f=new RegExp(In(a));for(let h of xe(p)){if(!f.test(h))continue;p[h]=Or(e,o,hr(a),p[h])}return p}function ZP(e,o,a,u){return v(e,"Decode")?fj(e,o,a,u):hj(e,o,a,u)}function e$(e,o,a,u){return me(o,a.$ref)?Or(e,o,o[a.$ref],u):u}function t$(e,o,a,u){return v(e,"Decode")?$r(e,o,a,e$(e,o,a,u)):e$(e,o,a,$r(e,o,a,u))}function gj(e,o,a,u){if(!$e(u))return u;for(let p=0;p<Math.min(a.items.length,u.length);p++)u[p]=Or(e,o,a.items[p],u[p]);return $r(e,o,a,u)}function yj(e,o,a,u){let p=$r(e,o,a,u);if(!$e(p))return u;for(let f=0;f<Math.min(a.items.length,p.length);f++)p[f]=Or(e,o,a.items[f],p[f]);return p}function r$(e,o,a,u){return v(e,"Decode")?gj(e,o,a,u):yj(e,o,a,u)}function xj(e,o,a,u){for(let p of a.anyOf){if(!mr(o,p,u))continue;let f=Or(e,o,p,u);return $r(e,o,a,f)}return u}function Ij(e,o,a,u){let p=$r(e,o,a,u);for(let f of a.anyOf){let h=Or(e,o,f,Wr(p));if(!mr(o,f,h))continue;return h}return p}function n$(e,o,a,u){return v(e,"Decode")?xj(e,o,a,u):Ij(e,o,a,u)}function Or(e,o,a,u){return kt(a)?zP(e,o,a,u):cr(a)?VP(e,o,a,u):We(a)?XP(e,o,a,u):Qe(a)?YP(e,o,a,u):nr(a)?ZP(e,o,a,u):Yt(a)?t$(e,o,a,u):dt(a)?r$(e,o,a,u):ye(a)?n$(e,o,a,u):$r(e,o,a,u)}class o$ extends Ra{constructor(e,o){super("Decode",e,o)}}function Ej(e,o,a){if(!mr(e,o,a))throw new o$(a,Hs(e,o,a));return a}function bj(e,o,a){let u=rs().unionPrioritySort?mu(o):o;return Or("Decode",e,u,a)}var Sj=pu([(e,o,a)=>Wr(a),(e,o,a)=>li(e,o,a),(e,o,a)=>Ts(e,o,a),(e,o,a)=>Go(e,o,a),(e,o,a)=>Ej(e,o,a),(e,o,a)=>bj(e,o,a)]);function sh(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return Sj(o,a,u)}class s$ extends Ra{constructor(e,o){super("Encode",e,o)}}function wj(e,o,a){if(!mr(e,o,a))throw new s$(a,Hs(e,o,a));return a}function Tj(e,o,a){let u=rs().unionPrioritySort?mu(o):o;return Or("Encode",e,u,a)}var Rj=pu([(e,o,a)=>Wr(a),(e,o,a)=>Tj(e,o,a),(e,o,a)=>li(e,o,a),(e,o,a)=>Ts(e,o,a),(e,o,a)=>Go(e,o,a),(e,o,a)=>wj(e,o,a)]);function ih(...e){let[o,a,u]=Cn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return Rj(o,a,u)}function kj(e,o){return Wn(o)||Ji(e,o.items)}function Aj(e,o){return Wn(o)||i$({...e,...o.$defs},rn(o.$ref))}function Pj(e,o){return Wn(o)||o.allOf.some((a)=>Ji(e,a))}function $j(e,o){return Wn(o)||xe(o.properties).some((a)=>Ji(e,o.properties[a]))}function Cj(e,o){return Wn(o)||Ji(e,hr(o))}function i$(e,o){if(ah.has(o.$ref))return!1;return ah.add(o.$ref),Wn(o)||me(e,o.$ref)&&Ji(e,e[o.$ref])}function vj(e,o){return Wn(o)||o.items.some((a)=>Ji(e,a))}function Mj(e,o){return Wn(o)||o.anyOf.some((a)=>Ji(e,a))}function Ji(e,o){return kt(o)?kj(e,o):cr(o)?Aj(e,o):We(o)?Pj(e,o):Qe(o)?$j(e,o):nr(o)?Cj(e,o):Yt(o)?i$(e,o):dt(o)?vj(e,o):ye(o)?Mj(e,o):Wn(o)}var ah=new Set;function uh(...e){let[o,a]=Cn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return ah.clear(),Ji(o,a)}class Rs extends Error{constructor(e,o){super(o);this.type=e}}function a$(e,o){return Ps(o.default)?o.default(o):mt(o.default)?Wr(o.default):o.default}function u$(e,o){if(Li(o)&&!Mo(o))throw new Rs(o,"Arrays with uniqueItems constraints must specify a default annotation");let a=_i(o)?o.minItems:0;return Array.from({length:a},()=>Vr(e,o.items))}function c$(e,o){return hs(o)?BigInt(o.exclusiveMinimum)+BigInt(1):gs(o)?BigInt(o.minimum):BigInt(0)}function m$(e,o){return!1}function p$(e,o){let a=Vr(e,o.instanceType);return class{constructor(){Object.assign(this,a)}}}function l$(e,o){return Vr({...e,...o.$defs},rn(o.$ref))}function d$(e,o){return Vr(e,On(o))}function f$(e,o){let a=Vr(e,o.returnType);return()=>a}function h$(e,o){return hs(o)&&Ft(o.exclusiveMinimum)?o.exclusiveMinimum+1:gs(o)?o.minimum:0}function g$(e,o){let a=Fo(e,o),u=On(a);return Vr(e,u)}function y$(e,o){return o.const}function x$(e,o){throw new Rs(o,"Cannot create TNever types")}function I$(e,o){return null}function E$(e,o){return hs(o)&&Ft(o.exclusiveMinimum)?o.exclusiveMinimum+1:gs(o)?o.minimum:0}function b$(e,o){return(rr(o.required)?[]:o.required).reduce((u,p)=>({...u,[p]:Vr(e,o.properties[p])}),{})}function S$(e,o){if(wa(o)&&!Mo(o))throw new Rs(o,"Record with the minProperties constraint must have a default annotation");return{}}function w$(e,o){return me(e,o.$ref)?Vr(e,e[o.$ref]):(()=>{throw new Rs(o,"Unable to deref Ref")})()}function T$(e,o){if((Ta(o)||ba(o))&&!Mo(o))throw Error("Strings with format or pattern constraints must specify default");let u=Sa(o)?o.minLength:0;return"".padEnd(u)}function R$(e,o){return Symbol()}function k$(e,o){let a=Du(o.pattern);if(en(a))throw new Rs(o,"Unable to create TemplateLiteral due to infinite type expansion");return Vr(e,a)}function A$(e,o){return Array.from({length:o.minItems},(a,u)=>Vr(e,o.items[u]))}function P$(e,o){return}function $$(e,o){if(v(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Vr(e,o.anyOf[0])}function C$(e,o){return}function Vr(e,o){return Mo(o)?a$(e,o):kt(o)?u$(e,o):To(o)?c$(e,o):zn(o)?m$(e,o):Jr(o)?p$(e,o):cr(o)?l$(e,o):Zr(o)?d$(e,o):Qr(o)?f$(e,o):yn(o)?h$(e,o):We(o)?g$(e,o):gt(o)?y$(e,o):wo(o)?x$(e,o):Ds(o)?I$(e,o):Cr(o)?E$(e,o):Qe(o)?b$(e,o):nr(o)?S$(e,o):Yt(o)?w$(e,o):en(o)?T$(e,o):Fs(o)?R$(e,o):lr(o)?k$(e,o):dt(o)?A$(e,o):fs(o)?P$(e,o):ye(o)?$$(e,o):Ro(o)?C$(e,o):void 0}function Ws(...e){let[o,a]=Cn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Vr(o,a)}class rl extends Ra{constructor(e,o){super("Parse",e,o)}}function Oj(e,o,a){if(!mr(e,o,a))throw new rl(a,Hs(e,o,a));return a}var v$=pu([(e,o,a)=>Wr(a),(e,o,a)=>li(e,o,a),(e,o,a)=>Ts(e,o,a),(e,o,a)=>Go(e,o,a),(e,o,a)=>Oj(e,o,a)]);var Lj=l({type:i("insert"),path:s(),value:Q()}),Nj=Object({type:i("update"),path:s(),value:Q()}),qj=l({type:i("delete"),path:s()}),PMe=y([Lj,Nj,qj]);class nl{constructor(e,o){this.hasCodec=uh(e,o),this.buildResult=Xp(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(rs().correctiveParse)return v$(this.Context(),this.Type(),e);throw new rl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Hs(this.Context(),this.Type(),e)}Clean(e){return Go(this.Context(),this.Type(),e)}Convert(e){return Ts(this.Context(),this.Type(),e)}Create(){return Ws(this.Context(),this.Type())}Default(e){return li(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?sh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?ih(this.Context(),this.Type(),e):this.Parse(e)}}function mh(...e){let[o,a]=Cn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return new nl(o,a)}var O$=new WeakMap,jj=Symbol.for("TypeBox.Kind");function Uj(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function Bj(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 ph(e){try{return L$(e)}catch{return}}function Gj(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 Kj(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]=Aa(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]=Aa(f,o.additionalProperties)}}function Hj(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]=Aa(e[a],u)}return}if(o.items&&typeof o.items==="object")for(let a=0;a<e.length;a++)e[a]=Aa(e[a],o.items)}function _$(e,o){for(let a of o)if(ph(a)?.Check(e))return e;for(let a of o){let u=structuredClone(e),p=Aa(u,a);if(ph(a)?.Check(p))return p}return e}function Aa(e,o){let a=e;if(Array.isArray(o.allOf))for(let f of o.allOf)a=Aa(a,f);if(Array.isArray(o.anyOf))a=_$(a,o.anyOf);if(Array.isArray(o.oneOf))a=_$(a,o.oneOf);let u=Uj(o),p=u.length>1&&u.some((f)=>Bj(a,f));if(u.length>0&&!p)for(let f of u){let h=Gj(a,f);if(h!==a){a=h;break}}if(u.includes("object")&&typeof a==="object"&&a!==null&&!Array.isArray(a))Kj(a,o);if(u.includes("array")&&Array.isArray(a))Hj(a,o);return a}function ol(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)ol(e[p],f)}else if(o.items)for(let p of e)ol(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"&&ph(f)?.Check(null)===!1)delete a[p];else ol(a[p],f)}}function L$(e){let o=e,a=O$.get(o);if(a)return a;let u=mh(e);return O$.set(o,u),u}function Wj(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 zj(e,o){let a=e.find((u)=>u.name===o.name);if(!a)throw Error(`Tool "${o.name}" not found`);return lu(a,o)}function lu(e,o){let a=structuredClone(o.arguments);ol(a,e.parameters),Ts(e.parameters,a);let u=L$(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(jj)){let h=Aa(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)=>` - ${Wj(h)}: ${h.message}`).join(`
|
|
22
|
-
`)||"Unknown validation error",f=`Validation failed for tool "${o.name}":
|
|
23
|
-
${p}
|
|
24
|
-
|
|
25
|
-
Received arguments:
|
|
26
|
-
${JSON.stringify(o.arguments,null,2)}`;throw Error(f)}var N$;function jc(){if(!N$)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return N$}async function q$(e,o,a,u,p,f){let h=j$(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 F$(I,g,a,p,u,f??jc()),g}async function D$(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 F$(h,f,o,u,a,p??jc()),f}async function F$(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 j$(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 C=await g.prepareRequest?.({context:h,model:g.model,thinkingLevel:g.reasoning??"off"},u);if(C)h=C.context??h,g={...g,model:C.model??g.model,reasoning:C.thinkingLevel===void 0?g.reasoning:C.thinkingLevel==="off"?void 0:C.thinkingLevel};let M=await Jj(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 V=M.content.filter((j)=>j.type==="toolCall"),_=[];if(k=!1,V.length>0){let j=M.stopReason==="length"?await Qj(V,p):await Xj(h,M,g,u,p);_.push(...j.messages),k=!j.terminate;for(let Y of _)h.messages.push(Y),o.push(Y)}I={message:M,toolResults:_,context:h,newMessages:o};let J=await g.finishTurn?.(I,u);if(await p({type:"turn_end",message:M,toolResults:_}),J?.action==="end"){await p({type:"agent_end",messages:o});return}if(E=J?.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 j$(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?lh(u,Vj):S):o,f=si(ce([...e.messages,...p]),(e.tools??[]).map(ct)),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?lh(u,f):S)}if(h)return o;let g=lh({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 Vj={toolsAdded:[],toolsRemoved:[]};function lh(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 Jj(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=vt({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 C of E)switch(C.type){case"start":k=C.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=C.partial,e.messages[e.messages.length-1]=k,await u({type:"message_update",assistantMessageEvent:C,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 Qj(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:fi(`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 Uc(p,o);let f=dh(p);await fh(f,o),a.push(f)}return{messages:a,terminate:!1}}async function Xj(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 Yj(e,o,f,a,u,p);return Zj(e,o,f,a,u,p)}async function Yj(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 B$(e,o,I,u,p),S;if(E.kind==="immediate")S={toolCall:I,result:E.result,isError:E.isError};else{let A=await K$(E,p,G$(I,f));S=await H$(e,o,E,A,u,p)}await Uc(S,f);let k=dh(S);if(await fh(k,f),h.push(S),g.push(k),p?.aborted)break}return{messages:g,terminate:U$(h)}}async function Zj(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 B$(e,o,E,u,p);if(S.kind==="immediate"){let k={toolCall:E,result:S.result,isError:S.isError};if(await Uc(k,f),h.push(k),p?.aborted)break;continue}if(h.push(async()=>{if(p?.aborted){let P={toolCall:E,result:fi("Operation aborted"),isError:!0};return await Uc(P,f),P}let k=await K$(S,p,G$(E,f)),A=await H$(e,o,S,k,u,p);return await Uc(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=dh(E);await fh(S,f),I.push(S)}return{messages:I,terminate:U$(g)}}function U$(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function eU(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 B$(e,o,a,u,p,f=e.tools??[]){let h=f.find((g)=>g.name===a.name);if(!h)return{kind:"immediate",result:fi(`Tool ${a.name} not found`),isError:!0};try{let g=eU(h,a),I=lu(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:fi("Operation aborted"),isError:!0};if(E?.block){let S=fi(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:fi("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:a,tool:h,args:I}}catch(g){return{kind:"immediate",result:fi(g instanceof Error?g.message:String(g)),isError:!0}}}function G$(e,o){return(a)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:a})}async function K$(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:fi(g instanceof Error?g.message:String(g)),isError:!0,durationMs:I}}finally{p=!1}}async function H$(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=fi(I instanceof Error?I.message:String(I)),g=!0}return{toolCall:a.toolCall,result:h,isError:g,durationMs:u.durationMs}}function fi(e){return{content:[{type:"text",text:e}],details:{}}}async function Uc(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 dh(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 fh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function tU(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var rU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},nU={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 oU(e){let o=e?.tools?.slice()??[],a=e?.messages?.slice()??[],u=po(e?.systemPrompt,o.map(ct));if(a[0]?.role!=="system"&&u)a.unshift(u);return{get systemPrompt(){return ii(a)},model:e?.model??nU,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 hh{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 gh{_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=oU(o.initialState),this.convertToLlm=o.convertToLlm??tU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??jc(),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 hh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new hh(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 q$(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),a,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await D$(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:rU,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 sl=Symbol("basalt.rebind-fetch");function ve(e,...o){return Object.assign(e,{aliases:o})}function Pa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function sU(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 W$(e,o){if(e.some((C)=>C.name===o))return o;let a=e.map((C)=>C.name),u=(C)=>a.filter((M)=>Pa(M)===C),p=u(Pa(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(Pa(f));if(h.length===1&&h[0])return h[0];let g=new Map;for(let C of e)for(let M of C.aliases??[]){let V=Pa(M);g.set(V,(g.get(V)??new Set).add(C.name))}let I=(C)=>[...new Set([...u(C),...g.get(C)??[]])],E=I(Pa(f));if(E.length===1&&E[0])return E[0];if(E.length>1)return o;let S=sU(f),k=new Set;S.forEach((C,M)=>{k.add(Pa(C));let V=S[M+1];if(V)k.add(Pa(C+V))});let A=new Set;for(let C of k)for(let M of I(C))A.add(M);let P=[...A];return P.length===1&&P[0]?P[0]:o}function T(e){return e}function Pn(e,o){let a=o.indexOf("/");if(a<=0)return;return e.getModel(o.slice(0,a),o.slice(a+1))}function Rt(e){return`${e.provider}/${e.id}`}function V$(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:z$(h?.headers??I?.headers),body:iU(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=z$(g.headers);if(!g.body)return a({at:I,status:E,statusText:S,headers:k,body:""}),g;let A="",P=new TextDecoder,C=new TransformStream({transform(_,J){J.enqueue(_),A+=P.decode(_,{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(C),V=new Response(M,g);try{Object.defineProperty(V,"url",{value:g.url})}catch{}return V}catch{}return g},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:p,[sl]:(f)=>V$(f,o,a)})}function z$(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 iU(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 aU(e,o){return W$(e,o)}function uU(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=aU(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 Bc(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)}>
|
|
27
|
-
${g.data}
|
|
28
|
-
</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(`
|
|
29
|
-
|
|
30
|
-
`),images:p}}function yh(e,o){let{merged:a,images:u}=Bc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:a},...u]:a,timestamp:Date.now()}}function J$(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 gh({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:V$(E?.fetch??globalThis.fetch,S?(C)=>S({...C,model:Rt(g)}):void 0,k?(C)=>k({...C,model:Rt(g)}):void 0)}:E,P=g.api==="openai-completions"||g.api==="openai-responses"?{...g,compat:{...g.compat,supportsDeveloperRole:!1}}:g;return uU(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(ct),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(Q$(g.message));return}if(g.type==="tool_execution_update"){let E=u.get(g.toolCallId)??Oe(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}:{}}:cU(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}=Bc(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(!E)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 xh(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 il(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}=Oe(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 Q$(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,...Oe(o.name,o.arguments)}})}function cU(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:Q$(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 et 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 X$}from"crypto";import{existsSync as mU}from"fs";import{readFile as Y$,realpath as al}from"fs/promises";import{dirname as pU,isAbsolute as Z$,relative as eC,resolve as tC,sep as rC}from"path";var nC=[...qi];class ul extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class cl{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=pU(tC(e)),u=tC(a,o??"web.tsx");if(!o&&!mU(u))return;let p=eC(await al(a),await al(u));if(Z$(p)||p===".."||p.startsWith(`..${rC}`))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 Y$(S).catch(()=>{return});if(!A||X$("sha256").update(A).digest("hex")!==k){E=!1;break}}if(E)return a.source;this.cache.delete(e)}let u=await al(o),p=new Map,f=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:nC,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(!nC.includes(S.path))throw Error(`Unsupported shared web import: ${S.path}`);return{path:S.path,external:!0}}),E.onLoad({filter:/.*/},async(S)=>{let k=eC(u,await al(S.path));if(Z$(k)||k===".."||k.startsWith(`..${rC}`))throw Error("Plugin web imports must stay inside its plugin directory");let A=await Y$(S.path);p.set(S.path,X$("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 ul(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 Ho(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function zs(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 ml(e){return e.content.flatMap((a)=>a.type==="text"&&a.text.trim()?[a.text.trim()]:[]).join(`
|
|
31
|
-
|
|
32
|
-
`)}function du(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function fu(e){return e.role==="assistant"&&e.content.length>0}function qe(e){let o=[],a=new Map,u=0;for(let p of e){let f=p.raw;if(f.role==="assistant"){if(fu(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 pl=new Set(["edit","write"]),oC=new Set(["grep","glob"]);function bo(e,o){let a=Oe(e.name,e.arguments).input?.[o];return typeof a==="string"?a:void 0}function sC(e){return[...new Set(qe(e).flatMap((o)=>pl.has(Oe(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&bo(o.call,"path")?[bo(o.call,"path")]:[]))]}function Ih(e){return!e.result?"pending":e.result.isError?"error":"completed"}function ll(e){let o=[{source:"ASSISTANT_TOOL",text:`${Oe(e.call.name,e.call.arguments).name}(${Ho(Oe(e.call.name,e.call.arguments).input)}) [${Ih(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:du(e.result)});return o}function H(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 Eh=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}${Ho(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")u+=p.text;else a++;else u=Ho(e);return H(u)+16+a*Eh}function Ct(e=[]){return e.reduce((o,a)=>o+H(a.name+a.description+Ho(a.parameters))+16,0)}function Gn(e,o){let a=e.replace(/\s+/g," ").trim();if(H(a)<=o)return a;let u=Math.min(a.length,o*4);while(u>0&&H(a.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${a.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function No(e,o,a=Number.POSITIVE_INFINITY){if(H(e)<=o&&e.length<=a)return e;let u=`
|
|
33
|
-
[... omitted; use history tools for the full text ...]
|
|
34
|
-
`,p=Math.floor((o-H(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(H(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 dl(e,o){if(H(e.join(`
|
|
35
|
-
`))<=o)return e;let a=(S)=>`- [... ${S} steps omitted; use history tools for the full text ...]`,u=o-H(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=H(`${k}
|
|
36
|
-
`);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 bt(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=lU(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=Qo(u.records);return o}function Qo(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 lU(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"&&Ea(a)?"interrupted":"failed";if(!a)return"completed";switch(a.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return Ea(a)?"interrupted":"failed";default:return"interrupted"}}function qt(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 fl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((a)=>a.entry.seq<=o)}function bh(e,o){return e.find((a)=>a.start<o&&!fl(a,o)&&a.records.some((u)=>u.entry.seq<=o))}function vr(e){let o=qt(e),u=bt(e).findLast((p)=>p.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function Xn(e){let o=qt(e);return bh(bt(e),o)?.end}function ln(e,o){let a=qt(e),u=bt(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(fu(k)||!f.length||k.role==="user"&&f.at(-1)?.assistant)f.push({end:S.entry.seq,tokens:A,assistant:fu(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 iC=2000;function It(e,o){let a=H(o);if(a<=iC)return o;let u=new TextEncoder().encode(o).length,p=o.split(`
|
|
37
|
-
`).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(`
|
|
38
|
-
`),h="</user-text-reference>",g=iC-H(`${f}
|
|
39
|
-
|
|
40
|
-
${h}`);if(g<=0)return o;let I=`${f}
|
|
41
|
-
${No(o,g,o.length-f.length-h.length-3)}
|
|
42
|
-
${h}`;return I.length<o.length&&H(I)<a?I:o}function aC(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=It(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=It(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 Sh(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 C=P.raw.content;return typeof C==="string"?[]:C.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?No(a.map((C)=>zs(C.raw)).join(`
|
|
43
|
-
|
|
44
|
-
`),600):a.map((C,M)=>`<user-message sequence="${M+1}">
|
|
45
|
-
${It(C.entry.seq,zs(C.raw))}
|
|
46
|
-
</user-message>`).join(`
|
|
47
|
-
|
|
48
|
-
`);h=[`<chunk-input id="${e.id}" status="${f}"${o?' excerpt="true"':""}>`,P,...o?[p]:[],"</chunk-input>"].join(`
|
|
49
|
-
`)}let I=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,E=I?ml(I):"",S=[];if(f!=="completed"){let P=qe(e.records),C=new Map(P.map((j)=>[j.call,j])),M=P.slice(-3),V=new Set(M.map((j)=>j.message)),_=[],J=[];for(let j of e.records){let Y=j.raw;if(Y.role!=="assistant")continue;let te=V.has(Y);for(let L of Y.content)if(L.type==="text"&&Y!==I&&L.text.trim())if(te)J.push(`ASSISTANT: ${Gn(L.text,50)}`);else _.push(`- ASSISTANT: ${Gn(L.text,50)}`);else if(L.type==="toolCall"){let se=C.get(L);if(!se)continue;if(te){if(M.includes(se))for(let he of ll(se))J.push(`${he.source}: ${No(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else _.push(`- ${L.name}(${Gn(Ho(L.arguments),40)}) [${Ih(se)}]`)}}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,..._.length?[`Earlier steps, oldest first:
|
|
50
|
-
${dl(_,o?300:800).join(`
|
|
51
|
-
`)}`]:[],...J)}let k=sC(e.records),A=[`<chunk-summary id="${e.id}" status="${f}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,E?o?No(E,600):E:"No final assistant response was recorded.",...S,...k.length?[`Recorded file changes:
|
|
52
|
-
${No(k.join(`
|
|
53
|
-
`),250)}`]:[],...o&&f==="completed"?[p]:[],"</chunk-summary>"].join(`
|
|
54
|
-
`);return{input:h,images:u,summary:A,tokens:dU(h,A,u.length)}}function dU(e,o,a){return(e?H(e)+16:0)+H(o)+16+a*Eh}var fU=["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."],hU="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.",gU=1500,yU=80,xU=240;function uC(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=Sh(I),S=p+E.tokens>f?Sh(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 cC(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)=>zs(k.raw));if(!E.length)return[];let S=I===o[0]?xU:yU;return[`- ${I.id} [${I.status}]: ${Gn(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">',...fU,...p?[hU]:[],"",`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:",No(f.join(`
|
|
55
|
-
`),gU)]:[],"</conversation-checkpoint>"].join(`
|
|
56
|
-
`)}function mC(e,o){let a=e.split(`
|
|
57
|
-
`),u=o.split(`
|
|
58
|
-
`),p=new Set(a),f=new Set(u),h=[...a.filter((I)=>I.trim()&&!f.has(I)).map((I)=>`- ${Gn(I,40)}`),...u.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`+ ${Gn(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("+"))?[`@ ${Gn(g,40)}`]:[]]}function hl(e,o){if(!o)return e;let a=o.endsWith("/")?o:`${o}/`;return e.startsWith(a)?e.slice(a.length):e}function IU(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 EU(e,o){let a=bo(e,"path");if(pl.has(e.name)&&a)return`file:${hl(a,o)}`;let u=bo(e,"command");if(u)return`command:${u}`;return`${e.name}:${Ho(e.arguments)}`}function bU(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 qe(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(!fu(h))continue;let g=++a.steps,I=ml(h);if(I)a.narration.push({step:g,text:Gn(I,60)});for(let{call:E,result:S}of u.get(g)??[]){if(!S)continue;let k=Oe(E.name,E.arguments),A={...E,name:k.name,arguments:k.input},P=EU(A,o),C=du(S);if(S.isError){let Y=bo(A,"command"),te=Y?`${A.name} \`${Gn(Y,40)}\``:`${A.name} ${P.startsWith("file:")?P.slice(5):Gn(Ho(A.arguments),40)}`,L={step:g,key:P,what:te,detail:No(C.trim().split(`
|
|
59
|
-
`).slice(0,8).join(`
|
|
60
|
-
`),200)};a.errors.push(L);let se=p.get(P)??[];se.push(L),p.set(P,se);continue}for(let Y of p.get(P)??[])Y.resolved=g;p.delete(P);let M=bo(A,"path");if(pl.has(A.name)&&M){let Y=hl(M,o),te=a.files.get(Y)??{count:0,first:g,last:g,diffs:[]};if(te.count++,te.last=g,te.diffs.push({step:g,lines:A.name==="edit"?bo(A,"old_string")!==void 0?mC(bo(A,"old_string")??"",bo(A,"new_string")??""):[]:mC("",bo(A,"content")??"")}),te.diffs.length>3)te.diffs.shift();a.files.set(Y,te);continue}let V=A.name==="read"?[...M?[M]:[],...IU(A)]:[];if(V.length){for(let Y of V){let te=hl(Y,o),L=a.reads.get(te)??[];L.push(g),a.reads.set(te,L)}continue}if(oC.has(A.name)){let Y=M?` in ${hl(M,o)}`:"",te=A.name==="grep"&&bo(A,"glob")?` (${bo(A,"glob")})`:"",L=`${A.name} ${bo(A,"pattern")??""}${Y}${te}`.replace(/\s+/g," "),se=a.searches.get(L)??{steps:[],head:""};se.steps.push(g),se.head=Gn(C.trim().split(`
|
|
61
|
-
`)[0]??"",25),a.searches.set(L,se);continue}let _=bo(A,"command");if(_){let Y=C.trim().split(`
|
|
62
|
-
`);a.commands.push({step:g,command:Gn(_,40),exit:"0",lines:Y.length,tail:Y.slice(-3).map((te)=>Gn(te,40))});continue}let J=`${A.name} ${Gn(Ho(A.arguments),40)}`,j=a.other.get(J)??[];j.push(g),a.other.set(J,j)}}return a}function pC(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Gc(e,o,a){let u=(E,S)=>S===void 0||!E.length?E:dl(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,`
|
|
63
|
-
`)}`:""}`:`- step ${E.step} ${E.what} (UNRESOLVED): ${E.detail.replace(/\n/g,`
|
|
64
|
-
`)}`)),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)"} (${pC(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(`
|
|
65
|
-
`));if(p.push("",`## Commands (${I.length})`,...u(I,a.lists)),e.other.size){let E=[...e.other].map(([S,k])=>`- ${S} (${pC(k)})`);p.push("",`## Other tool calls (${E.length})`,...u(E,a.lists))}return p.push("</work-state>"),p.join(`
|
|
66
|
-
`)}function Yn(e,o,a,u){let p=bU(e,u),f=Gc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(H(f)<=a)return f;let h={...p,narration:[]};for(let E of[Number.POSITIVE_INFINITY,20,10,5]){let S=H(Gc(h,o,{diffFiles:E}));if(S>a*0.7)continue;return Gc(p,o,{narration:Math.max(500,a-S),diffFiles:E})}let g=Math.max(300,Math.floor(a*0.1)),I=H(Gc(h,o,{diffFiles:0,lists:g}));return Gc(p,o,{narration:Math.max(500,a-I),diffFiles:0,lists:g})}function gl(e){return{role:"user",content:e,timestamp:0}}function wh(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 lC(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:gl(e.input)}function hu(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:`
|
|
67
|
-
|
|
68
|
-
`},...f(p)],timestamp:Math.max(u.timestamp,p.timestamp)};continue}o.push(a)}return o}function dC(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 SU(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=qt(e),f=bt(e),h=f.filter((X)=>fl(X,p)),g=bh(f,p),I=[],E=[],S=0;for(let X of f){if(fl(X,p))continue;let ee=[];for(let be of X.records){if(X===g&&be.entry.seq<=p)continue;let Xe=be.raw.role==="user"?aC(be):be.raw;S+=G(Xe),I.push(Xe),ee.push(Xe)}if(u.inspect&&ee.length)E.push({id:`recent-${X.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${X.id}`,tokens:ee.reduce((be,Xe)=>be+G(Xe),0),detail:JSON.stringify(ee,SU,2)})}if(!h.length&&!g)return{items:E,messages:hu(I),visible:0,archived:0,open:S,tokens:S,untrimmed:S};let k=uC(h,a,!!g),{visible:A,archived:P}=k,C=k.tokens,M=[],V="",_="";if(g){let X=g.records.filter((be)=>be.entry.seq<=p),ee=X.filter((be)=>be.entry.type==="user"&&!be.entry.notices&&be.raw.role==="user");if(ee.length){V=[`<chunk-input id="${g.id}" status="partial">`,...ee.map((Xe,Ge)=>`<user-message sequence="${Ge+1}">
|
|
69
|
-
${It(Xe.entry.seq,zs(Xe.raw))}
|
|
70
|
-
</user-message>`),"</chunk-input>"].join(`
|
|
71
|
-
`);let be=ee.flatMap((Xe)=>{let Ge=Xe.raw.content;return typeof Ge==="string"?[]:Ge.filter((ar)=>ar.type==="image")});M.push(be.length?{role:"user",content:[{type:"text",text:V},...be],timestamp:0}:gl(V))}_=Yn(X,g,a.index,u.cwd),M.push(wh(_,o))}let J=e.flatMap((X)=>{let ee=X.raw;if(X.entry.seq>p||ee?.role!=="toolResult"||ee.toolName!=="skill")return[];return[gl(ee.content.filter((be)=>be.type==="text").map((be)=>be.text).join(`
|
|
72
|
-
`))]}),j="",Y=e.findLast((X)=>X.entry.type==="compaction")?.entry.time??0,te=()=>{j=cC({runs:h,visible:A.map((ee)=>ee.run),archived:P,partial:!!g,tokens:C,budget:a});let X=[gl(j)];for(let{content:ee}of A){if(ee.input)X.push(lC(ee));X.push(wh(ee.summary,o))}return[...X,...J,...M].map((ee)=>({...ee,timestamp:Y}))},L=(X)=>X.reduce((ee,be)=>ee+G(be),0),se=te(),he=L(se)+S,Me=he,{trim:ze}=u;while(ze&&ze.fixed+he>ze.limit){let X=g||A.at(-1)?.run.status==="completed"?A:A.slice(0,-1);if(!X.length)break;let ee=0,be=0;for(let Xe of X)if(be++,ee+=Xe.content.tokens,ee>=ze.fixed+he-ze.limit)break;P=[...P,...A.slice(0,be).map((Xe)=>Xe.run)],A=A.slice(be),C-=ee,se=te(),he=L(se)+S}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:G(se[0]),detail:j},...A.map(({run:X,content:ee})=>({id:X.id,label:`Chunk ${X.id}`,state:"sealed",tokens:(ee.input?G(lC(ee)):0)+G(wh(ee.summary,o)),detail:[ee.input,ee.summary].filter(Boolean).join(`
|
|
73
|
-
|
|
74
|
-
`)})),...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:[V,_].filter(Boolean).join(`
|
|
75
|
-
|
|
76
|
-
`)}]:[],...E]:[],messages:hu([...se,...I]),visible:A.length,archived:P.length,open:S,tokens:he,untrimmed:Me}}function de(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Th=0.97,wU=0.97,fC=0.5,TU=0.05,RU=20000,kU=24000;function cn(e){return{target:RU,hard:kU,index:Math.floor(de(e)*TU)}}function Rh(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class un{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 cn(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)*Th/this.ratio)}prepare(e,o,a,u){let p=de(a),f=cn(a),h=e.reduce((L,se)=>L+G(se),0)+Ct(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*Th/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)),C=this.dueSeal(a);if(C!==void 0)this.fold(C,!1),this.reshapedAfter=S?.entry.seq??-1;let M=E(),V=k.reduce((L,se)=>L+G(se.raw),0);if(this.lastEstimate===0&&S&&A&&!P()){let L=A.usage.input+A.usage.cacheRead+A.usage.cacheWrite,se=h+M.untrimmed-G(A)-V;if(L>0&&se>0)this.ratio=Math.min(2,Math.max(0.5,L/se))}let J=((L)=>{let se=h+L.untrimmed,he=h+L.tokens;return((S&&A&&!P()&&Rh(A)>0?Rh(A)+Math.round(this.ratio*V):void 0)??Math.round(se*this.ratio))-Math.round((se-he)*this.ratio)})(M);if(J>p*wU){let L=J-M.open*this.ratio,se=Math.max(1000,Math.floor((p*fC-L-f.index)/this.ratio)),he=S?.entry.seq??-1,Me=I().findLast((be)=>be.entry.type==="compaction"&&be.entry.partial)?.entry.seq??-1,ze=Math.max(this.lastFoldSeq,Me),ee=(ze>0?I().filter((be)=>be.entry.seq>ze&&be.raw?.role==="assistant").length:999)<=1;if(!ee||this.consecutivePartialFolds<2){let be=ln(I(),se);if(be!==void 0)this.fold(be,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=ee?this.consecutivePartialFolds+1:1,M=E()}}else this.consecutivePartialFolds=0;this.lastEstimate=h+M.tokens;let j=M.messages,Y=h+M.tokens;if(Math.round(Y*this.ratio)>p)j=AU(j,Math.floor((p-h)/this.ratio)),Y=h+j.reduce((L,se)=>L+G(se),0);return this.lastEstimate=Y,{messages:hu([...e,...j]),estimate:Y}}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||Rh(u)+h<Math.floor(de(e)*Th))return}return vr(o)}recover(e){let o=de(e),a=cn(e),u=Ce(this.records(),e,a,{cwd:this.cwd()}),p=Math.floor((o*fC-(o-u.open*this.ratio)-a.index)/this.ratio),f=ln(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 kh=500;function AU(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)<=kh)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(kh,Math.floor(g/2)),E={...h,content:h.content.map((k)=>k.type==="text"?{...k,text:No(k.text,I)}:k)},S=G(E);u[f]=S<g?S:kh,a[f]=E,p-=g-S}return a}var PU=2000;function gu(e,o){let a=[];for(let u of o.replace(/\r\n/g,`
|
|
77
|
-
`).split(`
|
|
78
|
-
`))for(let p=0;p<Math.max(u.length,1);){let f=Math.min(u.length,p+PU);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 _r(e){let o=[],a=qe(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(...gu(f.entry.type==="user"&&f.entry.notices?"NOTICE":"USER",zs(h)));else if(h.role==="assistant"){for(let g of h.content)if(g.type==="text"&&g.text.trim())o.push(...gu("ASSISTANT",g.text));else if(g.type==="toolCall"){let I=u.get(g);if(I)for(let E of ll(I))o.push(...gu(E.source,E.text))}}else if(h.role==="toolResult"&&!p.has(h))o.push(...gu(h.isError?"TOOL_ERROR":"TOOL_OUTPUT",du(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 gu("USER",zs(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 gu("EXTENSION",a.display.text).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function pn(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(`
|
|
79
|
-
`)}import{AsyncLocalStorage as $U}from"async_hooks";import{chmodSync as xC,existsSync as CU,mkdirSync as vU,readFileSync as MU,renameSync as OU,writeFileSync as _U}from"fs";import{dirname as LU,join as NU}from"path";function hC(){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 gC(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 Kc(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 yC(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(Kc(k)&&!Kc(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,V)=>{A.set(V,M)}),S.origin!==k.origin)A.delete("authorization"),A.delete("cookie"),A.delete("proxy-authorization");let P=(f?.method??E?.method??"GET").toUpperCase(),C={...f,method:P,headers:A};if(g.status===303||(g.status===301||g.status===302)&&P==="POST")C.method="GET",delete C.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,C,h+1)};return Object.assign((p,f)=>a(p,f,0),{preconnect:e.preconnect})}var Ah=zi,EC=Tr,IC=new $U;class Ui{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;hC(),this.path=NU(e,"proxy.json");let a=async(u,p)=>{let f=IC.getStore();if(!f)return this.baseFetch(u,p);return this.createFetch(f)(u,p)};globalThis.fetch=Object.assign(a,{preconnect:o.preconnect})}load(){if(!CU(this.path))return;this.config=this.validate(JSON.parse(MU(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{vU(LU(this.path),{recursive:!0});let a=`${this.path}.tmp-${process.pid}`;_U(a,`${JSON.stringify(o,null,2)}
|
|
80
|
-
`,{mode:384}),xC(a,384),OU(a,this.path),xC(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")=>yC(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)=>FU(h,S))??!1;if(Kc(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 bC(e,this)}providerOptions(e,o,a){let u=Object.assign({},e),p=e?.fetch,h=p?.[sl]?.call(p,this.baseFetch)??p??this.baseFetch;u.fetch=this.createFetch(o,h);let g=gC({...process.env,...e?.env}),I=!1;if(a)try{I=Kc(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 IC.run(e,o)}wrapProvider(e){let o=Gt(e.id),a={...e.auth},u=e.auth.oauth;if(u){let S=e.id==="openai"||e.id===wt?Ah: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=Zo(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=Ph(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(qU),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=DU(o.defaultProfileID);if(f&&!p.has(f))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let h=Ph(o.routes)??{},g={};for(let[I,E]of Object.entries(h)){if(I!==Ah&&I!==EC&&!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 bC{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 Gt(e){return`${Gi}${e}`}function ws(e){return[{id:Ah,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:EC,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:Gt(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function qU(e){let o=Ph(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=Zo(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 DU(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 Ph(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function FU(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 xg}from"path";import{existsSync as jC}from"fs";import{realpath as UC}from"fs/promises";import{dirname as BC,isAbsolute as rB,join as GC,relative as nB,resolve as Lh,sep as oB}from"path";import{existsSync as jU,watch as UU}from"fs";import{readdir as BU,stat as GU}from"fs/promises";import{basename as $h,dirname as KU,join as SC,resolve as HU}from"path";class Ch{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 BU(g)}catch(E){if(E instanceof Error&&"code"in E&&E.code==="ENOENT")continue;throw E}for(let E of I.sort()){let S=SC(g,E),k=(await GU(S)).isDirectory()?SC(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=$h(k)==="index.ts"?$h(KU(k)):$h(k,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let C={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};a.push({definition:C,path:k}),this.slots.set(P,{definition:C,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(!jU(g.path))continue;let I=UU(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(`${HU(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 wC(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 WU}from"async_hooks";import{isDeepStrictEqual as TC}from"util";var $a=new WU;function Vs(){let e=$a.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function yu(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 RC(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)&&!TC(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"&&so.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(!TC(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 kC(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=$a.run(E,()=>{let k=yu(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 C=P===void 0?void 0:RC(h,P);if(E.violated)throw Error("entry.before_append attempted a database write");return{validated:C,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 zU(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return yu(o);return structuredClone(o)}async function AC(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 C=p==="prompt.fragments"?JSON.stringify([h?.id,E]):void 0,M=C===void 0?void 0:S.promptCache.get(A)?.get(C);try{let V=zU(p,E),_=P?.timeoutMs,J=typeof _==="function"?_({runtime:e.runtime,session:h,connection:g}):_,j=await o((Y)=>A(V,{runtime:e.runtime,session:h,connection:g,signal:Y}),J);if(C!==void 0){let Y=j===void 0?E:j;if(!Array.isArray(Y)||Y.some((L)=>typeof L!=="string"))throw Error("Prompt fragments must be strings");if(M&&JSON.stringify(M)!==JSON.stringify(Y))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let te=S.promptCache.get(A)??new Map;te.set(C,[...Y]),S.promptCache.set(A,te)}if(S.failures=0,j!==void 0&&p!=="entry.after_append")E=j}catch(V){if(M)E=structuredClone(M);if(a(S,V),P?.errorMode==="propagate")throw V}}}return E}class Hc{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 VU}from"fs";import{dirname as JU,resolve as PC}from"path";var vh=new WeakMap;function $C(e){return[...e].map((o)=>{let a=Boolean(o.path&&(Boolean(o.definition.webEntry)||VU(PC(JU(PC(o.path)),"web.tsx"))));if(o.current&&!vh.has(o.current))vh.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?vh.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 Mh{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:yu(a),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await $a.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 CC(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 QU(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 XU(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=Pn(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?Rt(p):u;if(!f.some((g)=>g.id===h)){let g=f[0];if(g)p=Pn(e.options.models,g.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function vC(e,o){QU(o);let a=await XU(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${CC(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${CC(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:Rt(a)}}var YU=["active","archived","all"];function MC(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function ZU(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&&!YU.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 eB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function OC(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=MC(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(eB):I)}return{list(a={}){ZU(a);let u=a.limit===void 0?void 0:MC(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 _C(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=(_,J)=>{if(k(),!E){I.set(_,J);return}if(J===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,_);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,_,J)},P={get:(_)=>{k();let J=I.has(_)?I.get(_):g.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,_)?.value;return J==null?void 0:JSON.parse(J)},set:(_,J)=>{let j=JSON.stringify(J);if(j===void 0)throw Error("Plugin KV values must be JSON serializable");A(_,j)},delete:(_)=>A(_,null)},C=()=>{if(k(),E)throw Error("Register resources during setup only")},M=[...o.migrations??[]].sort((_,J)=>_.version-J.version),V=new Set;try{for(let _ of M){if(!Number.isSafeInteger(_.version)||_.version<1||V.has(_.version))throw Error("Plugin migration versions must be unique positive integers");if(V.add(_.version),g.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,_.version))continue;g.transaction(()=>{if(_.sql!==void 0)g.run(_.sql);else _.up({...P,db:g});for(let[J,j]of I)if(j===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,J);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,J,j);g.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,_.version)})(),e.runtime.store.invalidateEntryCache(),I.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:OC(e.runtime),complete:(_)=>vC(e.runtime,_),kv:P,database:g,broadcast:(_)=>{e.runtime.emitEvent(_)},registerInputGate:(_)=>{C(),h.gates.push(_)},registerNoticeSource:(_,J)=>{if(C(),!_||!Number.isSafeInteger(J.textLimit)||J.textLimit<1||!Number.isSafeInteger(J.summaryLimit)||J.summaryLimit<1)throw Error("Notice source limits must be positive integers");h.noticeSources.set(_,{...J})},provide:(_,J)=>{if(C(),_.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(h.services.has(_.name))throw Error(`Duplicate plugin service: ${_.name}`);if(!_.validate(J))throw Error(`Invalid plugin service: ${_.name}`);h.services.set(_.name,J)},on:(_,J,j)=>{if(C(),j?.promptPosition&&_!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let Y=h.hooks.get(_)??[];if(Y.push(J),h.hooks.set(_,Y),j)h.hookOptions.set(J,j)},registerHistoryResolver:(_)=>{C(),h.historyResolvers.push(_)},registerTool:(_,J)=>{if(C(),!_.name||["toolsearch","tool_search","tool_call"].includes(_.name.toLowerCase())||tB(e,p,o.id).has(_.name.toLowerCase())||h.tools.some((Y)=>Y.name.toLowerCase()===_.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${_.name}`);let j=a?"always":"defer";if(typeof J?.defer==="boolean")j=J.defer?"defer":"always";else if(J?.defer!==void 0)j=J.defer;h.tools.push({..._,defer:j,source:`plugin:${o.id}`,group:J?.group,aliases:J?.aliases,builtin:a})},registerRoute:(_)=>{if(C(),!(_.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((J)=>_.path===J||_.path.startsWith(`${J}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(_.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(h.routes.some((J)=>J.path===_.path&&J.method===_.method))throw Error("Duplicate plugin route");h.routes.push(_)},registerWebSocket:(_)=>{if(C(),!_.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(h.websockets.some((J)=>J.path===_.path))throw Error("Duplicate plugin WebSocket route");h.websockets.push(_)},registerCommand:(_)=>{C(),h.commands.push(_)},registerWebContribution:(_)=>{C(),h.web.push(_)},registerToolPolicy:(_,J)=>{C(),h.policies.set(_,J)},appendExtension:(_,J)=>{if(Vs(),k(),!E)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(_,J)},onDeactivate:(_)=>{C(),h.deactivators.push(_)},onDispose:(_)=>{C(),h.disposers.push(_)}})),g.transaction(()=>{for(let[_,J]of I)if(J===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,_);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,_,J)})(),I.clear(),E=!0,h}catch(_){throw S=!1,await f(h),_}}function tB(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 Oh{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 LC(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 _h(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 NC(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 qC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((p)=>p.method===o.method&&_h(p.path,o)!==void 0))}finally{a.release()}}function DC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((p)=>p.public===!0&&p.method===o.method&&_h(p.path,o)!==void 0))}finally{a.release()}}async function FC(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=_h(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:C,value:M}=await k.read();if(C)P.close(),S();else P.enqueue(M)}catch(C){P.error(C),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 Nh{runtime;options;slots=new Map;retirement=new Oh(this.deadline.bind(this));observers=new Mh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new cl;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 Ch(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(Lh(a));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await UC(e),a=[...this.directories,GC(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>GC(u.directory,".basalt","plugins"))];for(let u of a){if(!jC(u))continue;let p=nB(await UC(u),o);if(p&&p!==".."&&!p.startsWith(`..${oB}`)&&!rB(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 et(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 et(g.errors)}let a=o.builtin&&!jC(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 _C(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 Hc(this,e)}async invoke(e,o,a,u,p,f="end"){return AC(this,this.deadline.bind(this),this.fail.bind(this),e,o,a,u,p,f)}pinEntry(e){if($a.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 Hc(this,o)}beforeEntry(e,o,a,u){return kC(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 wC(e,o,a)}appendExtension(e,o){return Vs(),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,BC(Lh(o.path)));return{ok:!0}}catch(o){if(o instanceof ul)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,BC(Lh(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 NC(this,this.deadline.bind(this),e,o,a)}hasRoute(e){return qC(this,e)}isPublicRoute(e){return DC(this,e)}route(e){return FC(this,this.deadline.bind(this),e)}websocket(e){return LC(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 KC}from"fs";import{join as sB}from"path";var iB=500,aB=1000,uB=3600000,cB=5000,mB=2000,pB=3,lB=1073741824;class qh{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;constructor(e){this.options=e;if(this.indexPath=sB(e.dataDir,is),this.features={...ss(),...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+=KC(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=KC(this.options.store.path).size}catch{}return Math.max(lB,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(),fo(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.worker;if(!o)return e();Atomics.store(this.flags,Je,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Mt,0,cB);try{return e()}finally{Atomics.store(this.flags,Je,0),Atomics.notify(this.flags,Je)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=ls(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,Je,0),Atomics.store(this.flags,Mt,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<pB&&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.stopping=(async()=>{Atomics.store(this.flags,Je,0),Atomics.notify(this.flags,Je);let o=new Promise((a)=>{this.stopped=a});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(mB)]),e.terminate(),this.worker=void 0,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,iB-(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)fo(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),uB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,aB-(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{existsSync as Eu,mkdirSync as IB,readdirSync as QC,readFileSync as WC,realpathSync as Dh,statSync as El,writeFileSync as Fh}from"fs";import{dirname as Il,isAbsolute as jh,relative as XC,resolve as EB}from"path";import{existsSync as Wc}from"fs";import{dirname as yB,join as Iu}from"path";import{mkdirSync as dB,writeFileSync as fB}from"fs";import{tmpdir as hB}from"os";import{join as HC}from"path";var yl=2000,Pe=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function xu(e,o){return e.map((a,u)=>{let p=a.length>yl?`${a.slice(0,yl)}\u2026 [line truncated]`:a;return`${String(o+u).padStart(6)} ${p}`}).join(`
|
|
81
|
-
`)}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(`
|
|
82
|
-
`).length-1;return`${e.slice(0,a)}
|
|
83
|
-
|
|
84
|
-
\u2026 [${p} characters, ~${f} lines omitted] \u2026
|
|
85
|
-
|
|
86
|
-
${e.slice(-u)}`}var gB=0;function tt(e,o,a){if(e.length<=o)return e;let u=le(e,o);try{let p=a?Xo(a):HC(hB(),"basalt-output");dB(p,{recursive:!0});let f=HC(p,`${process.pid}-${Date.now().toString(36)}-${gB++}.txt`);return fB(f,e),`${u}
|
|
87
|
-
[Full output saved to ${f}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var Bi=120000,Fi=600000,Ca;function xB(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function zt(){if(Ca!==void 0)return Ca||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let p=Iu(u,"bash.exe");if(xB(p))continue;if(Wc(p))return Ca=p,p}for(let u of o){let p=Iu(u,"git.exe");if(Wc(p)){let f=yB(u),h=Iu(f,"bin","bash.exe");if(Wc(h))return Ca=h,h;let g=Iu(f,"usr","bin","bash.exe");if(Wc(g))return Ca=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?Iu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?Iu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of a)if(Wc(u))return Ca=u,u;Ca="";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 jt(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")return{argv:[zt()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=zt();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function Vt(e,o){let a=await He(e,o.signal);if(a)return{output:a,code:126,timedOut:!1};let{argv:u,isWindows:p}=jt(e,o.shell),f=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,...hn(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((Y)=>Y.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),h=!1,g=()=>{try{if(p)f.kill();else process.kill(-f.pid,"SIGKILL")}catch{}},I=setTimeout(()=>{h=!0,g()},o.timeout);o.signal?.addEventListener("abort",g,{once:!0});let E=Pe*2,S="",k="",A=0,P=0,C="",M=(Y=!1)=>{let te=A-S.length-k.length,L=te>0?`${S}
|
|
88
|
-
\u2026 [${te} characters omitted] \u2026
|
|
89
|
-
${k}`:S+k;if(!Y)return le(L,Pe);return tt(C.length===A?C:L,Pe,o.cwd)},V=()=>{let Y=new to;return async(te)=>{for await(let se of te){let he=Y.decode(se);if(A+=he.length,C.length<4000000)C+=he;if(S.length<E)S+=he;else k=(k+he).slice(-E);if(o.onOutput){let Me=performance.now();if(Me-P>=80)P=Me,o.onOutput(M())}}let L=Y.flush();if(L){if(A+=L.length,C.length<4000000)C+=L;if(S.length<E)S+=L;else k=(k+L).slice(-E)}}},_=Promise.all([V()(f.stdout),V()(f.stderr)]),J=await f.exited;if(clearTimeout(I),o.signal?.removeEventListener("abort",g),await Promise.race([_.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))k+=`
|
|
90
|
-
[background processes are still running; their later output is not captured]`;return{output:M(!0),code:h?null:J,timedOut:h}}class Uh{seen=new Map;mark(e,o=El(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return El(e).mtimeMs!==o?"changed":void 0}}var zC=2000,bB=500,SB=10485760,xl=20,wB=6,TB=40000,RB=80000;function kB(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 YC(e,o,a=[],u){let p=(C)=>jh(C)?C:EB(e,C),f=(C)=>{let M=XC(e,C);return M&&!M.startsWith("..")&&!jh(M)?M:C},h=(C)=>{let M=C;while(!Eu(M)&&Il(M)!==M)M=Il(M);let V=Dh(M);if(a.some((_)=>Eu(_)&&JC(Dh(_),V))&&!JC(Dh(e),V))throw Error("External directories are read-only")},g=(C,M,V)=>{let _=p(C);if(!Eu(_))throw Error(`No such file or directory: ${_}${CB(_)}`);let J=El(_);if(J.isDirectory()){let ee=QC(_,{withFileTypes:!0}).map((Ge)=>Ge.isDirectory()?`${Ge.name}/`:Ge.name).sort(),be=ee.slice(0,bB),Xe=ee.length-be.length;return c(`${be.join(`
|
|
91
|
-
`)}${Xe>0?`
|
|
92
|
-
\u2026 and ${Xe} more entries`:""}`||"(empty directory)").content}let j=WC(_),Y=kB(j);if(Y){if(J.size>SB)throw Error(`${_} exceeds the 10 MB image limit (${J.size} bytes)`);return o.mark(_),[{type:"text",text:`Read image ${f(_)} (${Y}, ${J.size} bytes)`},{type:"image",data:j.toString("base64"),mimeType:Y}]}if(j.subarray(0,8192).includes(0))throw Error(`${_} looks like a binary file (${J.size} bytes)`);o.mark(_);let te=j.toString("utf8");if(!te)return c("(empty file)").content;let L=te.replace(/\r?\n$/,"").split(/\r?\n/),se=(M??1)-1;if(se>=L.length)throw Error(`offset ${M} is past the end of the file (${L.length} lines)`);let he=Math.min(L.length,se+(V??zC)),Me=0,ze=se;while(ze<he){let ee=L[ze]?.length??0;if(ze>se&&Me+ee>TB)break;Me+=ee,ze++}let X=xu(L.slice(se,ze),se+1);if(ze<he)X+=`
|
|
93
|
-
|
|
94
|
-
(Showing lines ${se+1}-${ze} of ${L.length} (truncated at line ${ze} due to safety budget). Use offset/limit to read specific windows.)`;else if(se>0||ze<L.length)X+=`
|
|
95
|
-
|
|
96
|
-
(Showing lines ${se+1}-${ze} 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.
|
|
97
|
-
- path may be absolute or relative to the working directory.
|
|
98
|
-
- By default reads up to ${zC} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
|
|
99
|
-
- Lines longer than ${yl} characters are truncated.
|
|
100
|
-
- Reading a directory lists its entries (directories end with /).
|
|
101
|
-
- Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
|
|
102
|
-
- To read several files at once, give paths instead of path (up to ${xl}, 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.
|
|
103
|
-
- 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(W(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:xl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(C,M){let V=[...M.path!==void 0?[{path:M.path,offset:M.offset,limit:M.limit}]:[],...M.paths??[]];if(V.length===0)throw Error("Give path, or paths to read several files");if(V.length===1){let te=V[0];return{content:g(te.path,te.offset,te.limit),details:void 0}}if(V.length>xl)throw Error(`Read at most ${xl} paths per call`);let _=[],J=[],j=0,Y=(te)=>{let L=_.at(-1);if(te.type==="text"&&L?.type==="text")L.text+=`
|
|
104
|
-
|
|
105
|
-
${te.text}`;else _.push(te)};for(let te of V){let L=`==> ${f(p(te.path))} <==`;if(j>=RB){Y({type:"text",text:`${L}
|
|
106
|
-
(Skipped due to total read safety budget; read in separate calls)`});continue}try{let se=g(te.path,te.offset,te.limit);for(let he=0;he<se.length;he++){let Me=se[he];if(!Me)continue;if(Me.type==="text")j+=Me.text.length,Y(he===0?{...Me,text:`${L}
|
|
107
|
-
${Me.text}`}:Me);else Y(Me)}}catch(se){let he=se instanceof Error?se.message:String(se);J.push(he),Y({type:"text",text:`${L}
|
|
108
|
-
Error: ${he}`})}}if(J.length===V.length)throw Error(J.join(`
|
|
109
|
-
`));return{content:_,details:void 0}}}),E=async(C,M,V,_)=>{let J=_?.update,j=await Vt(C,{cwd:e,timeout:120000,signal:V,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:J?(he)=>J(c(`${_.prefix}
|
|
110
|
-
|
|
111
|
-
$ ${C}
|
|
112
|
-
${he.trimEnd()}`)):void 0}),Y=j.output.trimEnd()||"(no output)",te=j.timedOut?"killed after 120s timeout":j.code===0?"exit code 0":`exit code ${j.code}`,L=j.timedOut||j.code!==0,se=L?`
|
|
113
|
-
${M}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
|
|
114
|
-
|
|
115
|
-
$ ${C}
|
|
116
|
-
${Y}
|
|
117
|
-
[${te}]${se}`,failed:L}},S=(C,M=!1)=>{let V=o.check(C);if(V==="changed")return`Note: ${f(C)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(V==="unread"&&M)return`Note: ${f(C)} 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.
|
|
118
|
-
- An existing file is replaced whole, including changes made since you last read it.
|
|
119
|
-
- Prefer the edit tool for changing existing files; use write for new files or full rewrites.
|
|
120
|
-
- 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.
|
|
121
|
-
- 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(C,M,V,_){let J=p(M.path);h(J);let j=Eu(J),Y;if(j){if(El(J).isDirectory())throw Error(`${J} is a directory`);Y=S(J,!0)}IB(Il(J),{recursive:!0}),Fh(J,M.content),o.mark(J);let te=M.content?M.content.split(`
|
|
122
|
-
`).length:0,L=`${j?"Overwrote":"Created"} ${f(J)} (${te} lines)${Y?`
|
|
123
|
-
${Y}`:""}`;if(M.then_run){let se=await E(M.then_run,`${f(J)} was written as given`,V,{prefix:L,update:_});if(L+=se.out,se.failed)return{...c(L),isError:!0}}return c(L)}}),A=(C,M,V,_)=>{let J=p(C);if(!Eu(J))throw Error(`File not found: ${J} (use write to create it)`);h(J);let j=S(J),Y=WC(J,"utf8"),te=Y,L=te.includes(`\r
|
|
124
|
-
`),se=[],he=[],Me=0,ze=0;return M.forEach((X,ee)=>{let be=_?`edits[${V+ee}]: `:"";try{if(X.old_string===X.new_string)throw Error(`${be}old_string and new_string are identical`);if(!X.old_string)throw Error(`${be}old_string is empty (use write to create or replace a whole file)`);let Xe=L&&!X.old_string.includes(`\r
|
|
125
|
-
`),Ge=Xe?X.old_string.replace(/\n/g,`\r
|
|
126
|
-
`):X.old_string,ar=Xe?X.new_string.replace(/\n/g,`\r
|
|
127
|
-
`):X.new_string,Re=AB(te,Ge).map((Ot)=>[Ot,Ot+Ge.length]);if(Re.length===0)Re=PB(te,Ge);if(Re.length===0)throw Error(`${be}old_string not found in ${f(J)}; read the relevant lines and copy the exact text.${$B(te,Ge)}`);if(Re.length>1&&!X.replace_all){let Ot=Re.map(([it])=>VC(te,it)).join(", ");throw Error(`${be}old_string occurs ${Re.length} times (lines ${Ot}); add surrounding lines to make it unique, or set replace_all.`)}let ke=VC(te,Re[0][0]),Wt=X.replace_all?Re:[Re[0]],ft="",Dt=0;for(let[Ot,it]of Wt)ft+=te.slice(Dt,Ot)+ar,Dt=it;te=ft+te.slice(Dt),Me++,ze+=Wt.length;let Ir=te.split(/\r?\n/),fr=ke+ar.split(/\r?\n/).length-1,tr=Math.max(1,ke-1),st=Math.min(Ir.length,fr+1);if(st-tr+1<=wB+2)se.push(xu(Ir.slice(tr-1,st),tr));else se.push(`${xu(Ir.slice(tr-1,ke+1),tr)}
|
|
128
|
-
\u2026 (${fr-ke-3} lines as given)
|
|
129
|
-
${xu(Ir.slice(fr-2,st),fr-1)}`)}catch(Xe){he.push(Xe instanceof Error?Xe.message:String(Xe))}}),{path:J,original:Y,content:te,echoes:se,applied:Me,total:ze,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.
|
|
130
|
-
- No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
|
|
131
|
-
- 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.
|
|
132
|
-
- 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.
|
|
133
|
-
- 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.
|
|
134
|
-
- To create a file use write; to delete or move files use bash.
|
|
135
|
-
- 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.
|
|
136
|
-
- 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(W(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(C,M,V,_){let J=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(J.length===0)throw Error("Give old_string and new_string, or edits");let j=J.length>1,Y=new Map;J.forEach((X,ee)=>{if(!X.path)throw Error(`${j?`edits[${ee}]: `:""}path is required`);let be=p(X.path),Xe=Y.get(be)??{raw:X.path,steps:[],offset:ee};Xe.steps.push(X.step),Y.set(be,Xe)});let te=[],L=[];for(let X of Y.values())try{let ee=A(X.raw,X.steps,X.offset,j);if(ee.applied>0)te.push(ee);L.push(...ee.failed)}catch(ee){let be=ee instanceof Error?ee.message:String(ee);L.push(`${j?`edits[${X.offset}]: `:""}${be}`)}if(te.length===0)throw Error(L.join(`
|
|
137
|
-
`));let se=[];try{for(let X of te)Fh(X.path,X.content),se.push(X)}catch(X){for(let ee of se)Fh(ee.path,ee.original);throw X}for(let X of te)o.mark(X.path);let Me=te.map((X)=>{let ee=X.total===1?"1 occurrence":`${X.total} occurrences`,be=X.note?`
|
|
138
|
-
${X.note}`:"";if(!j)return`Edited ${f(X.path)} (${ee}).${be}
|
|
139
|
-
${X.echoes[0]}`;let Xe=X.failed.length>0?`, ${X.failed.length} failed`:"";return`Edited ${f(X.path)} (${X.applied} edits${Xe}, ${ee}). Regions are shown as they were right after each edit; later edits may shift line numbers.${be}
|
|
140
|
-
${X.echoes.map((Ge,ar)=>`--- edit ${ar+1}
|
|
141
|
-
${Ge}`).join(`
|
|
142
|
-
`)}`}).join(`
|
|
143
|
-
|
|
144
|
-
`),ze=!1;if(M.then_run){let X=await E(M.then_run,"The edits above were applied",V,{prefix:Me,update:_});if(Me+=X.out,X.failed)ze=!0}if(L.length>0)Me+=`
|
|
145
|
-
|
|
146
|
-
${L.length===1?"1 edit":`${L.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
|
|
147
|
-
- ${L.join(`
|
|
148
|
-
- `)}`,ze=!0;return ze?{...c(Me),isError:!0}:c(Me)}});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 AB(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 VC(e,o){let a=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)a++;return a}function PB(e,o){let a=o.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),u=[],p=e.split(`
|
|
149
|
-
`),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(`
|
|
150
|
-
`)&&S<e.length?e[S]==="\r"?2:1:0;g.push([u[I],S+k]),I+=a.length-1}return g}function $B(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(`
|
|
151
|
-
`))===u)return` A match ignoring whitespace exists at line ${g+1}; copy the exact indentation and line breaks from the read output:
|
|
152
|
-
${le(xu(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 CB(e){let o=Il(e);if(!Eu(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let p=QC(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 JC(e,o){let a=XC(e,o);return a===""||!a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&a!==".."&&!jh(a)}var Bh=20,Gh=80,vB=5,MB=(e)=>e!==void 0&&e>0?e:void 0;function ZC(e,o){let a=Zn(e,o)??eo(e,o);if(!a)throw Error(`No user message with seq ${o}`);return a}function bl(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=MB(h.seq);return{scope:g,seq:I,runs:()=>bt(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)
|
|
153
|
-
`:""}},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.
|
|
154
|
-
- 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).
|
|
155
|
-
- 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(W(s({minLength:1}),{maxItems:vB,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:Bh,description:`Hits to return (default ${Bh})`})),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=[ZC(I.records,E)];else{let se=S(),he=g.chunk_id?se.filter((Me)=>Me.id===g.chunk_id):se;if(g.chunk_id&&!he.length)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);P=he.map(_r)}let C=(se)=>g.case_sensitive?se:se.toLowerCase(),M=[g.pattern,...(g.also??[]).filter(Boolean)].map(C),V=g.head_limit??Bh,_=g.offset??0,J=[],j=new Map,Y=0;for(let se of P)se.forEach((he,Me)=>{let ze=C(he.text);if(!M.every((ee)=>ze.includes(ee)))return;if(j.set(he.chunk,(j.get(he.chunk)??0)+1),Y++,Y<=_||J.length>=V)return;let X=se.slice(Math.max(0,Me-2),Me+3);J.push(`${k} chunk ${he.chunk} line ${he.line}:
|
|
156
|
-
${pn(X," ")}`)});if(!Y)return c(`${A}No matches`);if(!J.length)return c(`${A}No matches at offset ${_} (total ${Y})`);let te=Y-_-J.length,L=j.size>1?` (all matches by chunk: ${[...j].map(([se,he])=>`${se} ${he}`).join(", ")})`:"";return c(`${A}${J.join(`
|
|
157
|
-
|
|
158
|
-
`)}${te>0?`
|
|
159
|
-
|
|
160
|
-
\u2026 ${te} more matches${L}; continue with offset=${_+J.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:Gh,description:`Lines to return (default ${Gh})`}))}),async execute(h,g){let{scope:I,seq:E,runs:S,reference:k,both:A}=u(g),P;if(E!==void 0)P=ZC(I.records,E);else if(g.chunk_id){let _=S().find((J)=>J.id===g.chunk_id);if(!_)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);P=_r(_)}else{let _=S().map((J)=>`${k} ${J.id} (${J.status}, ${_r(J).length} lines)`);return c(_.length?`Pass chunk_id or seq. Chunks in this session:
|
|
161
|
-
${_.join(`
|
|
162
|
-
`)}`:"This session has no history yet")}let C=g.offset??0,M=P.slice(C,C+(g.limit??Gh));if(!M.length)return c(`No lines at offset ${C} (total ${P.length})`);let V=P.length-C-M.length;return c(`${A}${k} ${E!==void 0?`seq=${E}`:g.chunk_id}
|
|
163
|
-
${pn(M)}${V>0?`
|
|
164
|
-
|
|
165
|
-
\u2026 ${V} more lines; continue with offset=${C+M.length}`:""}`)}});return[p,f]}import{existsSync as OB,statSync as e0}from"fs";import{isAbsolute as t0,relative as _B,resolve as r0}from"path";var Sl=200,LB=30000,wl=Bun.which("rg");async function Kh(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 n0(e){let o=(f)=>f?t0(f)?f:r0(e,f):e,a=(f)=>{let h=_B(e,f);return h&&!h.startsWith("..")&&!t0(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).
|
|
166
|
-
- Respects .gitignore and skips .git. Use it instead of find or ls -R.
|
|
167
|
-
- 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=e0(I).isDirectory()}catch{}if(!E)throw Error(`Directory not found: ${a(I)}`);let S;if(wl)S=(await Kh([wl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",h.pattern],I,g)).split(`
|
|
168
|
-
`).filter(Boolean);else{S=[];for await(let C of new Bun.Glob(h.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(C))S.push(C)}if(!S.length)return c("No files found");let k=S.map((C)=>{let M=r0(I,C);try{return{path:M,time:e0(M).mtimeMs}}catch{return{path:M,time:0}}});k.sort((C,M)=>M.time-C.time);let A=k.slice(0,Sl).map((C)=>a(C.path)),P=S.length-A.length;return c(`${A.join(`
|
|
169
|
-
`)}${P>0?`
|
|
170
|
-
\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.
|
|
171
|
-
- output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
|
|
172
|
-
- Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
|
|
173
|
-
- Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
|
|
174
|
-
- 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(!OB(I))throw Error(`Path not found: ${a(I)}`);let E=h.output??"files",S;if(wl){let P=[wl,"--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 Kh(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 Kh(P,e,g)}let k=`${e}/`,A=S.split(`
|
|
175
|
-
`).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>Sl)return c(`${A.slice(0,Sl).join(`
|
|
176
|
-
`)}
|
|
177
|
-
\u2026 ${A.length-Sl} more files; narrow the search`);return c(tt(A.join(`
|
|
178
|
-
`),LB,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 o0(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.
|
|
179
|
-
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.
|
|
180
|
-
- Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
|
|
181
|
-
- 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.
|
|
182
|
-
- 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:W(l({content:s({minLength:1,description:"What to do, in imperative form"}),status:y(Zi.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 s0(e){let o=de(e);return{target:o,hard:o,index:o}}class Tl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},a){this.records=e;this.cwd=o;if(a)this.defaultPolicy=new un(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)??s0(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)+Ct(o),h=Math.max(0,de(a)*this.recoveryRatio-f),g=Ce(u??this.records(),a,s0(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 Wh,readFileSync as NB}from"fs";import{homedir as qB}from"os";import{dirname as i0,join as zh,resolve as DB}from"path";var FB=`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.
|
|
183
|
-
|
|
184
|
-
# How to work
|
|
185
|
-
|
|
186
|
-
- 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.
|
|
187
|
-
- 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.
|
|
188
|
-
- 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.
|
|
189
|
-
- 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.
|
|
190
|
-
|
|
191
|
-
# Making changes
|
|
192
|
-
|
|
193
|
-
- 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.
|
|
194
|
-
- 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.
|
|
195
|
-
- 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.
|
|
196
|
-
- 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).
|
|
197
|
-
- Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
|
|
198
|
-
- 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.
|
|
199
|
-
|
|
200
|
-
# Verifying
|
|
201
|
-
|
|
202
|
-
- 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.
|
|
203
|
-
- 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.
|
|
204
|
-
- 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.
|
|
205
|
-
- 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.
|
|
206
|
-
- 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.
|
|
207
|
-
|
|
208
|
-
# Tools
|
|
209
|
-
|
|
210
|
-
- Tool calls are the only way to act; describing an action does not perform it.
|
|
211
|
-
- 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.
|
|
212
|
-
- 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.
|
|
213
|
-
- 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.
|
|
214
|
-
- 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.
|
|
215
|
-
- 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.
|
|
216
|
-
- 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 &&.
|
|
217
|
-
- 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.
|
|
218
|
-
|
|
219
|
-
# Honesty
|
|
220
|
-
|
|
221
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
222
|
-
- Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
|
|
223
|
-
- When the user asks you to run something, run it, even when you can predict the result.
|
|
224
|
-
- If a step failed, was skipped or could not be verified, say which one and why.
|
|
225
|
-
|
|
226
|
-
# Safety
|
|
227
|
-
|
|
228
|
-
- 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.
|
|
229
|
-
- 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.
|
|
230
|
-
- 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.
|
|
231
|
-
- Never print, log or commit secrets such as API keys, tokens or passwords.
|
|
232
|
-
|
|
233
|
-
# Communication
|
|
234
|
-
|
|
235
|
-
- Reply in the same language the user writes in.
|
|
236
|
-
- 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.
|
|
237
|
-
- 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.
|
|
238
|
-
- Do not use emojis unless the user does or asks for them.
|
|
239
|
-
- 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.
|
|
240
|
-
- Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,jB=`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.
|
|
241
|
-
|
|
242
|
-
# Tools
|
|
243
|
-
|
|
244
|
-
- 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.
|
|
245
|
-
- 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.
|
|
246
|
-
- Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
|
|
247
|
-
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
|
|
248
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
249
|
-
|
|
250
|
-
# Communication
|
|
251
|
-
|
|
252
|
-
- Reply in the same language the user writes in.
|
|
253
|
-
- Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
|
|
254
|
-
- Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,UB=["AGENTS.md","CLAUDE.md"],BB=20000;function a0(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?FB:jB}],a=[];if(e.globalInstructions?.trim())a.push(Hh("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of GB(e.project.directory))a.push(Hh(u.path,u.content));if(e.project.instructions.trim())a.push(Hh(`Project "${e.project.name}" instructions`,e.project.instructions))}if(a.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
|
|
255
|
-
|
|
256
|
-
# Instructions from the user and project
|
|
257
|
-
|
|
258
|
-
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.
|
|
259
|
-
|
|
260
|
-
${a.join(`
|
|
261
|
-
|
|
262
|
-
`)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
|
|
263
|
-
|
|
264
|
-
${KB(e)}`}),o}function Hh(e,o){return`<instructions source="${e}">
|
|
265
|
-
${le(o.trim(),BB)}
|
|
266
|
-
</instructions>`}function GB(e){let o=[],a=e;for(let u=0;u<20;u++){for(let f of UB){let h=zh(a,f);if(Wh(h)){try{o.unshift({path:h,content:NB(h,"utf8")})}catch{}break}}if(Wh(zh(a,".git"))||a===qB())break;let p=i0(a);if(p===a)break;a=p}return o}function KB(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}=jt("",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>
|
|
267
|
-
${h.join(`
|
|
268
|
-
`)}
|
|
269
|
-
</environment>`}function HB(e){let o=DB(e);while(!0){if(Wh(zh(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let a=i0(o);if(a===o)return!1;o=a}}async function u0(e,o){if(o?.aborted||HB(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(`
|
|
270
|
-
`):[],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?`
|
|
271
|
-
${g.join(`
|
|
272
|
-
`)}`:" clean"}`,f?`Recent commits:
|
|
273
|
-
${f}`:"Recent commits: none"].join(`
|
|
274
|
-
`)}function Kt(e){let a=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?bl(e.records,e.history):[],u=e.directory??process.cwd();return[...YC(u,new Uh,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...n0(u),o0(e.onTodos),...a]}class Qi{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||!ts.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!es.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 Vh(e){return{name:e.name,description:e.description,parameters:e.parameters}}function Jh(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)=>Jh(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]=Jh(p[f],h);return p}return u}function WB(e){let o=e.prepareArguments;return{...e,prepareArguments:(a)=>{let u=Jh(a,e.parameters);return o?o(u):u}}}function zB(e,o,a){let u=e.prepareArguments?e.prepareArguments(a):a;return lu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class Qh{retrieved=new Map;stub(e,o){let a=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${a}
|
|
275
|
-
(Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,p,f,h)=>{let g=JSON.stringify(Vh(e)),I;try{I=zB(e,u,p??{})}catch(k){return{...c(`Invalid arguments for ${e.name}: ${String(k)}
|
|
276
|
-
Schema: ${g}`),isError:!0}}let E=await e.execute(u,I,f,h),S=E.content.map((k)=>k.type==="text"?{...k,text:tt(k.text,Pe,o)}:k);return{...E,content:S}}}}assemble(e,o,a,u){let p=e.map(WB),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(Vh(A)),C=this.retrieved.get(A.name);if(C?.schema===P)return{name:A.name,status:"\u5DF2\u53D6\u56DE",callID:C.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(A.name,{schema:P,callID:g}),Vh(A)})))}}),"tool_search")]}}async function Rl(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 VB=3,c0={attempts:10,delayMs:2000},JB=/\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 QB(e,o){if(e.stopReason!=="error")return!1;if(Ea(e,o))return!1;return!JB.test(e.errorMessage??"")}function m0(e,o,a){if(Ea(e,o))return!0;if(a?.preserveHistory!==!0)return!1;return e.errorMessage===(a.overflowError??"Context exceeds the request budget")}var p0="\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 l0(e){if(e.stopReason!=="length")return!1;return!e.content.some((o)=>o.type==="text"&&o.text.trim()||o.type==="toolCall")}function XB(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 d0(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<VB){let M=e.records.findLast((_)=>_.raw?.role==="assistant")?.raw;if(M&&l0(M)){if(!e.context.recover(p))throw Error(p0);g.throwIfAborted(),S++,await u.retry();continue}if(M?.stopReason!=="error")return;if(!m0(M,p.contextWindow,a)){if(!QB(M,p.contextWindow)||k>=c0.attempts)return;k++,await XB(c0.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((C)=>C.raw?.role==="assistant")?.raw;if(P&&l0(P))throw Error(p0);if(a?.preserveHistory===!0&&P?.stopReason==="error"&&m0(P,p.contextWindow,a))throw Error(a.overflowError??"Context exceeds the request budget")}async function f0(e,o,a,u,p,f){f.throwIfAborted();let h,g;try{g=await Promise.race([Rl(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,C,M,V)=>{let _=u()??g.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),J=_?I.policy(_):void 0;if(_&&!J?.(A.name,e))throw Error(`Tool ${A.name} is unavailable under tool policy ${_}`);let j=await I.invoke("tool.before_call",{name:A.name,callID:P,args:C},e);if(j.block)throw Error(j.block);let Y=await N.run(e,()=>A.execute(P,j.args,M,V));return I.invoke("tool.after_result",Y,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((C)=>C.entry.type==="compaction")){let M=bl(()=>e.records,(V)=>e.resolveHistory(V)).map(E);for(let V of M)if(!S.some((_)=>_.name===V.name))S.push(V)}}let A=new Qi(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 h0(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 _ of k?.notices??[])e.notice(_);await f.work,await f.flushNotices();let A=await o()?.invoke("projection.before",e.records,e),P=await o()?.invoke("projection.prefix",[],e)??[],C=e.context.prepare([...g,...P],I,E,A,a()?.preserveHistory===!0);if(a()?.preserveHistory===!0&&C.estimate>de(E))throw Error(a()?.overflowError??"Context exceeds the request budget");let M=C.messages,V=await o()?.invoke("projection.after",M,e)??M;return hu(dC(V))}}}async function g0(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((C,M)=>({...C,text:P[M]?.text??C.text}))}}finally{await f?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let h=p.map((P)=>P.text).join(`
|
|
277
|
-
`),g=p.map((P)=>o.plugins?.noticeSource(P.sourceKind)),I=Math.max(800,...g.map((P)=>P?.summaryLimit??800)),E=h.length>I?`
|
|
278
|
-
[\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]"}
|
|
279
|
-
${h.slice(0,I)}${E}`,A={role:"user",content:k,timestamp:Date.now()};return a({type:"user",text:k,notices:u.map(({text:P,...C})=>C)},A),A}class Xh{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:"basalt.notice",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=g0(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 YB=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 Yh(e){let o={};for(let[a,u]of Object.entries(e)){if(!YB.has(a.toLowerCase())){o[a]=u;continue}let p=/^bearer\s+/i.exec(u)?.[0];o[a]=p?`${p}***`:"***"}return o}function y0(e,o,a,u){let f=(a.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:a.systemPrompt}]).map((L,se)=>({id:`system-${se}`,label:L.label,detail:L.detail,tokens:H(L.detail)+(se===0?16:0)})),h=a.tools.map((L)=>{let se=L,he=se.defer==="defer"||L.description.includes("(Parameters not inlined: use toolsearch");return{name:L.name,description:L.description,group:se.group??"\u5185\u7F6E",schema:L.parameters,deferred:he}});f.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Ct(a.tools),detail:JSON.stringify(h,null,2)});let g=f.reduce((L,se)=>L+se.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 se=L.raw.usage;S??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},S.input+=se.input,S.output+=se.output,S.cacheRead+=se.cacheRead,S.cacheWrite+=se.cacheWrite,S.cost+=se.cost.total;let he=L.entry.generationMs??L.raw.generationMs;if(typeof he==="number"&&he>0&&se.output>0)k+=he,A+=se.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,C=e.context.calibrationRatio??1,M=Math.round(P*C),V=I.findLast((L)=>L.raw?.role==="assistant"),_=V?.raw,j=(V?I.filter((L)=>L.entry.seq>V.entry.seq&&L.raw):I.filter((L)=>L.raw)).length>0,Y,te;if(_){let L=_.usage,se=L.input+L.cacheRead+L.cacheWrite;if(se>0)Y=se,te=L.cacheRead/se}return{contextWindow:o.contextWindow,usableWindow:de(o),items:[...f,...E.items],calibratedTokens:M,calibrationRatio:C,lastInputTokens:Y,lastCacheHitRate:te,hasPendingOutput:j,tools:h,usage:S}}class rt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class oe extends Error{constructor(e="session"){super(`${e} is busy`)}}var Zh="medium",ZB=1e6;class kl{row;ctx;events;notices;lease;policyID;discovery=new Qh;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Rl(this,this.ctx,e);return new Qi(this.ctx.store).partition(o.tools).filter((a)=>this.permitsTool(a.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new oe;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 Xh(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 Tl(()=>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=Pn(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:Yh(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:Yh(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??Zh}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??Zh,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,ZB);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=Pn(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 Rl(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new Qi(this.ctx.store).partition(p.tools),(h)=>this.permitsTool(h),p.cwd);let f=y0(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 rt}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"||!Pn(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,jl(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=jl(o),u=yh(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 oe;if(e!==void 0)this.stopped=!1;let u=Pn(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:eG(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 qe(g.filter((A)=>A.raw))){if(k.result)continue;let A=k.message.stopReason;if(A==="error"||A==="aborted")continue;let{body:P,raw:C}=il(k.call);this.append(P,C)}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 xh(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 d0(this,this.lease,this.setup,h,u,e,o,p.signal,a!==void 0&&e===void 0),xh(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=Pn(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 f0(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=J$({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??Zh,captureRequest:(f)=>{this.lastRequestSnapshot=f},captureResponse:(f)=>{this.lastResponseSnapshot=f},steerConsumed:(f)=>this.markSteerConsumed(f),hooks:{tools:p,...h0(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=Pn(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=vr(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return 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 eG(e,o){let u=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
|
|
280
|
-
`)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var I0=new Set(["user","assistant","tool_result","run","compaction"]),tG=new Set(["user","assistant","toolResult"]);function E0(e,o,a){return{format:ri,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)=>I0.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===ri)return rG(e);if(yr(e.info)&&Array.isArray(e.messages))return oG(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 rG(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"||!I0.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,nG(g,h);let S=p.raw;if(S!==void 0&&!(yr(S)&&typeof S.role==="string"&&tG.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:jr(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(S0):[],created:hi(o.created)??Date.now(),updated:hi(o.updated)??Date.now(),needsRaw:!1,records:u}}function nG(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"&&Wi.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 oG(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(sG),f=[],h=0,g=0,I=(V,_)=>{g=Math.max(g,_??g),h+=1,f.push({entry:{...V,seq:h,time:g}})},E=!1,S=(V,_)=>{if(!E)return;E=!1,I({type:"run",state:"end",reason:V,..._?{error:_}:{}},void 0)};for(let V of p){let _=yr(V.info)?V.info:{},J=Array.isArray(V.parts)?V.parts.filter(yr):[],j=hi(yr(_.time)?_.time.created:void 0);if(_.role==="user"){S("done");let Y=iG(J);if(!Y)continue;I({type:"run",state:"start"},j),I(Y,j),E=!0}else if(_.role==="assistant"){if(!E)I({type:"run",state:"start"},j),E=!0;cG(_,J,I);let Y=b0(_.error);if(Y)S(Y.aborted?"aborted":"error",Y.aborted?void 0:Y.message)}}S("done");let k=p.findLast((V)=>yr(V.info)&&V.info.role==="assistant"),A=yr(k?.info)?k.info:void 0,P=jr(u?.providerID)||jr(A?.providerID),C=jr(u?.id)||jr(A?.modelID),M=P&&C?`${P}/${C}`:void 0;return{title:jr(o.title),model:M,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(S0):[],created:hi(a.created)??f[0]?.entry.time??Date.now(),updated:hi(a.updated)??f.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:f}}function sG(e,o){let a=(p)=>(yr(p.info)&&yr(p.info.time)?hi(p.info.time.created):void 0)??0,u=(p)=>yr(p.info)?jr(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)=>jr(u.text)).join(`
|
|
281
|
-
|
|
282
|
-
`),a=e.flatMap((u)=>u.type==="file"?aG(u):[]);if(!o.trim()&&a.length===0)return;return{type:"user",text:o,...a.length?{attachments:a}:{}}}function aG(e){let o=jr(e.mime)||"application/octet-stream",a=jr(e.filename)||"file",u=jr(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 uG(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 cG(e,o,a){let u=`${jr(e.providerID)}/${jr(e.modelID)}`,p=b0(e.error),f=uG(o);f.forEach((h,g)=>{let I=h.flatMap((k)=>{if(k.type==="reasoning")return jr(k.text).trim()?[{type:"thinking",text:jr(k.text)}]:[];if(k.type==="text")return k.ignored!==!0&&jr(k.text).trim()?[{type:"text",text:jr(k.text)}]:[];return[{type:"tool_call",id:x0(k.callID),name:jr(k.tool),input:yr(k.state)&&yr(k.state.input)?k.state.input:{}}]}),E=g===f.length-1,S=mG(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",C=A.status==="pending"||A.status==="running",M=P?[jr(A.output),jr(A.error)].filter(Boolean).join(`
|
|
283
|
-
`):C?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":jr(A.output);a({type:"tool_result",callID:x0(k.callID),name:jr(k.tool),output:M,isError:P||C},hi(yr(A.time)?A.time.end:void 0))}})}function x0(e){return jr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function b0(e){if(!yr(e))return;let o=yr(e.data)?e.data:{};return{message:jr(o.message)||jr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function mG(e){for(let o of e){let a=yr(o.time)?hi(o.time.start):yr(o.state)?pG(o.state):void 0;if(a!==void 0)return a}return}function pG(e){return yr(e.time)?hi(e.time.start):void 0}function S0(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 w0(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:lG(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:dG(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 lG(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)}>
|
|
284
|
-
${f.data}
|
|
285
|
-
</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(`
|
|
286
|
-
|
|
287
|
-
`);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 jr(e){return typeof e==="string"?e:""}function hi(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function dG(e){return yr(e)?e:{}}function Qt(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:C})=>C.seq<=A);k.entry.through=P?I.get(P.entry.seq)??0:0}return k})}function Jt(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 k0}from"buffer";import{createHash as fG}from"crypto";import{isDeepStrictEqual as Al}from"util";var Pl="@blob:";function bu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function T0(e,o,a){if(typeof e!=="string"||e.length<256||e.startsWith(Pl))return;let u=k0.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let p=fG("sha256").update(u).digest("hex");return a.put(p,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Pl}${p}`}function R0(e,o){if(typeof e!=="string"||!e.startsWith(Pl))return;let a=o.get(e.slice(Pl.length));if(a===void 0)return;return k0.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=T0(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=T0(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 gi(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=R0(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=R0(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 zc(e,o){if(!bu(o))return o;if(e.type==="user"){let{merged:a,images:u}=Bc(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&&Al(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((J)=>({type:"image",mimeType:J.mimeType,data:J.data}))];if("details"in o?!Al(o.details,e.meta):e.meta!==void 0)return o;let{role:S,toolCallId:k,toolName:A,content:P,details:C,isError:M,timestamp:V,..._}=o;if(Al(g,I))return{role:"toolResult",...p!==e.name?{toolName:p}:{},..._,timestamp:h};if(Array.isArray(g)){let J=e.images??[],j=0,Y=!0,te=g.map((L)=>{if(bu(L)&&L.type==="image"){let se=J[j++],he=Object.keys(L);if(se&&he.length===3&&L.mimeType===se.mimeType&&L.data===se.data)return{type:"image",mimeType:L.mimeType};Y=!1}return L});if(Y&&j===J.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:te,..._,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(bu(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&&Al(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 eg(e,o){if(!bu(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}=Bc(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(bu(P)&&P.type==="image"&&!("data"in P)){let C=k[A++];if(C)return{type:"image",mimeType:P.mimeType,data:C.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(bu(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 A0(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=gi(E,u),k=$l(S,u),A=k===E?I.body:JSON.stringify(k),P=I.raw;if(I.raw!==null)try{let C=JSON.parse(I.raw),M=eg(S,C),V=zc(S,M);P=JSON.stringify(V)}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 hG}from"bun:sqlite";import{chmodSync as P0,existsSync as gG,mkdirSync as yG}from"fs";import{dirname as xG}from"path";var tg=[`
|
|
288
|
-
CREATE TABLE projects (
|
|
289
|
-
id TEXT PRIMARY KEY,
|
|
290
|
-
name TEXT NOT NULL,
|
|
291
|
-
directory TEXT NOT NULL UNIQUE,
|
|
292
|
-
instructions TEXT NOT NULL DEFAULT '',
|
|
293
|
-
created INTEGER NOT NULL,
|
|
294
|
-
updated INTEGER NOT NULL
|
|
295
|
-
);
|
|
296
|
-
CREATE TABLE automations (
|
|
297
|
-
id TEXT PRIMARY KEY,
|
|
298
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
299
|
-
name TEXT NOT NULL,
|
|
300
|
-
prompt TEXT NOT NULL,
|
|
301
|
-
schedule TEXT NOT NULL,
|
|
302
|
-
model TEXT NOT NULL,
|
|
303
|
-
enabled INTEGER NOT NULL,
|
|
304
|
-
created INTEGER NOT NULL,
|
|
305
|
-
updated INTEGER NOT NULL,
|
|
306
|
-
next_run INTEGER,
|
|
307
|
-
last_run INTEGER,
|
|
308
|
-
last_session_id TEXT
|
|
309
|
-
);
|
|
310
|
-
CREATE TABLE sessions (
|
|
311
|
-
id TEXT PRIMARY KEY,
|
|
312
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
313
|
-
automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
|
|
314
|
-
title TEXT NOT NULL DEFAULT '',
|
|
315
|
-
model TEXT NOT NULL,
|
|
316
|
-
todos TEXT NOT NULL DEFAULT '[]',
|
|
317
|
-
created INTEGER NOT NULL,
|
|
318
|
-
updated INTEGER NOT NULL
|
|
319
|
-
);
|
|
320
|
-
CREATE INDEX sessions_project ON sessions(project_id);
|
|
321
|
-
CREATE TABLE entries (
|
|
322
|
-
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
323
|
-
seq INTEGER NOT NULL,
|
|
324
|
-
time INTEGER NOT NULL,
|
|
325
|
-
body TEXT NOT NULL,
|
|
326
|
-
raw TEXT,
|
|
327
|
-
PRIMARY KEY (session_id, seq)
|
|
328
|
-
) WITHOUT ROWID;
|
|
329
|
-
`,"","","",`
|
|
330
|
-
ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
|
|
331
|
-
ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
|
|
332
|
-
ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
|
|
333
|
-
CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
|
|
334
|
-
ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
|
|
335
|
-
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,
|
|
336
|
-
PRIMARY KEY (namespace, key));
|
|
337
|
-
CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
|
|
338
|
-
PRIMARY KEY (namespace, version));
|
|
339
|
-
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);
|
|
340
|
-
CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
|
|
341
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
342
|
-
END;
|
|
343
|
-
CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
|
|
344
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
|
|
345
|
-
END;
|
|
346
|
-
CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
|
|
347
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
348
|
-
END;
|
|
349
|
-
CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
|
|
350
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
351
|
-
END;
|
|
352
|
-
CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
|
|
353
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
354
|
-
END;
|
|
355
|
-
CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
|
|
356
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
|
|
357
|
-
END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
|
|
358
|
-
WHERE json_extract(body,'$.type')='compaction';
|
|
359
|
-
CREATE TABLE IF NOT EXISTS blobs (
|
|
360
|
-
hash TEXT PRIMARY KEY,
|
|
361
|
-
mime TEXT NOT NULL,
|
|
362
|
-
data BLOB NOT NULL
|
|
363
|
-
) WITHOUT ROWID;
|
|
364
|
-
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 IG=[20,50,100,200,400,800];function EG(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 rg(e){let o=0;while(!0)try{return e()}catch(a){let u=IG[o];if(u===void 0||!EG(a))throw a;o++,Bun.sleepSync(u)}}function $0(e,o){if(e!==":memory:")yG(xG(e),{recursive:!0});let a=new hG(e,{create:!0,strict:!0}),u=(f,h=!0)=>new Proxy(function(...g){return Reflect.apply(f,this,g)},{apply(g,I,E){Vs();let S=o.length===0&&!a.inTransaction,k=h?Reflect.get(f,"immediate"):void 0,A=()=>{let P=[];o.push(P);let C=!1;try{let M=typeof k==="function"?Reflect.apply(k,f,E):Reflect.apply(g,I,E);return C=!0,M}finally{o.pop();let M=o.at(-1);if(C&&M)M.push(...P);else for(let V of P)if(C)V.commit();else V.rollback()}};return S?rg(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)=>{Vs();let k=(h==="run"||h==="exec")&&o.length===0&&!a.inTransaction?rg(()=>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,C){let M=Reflect.get(A,P,A);if(typeof M!=="function")return M;return(...V)=>{Vs();let j=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!a.inTransaction?rg(()=>Reflect.apply(M,A,V)):Reflect.apply(M,A,V);return j===A?C:j}}})}}});if(e!==":memory:")P0(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"),bG(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(gG(h))P0(h,384)}return p}function bG(e,o=tg){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?SG(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 SG(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(`
|
|
365
|
-
`,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 Cl=({position:e,closed_at:o,...a})=>({...a,closedAt:o??null}),vl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch{}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 Ml=new Set(["user","run","extension","notice_pending","compaction"]);class Ol{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=$0(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(Cl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Cl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Cl(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(vl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(vl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(vl)}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,Qt(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(zc(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){Vs();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),C=P===k&&!f?S:JSON.stringify(P),M=u===void 0?null:JSON.stringify(zc(k,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,g,A.time,C,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,C),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=gi(JSON.parse(u.body),this.blobs),f=zc(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)=>Ml.has(h))?this.cachedEntries(e):void 0;if(p&&a)return p.filter((g)=>g.seq>o&&a.includes(g.type)).map((g)=>({...u?gi(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)=>({...gi(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=[...Ml],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||!Ml.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)=>({...gi(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=gi(JSON.parse(a.body),this.blobs);return{entry:{...u,seq:a.seq,time:a.time},...a.raw===null?{}:{raw:eg(u,JSON.parse(a.raw))}}})}lastEntry(e,o){if(Ml.has(o)){let u=this.cachedEntries(e);if(u){let p=u.findLast((f)=>f.type===o);return p?{...gi(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?{...gi(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==="basalt.notice"&&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 ne(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as wG,readdirSync as M0,statSync as O0}from"fs";import{join as _0}from"path";function Vc(e){try{return O0(e).size}catch{return 0}}function L0(e){try{return Math.round(O0(e).mtimeMs)}catch{return}}function N0(e){let o=0,a=0;try{let u=M0(e,{withFileTypes:!0});for(let p of u){let f=_0(e,p.name);if(p.isDirectory()){let h=N0(f);o+=h.bytes,a+=h.files}else if(p.isFile())o+=Vc(f),a+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:a}}function TG(e){if(!wG(e))return[];try{return M0(e,{withFileTypes:!0}).flatMap((o)=>{let a=_0(RG(e),o.name),u=L0(a);if(o.isDirectory()){let p=N0(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:Vc(a),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,a)=>a.bytes-o.bytes||o.name.localeCompare(a.name))}catch{return[]}}function RG(e){return e}function yi(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 C0(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 kG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},AG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function PG(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 $G(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,a=e.db.query(`SELECT
|
|
366
|
-
count(*) AS total,
|
|
367
|
-
sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
|
|
368
|
-
sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
|
|
369
|
-
sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
|
|
370
|
-
sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
|
|
371
|
-
FROM sessions`).get(),u=e.db.query(`SELECT
|
|
372
|
-
count(*) AS total,
|
|
373
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
374
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
|
|
375
|
-
min(time) AS oldest_time,
|
|
376
|
-
max(time) AS newest_time
|
|
377
|
-
FROM entries`).get(),f=e.db.query(`SELECT
|
|
378
|
-
coalesce(json_extract(body, '$.type'), 'unknown') AS type,
|
|
379
|
-
count(*) AS count,
|
|
380
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
381
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes
|
|
382
|
-
FROM entries
|
|
383
|
-
GROUP BY type
|
|
384
|
-
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
|
|
385
|
-
namespace,
|
|
386
|
-
count(*) AS keys,
|
|
387
|
-
coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
|
|
388
|
-
FROM plugin_kv
|
|
389
|
-
GROUP BY namespace
|
|
390
|
-
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 _l(e,o){let a=yi(e,"page_size"),u=yi(e,"page_count"),p=yi(e,"freelist_count"),f=e.db.query("PRAGMA journal_mode").get(),h=e.db.query("SELECT sqlite_version() AS v").get(),g=yi(e,"synchronous"),I=yi(e,"auto_vacuum"),E=yi(e,"cache_size"),S=E<0?Math.abs(E)*1024:E*a,k=yi(e,"foreign_keys")===1,A=yi(e,"busy_timeout"),P=C0(e,"encoding")??"UTF-8",C=C0(e,"quick_check(1)")??"ok",M=e.path!==":memory:"?L0(e.path):void 0,V=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),_=PG(e),J=TG(o);return{dataDir:o,databasePath:e.path,dataBytes:J.reduce((j,Y)=>j+Y.bytes,0),database:{size:Vc(e.path),walSize:Vc(`${e.path}-wal`),shmSize:Vc(`${e.path}-shm`),sqliteVersion:h?.v??"unknown",journalMode:f?.journal_mode??"unknown",synchronous:kG[g]??String(g),foreignKeys:k,busyTimeout:A,encoding:P,autoVacuum:AG[I]??String(I),cacheSizeBytes:S,pageSize:a,pageCount:u,freelistCount:p,reclaimableBytes:p*a,schemaVersion:yi(e,"user_version"),...M!==void 0?{lastModified:M}:{},integrity:C},analytics:$G(e),entries:J,tables:V.map(({name:j,sql:Y})=>{let te=j.replaceAll('"','""'),L=e.db.query(`SELECT count(*) AS count FROM "${te}"`).get().count,se=e.db.query(`PRAGMA table_info("${te}")`).all().map((X)=>X.name),he=e.db.query(`PRAGMA index_list("${te}")`).all().length,Me=Boolean(Y&&/WITHOUT\s+ROWID/i.test(Y)),ze=_.get(j);return{name:j,rows:L,...ze?{bytes:ze.bytes,pages:ze.pages}:{},indexes:he,columns:se,withoutRowid:Me}})}}function v0(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 q0(e,o,a){let u=_l(e,o);if(a.vacuum)A0(e.db),e.invalidateEntryCache(),v0(e),e.db.run("VACUUM");else if(a.checkpoint)v0(e);if(a.checkpoint||a.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:_l(e,o)}}var CG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Ll{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(CG.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 D0(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 F0(e,o){let a=e.options.visibleModelProviders?.(),p=(await e.options.models.getAvailable().catch(()=>[])).filter((h)=>!a||a.includes(h.provider)).map((h)=>({...D0(Rt(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=Pn(e.options.models,h);if(!g||a&&!a.includes(g.provider))continue;f.add(h),p.push({...D0(h,g),available:!1})}return{models:p}}function j0(e,o){if(typeof o!=="string"||!Pn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as vG,statSync as MG}from"fs";import{basename as OG,resolve as _G}from"path";class ng{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=_G(e.directory.trim());if(!vG(o)||!MG(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:ne("p"),name:e.name?.trim()||OG(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 oe("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 tK,readFileSync as rK}from"fs";import{homedir as nK}from"os";import{join as Su}from"path";var z0=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),LG={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"]},NG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),ig={'"':['"'],"\u201C":["\u201D",'"']},og=(e)=>e!==void 0&&/\s/.test(e),V0=(e)=>[...new Set(e)],Jc=(e)=>[...e].length;var qG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function DG(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),C=Number(I[7]??0);if(A>23||P>59||C>59)return null;let M=new Date(E,S-1,k,A,P,C);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 FG=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),ag=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),ug=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function sg(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=LG[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=DG(h,f);if(!E)return g("bad_filter_value",`${o}:${h} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=ag(e.after,E.start);else if(o==="before")e.before=ug(e.before,E.start);else if(e.after=ag(e.after,E.start),E.end!==void 0)e.before=ug(e.before,E.end)}}}function jG(e,o){let a={},u=(C,M)=>{let V=V0([...C??[],...M]);return V.length?V: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=ag(e?.after,o.after),P=ug(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 U0(e,o){let a=ig[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 B0(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 z0.has(u)?u:void 0}function G0(e,o,a){let u=e==="word"&&!a&&Jc(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 UG(e,o){let a=[],u=e.length,p=0;while(p<u){if(og(e[p])){p++;continue}let f=!1;if(e[p]==="-"){if(p+1>=u||og(e[p+1])){p++;continue}f=!0,p++}if(ig[e[p]]){let P=U0(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 C=P.text.trim();if(C)a.push({kind:"term",negated:f,term:G0("phrase",C,!1)});continue}let h=[],g;while(p<u&&!og(e[p])){let P=e[p],C=e[p+1];if(P==="\\"&&C!==void 0&&NG.has(C)){h.push({c:C,esc:!0}),p+=2;continue}let M=ig[P]?B0(h):void 0;if(M){let V=U0(e,p);if(p=V.next,!V.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});g={key:M,value:V.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,C)=>C>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),E=I>0?B0(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:G0("word",A,k)})}return a}var BG=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function K0(e){let o=[];return{rest:e.replace(BG,(u,p,f,h,g)=>{let I=h.toLowerCase();if(!z0.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 H0={n:`
|
|
391
|
-
`,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function GG(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 H0)return{kind:"lit",ch:H0[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 C=o.indexOf(">",a);a=C<0?o.length:C+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 W0(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(...J0(g.alts));else u()}};return p(e),u(),o}function J0(e){if(e.length===1)return W0(e[0]);let o=[];for(let a of e){let u=W0(a).filter((p)=>p.length===1).map((p)=>p[0]);if(!u.length)return[];o.push(u.reduce((p,f)=>Jc(f)>Jc(p)?f:p))}return[V0(o)]}var KG=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function HG(e){return!/^\s*$/.test(e)&&(Jc(e)>=2||KG.test(e))}function WG(e){let o;try{o=J0(GG(e))}catch{return[]}let a=o.filter((I)=>I.every(HG)),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(Jc));return h.sort((I,E)=>g(E)-g(I))}function zG(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 VG(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 Nl(e,o={}){let a=o.now??Date.now(),u=e.q??"",p=FG(),f=p.diagnostics,h,g=[];if(e.mode==="regex"){let M=K0(u);for(let V of M.filters)sg(p,V.key,V.value,V.negated,V.quoted,a);h=M.rest}else{let M=K0(u),V=/^\/([\s\S]+)\/$/.exec(M.rest);if(V){for(let _ of M.filters)sg(p,_.key,_.value,_.negated,_.quoted,a);h=V[1]}else{g=[{include:[],exclude:[]}];for(let _ of UG(u,f)){let J=g[g.length-1];if(_.kind==="or")g.push({include:[],exclude:[]});else if(_.kind==="filter")sg(p,_.key,_.value,_.negated,_.quoted,a);else(_.negated?J.exclude:J.include).push(_.term)}g=g.filter((_)=>_.include.length||_.exclude.length)}}let I=g.flatMap((M)=>[...M.include,...M.exclude]),E=h!==void 0?zG(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=VG(h,S);if("message"in M)P={code:"bad_regex",message:M.message};else{let V=WG(h);A={source:h,flags:M.flags,literals:V,deepScan:V.length===0}}}let C=jG(e.filters,p);return{mode:h!==void 0?"regex":"text",branches:g,...A?{regex:A}:{},filters:C,currentSession:p.currentSession,caseSensitive:S,smartCase:k,wholeWord:e.wholeWord??!1,fuzzy:g.some((M)=>M.include.some((V)=>V.fuzzy)),hasPositive:A!==void 0||g.some((M)=>M.include.length>0),hasFilters:Object.keys(C).length>0||p.currentSession,...P?{error:P}:{},diagnostics:f}}var mg={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},Q0=new WeakMap;function X0(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,a=Q0.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 Q0.set(e,{version:o,terms:u}),u}var cg=32,JG=1024,Qc=(e)=>`"${e.replaceAll('"','""')}"`;function QG(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 pg(e,o){let a=Lt(o.trim());if(!a||a.length>64)return[];let u=X0(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(QG(a,g.t)<=f)h.push(g.t);if(h.length>=8)break}return[...new Set([...p,...h])].slice(0,8)}function Y0(e,o){let a=!1,u=[],p=[],f=o.filters,h=(V,_)=>{if(!_?.length)return;p.push(`${V} IN (${_.map(()=>"?").join(",")})`),u.push(..._)};if(h("s.project_id",f.projectID),f.sessionID?.length){p.push(`(${f.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let V of f.sessionID)u.push(V,V)}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((V)=>Fe[V])),h("r.tool",f.tools),f.model?.length){p.push(`(${f.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let V of f.model)u.push(V,V)}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((
|
|
392
|
-
SELECT max(json_extract(body,'$.through')) FROM store.entries
|
|
393
|
-
WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
|
|
394
|
-
),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=(V)=>{let _=(Y)=>{let te=Lt(Y);if(!V&&S){if([...te].length<3){let X=[...te].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(te,`${te}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(te);if([...te].length===1&&X.length>cg)X.length=cg,a=!0;if(!X.length)return Qc("__basalt_no_short_match__");return`(${X.map((ee)=>Qc(ee.term)).join(" OR ")})`}return Qc(te)}let L=/^[\p{Script=Latin}\p{N}]+$/u.test(Y)?[te]:ms(Y),se=L.filter((X)=>!/^[a-z0-9]{1,2}$/.test(X)),he=se.length?se:L;if(!he.length){k=!0;return}let Me=he.map((X,ee)=>{let be=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(X),Xe=he.length>2&&ee>0&&ee<he.length-1;if(be||Xe){let Re=e.query("SELECT n FROM term WHERE t=?").get(X)?.n??0;return{expression:Qc(X),frequency:Re}}let Ge=[X],ar=0;for(let Re of X0(e)){if(!Re.t.includes(X))continue;if(ar+=Re.n,Re.t!==X)Ge.push(Re.t);if(Ge.length>=cg){a=!0;break}}return{expression:`(${Ge.map(Qc).join(" OR ")})`,frequency:ar}});return Me.sort((X,ee)=>X.frequency-ee.frequency),`(${Me.slice(0,(Me[0]?.frequency??1/0)<=JG?1:2).map((X)=>X.expression).join(" AND ")})`},J=o.regex?o.regex.literals:o.branches.map((Y)=>Y.include.map((te)=>te.text));if(o.regex){let Y=J.map((te)=>te.map(_));if(Y.some((te)=>te.some((L)=>!L)))return;return Y.map((te)=>`(${te.join(" OR ")})`).join(" AND ")||void 0}let j=J.map((Y)=>{let te=Y.filter((L)=>!/^[a-z0-9]{1,2}$/i.test(L));return(te.length?te:Y).map(_)});if(j.some((Y)=>!Y.length||Y.some((te)=>!te)))return;return j.map((Y)=>`(${Y.join(" AND ")})`).join(" OR ")||void 0},P=A(!1),C=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:C,scan:k,where:p.length?p.join(" AND "):"1",bindings:u,forks:M,sessionWhere:g,sessionBindings:I,partial:a,candidateLimit:o.branches.some((V)=>V.include.length>0&&V.include.every((_)=>[..._.text].length<2))?512:void 0}}function Z0(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 ql(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(mg).map(([a,u])=>`WHEN ${Fe[a]} THEN ${u}`).join(" ")} ELSE 1 END) *
|
|
395
|
-
(0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function ev(e,o,a,u){let p=Math.max(0,u-a)/86400000;return Math.max(0.000000001,-e)*mg[o]*(0.3+0.7/(1+p/30))}function lg(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 fg=512;function tv(e,o,a){let u=performance.now(),p=o.partial;hg(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 ?
|
|
396
|
-
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 ?
|
|
397
|
-
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=Z0(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
|
|
398
|
-
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 rv(e,o,a,u,p){let f=performance.now();if(o.candidateLimit){let g=e.query(`
|
|
399
|
-
SELECT r.session_id,r.seq,${ql(u)} AS score
|
|
400
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
401
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
402
|
-
WHERE ${o.where} LIMIT ${o.candidateLimit+1}
|
|
403
|
-
`).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(`
|
|
404
|
-
SELECT r.session_id,${a?"r.seq":"0"} AS seq,max(${ql(u)}) AS score
|
|
405
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
406
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
407
|
-
WHERE ${o.where}
|
|
408
|
-
GROUP BY r.session_id${a?",r.seq":""}
|
|
409
|
-
ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
|
|
410
|
-
`).all(...o.bindings);return p?.("filter",performance.now()-f),h}var nv=new WeakMap,XG=`WITH RECURSIVE lineage(child,ancestor,through) AS (
|
|
411
|
-
SELECT id,forked_from_id,forked_from_seq FROM store.sessions
|
|
412
|
-
WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
|
|
413
|
-
UNION
|
|
414
|
-
SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
|
|
415
|
-
FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
|
|
416
|
-
WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
|
|
417
|
-
)`;function hg(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(`${XG} 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();nv.set(e,new Map(a.map((u)=>[u.ancestor,u.through])))}function dg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
|
|
418
|
-
SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
|
|
419
|
-
JOIN store.sessions ps ON ps.id=pr.session_id
|
|
420
|
-
WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
|
|
421
|
-
AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
|
|
422
|
-
AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
|
|
423
|
-
SELECT 1 FROM store.entries original JOIN store.entries copied
|
|
424
|
-
ON copied.session_id=r.session_id AND copied.seq=r.seq
|
|
425
|
-
WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
|
|
426
|
-
))
|
|
427
|
-
))`}function ov(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(`
|
|
428
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${h>4000?"INDEXED BY ref_time":""}
|
|
429
|
-
${g} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${dg(o)}
|
|
430
|
-
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(`
|
|
431
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${g}
|
|
432
|
-
WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
|
|
433
|
-
AND ${o.where} AND ${dg(o)} AND NOT EXISTS (
|
|
434
|
-
SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
|
|
435
|
-
)`).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 sv(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(`
|
|
436
|
-
SELECT r.session_id,${I?"r.seq":"0"} AS seq,
|
|
437
|
-
max(${ql(p)}) AS relevance,max(r.time) AS time
|
|
438
|
-
FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
|
|
439
|
-
WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
|
|
440
|
-
GROUP BY r.session_id${I?",r.seq":""}
|
|
441
|
-
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 iv(e,o,a,u,p,f){let h=performance.now(),g=p?o:{...o,forks:!1},I=e.query(`
|
|
442
|
-
SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
|
|
443
|
-
${g.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
444
|
-
WHERE r.session_id=? ${u?"AND r.seq=?":""}
|
|
445
|
-
AND ${o.where} AND ${dg(g)}
|
|
446
|
-
${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 gg(e,o,a,u){if(!o.forks)return[];let p=nv.get(e)?.get(a.session_id);if(p===void 0||a.seq>p)return[];return e.query(`
|
|
447
|
-
SELECT DISTINCT r.session_id,s.title,e.body
|
|
448
|
-
FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
|
|
449
|
-
CROSS JOIN ref r ON r.session_id=l.child
|
|
450
|
-
JOIN store.sessions s ON s.id=r.session_id
|
|
451
|
-
LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
|
|
452
|
-
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 nt(h,!0).some((g)=>g.part===a.part&&g.kind===yo[a.kind]&&g.text===u)}).map((f)=>f.session_id)}function YG(e,o){let a=o?e:Lt(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:Lt(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 Dl(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&&!av(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}=YG(e,o.caseSensitive),f=(I)=>{let E=o.caseSensitive?I.text:Lt(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,C=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||C)&&(!o.wholeWord||av(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 av(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 Fl(e,o){let a=e.split(`
|
|
453
|
-
`),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,C])=>C>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,C])=>[Math.max(0,P-I-S),Math.min(k.length,C-I-S)]);return{text:k,line:h+1,ranges:A.filter(([P,C])=>P<C)}})}var uv=3;function ZG(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 cv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function eK(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&&!ZG(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 dn(e,o){let a=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return eK(e.cursor,a)}async function Ar(e,o,a){let u="search"in e?e.search:e,p=performance.now(),f=(Re)=>{if(!a.signal?.aborted)a.onEvent(Re)};if(a.signal?.aborted)return;let h=dn(o,a.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let g=Nl(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((Re)=>Y0(Re,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,C=[],M=!1,V=new Map,_=new WeakMap,J=new Map,j=new Map,{offset:Y,window:te}=h,L=[...h.seen],se=[...h.emitted],he=!1,Me=Math.max(1,Math.min(200,o.limit??30)),ze=Math.min(E.candidateLimit??2000,o.group==="none"?fg:Math.min(2000,Math.max(fg,Me*32))),X=(Re,ke)=>{let Wt=A.get(ke);if(Wt)return Wt;let ft=Re.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(ke);if(ft)A.set(ke,ft);return ft??void 0},ee=(Re,ke,Wt)=>{if(a.allowedSessionIDs&&!a.allowedSessionIDs.has(ke.session_id))return;if(a.excludeEntry?.sessionID===ke.session_id&&a.excludeEntry.seq===ke.seq)return;let ft=X(Re,ke.session_id);if(!ft)return;let Dt=yo[ke.kind];if(!Dt)return;let Ir=ft.title;if(ke.seq!==0){let it=`${ke.session_id}:${ke.seq}`,ur=j.get(it);if(!ur){let on=Wt?void 0:Re.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(ke.session_id,ke.seq);if(!Wt&&!on)return;let or=Wt??JSON.parse(on?.body??"null");ur=nt(or,!0),j.set(it,ur)}let pr=ur.find((on)=>on.part===ke.part&&on.kind===Dt);if(!pr)return;Ir=pr.text}let fr=Dl(Ir,g);if(!fr)return;let tr=P.get(ft.id);if(tr===void 0)tr=Re.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(ft.id)?.through??0,P.set(ft.id,tr);let st=ke.seq>0&&ke.seq<=tr;if(g.filters.compacted!==void 0&&st!==g.filters.compacted)return;let Ot={sessionID:ft.id,seq:ke.seq,time:ke.time,field:Dt,tool:ke.tool??void 0,isError:Boolean(ke.err),model:ke.model??void 0,snippet:[],score:ev(ke.relevance,Dt,ke.time,h.now),flags:{archived:ft.archived_at!==null,compacted:st,partial:Ir.length>cs+us}};return V.set(Ot,{text:Ir,ranges:fr}),C.push(Ot),M=!0,J.set(Ot,{doc:ke.doc,part:ke.part}),Ot},be=(Re)=>{let ke=performance.now(),Wt=[...Re].sort((st,Ot)=>st.time-Ot.time||st.sessionID.localeCompare(Ot.sessionID)),ft=[],Dt=new Map;for(let st of Wt){let Ot=J.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((qo)=>X(qo,ur?.forked_from_id??""));let on=`${ur?.id??st.sessionID}:${st.seq}:${Ot?.part}:${Ot?.doc}`,or=Dt.get(on);if(or){if(or.sessionID!==st.sessionID)or.forks=[...new Set([...or.forks??[],st.sessionID])]}else Dt.set(on,st),ft.push(st)}let Ir=[],fr=new Map,tr=new Map;for(let st of ft){let Ot=`${st.sessionID}:${st.seq}`,it=tr.get(Ot);if(!it){tr.set(Ot,st),_.set(st,[st]);continue}let ur=[..._.get(it)??[it],st],pr=st.score>it.score?st:it;if(pr.forks=[...new Set([...it.forks??[],...st.forks??[]])],!pr.forks.length)pr.forks=void 0;pr.flags={archived:it.flags.archived||st.flags.archived,compacted:it.flags.compacted||st.flags.compacted,partial:it.flags.partial||st.flags.partial},tr.set(Ot,pr),_.set(pr,ur)}for(let st of lg([...tr.values()],o.sort??"best")){let Ot=A.get(st.sessionID);if(!Ot)continue;let it=o.group==="none"?void 0:fr.get(Ot.id);if(!it)it={session:{id:Ot.id,title:Ot.title,projectID:Ot.project_id,updated:Ot.updated},hits:[],more:0,...S&&o.group!=="none"?{moreIsLowerBound:!0}:{}},Ir.push(it),fr.set(Ot.id,it);if(it.hits.length<uv||o.group==="none")it.hits.push(st);else it.more++}return a.onTiming?.("group",performance.now()-ke),Ir},Xe=(Re)=>{for(let ke of Re)for(let Wt of ke.hits){if(a.allowedSessionIDs&&Wt.forks)Wt.forks=Wt.forks.filter((Ir)=>a.allowedSessionIDs?.has(Ir));let ft=performance.now(),Dt=new Map;for(let Ir of _.get(Wt)??[Wt]){let fr=V.get(Ir);if(!fr)continue;for(let tr of Fl(fr.text,fr.ranges)){let st=`${tr.line}:${tr.text}`,Ot=Dt.get(st);if(!Ot)Dt.set(st,tr);else Ot.ranges=[...new Map([...Ot.ranges,...tr.ranges].map((it)=>[it.join(":"),it])).values()]}}Wt.snippet=[...Dt.values()],a.onTiming?.("snippet",performance.now()-ft)}},Ge=o.deep||E.scan,ar=(Re,ke)=>{let Wt=X(Re,ke.session_id);if(!Wt)return[];let ft=iv(Re,E,ke,o.group==="none",Wt.forked_from_id!==null,a.onTiming);if(E.candidateLimit&&ft.length>E.candidateLimit)ft.length=E.candidateLimit,S=!0;let Dt=C.length,Ir=performance.now();for(let fr of ft){if(a.signal?.aborted)break;let tr=ee(Re,fr);if(!tr)continue;let st=gg(Re,E,fr,V.get(tr)?.text??"");if(st.length)tr.forks=st}return a.onTiming?.("body",performance.now()-Ir),C.slice(Dt)};if(Ge){S=!1;let Re=[],ke=new Set,Wt=u.withIndex((it)=>{hg(it,E);for(let or of it.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(it.query(`SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}`).all(...E.sessionBindings).map((or)=>or.id)),pr=(or)=>{if(ke.has(or.id))return;ke.add(or.id);let qo=or.forked_from_id?A.get(or.forked_from_id):void 0;if(qo)pr(qo);if(ur.has(or.id))Re.push(or)};for(let or of A.values())pr(or);return(it.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
|
|
454
|
-
SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}
|
|
455
|
-
)`).get(...E.sessionBindings)?.n??0)+ur.size})??0,ft=0,Dt=0,Ir=0;if(g.regex?.deepScan)f({type:"groups",groups:[]});let fr=new Set,tr=new Set,st=new Map,Ot=()=>{let it=be(C),ur=[];for(let pr of it){let on=pr.session.id,or=o.group==="none"?void 0:st.get(on);if(o.group!=="none"&&tr.has(on)&&!or)continue;if(!or){if(tr.add(on),Dt<h.offset){Dt++;continue}if(Ir>=Me){he=!0;break}Ir++,Y++}if(o.group!=="none"){let qo=(or?.count??0)+pr.hits.length+pr.more;pr.hits=pr.hits.slice(0,uv-(or?.shown??0));let wu=(or?.shown??0)+pr.hits.length;pr.more=qo-wu,st.set(on,{shown:wu,count:qo})}ur.push(pr)}if(ur.length)Xe(ur),f({type:"groups",groups:ur});C.length=0,V.clear(),J.clear(),j.clear()};for(let it of Re){if(a.signal?.aborted||he)break;let ur=-1,pr;for(;;){if(a.signal?.aborted||he)break;let on=u.withIndex((or)=>{let qo=or.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(it.id,Math.max(0,ur));if(ur<0)qo.unshift({seq:0,time:it.updated,body:null});for(let Xi of qo){if(a.signal?.aborted)break;let Tu=Xi.body?JSON.parse(Xi.body):void 0;if(Tu?.type==="assistant")pr=Tu.model;let lv=Tu?nt(Tu,!0):[{part:0,kind:"title",text:it.title}];for(let Wo of lv){if(a.signal?.aborted)break;let Js={session_id:it.id,seq:Xi.seq,part:Wo.part,doc:Number(BigInt(Bun.hash(Wo.text))&0x1fffffffffffffn),kind:Fe[Wo.kind],tool:Wo.tool??null,err:Number(Wo.err??!1),model:Wo.model??(Wo.tool?pr:void 0)??null,time:Xi.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
|
|
456
|
-
JOIN store.sessions s ON s.id=r.session_id WHERE ${E.where}`).get(Js.session_id,Js.seq,Js.kind,Js.tool,Js.err,Js.model,Js.time,...E.bindings))continue;let xi=it,Ig=new Set;while(xi.forked_from_id&&xi.forked_from_seq!==null&&Xi.seq<=xi.forked_from_seq&&!Ig.has(xi.id)){Ig.add(xi.id);let Ru=A.get(xi.forked_from_id);if(!Ru)break;xi=Ru}let Eg=`${xi.id}:${Xi.seq}:${Wo.part}:${Bun.hash(Wo.text)}`;if(fr.has(Eg))continue;let bg=ee(or,Js,Tu);if(bg){if(fr.add(Eg),E.forks){let Ru=or.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(it.id,Xi.seq,Wo.part);if(Ru){let Sg=gg(or,E,{...Js,doc:Ru.doc},Wo.text);if(Sg.length)bg.forks=Sg}}}}}let wu=qo.at(-1);if(wu)ur=wu.seq;return qo.length});if(on===void 0){f({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(ft+=on,f({type:"progress",scanned:ft,total:Wt}),a.signal?.aborted)return;if(Ot(),!on||he)break;await Bun.sleep(0)}}}else u.withIndex((Re)=>{if(S=tv(Re,E,a.onTiming)||S,g.regex?g.regex.literals.every((ft)=>ft.some((Dt)=>[...Dt].length<3)):g.branches.some((ft)=>ft.include.length>0&&ft.include.every((Dt)=>[...Dt.text].length<3)))Re.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let ft=rv(Re,E,o.group==="none",h.now,a.onTiming);if(S||=E.partial,E.candidateLimit&&ft.length>E.candidateLimit)ft.length=E.candidateLimit,S=!0;let Dt=[];for(let fr of ft){if(a.signal?.aborted)return;let tr=Dt[Me]?.key.score;if(tr!==void 0&&fr.score+0.000000000001<tr)break;let st=C.length,Ot=ar(Re,fr);C.splice(st);let it=lg([...Ot],"best")[0];if(!it)continue;let ur={score:it.score,sessionID:it.sessionID,seq:o.group==="none"?it.seq:0};if(h.after&&cv(ur,h.after)<=0)continue;if(Dt.push({key:ur,hits:Ot}),Dt.sort((pr,on)=>cv(pr.key,on.key)),Dt.length>Me+1)Dt.length=Me+1}he=Dt.length>Me;let Ir=Dt.slice(0,Me);for(let fr of Ir)C.push(...fr.hits);k=Ir.at(-1)?.key;return}let Wt=0;for(;;){if(a.signal?.aborted)return;let ft=ov(Re,E,te,ze,a.onTiming),Dt=E.candidateLimit!==void 0&&te+ft>=E.candidateLimit;S||=Dt;let Ir=sv(Re,o,Y,Me-Wt+1,h.now,L,a.onTiming);he=Ir.length>Me-Wt;let fr=Ir.slice(0,Me-Wt);if(!fr.length){if(ft<ze||Dt){he=!1;break}te+=ft,Y=0,L=[...new Set([...L,...se])],se=[];continue}for(let tr of fr)if(Y++,ar(Re,tr).length){if(Wt++,o.group!=="none")se.push(tr.session_id)}if(Wt>=Me){he||=!Dt&&ft>=ze;break}if(!he){if(ft<ze||Dt)break;te+=ft,Y=0,L=[...new Set([...L,...se])],se=[]}}});if(a.signal?.aborted)return;if(!Ge){let Re=be(C);Xe(Re),f({type:"groups",groups:Re})}if(!M){let Re=g.branches.flatMap((ke)=>ke.include).find((ke)=>ke.fuzzy)?.text;if(Re)f({type:"suggest",terms:u.withIndex((ke)=>pg(ke,Re))??[]})}f({type:"done",cursor:he?Buffer.from(JSON.stringify(!Ge&&o.sort!=="recent"?{...h,offset:0,window:0,seen:[],emitted:[],after:k}:{...h,offset:Y,window:te,seen:L,emitted:se})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:S,index:u.status()})}function no(e,o){return e.withIndex((a)=>pg(a,o))??[]}function mv(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}),Dn()])),scope:n(y([i("session"),i("project"),i("all"),i(""),Dn()])),fields:n(y([W(xr({type:"string",enum:[...Sn]})),Dn()])),tool:n(y([s(),Dn()])),isError:n(y([D(),Dn()])),after:n(y([s(),re(),Dn()])),before:n(y([s(),re(),Dn()])),limit:n(y([x(),Dn()])),session:n(y([s(),Dn()])),seq:n(y([x(),Dn()])),around:n(y([x(),Dn()]))}),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 ee=typeof X==="number"?X:Date.parse(X);if(!Number.isFinite(ee)||Math.abs(ee)>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 ee},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 C=[];if(E&&g.session&&g.seq!==void 0){if(!e.sessions().find((Ge)=>Ge.id===g.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let ee=g.around??3,be=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-ee),g.seq+ee);if(!be.some((Ge)=>Ge.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:be.map((Ge)=>{let ar={...JSON.parse(Ge.body),seq:Ge.seq,time:Ge.time};return`[seq=${Ge.seq}]
|
|
457
|
-
${nt(ar,!0).map((Re)=>`${Re.kind}: ${Re.kind==="error"?Re.text.replace(/^(?:error:\s*)+/i,""):Re.text}`).join(`
|
|
458
|
-
`).slice(0,4000)}`}).join(`
|
|
459
|
-
|
|
460
|
-
`)||"No history content"}],details:{groups:C,count:be.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,V=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,_=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)),J={q:I,filters:{tools:g.tool?.trim()?[g.tool.trim()]:void 0,isError:g.isError,after:A,before:P},group:"none",limit:M},j=Nl(J);if(j.error)throw Error(j.error.message);if(g.fields?.length){if(j.filters.fields=g.fields.filter((X)=>(X in Fe)),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 Y=o.status().state!=="ready",te=!1;if(!Y){let X=j.filters.fields??Object.keys(Fe).filter((Xe)=>(Xe in Fe)),ee=X.filter((Xe)=>Xe!=="title"),be=ee.length?[ee]:[];if(X.includes("title"))be.push(["title"]);for(let Xe of be){if(C.length>=M&&te)break;if(await Ar(o,{...J,limit:Math.max(1,M-C.length),filters:{...j.filters,fields:Xe}},{signal:h,excludeEntry:V===void 0?void 0:{sessionID:a,seq:V},sessionID:a,allowedSessionIDs:_,onEvent(Ge){if(Ge.type==="groups")C.push(...Ge.groups);if(Ge.type==="done")te||=Boolean(Ge.cursor)||Ge.partial;if(Ge.type==="error")if(Ge.code==="unavailable")Y=!0;else throw Error(Ge.message)}}),Y)break}}let L=[],se=0;if(Y){C.length=0;let X=performance.now()+2000;e:for(let ee of e.sessions()){if(!_.has(ee.id))continue;if(j.filters.sessionID&&!j.filters.sessionID.includes(ee.id))continue;if(j.filters.projectID&&(!ee.projectID||!j.filters.projectID.includes(ee.projectID)))continue;let be=Number.MAX_SAFE_INTEGER,Xe=!0;for(;;){let Ge=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(ee.id,be);if(Xe)Ge.push({body:"null",seq:0,time:ee.updated}),Xe=!1;if(!Ge.length)break;for(let ar of Ge){if(ar.seq>0)be=ar.seq;if(h?.aborted)throw Error("History search cancelled");if(se>=1e4||performance.now()>X){te=!0;break e}if(se++,ee.id===a&&ar.seq===V)continue;if(j.filters.after!==void 0&&ar.time<j.filters.after||j.filters.before!==void 0&&ar.time>=j.filters.before)continue;let Re=ar.seq===0?[{part:0,kind:"title",text:ee.title,tool:void 0,err:!1}]:nt(JSON.parse(ar.body),!0);for(let ke of Re){if(j.filters.fields&&!j.filters.fields.includes(ke.kind))continue;if(j.filters.tools&&(!ke.tool||!j.filters.tools.includes(ke.tool)))continue;if(j.filters.isError!==void 0&&Boolean(ke.err)!==j.filters.isError)continue;let Wt=Dl(ke.text,j);if(!Wt)continue;if(C.length>=M&&ke.kind!=="title"){te=!0;break e}(ke.kind==="title"?L:C).push({session:{id:ee.id,title:ee.title,projectID:ee.projectID,updated:ee.updated},more:0,hits:[{sessionID:ee.id,seq:ar.seq,time:ar.time,field:ke.kind,tool:ke.tool,isError:Boolean(ke.err),snippet:Fl(ke.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-C.length))te=!0;if(C.push(...L.slice(0,M)),C.sort((X,ee)=>Number(X.hits[0]?.field==="title")-Number(ee.hits[0]?.field==="title")),C.length>M)te=!0;C.length=Math.min(C.length,M);let he=new Map;for(let X of C)for(let ee of X.hits){let be=he.get(X.session.id)??[];be.push(`[${X.session.title.replace(/[\r\n]/g," ")} \xB7 ${ee.sessionID} \xB7 ${ee.seq} \xB7 ${new Date(ee.time).toISOString()} \xB7 ${ee.field}${ee.tool?`/${ee.tool}`:""}]
|
|
461
|
-
${ee.snippet.slice(0,3).map((Xe)=>{let Ge=Xe.text;for(let[ar,Re]of[...Xe.ranges].sort((ke,Wt)=>Wt[0]-ke[0]))Ge=`${Ge.slice(0,ar)}\u3010${Ge.slice(ar,Re)}\u3011${Ge.slice(Re)}`;return Ge}).join(`
|
|
462
|
-
`)}`),he.set(X.session.id,be)}let Me="";if(Y){if(Me="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")Me="\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 ze=C.reduce((X,ee)=>X+ee.hits.length,0);return{content:[{type:"text",text:[Me,Y&&te?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${se} \u6761`:"",[...he.values()].map((X)=>X.join(`
|
|
463
|
-
|
|
464
|
-
`)).join(`
|
|
465
|
-
|
|
466
|
-
`),ze===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 ${ze} \u6761\uFF1B${te?"\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(`
|
|
467
|
-
`)}],details:{groups:C,count:ze}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var yg="basalt.git-snapshot";async function pv(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??Kt({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(mv(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(yg,o.id),C;try{C=P?JSON.parse(P.value):void 0}catch{C=void 0}if(C?.compactions===k&&(C.summary===void 0||typeof C.summary==="string"))E=C.summary;else if(E=await u0(u.directory,a),!e.isClosed&&!a?.aborted)A.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(yg,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(yg)}let S=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:a0({project:u,globalInstructions:sK(e),git:E,shell:e.serverShell()});return{systemPrompt:S.map((k)=>k.detail).join(""),systemParts:S,tools:[...I,...e.tools.snapshot()],cwd:p}}var oK=[Su(".basalt","AGENTS.md"),Su(".agents","AGENTS.md"),Su(".opencode","AGENTS.md"),Su(".claude","CLAUDE.md"),Su(".codex","AGENTS.md")];function sK(e){let o=e.options.homeDir??nK();for(let a of oK){let u=Su(o,a);try{if(tK(u))return rK(u,"utf8")}catch{return}}return}class Jo{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 ng(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Ol(xg(e.dataDir,"basalt.db")),this.plugins=new Nh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Ll(this.plugins,()=>this.builtinToolNames()),this.search=new qh({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 Jo(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??[xg(this.options.dataDir,"plugins"),...this.projects().map((e)=>xg(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 F0(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{..._l(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>q0(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(!Pn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let a=Date.now(),u={id:ne("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 E0(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&&Pn(this.options.models,h)!==void 0),u=a?Pn(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:ne("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?w0(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 oe;if(!Pn(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 qe(h)){if(g.result)continue;let{body:I,raw:E}=il(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 oe;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 oe;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.all(a.map((p)=>p.idle())).then(u)}open(e,o="create"){let a=e.id,u=new kl(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)=>pv(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 Qi(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(!ei.includes(e))throw new t(`Invalid shell type; must be ${ei.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{Ve,at,Di,N,jo,Jn,Vo,He,W,n,l,Q,xr,D,x,i,re,s,y,Ke,Le,Ko,ve,T,Rt,et,R,qe,H,G,Ct,bt,Qo,qt,vr,Xn,ln,It,Yn,Ce,de,cn,un,_r,Zn,eo,pn,Ui,Gt,ws,Pe,c,le,tt,Bi,Fi,zt,to,jt,Vt,Kt,rt,oe,ro,Qt,Jt,ne,dn,Ar,no,Jo};
|