@bkm016/basalt 0.1.22 → 0.1.23
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-01g872ez.js +3 -0
- package/chunk-078td1r4.js +7 -0
- package/chunk-1mhv12a5.js +3 -0
- package/chunk-1zrht78t.js +2 -0
- package/chunk-2e4xds74.js +18 -0
- package/chunk-2hkpqjqj.js +3 -0
- package/chunk-2mhpgb4t.js +2 -0
- package/chunk-3nwqng5t.js +59 -0
- package/chunk-3zm1ejmh.js +3 -0
- package/chunk-4d9p68s9.js +3 -0
- package/chunk-5h96jz3p.js +3 -0
- package/chunk-5znfck4s.js +5 -0
- package/chunk-6048rq29.js +8 -0
- package/chunk-61zk13qr.js +3 -0
- package/chunk-62ty404c.js +2 -0
- package/chunk-6vp2nqbj.js +2 -0
- package/chunk-7a5derff.js +25 -0
- package/chunk-7qhbff72.js +5 -0
- package/chunk-7xw6fpx3.js +3 -0
- package/chunk-84rk4tew.js +2 -0
- package/chunk-8np9b2y8.js +3 -0
- package/chunk-8wb8yr7d.js +12 -0
- package/chunk-93b76hhg.js +11 -0
- package/chunk-9h05aqdd.js +25 -0
- package/chunk-a2jsx2ew.js +3 -0
- package/chunk-a2qwx6cr.js +2 -0
- package/chunk-a7h459z1.js +2 -0
- package/chunk-atjwde1c.js +2 -0
- package/chunk-bk20awc9.js +10 -0
- package/chunk-bm2jhkqt.js +3 -0
- package/chunk-bp4zk5ch.js +3 -0
- package/chunk-c5ess8kd.js +3 -0
- package/chunk-cj7yhgnd.js +2 -0
- package/chunk-cjq2bzkf.js +3 -0
- package/chunk-csrpxzn7.js +3 -0
- package/chunk-cwesdh51.js +39 -0
- package/chunk-drbd6485.js +3 -0
- package/chunk-dt594v3d.js +9 -0
- package/chunk-dwxp0gtf.js +4 -0
- package/chunk-ejdewe04.js +3 -0
- package/chunk-fkzk83xs.js +2 -0
- package/chunk-fsnc2sja.js +3 -0
- package/chunk-g18hxgdr.js +12 -0
- package/chunk-hfwy0rzt.js +10 -0
- package/chunk-hg5wmrfb.js +3 -0
- package/chunk-hvex6qjc.js +5 -0
- package/chunk-hw8xknv5.js +2 -0
- package/chunk-j91wgfzj.js +2 -0
- package/chunk-jyx4ynyp.js +3 -0
- package/chunk-jz1pavma.js +20 -0
- package/chunk-kjjrmfmt.js +2 -0
- package/chunk-kz1ja7t7.js +31 -0
- package/chunk-mh4s6m7e.js +2 -0
- package/chunk-n0g6w24y.js +3 -0
- package/chunk-nnp82zvz.js +5 -0
- package/chunk-p34keb5j.js +3 -0
- package/chunk-pcxaycc3.js +3560 -0
- package/chunk-pdwexj34.js +16 -0
- package/chunk-phpse938.js +3 -0
- package/chunk-pt14ba7d.js +15 -0
- package/chunk-q0hvv6bh.js +390 -0
- package/chunk-qd4xtknk.js +2 -0
- package/chunk-qfg0dr8f.js +2 -0
- package/chunk-qnrkh3ca.js +7 -0
- package/chunk-r1t5yhee.js +7 -0
- package/chunk-r5na5qx5.js +2 -0
- package/chunk-r7a6q57s.js +2 -0
- package/chunk-smsn4ebc.js +4 -0
- package/chunk-sqr8tx1m.js +471 -0
- package/chunk-t4twa09y.js +2 -0
- package/chunk-tjs6h6zk.js +4 -0
- package/chunk-tvbh69tm.js +3 -0
- package/chunk-tvv9yfqv.js +11 -0
- package/chunk-vbdf5psp.js +2 -0
- package/chunk-vr60qwyg.js +2 -0
- package/chunk-w509y6w6.js +2 -0
- package/chunk-w7n83ye7.js +7 -0
- package/chunk-wacjm9ww.js +3 -0
- package/chunk-xex050bc.js +3 -0
- package/chunk-y0fgbrkc.js +2 -0
- package/chunk-ysfpdxjy.js +3 -0
- package/chunk-ytsnns2n.js +2 -0
- package/chunk-zwgdbrbg.js +2 -0
- package/chunk-zz7qjanc.js +2 -0
- package/compiled.js +8 -8
- package/package.json +1 -1
- package/ui-test-worker.js +57 -57
- package/web/chunk-07q4pdkf.js +1 -0
- package/web/chunk-07q4pdkf.js.br +0 -0
- package/web/chunk-07q4pdkf.js.gz +0 -0
- package/web/chunk-0s237vb2.js +2 -0
- package/web/chunk-0s237vb2.js.br +0 -0
- package/web/chunk-0s237vb2.js.gz +0 -0
- package/web/chunk-0zbmaspt.js +24 -0
- package/web/chunk-0zbmaspt.js.br +0 -0
- package/web/chunk-0zbmaspt.js.gz +0 -0
- package/web/chunk-11p8z5sv.js +8 -0
- package/web/chunk-11p8z5sv.js.br +0 -0
- package/web/chunk-11p8z5sv.js.gz +0 -0
- package/web/chunk-1axadk7j.js +2 -0
- package/web/chunk-1axadk7j.js.br +0 -0
- package/web/chunk-1axadk7j.js.gz +0 -0
- package/web/chunk-1ebz6hbk.js +1 -0
- package/web/chunk-1ebz6hbk.js.br +0 -0
- package/web/chunk-1ebz6hbk.js.gz +0 -0
- package/web/chunk-1pg22vjr.js +38 -0
- package/web/chunk-1pg22vjr.js.br +0 -0
- package/web/chunk-1pg22vjr.js.gz +0 -0
- package/web/chunk-1ys90q5s.js +1 -0
- package/web/chunk-1ys90q5s.js.br +0 -0
- package/web/chunk-1ys90q5s.js.gz +0 -0
- package/web/chunk-1zd8azrg.js +34 -0
- package/web/chunk-1zd8azrg.js.br +0 -0
- package/web/chunk-1zd8azrg.js.gz +0 -0
- package/web/chunk-22rjbwxp.js +303 -0
- package/web/chunk-22rjbwxp.js.br +0 -0
- package/web/chunk-22rjbwxp.js.gz +0 -0
- package/web/chunk-2eg9t1mz.js +2 -0
- package/web/chunk-2eg9t1mz.js.br +0 -0
- package/web/chunk-2eg9t1mz.js.gz +0 -0
- package/web/chunk-2emc5sd7.js +12 -0
- package/web/chunk-2emc5sd7.js.br +0 -0
- package/web/chunk-2emc5sd7.js.gz +0 -0
- package/web/chunk-2gj9yydt.js +2 -0
- package/web/chunk-2gj9yydt.js.br +0 -0
- package/web/chunk-2gj9yydt.js.gz +0 -0
- package/web/chunk-2jvy4y1e.js +1 -0
- package/web/chunk-2jvy4y1e.js.br +0 -0
- package/web/chunk-2jvy4y1e.js.gz +0 -0
- package/web/chunk-2kwn5gsx.js +1 -0
- package/web/chunk-2kwn5gsx.js.br +0 -0
- package/web/chunk-2kwn5gsx.js.gz +0 -0
- package/web/chunk-2r84nrwk.js +99 -0
- package/web/chunk-2r84nrwk.js.br +0 -0
- package/web/chunk-2r84nrwk.js.gz +0 -0
- package/web/chunk-3abhxhtv.js +2 -0
- package/web/chunk-3abhxhtv.js.br +0 -0
- package/web/chunk-3abhxhtv.js.gz +0 -0
- package/web/chunk-3cgxntbk.js +2 -0
- package/web/chunk-3cgxntbk.js.br +0 -0
- package/web/chunk-3cgxntbk.js.gz +0 -0
- package/web/chunk-3g3n9pc5.js +332 -0
- package/web/chunk-3g3n9pc5.js.br +0 -0
- package/web/chunk-3g3n9pc5.js.gz +0 -0
- package/web/chunk-3qmpdzq2.js +1 -0
- package/web/chunk-3qmpdzq2.js.br +0 -0
- package/web/chunk-3qmpdzq2.js.gz +0 -0
- package/web/chunk-3rxjewe5.js +2 -0
- package/web/chunk-3rxjewe5.js.br +0 -0
- package/web/chunk-3rxjewe5.js.gz +0 -0
- package/web/chunk-3vh17h7n.js +62 -0
- package/web/chunk-3vh17h7n.js.br +0 -0
- package/web/chunk-3vh17h7n.js.gz +0 -0
- package/web/chunk-49ywdzda.js +36 -0
- package/web/chunk-49ywdzda.js.br +0 -0
- package/web/chunk-49ywdzda.js.gz +0 -0
- package/web/chunk-5ch8rwjz.js +2 -0
- package/web/chunk-5ch8rwjz.js.br +0 -0
- package/web/chunk-5ch8rwjz.js.gz +0 -0
- package/web/chunk-5k1xca5m.js +324 -0
- package/web/chunk-5k1xca5m.js.br +0 -0
- package/web/chunk-5k1xca5m.js.gz +0 -0
- package/web/chunk-5kcmtrrk.js +2 -0
- package/web/chunk-5kcmtrrk.js.br +0 -0
- package/web/chunk-5kcmtrrk.js.gz +0 -0
- package/web/chunk-5t1yv276.js +1 -0
- package/web/chunk-5t1yv276.js.br +0 -0
- package/web/chunk-5t1yv276.js.gz +0 -0
- package/web/chunk-612xftnp.js +1 -0
- package/web/chunk-612xftnp.js.br +0 -0
- package/web/chunk-612xftnp.js.gz +0 -0
- package/web/chunk-6183jmyq.js +2 -0
- package/web/chunk-6183jmyq.js.br +0 -0
- package/web/chunk-6183jmyq.js.gz +0 -0
- package/web/chunk-66zp24sf.js +2 -0
- package/web/chunk-66zp24sf.js.br +0 -0
- package/web/chunk-66zp24sf.js.gz +0 -0
- package/web/chunk-67wywbgr.js +2 -0
- package/web/chunk-67wywbgr.js.br +0 -0
- package/web/chunk-67wywbgr.js.gz +0 -0
- package/web/chunk-6j0d6131.js +1 -0
- package/web/chunk-6j0d6131.js.br +0 -0
- package/web/chunk-6j0d6131.js.gz +0 -0
- package/web/chunk-6ycpdpfj.js +107 -0
- package/web/chunk-6ycpdpfj.js.br +0 -0
- package/web/chunk-6ycpdpfj.js.gz +0 -0
- package/web/chunk-79tbvvqj.js +1 -0
- package/web/chunk-79tbvvqj.js.br +0 -0
- package/web/chunk-79tbvvqj.js.gz +0 -0
- package/web/chunk-7bcksmqx.js +2 -0
- package/web/chunk-7bcksmqx.js.br +0 -0
- package/web/chunk-7bcksmqx.js.gz +0 -0
- package/web/chunk-7c2zkqgd.js +89 -0
- package/web/chunk-7c2zkqgd.js.br +0 -0
- package/web/chunk-7c2zkqgd.js.gz +0 -0
- package/web/chunk-7ed42dqv.js +1 -0
- package/web/chunk-7ed42dqv.js.br +0 -0
- package/web/chunk-7ed42dqv.js.gz +0 -0
- package/web/chunk-7mzdjjha.js +1 -0
- package/web/chunk-7mzdjjha.js.br +0 -0
- package/web/chunk-7mzdjjha.js.gz +0 -0
- package/web/chunk-7t1sb86g.js +2 -0
- package/web/chunk-7t1sb86g.js.br +0 -0
- package/web/chunk-7t1sb86g.js.gz +0 -0
- package/web/chunk-7t5kzbp1.js +1 -0
- package/web/chunk-7t5kzbp1.js.br +0 -0
- package/web/chunk-7t5kzbp1.js.gz +0 -0
- package/web/chunk-7tmzvm05.js +2 -0
- package/web/chunk-7tmzvm05.js.br +0 -0
- package/web/chunk-7tmzvm05.js.gz +0 -0
- package/web/chunk-80k4k6aw.js +7 -0
- package/web/chunk-80k4k6aw.js.br +0 -0
- package/web/chunk-80k4k6aw.js.gz +0 -0
- package/web/chunk-8tvy5xbr.js +217 -0
- package/web/chunk-8tvy5xbr.js.br +0 -0
- package/web/chunk-8tvy5xbr.js.gz +0 -0
- package/web/chunk-95jr0f0q.js +139 -0
- package/web/chunk-95jr0f0q.js.br +0 -0
- package/web/chunk-95jr0f0q.js.gz +0 -0
- package/web/chunk-9h6ayn54.js +16 -0
- package/web/chunk-9h6ayn54.js.br +0 -0
- package/web/chunk-9h6ayn54.js.gz +0 -0
- package/web/chunk-9jzpxvwa.js +106 -0
- package/web/chunk-9jzpxvwa.js.br +0 -0
- package/web/chunk-9jzpxvwa.js.gz +0 -0
- package/web/chunk-9kx2s040.js +1 -0
- package/web/chunk-9kx2s040.js.br +0 -0
- package/web/chunk-9kx2s040.js.gz +0 -0
- package/web/chunk-9mdbahpr.js +2 -0
- package/web/chunk-9mdbahpr.js.br +0 -0
- package/web/chunk-9mdbahpr.js.gz +0 -0
- package/web/chunk-9w6mjqgp.js +1 -0
- package/web/chunk-9w6mjqgp.js.br +0 -0
- package/web/chunk-9w6mjqgp.js.gz +0 -0
- package/web/chunk-9xb3j03w.js +142 -0
- package/web/chunk-9xb3j03w.js.br +0 -0
- package/web/chunk-9xb3j03w.js.gz +0 -0
- package/web/chunk-abzt3tzj.js +1 -0
- package/web/chunk-abzt3tzj.js.br +0 -0
- package/web/chunk-abzt3tzj.js.gz +0 -0
- package/web/chunk-ahebswgf.js +1 -0
- package/web/chunk-ahebswgf.js.br +0 -0
- package/web/chunk-ahebswgf.js.gz +0 -0
- package/web/chunk-ahsw5yz2.js +2 -0
- package/web/chunk-ahsw5yz2.js.br +0 -0
- package/web/chunk-ahsw5yz2.js.gz +0 -0
- package/web/chunk-b21jhnc3.js +1 -0
- package/web/chunk-b21jhnc3.js.br +2 -0
- package/web/chunk-b21jhnc3.js.gz +0 -0
- package/web/chunk-b3cn4qmw.js +1 -0
- package/web/chunk-b3cn4qmw.js.br +0 -0
- package/web/chunk-b3cn4qmw.js.gz +0 -0
- package/web/chunk-b4qxx7jx.js +2 -0
- package/web/chunk-b4qxx7jx.js.br +0 -0
- package/web/chunk-b4qxx7jx.js.gz +0 -0
- package/web/chunk-b79d9r5v.js +98 -0
- package/web/chunk-b79d9r5v.js.br +0 -0
- package/web/chunk-b79d9r5v.js.gz +0 -0
- package/web/chunk-b9x115jw.css +1 -0
- package/web/chunk-b9x115jw.css.br +0 -0
- package/web/chunk-b9x115jw.css.gz +0 -0
- package/web/chunk-bbnamv1j.js +1 -0
- package/web/chunk-bbnamv1j.js.br +2 -0
- package/web/chunk-bbnamv1j.js.gz +0 -0
- package/web/chunk-bgqfryh2.js +1 -0
- package/web/chunk-bgqfryh2.js.br +0 -0
- package/web/chunk-bgqfryh2.js.gz +0 -0
- package/web/chunk-bjrnqvf4.js +1 -0
- package/web/chunk-bjrnqvf4.js.br +0 -0
- package/web/chunk-bjrnqvf4.js.gz +0 -0
- package/web/chunk-cbh6w44y.js +1 -0
- package/web/chunk-cbh6w44y.js.br +0 -0
- package/web/chunk-cbh6w44y.js.gz +0 -0
- package/web/chunk-d0bt1ypq.js +140 -0
- package/web/chunk-d0bt1ypq.js.br +0 -0
- package/web/chunk-d0bt1ypq.js.gz +0 -0
- package/web/chunk-ddfd1c5x.js +1 -0
- package/web/chunk-ddfd1c5x.js.br +0 -0
- package/web/chunk-ddfd1c5x.js.gz +0 -0
- package/web/chunk-deqy1rfx.js +1 -0
- package/web/chunk-deqy1rfx.js.br +0 -0
- package/web/chunk-deqy1rfx.js.gz +0 -0
- package/web/chunk-dk3dpdnc.js +4 -0
- package/web/chunk-dk3dpdnc.js.br +0 -0
- package/web/chunk-dk3dpdnc.js.gz +0 -0
- package/web/chunk-dr35dsw5.js +1 -0
- package/web/chunk-dr35dsw5.js.br +0 -0
- package/web/chunk-dr35dsw5.js.gz +0 -0
- package/web/chunk-drr7mqg2.js +1 -0
- package/web/chunk-drr7mqg2.js.br +0 -0
- package/web/chunk-drr7mqg2.js.gz +0 -0
- package/web/chunk-dy9amqbz.js +1 -0
- package/web/chunk-dy9amqbz.js.br +0 -0
- package/web/chunk-dy9amqbz.js.gz +0 -0
- package/web/chunk-e039ekp7.js +89 -0
- package/web/chunk-e039ekp7.js.br +0 -0
- package/web/chunk-e039ekp7.js.gz +0 -0
- package/web/chunk-e2e2fdwq.js +30 -0
- package/web/chunk-e2e2fdwq.js.br +0 -0
- package/web/chunk-e2e2fdwq.js.gz +0 -0
- package/web/chunk-e5j1v42p.js +7 -0
- package/web/chunk-e5j1v42p.js.br +0 -0
- package/web/chunk-e5j1v42p.js.gz +0 -0
- package/web/chunk-ef0wf92p.js +2 -0
- package/web/chunk-ef0wf92p.js.br +0 -0
- package/web/chunk-ef0wf92p.js.gz +0 -0
- package/web/chunk-emsyqa1e.js +1 -0
- package/web/chunk-emsyqa1e.js.br +0 -0
- package/web/chunk-emsyqa1e.js.gz +0 -0
- package/web/chunk-en7n9d1p.js +41 -0
- package/web/chunk-en7n9d1p.js.br +0 -0
- package/web/chunk-en7n9d1p.js.gz +0 -0
- package/web/chunk-ez4yt1s1.js +1 -0
- package/web/chunk-ez4yt1s1.js.br +0 -0
- package/web/chunk-ez4yt1s1.js.gz +0 -0
- package/web/chunk-f620k3hk.js +1 -0
- package/web/chunk-f620k3hk.js.br +0 -0
- package/web/chunk-f620k3hk.js.gz +0 -0
- package/web/chunk-fe2hpamc.js +200 -0
- package/web/chunk-fe2hpamc.js.br +0 -0
- package/web/chunk-fe2hpamc.js.gz +0 -0
- package/web/chunk-fm7saxzr.js +1 -0
- package/web/chunk-fm7saxzr.js.br +0 -0
- package/web/chunk-fm7saxzr.js.gz +0 -0
- package/web/chunk-fz5d3ayq.js +2 -0
- package/web/chunk-fz5d3ayq.js.br +0 -0
- package/web/chunk-fz5d3ayq.js.gz +0 -0
- package/web/chunk-gb2tkfv0.js +1 -0
- package/web/chunk-gb2tkfv0.js.br +0 -0
- package/web/chunk-gb2tkfv0.js.gz +0 -0
- package/web/chunk-gc1ypgy4.js +1 -0
- package/web/chunk-gc1ypgy4.js.br +0 -0
- package/web/chunk-gc1ypgy4.js.gz +0 -0
- package/web/chunk-h23pczjh.js +40 -0
- package/web/chunk-h23pczjh.js.br +0 -0
- package/web/chunk-h23pczjh.js.gz +0 -0
- package/web/chunk-h2sttxfn.js +1 -0
- package/web/chunk-h2sttxfn.js.br +2 -0
- package/web/chunk-h2sttxfn.js.gz +0 -0
- package/web/chunk-h5m9ggsm.js +2 -0
- package/web/chunk-h5m9ggsm.js.br +0 -0
- package/web/chunk-h5m9ggsm.js.gz +0 -0
- package/web/chunk-h5zc1hw5.js +1 -0
- package/web/chunk-h5zc1hw5.js.br +0 -0
- package/web/chunk-h5zc1hw5.js.gz +0 -0
- package/web/chunk-hkg6bts9.js +1 -0
- package/web/chunk-hkg6bts9.js.br +0 -0
- package/web/chunk-hkg6bts9.js.gz +0 -0
- package/web/chunk-hncdpeer.js +120 -0
- package/web/chunk-hncdpeer.js.br +0 -0
- package/web/chunk-hncdpeer.js.gz +0 -0
- package/web/chunk-j40wechd.js +2 -0
- package/web/chunk-j40wechd.js.br +0 -0
- package/web/chunk-j40wechd.js.gz +0 -0
- package/web/chunk-jddmse74.js +169 -0
- package/web/chunk-jddmse74.js.br +0 -0
- package/web/chunk-jddmse74.js.gz +0 -0
- package/web/chunk-jdvdg38q.js +3 -0
- package/web/chunk-jdvdg38q.js.br +0 -0
- package/web/chunk-jdvdg38q.js.gz +0 -0
- package/web/chunk-jf6q93m9.js +1 -0
- package/web/chunk-jf6q93m9.js.br +0 -0
- package/web/chunk-jf6q93m9.js.gz +0 -0
- package/web/chunk-jfd1gybx.js +39 -0
- package/web/chunk-jfd1gybx.js.br +0 -0
- package/web/chunk-jfd1gybx.js.gz +0 -0
- package/web/chunk-jkgkt722.js +1 -0
- package/web/chunk-jkgkt722.js.br +0 -0
- package/web/chunk-jkgkt722.js.gz +0 -0
- package/web/chunk-k427fwgp.js +1 -0
- package/web/chunk-k427fwgp.js.br +0 -0
- package/web/chunk-k427fwgp.js.gz +0 -0
- package/web/chunk-k8pezbya.js +2 -0
- package/web/chunk-k8pezbya.js.br +3 -0
- package/web/chunk-k8pezbya.js.gz +0 -0
- package/web/chunk-k9t941fj.js +1 -0
- package/web/chunk-k9t941fj.js.br +0 -0
- package/web/chunk-k9t941fj.js.gz +0 -0
- package/web/chunk-kkzwvnft.js +1 -0
- package/web/chunk-kkzwvnft.js.br +0 -0
- package/web/chunk-kkzwvnft.js.gz +0 -0
- package/web/chunk-kpm8gp4z.js +292 -0
- package/web/chunk-kpm8gp4z.js.br +0 -0
- package/web/chunk-kpm8gp4z.js.gz +0 -0
- package/web/chunk-kqyk2an3.js +214 -0
- package/web/chunk-kqyk2an3.js.br +0 -0
- package/web/chunk-kqyk2an3.js.gz +0 -0
- package/web/chunk-m3gryxba.js +2 -0
- package/web/chunk-m3gryxba.js.br +0 -0
- package/web/chunk-m3gryxba.js.gz +0 -0
- package/web/chunk-m8h3c5x3.js +1 -0
- package/web/chunk-m8h3c5x3.js.br +0 -0
- package/web/chunk-m8h3c5x3.js.gz +0 -0
- package/web/chunk-mb7sr4tf.js +55 -0
- package/web/chunk-mb7sr4tf.js.br +0 -0
- package/web/chunk-mb7sr4tf.js.gz +0 -0
- package/web/chunk-meqcd10n.js +1 -0
- package/web/chunk-meqcd10n.js.br +0 -0
- package/web/chunk-meqcd10n.js.gz +0 -0
- package/web/chunk-msrq7vsz.js +7 -0
- package/web/chunk-msrq7vsz.js.br +0 -0
- package/web/chunk-msrq7vsz.js.gz +0 -0
- package/web/chunk-myhtb5ps.js +2 -0
- package/web/chunk-myhtb5ps.js.br +0 -0
- package/web/chunk-myhtb5ps.js.gz +0 -0
- package/web/chunk-n1n55yt8.js +84 -0
- package/web/chunk-n1n55yt8.js.br +0 -0
- package/web/chunk-n1n55yt8.js.gz +0 -0
- package/web/chunk-nmgy1mrz.js +1 -0
- package/web/chunk-nmgy1mrz.js.br +0 -0
- package/web/chunk-nmgy1mrz.js.gz +0 -0
- package/web/chunk-nmnyaawa.js +24 -0
- package/web/chunk-nmnyaawa.js.br +0 -0
- package/web/chunk-nmnyaawa.js.gz +0 -0
- package/web/chunk-nwepnbvn.js +70 -0
- package/web/chunk-nwepnbvn.js.br +0 -0
- package/web/chunk-nwepnbvn.js.gz +0 -0
- package/web/chunk-p2cmfhpz.js +2 -0
- package/web/chunk-p2cmfhpz.js.br +0 -0
- package/web/chunk-p2cmfhpz.js.gz +0 -0
- package/web/chunk-pac9nyhp.js +2 -0
- package/web/chunk-pac9nyhp.js.br +0 -0
- package/web/chunk-pac9nyhp.js.gz +0 -0
- package/web/chunk-pdt40dj7.js +1 -0
- package/web/chunk-pdt40dj7.js.br +2 -0
- package/web/chunk-pdt40dj7.js.gz +0 -0
- package/web/chunk-phs38wt7.js +2 -0
- package/web/chunk-phs38wt7.js.br +0 -0
- package/web/chunk-phs38wt7.js.gz +0 -0
- package/web/chunk-prc7b9xh.js +1 -0
- package/web/chunk-prc7b9xh.js.br +0 -0
- package/web/chunk-prc7b9xh.js.gz +0 -0
- package/web/chunk-q1e80chw.js +1 -0
- package/web/chunk-q1e80chw.js.br +2 -0
- package/web/chunk-q1e80chw.js.gz +0 -0
- package/web/chunk-q6aqg79d.js +2 -0
- package/web/chunk-q6aqg79d.js.br +0 -0
- package/web/chunk-q6aqg79d.js.gz +0 -0
- package/web/chunk-q6sv3fhe.js +2 -0
- package/web/chunk-q6sv3fhe.js.br +0 -0
- package/web/chunk-q6sv3fhe.js.gz +0 -0
- package/web/chunk-rbd2n2mr.js +1 -0
- package/web/chunk-rbd2n2mr.js.br +0 -0
- package/web/chunk-rbd2n2mr.js.gz +0 -0
- package/web/chunk-rbh0yrp6.js +1 -0
- package/web/chunk-rbh0yrp6.js.br +0 -0
- package/web/chunk-rbh0yrp6.js.gz +0 -0
- package/web/chunk-rdarpbhd.js +2 -0
- package/web/chunk-rdarpbhd.js.br +0 -0
- package/web/chunk-rdarpbhd.js.gz +0 -0
- package/web/chunk-rf93p28v.js +1 -0
- package/web/chunk-rf93p28v.js.br +0 -0
- package/web/chunk-rf93p28v.js.gz +0 -0
- package/web/chunk-rjvdk0s6.js +1 -0
- package/web/chunk-rjvdk0s6.js.br +0 -0
- package/web/chunk-rjvdk0s6.js.gz +0 -0
- package/web/chunk-rvmk483c.js +1 -0
- package/web/chunk-rvmk483c.js.br +0 -0
- package/web/chunk-rvmk483c.js.gz +0 -0
- package/web/chunk-s99vfrrz.js +1 -0
- package/web/chunk-s99vfrrz.js.br +0 -0
- package/web/chunk-s99vfrrz.js.gz +0 -0
- package/web/chunk-saem11tv.js +2 -0
- package/web/chunk-saem11tv.js.br +0 -0
- package/web/chunk-saem11tv.js.gz +0 -0
- package/web/chunk-scv8t4m6.js +1 -0
- package/web/chunk-scv8t4m6.js.br +0 -0
- package/web/chunk-scv8t4m6.js.gz +0 -0
- package/web/chunk-stsmcqxe.js +1 -0
- package/web/chunk-stsmcqxe.js.br +0 -0
- package/web/chunk-stsmcqxe.js.gz +0 -0
- package/web/chunk-svaq7f3c.js +1134 -0
- package/web/chunk-svaq7f3c.js.br +0 -0
- package/web/chunk-svaq7f3c.js.gz +0 -0
- package/web/chunk-sy099zt8.js +1 -0
- package/web/chunk-sy099zt8.js.br +0 -0
- package/web/chunk-sy099zt8.js.gz +0 -0
- package/web/chunk-thqrbjwn.js +1 -0
- package/web/chunk-thqrbjwn.js.br +2 -0
- package/web/chunk-thqrbjwn.js.gz +0 -0
- package/web/chunk-ty1m1k6b.js +1 -0
- package/web/chunk-ty1m1k6b.js.br +0 -0
- package/web/chunk-ty1m1k6b.js.gz +0 -0
- package/web/chunk-w54qcqk3.js +1 -0
- package/web/chunk-w54qcqk3.js.br +0 -0
- package/web/chunk-w54qcqk3.js.gz +0 -0
- package/web/chunk-wgf4paqc.js +1 -0
- package/web/chunk-wgf4paqc.js.br +0 -0
- package/web/chunk-wgf4paqc.js.gz +0 -0
- package/web/chunk-ww5c1dmz.js +1 -0
- package/web/chunk-ww5c1dmz.js.br +0 -0
- package/web/chunk-ww5c1dmz.js.gz +0 -0
- package/web/chunk-x5m7phbb.js +1 -0
- package/web/chunk-x5m7phbb.js.br +0 -0
- package/web/chunk-x5m7phbb.js.gz +0 -0
- package/web/chunk-x9wzj52f.js +2 -0
- package/web/chunk-x9wzj52f.js.br +0 -0
- package/web/chunk-x9wzj52f.js.gz +0 -0
- package/web/chunk-xgfam7bx.js +1 -0
- package/web/chunk-xgfam7bx.js.br +0 -0
- package/web/chunk-xgfam7bx.js.gz +0 -0
- package/web/chunk-xnn07hr4.js +21 -0
- package/web/chunk-xnn07hr4.js.br +0 -0
- package/web/chunk-xnn07hr4.js.gz +0 -0
- package/web/chunk-xreg1e03.js +78 -0
- package/web/chunk-xreg1e03.js.br +0 -0
- package/web/chunk-xreg1e03.js.gz +0 -0
- package/web/chunk-xsxd3wsv.js +4 -0
- package/web/chunk-xsxd3wsv.js.br +0 -0
- package/web/chunk-xsxd3wsv.js.gz +0 -0
- package/web/chunk-y7jebh1j.js +1 -0
- package/web/chunk-y7jebh1j.js.br +0 -0
- package/web/chunk-y7jebh1j.js.gz +0 -0
- package/web/chunk-yhn2mwnb.js +291 -0
- package/web/chunk-yhn2mwnb.js.br +0 -0
- package/web/chunk-yhn2mwnb.js.gz +0 -0
- package/web/chunk-yj85fg74.js +1 -0
- package/web/chunk-yj85fg74.js.br +0 -0
- package/web/chunk-yj85fg74.js.gz +0 -0
- package/web/chunk-yjvjzayn.js +1 -0
- package/web/chunk-yjvjzayn.js.br +0 -0
- package/web/chunk-yjvjzayn.js.gz +0 -0
- package/web/chunk-yqwvedf5.js +370 -0
- package/web/chunk-yqwvedf5.js.br +0 -0
- package/web/chunk-yqwvedf5.js.gz +0 -0
- package/web/chunk-z3tr221x.js +1 -0
- package/web/chunk-z3tr221x.js.br +0 -0
- package/web/chunk-z3tr221x.js.gz +0 -0
- package/web/chunk-z4n3tx0q.js +1 -0
- package/web/chunk-z4n3tx0q.js.br +0 -0
- package/web/chunk-z4n3tx0q.js.gz +0 -0
- package/web/index.html +1 -1
- package/web/index.html.br +0 -0
- package/web/index.html.gz +0 -0
- package/worker.js +1 -1
- package/chunk-09tdbx7b.js +0 -3
- package/chunk-0b2brwjc.js +0 -3
- package/chunk-0rsyawz5.js +0 -8
- package/chunk-16yz5ebn.js +0 -2
- package/chunk-1kdd7xry.js +0 -2
- package/chunk-1td9hjn9.js +0 -25
- package/chunk-1xjkzzyh.js +0 -3
- package/chunk-38932kzp.js +0 -3
- package/chunk-3qxq264t.js +0 -2
- package/chunk-3s8rpc1w.js +0 -3
- package/chunk-4fbj3k59.js +0 -3
- package/chunk-5415fcz7.js +0 -10
- package/chunk-5kezbmgw.js +0 -3
- package/chunk-5m51j40e.js +0 -7
- package/chunk-5mt8xxex.js +0 -3
- package/chunk-5ph58x6w.js +0 -39
- package/chunk-6jdqe7sz.js +0 -4
- package/chunk-6ztgzx9s.js +0 -2
- package/chunk-7dzcdpdt.js +0 -2
- package/chunk-82djd5fk.js +0 -3
- package/chunk-86vhsd3y.js +0 -31
- package/chunk-8rfv9mm1.js +0 -15
- package/chunk-8tvz5ht1.js +0 -16
- package/chunk-9pjmwz01.js +0 -2
- package/chunk-9qzyn98b.js +0 -3
- package/chunk-9w1m9av8.js +0 -11
- package/chunk-9wjd9bxm.js +0 -2
- package/chunk-a3fpx924.js +0 -3
- package/chunk-b49005n2.js +0 -471
- package/chunk-bdz2561d.js +0 -2
- package/chunk-bkvhwgeb.js +0 -3
- package/chunk-bp9tfav3.js +0 -2
- package/chunk-cc9htxzx.js +0 -3557
- package/chunk-cr0tqn6j.js +0 -3
- package/chunk-cv5kdnsw.js +0 -3
- package/chunk-d79s1s4t.js +0 -25
- package/chunk-e0ytnnwt.js +0 -3
- package/chunk-e2m8ap8f.js +0 -3
- package/chunk-ec6bzt7w.js +0 -20
- package/chunk-enmrpjpt.js +0 -3
- package/chunk-eq54cmsa.js +0 -4
- package/chunk-fj56fznw.js +0 -3
- package/chunk-g54nd4fd.js +0 -5
- package/chunk-g8p5c4vx.js +0 -7
- package/chunk-g9bemxpt.js +0 -3
- package/chunk-gs5aebwh.js +0 -2
- package/chunk-hk5p2eee.js +0 -12
- package/chunk-jerp4pj5.js +0 -2
- package/chunk-jsvqp20s.js +0 -2
- package/chunk-k9x1r69s.js +0 -18
- package/chunk-kb526065.js +0 -2
- package/chunk-kpw1qa2n.js +0 -11
- package/chunk-mbvy2t23.js +0 -2
- package/chunk-mmnsdje8.js +0 -390
- package/chunk-nffwakxq.js +0 -2
- package/chunk-nfj8sj53.js +0 -2
- package/chunk-pzwaz2ew.js +0 -5
- package/chunk-qtgc74er.js +0 -5
- package/chunk-qtrd33pp.js +0 -7
- package/chunk-rbk6jxcr.js +0 -2
- package/chunk-rpbxbb92.js +0 -10
- package/chunk-rx812nrp.js +0 -3
- package/chunk-scy1p7x2.js +0 -9
- package/chunk-sfgw0vmt.js +0 -2
- package/chunk-t3mq64c8.js +0 -3
- package/chunk-tmefdwxy.js +0 -2
- package/chunk-tvg54x0x.js +0 -2
- package/chunk-v878x8zr.js +0 -7
- package/chunk-v89f2k9b.js +0 -2
- package/chunk-vhe16b65.js +0 -3
- package/chunk-vzrmdaba.js +0 -2
- package/chunk-w3skxmvx.js +0 -3
- package/chunk-w4kasz4j.js +0 -12
- package/chunk-w4zkgn1c.js +0 -4
- package/chunk-we5emq6f.js +0 -2
- package/chunk-x0dcabw6.js +0 -3
- package/chunk-xtj7b70y.js +0 -5
- package/chunk-xwew53k7.js +0 -59
- package/chunk-xyhr89y5.js +0 -3
- package/chunk-yce46csn.js +0 -2
- package/chunk-yetcb1z9.js +0 -3
- package/chunk-ypmpf75h.js +0 -2
- package/chunk-zkjnt298.js +0 -3
- package/chunk-zz48zvk5.js +0 -2
- package/web/chunk-04c54f1s.js +0 -1
- package/web/chunk-04c54f1s.js.br +0 -2
- package/web/chunk-04c54f1s.js.gz +0 -0
- package/web/chunk-04m1cb8w.js +0 -1
- package/web/chunk-04m1cb8w.js.br +0 -0
- package/web/chunk-04m1cb8w.js.gz +0 -0
- package/web/chunk-08z6mkgz.js +0 -40
- package/web/chunk-08z6mkgz.js.br +0 -0
- package/web/chunk-08z6mkgz.js.gz +0 -0
- package/web/chunk-0g9m3rpw.js +0 -55
- package/web/chunk-0g9m3rpw.js.br +0 -0
- package/web/chunk-0g9m3rpw.js.gz +0 -0
- package/web/chunk-0jccrdw3.js +0 -2
- package/web/chunk-0jccrdw3.js.br +0 -0
- package/web/chunk-0jccrdw3.js.gz +0 -0
- package/web/chunk-0rvx1z2b.js +0 -1
- package/web/chunk-0rvx1z2b.js.br +0 -0
- package/web/chunk-0rvx1z2b.js.gz +0 -0
- package/web/chunk-0vweazdh.js +0 -12
- package/web/chunk-0vweazdh.js.br +0 -0
- package/web/chunk-0vweazdh.js.gz +0 -0
- package/web/chunk-0wqmwnd8.js +0 -2
- package/web/chunk-0wqmwnd8.js.br +0 -0
- package/web/chunk-0wqmwnd8.js.gz +0 -0
- package/web/chunk-0z10aqp1.js +0 -2
- package/web/chunk-0z10aqp1.js.br +0 -0
- package/web/chunk-0z10aqp1.js.gz +0 -0
- package/web/chunk-12vcrj7y.js +0 -1
- package/web/chunk-12vcrj7y.js.br +0 -0
- package/web/chunk-12vcrj7y.js.gz +0 -0
- package/web/chunk-1vtf555r.js +0 -1
- package/web/chunk-1vtf555r.js.br +0 -0
- package/web/chunk-1vtf555r.js.gz +0 -0
- package/web/chunk-29z0ft67.js +0 -370
- package/web/chunk-29z0ft67.js.br +0 -0
- package/web/chunk-29z0ft67.js.gz +0 -0
- package/web/chunk-2q3m4btb.js +0 -1
- package/web/chunk-2q3m4btb.js.br +0 -0
- package/web/chunk-2q3m4btb.js.gz +0 -0
- package/web/chunk-2s6fhjjc.js +0 -1134
- package/web/chunk-2s6fhjjc.js.br +0 -0
- package/web/chunk-2s6fhjjc.js.gz +0 -0
- package/web/chunk-2vdx4ykn.js +0 -139
- package/web/chunk-2vdx4ykn.js.br +0 -0
- package/web/chunk-2vdx4ykn.js.gz +0 -0
- package/web/chunk-2zgqe8r7.js +0 -1
- package/web/chunk-2zgqe8r7.js.br +0 -0
- package/web/chunk-2zgqe8r7.js.gz +0 -0
- package/web/chunk-366a11ec.js +0 -1
- package/web/chunk-366a11ec.js.br +0 -0
- package/web/chunk-366a11ec.js.gz +0 -0
- package/web/chunk-3kqpmg83.js +0 -78
- package/web/chunk-3kqpmg83.js.br +0 -0
- package/web/chunk-3kqpmg83.js.gz +0 -0
- package/web/chunk-3rmqxna0.js +0 -1
- package/web/chunk-3rmqxna0.js.br +0 -0
- package/web/chunk-3rmqxna0.js.gz +0 -0
- package/web/chunk-3xmv2349.js +0 -21
- package/web/chunk-3xmv2349.js.br +0 -0
- package/web/chunk-3xmv2349.js.gz +0 -0
- package/web/chunk-46cdys11.js +0 -34
- package/web/chunk-46cdys11.js.br +0 -0
- package/web/chunk-46cdys11.js.gz +0 -0
- package/web/chunk-46mw23f0.js +0 -8
- package/web/chunk-46mw23f0.js.br +0 -0
- package/web/chunk-46mw23f0.js.gz +0 -0
- package/web/chunk-4mypk63p.js +0 -2
- package/web/chunk-4mypk63p.js.br +0 -0
- package/web/chunk-4mypk63p.js.gz +0 -0
- package/web/chunk-4r0dvjrr.js +0 -2
- package/web/chunk-4r0dvjrr.js.br +0 -0
- package/web/chunk-4r0dvjrr.js.gz +0 -0
- package/web/chunk-4v6m84pg.js +0 -3
- package/web/chunk-4v6m84pg.js.br +0 -0
- package/web/chunk-4v6m84pg.js.gz +0 -0
- package/web/chunk-4wd9r73y.js +0 -1
- package/web/chunk-4wd9r73y.js.br +0 -0
- package/web/chunk-4wd9r73y.js.gz +0 -0
- package/web/chunk-4ye31s2w.js +0 -1
- package/web/chunk-4ye31s2w.js.br +0 -4
- package/web/chunk-4ye31s2w.js.gz +0 -0
- package/web/chunk-52tt9qt4.js +0 -2
- package/web/chunk-52tt9qt4.js.br +0 -0
- package/web/chunk-52tt9qt4.js.gz +0 -0
- package/web/chunk-5cp4n5ck.js +0 -2
- package/web/chunk-5cp4n5ck.js.br +0 -0
- package/web/chunk-5cp4n5ck.js.gz +0 -0
- package/web/chunk-5kavsn22.js +0 -4
- package/web/chunk-5kavsn22.js.br +0 -0
- package/web/chunk-5kavsn22.js.gz +0 -0
- package/web/chunk-5q2h4tg8.js +0 -2
- package/web/chunk-5q2h4tg8.js.br +0 -4
- package/web/chunk-5q2h4tg8.js.gz +0 -0
- package/web/chunk-5tbk6dx6.js +0 -292
- package/web/chunk-5tbk6dx6.js.br +0 -0
- package/web/chunk-5tbk6dx6.js.gz +0 -0
- package/web/chunk-5yb0sm1r.js +0 -1
- package/web/chunk-5yb0sm1r.js.br +0 -0
- package/web/chunk-5yb0sm1r.js.gz +0 -0
- package/web/chunk-5yz46tjw.js +0 -2
- package/web/chunk-5yz46tjw.js.br +0 -0
- package/web/chunk-5yz46tjw.js.gz +0 -0
- package/web/chunk-619a8t38.js +0 -1
- package/web/chunk-619a8t38.js.br +0 -0
- package/web/chunk-619a8t38.js.gz +0 -0
- package/web/chunk-6areryyn.js +0 -2
- package/web/chunk-6areryyn.js.br +0 -0
- package/web/chunk-6areryyn.js.gz +0 -0
- package/web/chunk-6ms78sx5.js +0 -1
- package/web/chunk-6ms78sx5.js.br +0 -0
- package/web/chunk-6ms78sx5.js.gz +0 -0
- package/web/chunk-6ts9mtye.js +0 -2
- package/web/chunk-6ts9mtye.js.br +0 -0
- package/web/chunk-6ts9mtye.js.gz +0 -0
- package/web/chunk-79whhay2.js +0 -2
- package/web/chunk-79whhay2.js.br +0 -0
- package/web/chunk-79whhay2.js.gz +0 -0
- package/web/chunk-7cf1kk45.js +0 -1
- package/web/chunk-7cf1kk45.js.br +0 -2
- package/web/chunk-7cf1kk45.js.gz +0 -0
- package/web/chunk-7n1abr86.js +0 -1
- package/web/chunk-7n1abr86.js.br +0 -0
- package/web/chunk-7n1abr86.js.gz +0 -0
- package/web/chunk-7qxfx983.js +0 -1
- package/web/chunk-7qxfx983.js.br +0 -0
- package/web/chunk-7qxfx983.js.gz +0 -0
- package/web/chunk-89crtpnw.js +0 -1
- package/web/chunk-89crtpnw.js.br +0 -0
- package/web/chunk-89crtpnw.js.gz +0 -0
- package/web/chunk-8g239029.js +0 -1
- package/web/chunk-8g239029.js.br +0 -0
- package/web/chunk-8g239029.js.gz +0 -0
- package/web/chunk-91k30q92.js +0 -1
- package/web/chunk-91k30q92.js.br +0 -0
- package/web/chunk-91k30q92.js.gz +0 -0
- package/web/chunk-91nyvkrb.js +0 -324
- package/web/chunk-91nyvkrb.js.br +0 -0
- package/web/chunk-91nyvkrb.js.gz +0 -0
- package/web/chunk-9mbr6znb.js +0 -1
- package/web/chunk-9mbr6znb.js.br +0 -0
- package/web/chunk-9mbr6znb.js.gz +0 -0
- package/web/chunk-9mvw6a5v.js +0 -7
- package/web/chunk-9mvw6a5v.js.br +0 -0
- package/web/chunk-9mvw6a5v.js.gz +0 -0
- package/web/chunk-9r7nbre7.js +0 -2
- package/web/chunk-9r7nbre7.js.br +0 -0
- package/web/chunk-9r7nbre7.js.gz +0 -0
- package/web/chunk-9y9nwaqj.js +0 -1
- package/web/chunk-9y9nwaqj.js.br +0 -0
- package/web/chunk-9y9nwaqj.js.gz +0 -0
- package/web/chunk-a6hdn8tb.js +0 -169
- package/web/chunk-a6hdn8tb.js.br +0 -0
- package/web/chunk-a6hdn8tb.js.gz +0 -0
- package/web/chunk-ad6x47yy.js +0 -1
- package/web/chunk-ad6x47yy.js.br +0 -0
- package/web/chunk-ad6x47yy.js.gz +0 -0
- package/web/chunk-ar6m9fza.js +0 -7
- package/web/chunk-ar6m9fza.js.br +0 -0
- package/web/chunk-ar6m9fza.js.gz +0 -0
- package/web/chunk-ayqakyyq.js +0 -1
- package/web/chunk-ayqakyyq.js.br +0 -0
- package/web/chunk-ayqakyyq.js.gz +0 -0
- package/web/chunk-cc6hn5xv.js +0 -2
- package/web/chunk-cc6hn5xv.js.br +0 -0
- package/web/chunk-cc6hn5xv.js.gz +0 -0
- package/web/chunk-ccymg1hp.js +0 -1
- package/web/chunk-ccymg1hp.js.br +0 -0
- package/web/chunk-ccymg1hp.js.gz +0 -0
- package/web/chunk-cg9fe42b.js +0 -89
- package/web/chunk-cg9fe42b.js.br +0 -0
- package/web/chunk-cg9fe42b.js.gz +0 -0
- package/web/chunk-cmcgmf94.js +0 -1
- package/web/chunk-cmcgmf94.js.br +0 -0
- package/web/chunk-cmcgmf94.js.gz +0 -0
- package/web/chunk-cnbbvd6n.js +0 -1
- package/web/chunk-cnbbvd6n.js.br +0 -0
- package/web/chunk-cnbbvd6n.js.gz +0 -0
- package/web/chunk-cxp2nbtc.js +0 -106
- package/web/chunk-cxp2nbtc.js.br +0 -0
- package/web/chunk-cxp2nbtc.js.gz +0 -0
- package/web/chunk-d18r4m14.js +0 -141
- package/web/chunk-d18r4m14.js.br +0 -0
- package/web/chunk-d18r4m14.js.gz +0 -0
- package/web/chunk-dj2b64aj.js +0 -1
- package/web/chunk-dj2b64aj.js.br +0 -0
- package/web/chunk-dj2b64aj.js.gz +0 -0
- package/web/chunk-dmqtdeb4.js +0 -1
- package/web/chunk-dmqtdeb4.js.br +0 -0
- package/web/chunk-dmqtdeb4.js.gz +0 -0
- package/web/chunk-dsga6rp3.js +0 -1
- package/web/chunk-dsga6rp3.js.br +0 -0
- package/web/chunk-dsga6rp3.js.gz +0 -0
- package/web/chunk-e65y60v1.js +0 -2
- package/web/chunk-e65y60v1.js.br +0 -0
- package/web/chunk-e65y60v1.js.gz +0 -0
- package/web/chunk-ed8qqn45.js +0 -2
- package/web/chunk-ed8qqn45.js.br +0 -0
- package/web/chunk-ed8qqn45.js.gz +0 -0
- package/web/chunk-ef1h0tt7.js +0 -2
- package/web/chunk-ef1h0tt7.js.br +0 -0
- package/web/chunk-ef1h0tt7.js.gz +0 -0
- package/web/chunk-ek6q6a08.js +0 -1
- package/web/chunk-ek6q6a08.js.br +0 -2
- package/web/chunk-ek6q6a08.js.gz +0 -0
- package/web/chunk-et1nm6h1.js +0 -142
- package/web/chunk-et1nm6h1.js.br +0 -0
- package/web/chunk-et1nm6h1.js.gz +0 -0
- package/web/chunk-f1016wh6.js +0 -1
- package/web/chunk-f1016wh6.js.br +0 -0
- package/web/chunk-f1016wh6.js.gz +0 -0
- package/web/chunk-f42mwg61.js +0 -1
- package/web/chunk-f42mwg61.js.br +0 -0
- package/web/chunk-f42mwg61.js.gz +0 -0
- package/web/chunk-fk35d3bz.js +0 -332
- package/web/chunk-fk35d3bz.js.br +0 -0
- package/web/chunk-fk35d3bz.js.gz +0 -0
- package/web/chunk-fpwztdhn.js +0 -39
- package/web/chunk-fpwztdhn.js.br +0 -0
- package/web/chunk-fpwztdhn.js.gz +0 -0
- package/web/chunk-g30nqfka.js +0 -2
- package/web/chunk-g30nqfka.js.br +0 -0
- package/web/chunk-g30nqfka.js.gz +0 -0
- package/web/chunk-g3vbtxgy.js +0 -2
- package/web/chunk-g3vbtxgy.js.br +0 -0
- package/web/chunk-g3vbtxgy.js.gz +0 -0
- package/web/chunk-gbwy4pfg.css +0 -1
- package/web/chunk-gbwy4pfg.css.br +0 -0
- package/web/chunk-gbwy4pfg.css.gz +0 -0
- package/web/chunk-gepgx19m.js +0 -200
- package/web/chunk-gepgx19m.js.br +0 -0
- package/web/chunk-gepgx19m.js.gz +0 -0
- package/web/chunk-grz69q28.js +0 -36
- package/web/chunk-grz69q28.js.br +0 -0
- package/web/chunk-grz69q28.js.gz +0 -0
- package/web/chunk-gt62acsh.js +0 -2
- package/web/chunk-gt62acsh.js.br +0 -0
- package/web/chunk-gt62acsh.js.gz +0 -0
- package/web/chunk-h28xrvmg.js +0 -41
- package/web/chunk-h28xrvmg.js.br +0 -0
- package/web/chunk-h28xrvmg.js.gz +0 -0
- package/web/chunk-h80ypke7.js +0 -2
- package/web/chunk-h80ypke7.js.br +0 -0
- package/web/chunk-h80ypke7.js.gz +0 -0
- package/web/chunk-hj067dfg.js +0 -1
- package/web/chunk-hj067dfg.js.br +0 -2
- package/web/chunk-hj067dfg.js.gz +0 -0
- package/web/chunk-hp167dbv.js +0 -1
- package/web/chunk-hp167dbv.js.br +0 -0
- package/web/chunk-hp167dbv.js.gz +0 -0
- package/web/chunk-j4942vkb.js +0 -1
- package/web/chunk-j4942vkb.js.br +0 -0
- package/web/chunk-j4942vkb.js.gz +0 -0
- package/web/chunk-k1cd6e24.js +0 -1
- package/web/chunk-k1cd6e24.js.br +0 -0
- package/web/chunk-k1cd6e24.js.gz +0 -0
- package/web/chunk-k1d0y72z.js +0 -2
- package/web/chunk-k1d0y72z.js.br +0 -0
- package/web/chunk-k1d0y72z.js.gz +0 -0
- package/web/chunk-k9248573.js +0 -1
- package/web/chunk-k9248573.js.br +0 -0
- package/web/chunk-k9248573.js.gz +0 -0
- package/web/chunk-kh0xyffx.js +0 -1
- package/web/chunk-kh0xyffx.js.br +0 -0
- package/web/chunk-kh0xyffx.js.gz +0 -0
- package/web/chunk-kqgn9dsa.js +0 -7
- package/web/chunk-kqgn9dsa.js.br +0 -0
- package/web/chunk-kqgn9dsa.js.gz +0 -0
- package/web/chunk-kqngpw5m.js +0 -1
- package/web/chunk-kqngpw5m.js.br +0 -0
- package/web/chunk-kqngpw5m.js.gz +0 -0
- package/web/chunk-ktvxgxsd.js +0 -2
- package/web/chunk-ktvxgxsd.js.br +0 -0
- package/web/chunk-ktvxgxsd.js.gz +0 -0
- package/web/chunk-kzj105r1.js +0 -217
- package/web/chunk-kzj105r1.js.br +0 -0
- package/web/chunk-kzj105r1.js.gz +0 -0
- package/web/chunk-m14v2en1.js +0 -1
- package/web/chunk-m14v2en1.js.br +0 -0
- package/web/chunk-m14v2en1.js.gz +0 -0
- package/web/chunk-m34et8g4.js +0 -2
- package/web/chunk-m34et8g4.js.br +0 -0
- package/web/chunk-m34et8g4.js.gz +0 -0
- package/web/chunk-md1f6gmk.js +0 -1
- package/web/chunk-md1f6gmk.js.br +0 -0
- package/web/chunk-md1f6gmk.js.gz +0 -0
- package/web/chunk-n05xf20n.js +0 -98
- package/web/chunk-n05xf20n.js.br +0 -0
- package/web/chunk-n05xf20n.js.gz +0 -0
- package/web/chunk-n2k1gd6n.js +0 -84
- package/web/chunk-n2k1gd6n.js.br +0 -0
- package/web/chunk-n2k1gd6n.js.gz +0 -0
- package/web/chunk-n419cees.js +0 -1
- package/web/chunk-n419cees.js.br +0 -0
- package/web/chunk-n419cees.js.gz +0 -0
- package/web/chunk-n45fgfyt.js +0 -1
- package/web/chunk-n45fgfyt.js.br +0 -2
- package/web/chunk-n45fgfyt.js.gz +0 -0
- package/web/chunk-n5v71fas.js +0 -2
- package/web/chunk-n5v71fas.js.br +0 -0
- package/web/chunk-n5v71fas.js.gz +0 -0
- package/web/chunk-nm8yza3v.js +0 -140
- package/web/chunk-nm8yza3v.js.br +0 -0
- package/web/chunk-nm8yza3v.js.gz +0 -0
- package/web/chunk-nzey7cpv.js +0 -1
- package/web/chunk-nzey7cpv.js.br +0 -0
- package/web/chunk-nzey7cpv.js.gz +0 -0
- package/web/chunk-p76f6cf4.js +0 -2
- package/web/chunk-p76f6cf4.js.br +0 -0
- package/web/chunk-p76f6cf4.js.gz +0 -0
- package/web/chunk-pbg9rdwv.js +0 -1
- package/web/chunk-pbg9rdwv.js.br +0 -2
- package/web/chunk-pbg9rdwv.js.gz +0 -0
- package/web/chunk-qgtqwmkb.js +0 -1
- package/web/chunk-qgtqwmkb.js.br +0 -2
- package/web/chunk-qgtqwmkb.js.gz +0 -0
- package/web/chunk-qj9nd038.js +0 -1
- package/web/chunk-qj9nd038.js.br +0 -0
- package/web/chunk-qj9nd038.js.gz +0 -0
- package/web/chunk-qjaex9c0.js +0 -1
- package/web/chunk-qjaex9c0.js.br +0 -2
- package/web/chunk-qjaex9c0.js.gz +0 -0
- package/web/chunk-qq79vsm8.js +0 -70
- package/web/chunk-qq79vsm8.js.br +0 -0
- package/web/chunk-qq79vsm8.js.gz +0 -0
- package/web/chunk-qs5wnwd6.js +0 -30
- package/web/chunk-qs5wnwd6.js.br +0 -0
- package/web/chunk-qs5wnwd6.js.gz +0 -0
- package/web/chunk-qygjhm63.js +0 -1
- package/web/chunk-qygjhm63.js.br +0 -0
- package/web/chunk-qygjhm63.js.gz +0 -0
- package/web/chunk-r1dnh0s8.js +0 -1
- package/web/chunk-r1dnh0s8.js.br +0 -0
- package/web/chunk-r1dnh0s8.js.gz +0 -0
- package/web/chunk-r381n550.js +0 -1
- package/web/chunk-r381n550.js.br +0 -0
- package/web/chunk-r381n550.js.gz +0 -0
- package/web/chunk-r48vazdm.js +0 -291
- package/web/chunk-r48vazdm.js.br +0 -0
- package/web/chunk-r48vazdm.js.gz +0 -0
- package/web/chunk-r55seq42.js +0 -24
- package/web/chunk-r55seq42.js.br +0 -0
- package/web/chunk-r55seq42.js.gz +0 -0
- package/web/chunk-r5eakmw6.js +0 -1
- package/web/chunk-r5eakmw6.js.br +0 -0
- package/web/chunk-r5eakmw6.js.gz +0 -0
- package/web/chunk-r79zekav.js +0 -1
- package/web/chunk-r79zekav.js.br +0 -0
- package/web/chunk-r79zekav.js.gz +0 -0
- package/web/chunk-r8qyvcks.js +0 -89
- package/web/chunk-r8qyvcks.js.br +0 -0
- package/web/chunk-r8qyvcks.js.gz +0 -0
- package/web/chunk-r9dt0730.js +0 -1
- package/web/chunk-r9dt0730.js.br +0 -0
- package/web/chunk-r9dt0730.js.gz +0 -0
- package/web/chunk-rfsg5rke.js +0 -1
- package/web/chunk-rfsg5rke.js.br +0 -2
- package/web/chunk-rfsg5rke.js.gz +0 -0
- package/web/chunk-rpjzwknn.js +0 -1
- package/web/chunk-rpjzwknn.js.br +0 -0
- package/web/chunk-rpjzwknn.js.gz +0 -0
- package/web/chunk-s7h50avx.js +0 -2
- package/web/chunk-s7h50avx.js.br +0 -0
- package/web/chunk-s7h50avx.js.gz +0 -0
- package/web/chunk-sk3065js.js +0 -62
- package/web/chunk-sk3065js.js.br +0 -0
- package/web/chunk-sk3065js.js.gz +0 -0
- package/web/chunk-sk47kk5j.js +0 -1
- package/web/chunk-sk47kk5j.js.br +0 -0
- package/web/chunk-sk47kk5j.js.gz +0 -0
- package/web/chunk-smywa1zw.js +0 -2
- package/web/chunk-smywa1zw.js.br +0 -0
- package/web/chunk-smywa1zw.js.gz +0 -0
- package/web/chunk-t6agpn2z.js +0 -1
- package/web/chunk-t6agpn2z.js.br +0 -0
- package/web/chunk-t6agpn2z.js.gz +0 -0
- package/web/chunk-t9heac9a.js +0 -2
- package/web/chunk-t9heac9a.js.br +0 -0
- package/web/chunk-t9heac9a.js.gz +0 -0
- package/web/chunk-trssyq9a.js +0 -1
- package/web/chunk-trssyq9a.js.br +0 -0
- package/web/chunk-trssyq9a.js.gz +0 -0
- package/web/chunk-v329f8df.js +0 -24
- package/web/chunk-v329f8df.js.br +0 -0
- package/web/chunk-v329f8df.js.gz +0 -0
- package/web/chunk-vb2feptd.js +0 -2
- package/web/chunk-vb2feptd.js.br +0 -0
- package/web/chunk-vb2feptd.js.gz +0 -0
- package/web/chunk-vff33vj3.js +0 -1
- package/web/chunk-vff33vj3.js.br +0 -2
- package/web/chunk-vff33vj3.js.gz +0 -0
- package/web/chunk-w9adyaze.js +0 -16
- package/web/chunk-w9adyaze.js.br +0 -0
- package/web/chunk-w9adyaze.js.gz +0 -0
- package/web/chunk-wgc8z5jv.js +0 -1
- package/web/chunk-wgc8z5jv.js.br +0 -0
- package/web/chunk-wgc8z5jv.js.gz +0 -0
- package/web/chunk-wvdk3w03.js +0 -2
- package/web/chunk-wvdk3w03.js.br +0 -0
- package/web/chunk-wvdk3w03.js.gz +0 -0
- package/web/chunk-wvvrdqgb.js +0 -1
- package/web/chunk-wvvrdqgb.js.br +0 -2
- package/web/chunk-wvvrdqgb.js.gz +0 -0
- package/web/chunk-wxmaw4ht.js +0 -1
- package/web/chunk-wxmaw4ht.js.br +0 -0
- package/web/chunk-wxmaw4ht.js.gz +0 -0
- package/web/chunk-x19jdqnt.js +0 -38
- package/web/chunk-x19jdqnt.js.br +0 -0
- package/web/chunk-x19jdqnt.js.gz +0 -0
- package/web/chunk-x4153gx3.js +0 -214
- package/web/chunk-x4153gx3.js.br +0 -0
- package/web/chunk-x4153gx3.js.gz +0 -0
- package/web/chunk-x7wmb5d3.js +0 -4
- package/web/chunk-x7wmb5d3.js.br +0 -0
- package/web/chunk-x7wmb5d3.js.gz +0 -0
- package/web/chunk-xp2zpmpp.js +0 -303
- package/web/chunk-xp2zpmpp.js.br +0 -0
- package/web/chunk-xp2zpmpp.js.gz +0 -0
- package/web/chunk-xp9tdb5t.js +0 -1
- package/web/chunk-xp9tdb5t.js.br +0 -2
- package/web/chunk-xp9tdb5t.js.gz +0 -0
- package/web/chunk-y09v3sz7.js +0 -1
- package/web/chunk-y09v3sz7.js.br +0 -0
- package/web/chunk-y09v3sz7.js.gz +0 -0
- package/web/chunk-y10hsdq4.js +0 -1
- package/web/chunk-y10hsdq4.js.br +0 -0
- package/web/chunk-y10hsdq4.js.gz +0 -0
- package/web/chunk-ywmsxe5z.js +0 -99
- package/web/chunk-ywmsxe5z.js.br +0 -0
- package/web/chunk-ywmsxe5z.js.gz +0 -0
- package/web/chunk-yzyxa823.js +0 -2
- package/web/chunk-yzyxa823.js.br +0 -0
- package/web/chunk-yzyxa823.js.gz +0 -0
- package/web/chunk-z09emmrb.js +0 -1
- package/web/chunk-z09emmrb.js.br +0 -0
- package/web/chunk-z09emmrb.js.gz +0 -0
- package/web/chunk-zwx48gb8.js +0 -120
- package/web/chunk-zwx48gb8.js.br +0 -0
- package/web/chunk-zwx48gb8.js.gz +0 -0
package/chunk-b49005n2.js
DELETED
|
@@ -1,471 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ai,vn,z}from"./chunk-pzwaz2ew.js";import{cs,Xe,Et,us,yo,ds,ms,hs,Dt,bs,$e,So,it}from"./chunk-d79s1s4t.js";import{xt,yn,oo,Yt,Hi,io}from"./chunk-kpw1qa2n.js";import{ei,qi,so,bn,Gi,t,m,vt,Ki,Qi,Ji,Cr,ri,Xi,wn,oi,ao,si,lo,os,is,Ne}from"./chunk-g8p5c4vx.js";import{co,Es,xn}from"./chunk-5kezbmgw.js";import{b,ue}from"./chunk-t3mq64c8.js";import{uo,W,_n,De,ie,li,po,ut,as,er,Ie,U,mo,_t,Ue,Ir,q,Be,ho,At,fe,tr,ce,An,ci,Fe,ae,pt,fo,ui,_e,Ts,ls,Ae,go,d,Ps,ee,En,K,ks}from"./chunk-hk5p2eee.js";import{r,Ze}from"./chunk-zkjnt298.js";var qg=r(function(PK,Ng){var Rv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Vl=/[\n\r\u2028\u2029]/,kv=/[\s#!"$&'():;<=>@\\^`|~]/g;Ng.exports=function(o){var a=!1;return o.map(function(u){if(a&&typeof u==="string"&&Vl.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Vl.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(kv,"\\$&")}if("op"in u&&typeof u.op==="string"){if(Rv.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(Vl.test(u.comment))throw TypeError("`comment` must not contain line terminators");return a=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var Hg=r(function($K,Kg){var Bg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Dg=new RegExp("^"+Bg+"$"),Fg="|&;()<> \\t",Av="'([^']*?)'",Gg="(?:\\\\[\\s\\S]|[^\\\\'])*?",jg="\\$'"+Gg+"'",nm=new RegExp("\\$'"+Gg+"(?:(')|\\\\?$)","g"),Pv="abeEfnrtv",$v=`\x07\b\x1B\x1B\f
|
|
3
|
-
\r \v`,Cv=/^#$/,Jl="'",Ug='"',vu="$",ra="",vv=4294967296;for(rm=0;rm<4;rm++)ra+=(vv*Math.random()).toString(16);var rm,Mv=new RegExp("^"+ra);function Ov(e,o){var a=o.lastIndex,u=[],p;while(p=o.exec(e))if(u[u.length]=p,o.lastIndex===p.index)o.lastIndex+=1;return o.lastIndex=a,u}function _v(e,o,a){var u=typeof e==="function"?e(a):e[a];if(typeof u>"u"&&a!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+ra+JSON.stringify(u)+ra;return o+u}var Lv=/\\([0-7]{1,3}|x[\dA-Fa-f]{1,2}|u[\dA-Fa-f]{1,4}|U[\dA-Fa-f]{1,8}|c(?:\\\\|[\s\S])|[abeEfnrtv\\'"?])/g;function Nv(e,o){var a=o.charAt(0);if(a==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(a==="x"||a==="u"||a==="U"){var p=parseInt(o.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(a>="0"&&a<="7")return String.fromCharCode(parseInt(o,8)&255);var f=Pv.indexOf(o);return f<0?o:$v.charAt(f)}function qv(e){return e.replace(Lv,Nv).split("\x00")[0]}function Dv(e,o){return nm.lastIndex=o,!!nm.exec(e)[1]}function Fv(e,o,a){if(!a)a={};var u=a.escape||"\\",p=a.splitUnquoted===!0?`
|
|
4
|
-
`:typeof a.splitUnquoted==="string"?a.splitUnquoted:"",f="(\\"+u+`['"$\\`+u+Fg+"]|\\$\\$|\\$(?!"+jg.slice(2)+`)|[^\\s'"$`+Fg+"])+",h='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',g=new RegExp(["("+Bg+")","("+jg+"|"+f+"|"+h+"|"+Av+")+"].join("|"),"g"),x=Ov(e,g);if(x.length===0)return[];if(!o)o={};var I=!1;return x.map(function(E){var k=E[0];if(!k||I)return;if(Dg.test(k))return{op:k};var A=!1,P=!1,C="",M=[],J=!1,O=null,B=!1,L;function X(){L+=1;var me,he,we=k.charAt(L);if(we==="{"){if(L+=1,k.charAt(L)==="}")throw Error("Bad substitution: "+k.slice(L-2,L+1));var Ee=1;me=L;while(Ee>0&&me<k.length){if(k.charAt(me)==="{"&&k.charAt(me-1)==="$")Ee+=1;else if(k.charAt(me)==="}")Ee-=1;me+=1}if(Ee!==0)throw Error("Bad substitution: "+k.slice(L));me-=1,he=k.slice(L,me),L=me}else if(/[*@#?$!-]/.test(we))he=we;else{var ft=k.slice(L);if(me=ft.match(/[^\w\d_]/),!me)he=ft,L=k.length;else he=ft.slice(0,me.index),L+=me.index-1}return _v(o,"",he)}function te(){if(O===null)return;if(O===0){if(C!=="")M[M.length]=C,C=""}else{M[M.length]=C,C="";for(var me=1;me<O;me+=1)M[M.length]=""}O=null}for(L=0;L<k.length;L++){var j=k.charAt(L);if(p&&j!==vu)te();if(B=B||!A&&(j==="*"||j==="?"),P)C+=j,P=!1;else if(A)if(j===A)A=!1;else if(A==Jl)C+=j;else if(j===u)if(L+=1,j=k.charAt(L),j===Ug||j===u||j===vu)C+=j;else C+=u+j;else if(j===vu)C+=X();else C+=j;else if(j===Ug||j===Jl)A=j,J=!0;else if(Dg.test(j))return{op:k};else if(Cv.test(j)){I=!0;var re={comment:e.slice(E.index+L+1)};if(C.length)return[C,re];return[re]}else if(j===u)P=!0;else if(j===vu&&k.charAt(L+1)===Jl&&Dv(k,L))te(),J=!0,C+=qv(k.slice(L+2,nm.lastIndex-1)),L=nm.lastIndex-1;else if(j===vu){var ye=X();if(!p)C+=ye;else for(var Te=0;Te<ye.length;Te+=1){var ze=ye.charAt(Te);if(p.indexOf(ze)<0)te(),C+=ze;else if(O===null)O=ze===" "||ze==="\t"||ze===`
|
|
5
|
-
`?0:1;else if(ze!==" "&&ze!=="\t"&&ze!==`
|
|
6
|
-
`)O+=1}}else C+=j}if(B)return{op:"glob",pattern:C};if(p){if(O!==null&&O>0){M[M.length]=C,C="";for(var Y=1;Y<O;Y+=1)M[M.length]=""}if(C!==""||J&&M.length===0)M[M.length]=C;return M}return C}).reduce(function(E,k){if(typeof k>"u")return E;return[].concat(k).forEach(function(A){E[E.length]=A}),E},[])}Kg.exports=function(o,a,u){var p=Fv(o,a,u);if(typeof a!=="function")return p;return p.reduce(function(f,h){if(typeof h==="object")return f[f.length]=h,f;var g=h.split(RegExp("("+ra+".*?"+ra+")","g"));if(g.length===1)return f[f.length]=g[0],f;return g.filter(Boolean).forEach(function(x){f[f.length]=Mv.test(x)?JSON.parse(x.split(ra)[1]):x}),f},[])}});var Jo={};Ze(Jo,{AssistantMessageEventStream:()=>W,AssistantMessageFrameEncoder:()=>oR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>aR,EventStream:()=>uo,InMemoryCredentialStore:()=>po,InMemoryModelsStore:()=>mo,ModelsError:()=>U,StringEnum:()=>ED,Type:()=>Oe,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>ee,clampThinkingLevel:()=>K,cleanupSessionResources:()=>Es,collapseSystemMessages:()=>Fe,contentText:()=>Ir,createAssistantMessageDiagnostic:()=>er,createAssistantMessageEventStream:()=>_n,createFauxCore:()=>Hi,createInitialSystemMessage:()=>ho,createModels:()=>go,createProvider:()=>d,declarationsEqual:()=>fo,defaultProviderAuthContext:()=>li,envApiKeyAuth:()=>b,extractDiagnosticError:()=>as,fauxAssistantMessage:()=>Yt,fauxProvider:()=>io,fauxText:()=>xt,fauxThinking:()=>yn,fauxToolCall:()=>oo,formatThrownValue:()=>ut,getCurrentSystemMessage:()=>An,getCurrentSystemPrompt:()=>ci,getCurrentTools:()=>ce,getDeclaredTools:()=>_e,getInitialSystemMessage:()=>fe,getModelType:()=>_t,getOverflowPatterns:()=>hD,getSupportedThinkingLevels:()=>En,getSystemMessageText:()=>q,getToolStateChanges:()=>ui,hasApi:()=>Ps,hasNonAdditiveToolChanges:()=>ls,hasToolRedefinitions:()=>Ts,isContextOverflow:()=>Ta,isModelType:()=>Ue,isRecoverableLength:()=>fD,isRetryableAssistantError:()=>cR,lazyApi:()=>ie,lazyOAuth:()=>ue,lazyStream:()=>De,modelsAreEqual:()=>ks,normalizeContext:()=>At,parseJsonWithRepair:()=>vn,parseStreamingJson:()=>z,reduceAssistantMessageFrames:()=>pD,registerSessionResourceCleanup:()=>co,renderSystemMessageUpdate:()=>Be,repairJson:()=>ai,resolveTranscript:()=>ae,resolveTranscriptTools:()=>Ae,retryAssistantCall:()=>ID,retryDelayMs:()=>uR,toToolDeclaration:()=>pt,uuidv7:()=>xn,validateToolArguments:()=>yu,validateToolCall:()=>sU,withoutInitialSystemMessage:()=>tr});var _={};Ze(_,{Counted:()=>td,Entries:()=>pn,EntriesRegExp:()=>rd,Every:()=>on,EveryAll:()=>Dn,GraphemeCount:()=>lM,HasPropertyKey:()=>se,IsArray:()=>He,IsBigInt:()=>Kr,IsBoolean:()=>cn,IsClassInstance:()=>uy,IsConstructor:()=>Zl,IsDeepEqual:()=>Da,IsEqual:()=>v,IsFunction:()=>Os,IsGreaterEqualThan:()=>Na,IsGreaterThan:()=>sa,IsInteger:()=>am,IsLessEqualThan:()=>_s,IsLessThan:()=>Mu,IsMaxLength:()=>cy,IsMinLength:()=>my,IsMultipleOf:()=>ay,IsNull:()=>Oo,IsNumber:()=>Bt,IsObject:()=>lt,IsObjectNotArray:()=>rs,IsString:()=>yt,IsSymbol:()=>ed,IsUndefined:()=>nr,IsUnsafePropertyKey:()=>Ou,IsValueLike:()=>ia,Keys:()=>be,ShiftLeft:()=>bt,Some:()=>qa,SomeAll:()=>py,Symbols:()=>ly,Values:()=>nd});var da={};Ze(da,{Hash:()=>md,HashCode:()=>Wy});var Gt={};Ze(Gt,{ExtendsFalse:()=>et,ExtendsTrue:()=>Se,ExtendsUnion:()=>Md,IsExtendsFalse:()=>Ld,IsExtendsTrue:()=>_d,IsExtendsTrueLike:()=>Ro,IsExtendsUnion:()=>Od,Match:()=>wr});var Oe={};Ze(Oe,{Any:()=>Ba,Array:()=>H,BigInt:()=>Fu,Boolean:()=>D,Call:()=>sw,Capitalize:()=>lw,Codec:()=>ym,Conditional:()=>Ew,Constructor:()=>Ns,ConstructorParameters:()=>Sw,Cyclic:()=>Fs,Decode:()=>Qy,DecodeBuilder:()=>gm,Dependent:()=>la,Encode:()=>Xy,EncodeBuilder:()=>hm,Enum:()=>Ny,Evaluate:()=>qn,Exclude:()=>Tw,Extends:()=>Nn,ExtendsResult:()=>Gt,Extract:()=>kw,Function:()=>qs,Generic:()=>Ai,Identifier:()=>ju,Immutable:()=>Yy,Index:()=>Cw,Infer:()=>Du,InstanceType:()=>tT,Instantiate:()=>Ho,Integer:()=>S,Interface:()=>jS,Intersect:()=>jn,IsAny:()=>Fr,IsArray:()=>Rt,IsBigInt:()=>$o,IsBoolean:()=>xo,IsCall:()=>eu,IsCodec:()=>Qn,IsConstructor:()=>Yr,IsCyclic:()=>cr,IsDependent:()=>Hr,IsEnum:()=>rn,IsEnumValue:()=>Ly,IsFunction:()=>Zr,IsGeneric:()=>Ua,IsIdentifier:()=>rx,IsImmutable:()=>fa,IsInfer:()=>tn,IsInteger:()=>In,IsIntersect:()=>Ve,IsKind:()=>Re,IsLiteral:()=>It,IsNever:()=>Po,IsNull:()=>Us,IsNumber:()=>Lr,IsObject:()=>Je,IsOptional:()=>an,IsParameter:()=>ix,IsReadonly:()=>ga,IsRecord:()=>or,IsRef:()=>Zt,IsRefine:()=>xm,IsRest:()=>_i,IsSchema:()=>Dr,IsString:()=>nn,IsSymbol:()=>Bs,IsTemplateLiteral:()=>lr,IsThis:()=>Mm,IsTuple:()=>ht,IsUndefined:()=>gs,IsUnion:()=>xe,IsUnknown:()=>en,IsUnsafe:()=>fm,IsVoid:()=>Co,KeyOf:()=>nT,Literal:()=>i,Lowercase:()=>dw,Mapped:()=>pT,Module:()=>ZT,Never:()=>ir,NonNullable:()=>hT,Null:()=>Un,Number:()=>ne,Object:()=>l,Omit:()=>yT,Optional:()=>n,Parameter:()=>ya,Parameters:()=>ET,Partial:()=>ST,Pick:()=>$T,Readonly:()=>Zy,ReadonlyObject:()=>pf,ReadonlyType:()=>MT,Record:()=>Qe,RecordKey:()=>Oi,RecordPattern:()=>Sn,RecordValue:()=>hr,Ref:()=>sn,Refine:()=>ex,Required:()=>zT,Rest:()=>Ia,ReturnType:()=>JT,Script:()=>nR,String:()=>s,Symbol:()=>Ha,TemplateLiteral:()=>aS,This:()=>vm,Tuple:()=>zr,Uncapitalize:()=>fw,Undefined:()=>Va,Union:()=>y,Unknown:()=>Q,Unsafe:()=>vr,Uppercase:()=>hw,Void:()=>Om,With:()=>yp});var fu={};Ze(fu,{Clear:()=>Rk,Entries:()=>AF,Get:()=>CF,Has:()=>$F,IsDate:()=>pu,IsDateTime:()=>wp,IsDuration:()=>Tp,IsEmail:()=>Rp,IsHostname:()=>Op,IsIPv4:()=>Np,IsIPv6:()=>qp,IsIdnEmail:()=>_p,IsIdnHostname:()=>Lp,IsIri:()=>Fp,IsIriReference:()=>Dp,IsJsonPointer:()=>Up,IsJsonPointerUriFragment:()=>jp,IsRegex:()=>Bp,IsRelativeJsonPointer:()=>Gp,IsTime:()=>lu,IsUri:()=>Wp,IsUriReference:()=>Kp,IsUriTemplate:()=>Hp,IsUrl:()=>zp,IsUuid:()=>Vp,Reset:()=>Ak,Set:()=>PF,Test:()=>kk});var Ke=10,Sv=15000000;function ct(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&lo.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=Sv}function Hl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as Ag,existsSync as Pg,fchmodSync as wv,fsyncSync as $g,mkdirSync as Cg,openSync as vg,readFileSync as Mg,renameSync as Og,writeFileSync as _g}from"fs";import{dirname as Wl,join as Lg}from"path";class $i{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=Lg(e,"auth.json"),this.deviceIdPath=Lg(e,"device-id")}load(){if(!Pg(this.path))return;let e;try{e=JSON.parse(Mg(this.path,"utf8"))}catch{this.quarantine();return}let o=zl(e);if(o?.version!==1){this.quarantine();return}let a=zl(o.providers);if(!a){this.quarantine();return}for(let[u,p]of Object.entries(a)){if(!Tv(p))continue;this.providers[u]=p}}deviceId(){if(Pg(this.deviceIdPath)){let o=Mg(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return Cg(Wl(this.deviceIdPath),{recursive:!0}),_g(this.deviceIdPath,`${e}
|
|
7
|
-
`),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[vt]??=e,delete o.openai;try{this.persist(o)}catch(a){throw Error("\u8F6C\u79FB ChatGPT \u8BA2\u9605\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u65B0\u542F\u52A8",{cause:a})}this.providers=o,this.dirty=!1}async read(e,o){return o?.signal?.throwIfAborted(),this.flush(),this.providers[e]?structuredClone(this.providers[e]):void 0}async list(e){return e?.signal?.throwIfAborted(),this.flush(),Object.entries(this.providers).map(([o,a])=>({providerId:o,type:a.type}))}modify(e,o,a){return this.enqueue(e,()=>this.applyModify(e,o),a)}delete(e,o){return this.enqueue(e,()=>{if(!(e in this.providers)){this.flush();return}let a={...this.providers};delete a[e],this.persist(a),this.providers=a,this.dirty=!1},o)}async close(){this.closed=!0;try{while(this.chains.size)await Promise.all(this.chains.values());this.flush()}catch(e){throw this.closed=!1,e}}enqueue(e,o,a){if(this.closed)return Promise.reject(Error("\u51ED\u636E\u5B58\u50A8\u6B63\u5728\u5173\u95ED"));let u=a?.signal;if(u?.aborted)return Promise.reject(u.reason);let p=this.chains.get(e)??Promise.resolve(),f,h=p.then(()=>{if(u?.throwIfAborted(),f)u?.removeEventListener("abort",f);return o()}),g=h.then(()=>{return},()=>{return});if(this.chains.set(e,g),g.then(()=>{if(this.chains.get(e)===g)this.chains.delete(e)}),!u)return h;return new Promise((x,I)=>{let E=()=>I(u.reason);if(f=E,u.addEventListener("abort",E,{once:!0}),h.then((k)=>{u.removeEventListener("abort",E),x(k)},(k)=>{u.removeEventListener("abort",E),I(k)}),u.aborted)E()})}async applyModify(e,o){this.flush();let a=this.providers[e]?structuredClone(this.providers[e]):void 0,u=await o(a);if(u===void 0)return a?structuredClone(a):void 0;return this.providers[e]=structuredClone(u),this.dirty=!0,this.flush(),structuredClone(u)}flush(){if(!this.dirty)return;this.persist(this.providers),this.dirty=!1}persist(e){Cg(Wl(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,a=vg(o,"w",384);try{wv(a,384),_g(a,`${JSON.stringify({version:1,providers:e},null,2)}
|
|
8
|
-
`),$g(a)}finally{Ag(a)}if(Og(o,this.path),process.platform==="win32")return;let u=vg(Wl(this.path),"r");try{$g(u)}catch(p){if(!(p instanceof Error&&("code"in p)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(p.code))))throw p}finally{Ag(u)}}quarantine(){try{Og(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function zl(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function Tv(e){let o=zl(e);if(!o)return!1;if(o.type==="api_key")return o.key===void 0||typeof o.key==="string";if(o.type!=="oauth")return!1;return typeof o.refresh==="string"&&typeof o.access==="string"&&typeof o.expires==="number"}var jv=qg(),Ql=Hg();import{AsyncLocalStorage as Uv}from"async_hooks";var N=new Uv;var Bv=3,Wg=160,Gv=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),Kv=new Set(["if","then","else","elif","while","until","do","coproc","select","!","{","}"]),Jg=/^[A-Za-z_][A-Za-z0-9_]*=/,Hv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),Wv=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),zv=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,Vv=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),Jv=new Set(["command","builtin","nohup","time","setsid"]),Qv=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir"]],["nice",["-n","--adjustment"]],["exec",["-a"]],["timeout",["-s","-k","--signal","--kill-after"]],["stdbuf",["-i","-o","-e","--input","--output","--error"]],["watch",["-n","--interval"]],["xargs",["-I","-n","-P","-L","-s","-d","-E","-a","--arg-file","--delimiter","--max-args","--max-procs"]]]),Xv=new Map([["timeout",1]]),Yv=/^-(workingdirectory|verb|windowstyle|redirectstandardoutput|redirectstandarderror|redirectstandardinput|credential)$/i;function La(e){return{out:e.out,depth:e.depth+1}}function zg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.(exe|cmd|bat|ps1)$/,"")}function om(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 x=h+1;while(x<p){let I=e.charAt(x);if(I==="\\"){x+=2;continue}if(I===g)break;x++}h=x+1;continue}if(g===a)f++;else if(g===u){if(f--,f===0)return h+1}h++}return p}function Zv(e){let o={text:"",subs:[],heredocs:[]},a=[],u=[],p=e.length,f=0,h=0,g=null,x=(I)=>{if(e.charAt(I)==="`"){let P=I+1;while(P<p){let C=e.charAt(P);if(C==="\\"){P+=2;continue}if(C==="`")break;P++}return o.subs.push(e.slice(I+1,P)),P<p?P+1:p}if(e.charAt(I+1)==="("){let P=om(e,I+1,"(",")");if(e.charAt(I+2)==="(")return a.push(e.slice(I,P)),P;return o.subs.push(e.slice(I+2,P-1)),P}let k=om(e,I+1,"{","}"),A=e.slice(I+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=om(A,P+1,"(",")");o.subs.push(A.slice(P+2,M-1)),P=M-1}}return k};while(f<p){let I=e.charAt(f);if(g==="'"){if(I==="'")g=null;a.push(I),f++;continue}if(g==='"'){if(I==="\\"){if(!'$`"\\\n'.includes(e.charAt(f+1)))a.push("\\");a.push(I,e.charAt(f+1)),f+=2;continue}if(I==='"'){g=null,a.push(I),f++;continue}if(I==="`"||I==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=x(f);continue}a.push(I),f++;continue}if(I==="'"||I==='"'){g=I,a.push(I),f++;continue}if(I==="\\"){if(e.charAt(f+1)===`
|
|
9
|
-
`){f+=2;continue}if(e.charAt(f+1)==="\r"&&e.charAt(f+2)===`
|
|
10
|
-
`){f+=3;continue}a.push(I,e.charAt(f+1)),f+=2;continue}if(I==="`"||I==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=x(f);continue}if((I==="<"||I===">")&&e.charAt(f+1)==="("){let E=om(e,f+1,"(",")");o.subs.push(e.slice(f+2,E-1)),a.push("_"),f=E;continue}if(I==="#"){let E=a.at(-1);if(E===void 0||`
|
|
11
|
-
;&|()`.includes(E)){while(f<p&&e.charAt(f)!==`
|
|
12
|
-
`)f++;continue}a.push("\\#"),f++;continue}if(I==="<"&&e.charAt(f+1)==="<"&&e.charAt(f+2)!=="<"){let E=f+2;if(e.charAt(E)==="-")E++;a.push(e.slice(f,E));let k=E;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
|
|
13
|
-
;&|()<>`.includes(P))break;A+=P,k++}if(A)u.push(A);f=E;continue}if(I===`
|
|
14
|
-
`){if(u.length>0){let E=zv.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(`
|
|
15
|
-
`,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(E&&P>A)o.heredocs.push(e.slice(A,P))}}else f++;a.push(";",`
|
|
16
|
-
`),h=a.length;continue}a.push(I),f++}return o.text=a.join(""),o}function na(e,o,a){if(o.depth>Bv)return;let u=e;if(a!=="bash")u=u.replaceAll("\\","\\\\");if(a==="powershell")u=u.replace(/`([\s\S])/g,"\\$1");if(a==="cmd")u=u.replace(/\^([\s\S])/g,"\\$1");let p=Zv(u),f;try{f=Ql(p.text)}catch{for(let h of p.text.split(/&&|\|\||[;|&\n]/))sm(h.split(/\s+/).filter(Boolean).map((g)=>g.replace(/["']/g,"")),o)}if(f){let h=[];for(let g of f){if(typeof g==="string"){h.push({kind:"word",text:g});continue}if("pattern"in g){h.push({kind:"word",text:g.pattern});continue}if("op"in g)h.push({kind:"op",text:g.op})}eM(h,o)}for(let h of p.subs)na(h,La(o),"bash");for(let h of p.heredocs)na(h,La(o),"bash")}function eM(e,o){let a=[],u=()=>{if(a.length>0)sm(a,o);a=[]};for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;if(f.kind==="op"){if(Hv.has(f.text)){u();continue}if(Wv.has(f.text)){if(/^\d+$/.test(a.at(-1)??""))a.pop();p++}continue}a.push(f.text)}u()}function sm(e,o){let a=0;for(;;){let h=e[a];if(h===void 0)return;if(Kv.has(h)||Jg.test(h)){a++;continue}if(h==="function"){a+=2;continue}let g=nM(zg(h),e,a);if(g===a)break;a=g}let u=e[a];if(u===void 0)return;let p=zg(u),f=e.slice(a+1);if(p==="git"){sM(u,f,o);return}if(Gv.has(p)){rM(f,o);return}if(p==="eval"){na(f.join(" "),La(o),"bash");return}if(p==="iex"||p==="invoke-expression"){na(f.filter((h)=>!/^-command$/i.test(h)).join(" "),La(o),"powershell");return}if(p==="find"){for(let h=0;h<f.length;h++){if(!/^-(exec|execdir|ok|okdir)$/.test(f[h]??""))continue;let g=f.findIndex((x,I)=>I>h&&(x===";"||x==="+"));sm(f.slice(h+1,g<0?void 0:g),o),h=g<0?f.length:g}return}if(p==="start-process"||p==="saps"){tM(f,o);return}if(p==="powershell"||p==="pwsh")Vg(f,/^-(command|c)$/i,o,"powershell");if(p==="cmd")Vg(f,/^\/[ck]$/i,o,"cmd")}function Vg(e,o,a,u){for(let p=0;p<e.length;p++)if(o.test(e[p]??"")){let f=e.slice(p+1).join(" ");if(f.trim())na(f,La(a),u);return}}function tM(e,o){let a=[],u,p=[];for(let f=0;f<e.length;f++){let h=e[f]??"";if(/^-(filepath|path)$/i.test(h)){u=e[++f];continue}if(/^-(argumentlist|args)$/i.test(h)){p.push(e[++f]??"");continue}if(Yv.test(h)){f++;continue}if(h.startsWith("-"))continue;a.push(h)}if(u??=a.shift(),p.length===0)p.push(...a);if(!u)return;sm([u,...p.flatMap((f)=>f.split(/[\s,]+/)).filter(Boolean)],o)}function rM(e,o){for(let a=0;a<e.length;a++){let u=e[a]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){a++;continue}if(u.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(u);if(p){let f=p[1]||e[a+1];if(f)na(f,La(o),"bash");return}if(u.startsWith("-")||u==="")continue;return}}function nM(e,o,a){if(Jv.has(e)){let f=a+1;while(o[f]?.startsWith("-"))f++;return f}let u=Qv.get(e);if(!u)return a;let p=a+1;for(;;){let f=o[p];if(f===void 0)return p;let h=e==="env"?/^(?:-S|--split-string=?)([\s\S]*)$/.exec(f):null;if(h){let g=h[1]||o[p+1]||"";o.splice(p,h[1]?1:2,...g.split(/\s+/).filter(Boolean));continue}if(u.includes(f)){p+=2;continue}if(Jg.test(f)||f.startsWith("-")){p++;continue}return p+(Xv.get(e)??0)}}function bo(e,o){return e.some((a)=>a.length>1&&a.startsWith("-")&&!a.startsWith("--")&&a.slice(1).includes(o))}function Mn(e,o){return e.some((a)=>a===`--${o}`||a.startsWith(`--${o}=`))}var oM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(bo(e,"f")||bo(e,"i")||Mn(e,"force")||Mn(e,"interactive"))&&!(bo(e,"n")||Mn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>bo(e,"f")||Mn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>bo(e,"f")||Mn(e,"force")||Mn(e,"discard-changes")||bo(e,"C")||Mn(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>bo(e,"f")||bo(e,"d")||Mn(e,"force")||Mn(e,"force-with-lease")||Mn(e,"force-if-includes")||Mn(e,"delete")||Mn(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>Mn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>bo(e,"D")||bo(e,"M")||bo(e,"C")||bo(e,"f")||Mn(e,"force")?"branch -D/-M/-f \u5F3A\u5236\u5220\u9664\u3001\u8986\u76D6\u6216\u79FB\u52A8\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>Mn(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,prune:(e)=>bo(e,"n")||Mn(e,"dry-run")?void 0:"prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84","filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>bo(e,"f")||Mn(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(bo(e,"f")||Mn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function sM(e,o,a){let u=0;for(;;){let x=o[u];if(x===void 0)break;if(Vv.has(x)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(x)||/^-[Cc].+/.test(x)||x.startsWith("-")){u++;continue}break}let p=o[u]?.toLowerCase();if(!p)return;let f=oM[p];if(!f)return;let h=f(o.slice(u+1));if(!h)return;let g=[e,...o.slice(u)].join(" ");a.out.push({rule:p,fragment:g.length>Wg?`${g.slice(0,Wg)}\u2026`:g,reason:h})}function Ko(e,o="bash"){let a={out:[],depth:0};return na(e,a,o),a.out}function Qg(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),a=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${a}`}var Xl=new Map;function iM(e,o,a,u,p){let f=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((h)=>{let g=(I)=>{if(!Xl.delete(f))return;p?.removeEventListener("abort",x),h(I)},x=()=>{Xg(e,f),g("aborted")};if(Xl.set(f,{session:e,finish:g}),e.appendExtension({namespace:bn,kind:"requested",schemaVersion:1,payload:{id:f,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:I,reason:E})=>({fragment:I,reason:E})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${a}`}}),p?.aborted)x();else p?.addEventListener("abort",x,{once:!0})})}function Xg(e,o){try{e.appendExtension({namespace:bn,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Jn(e,o,a){let u=Xl.get(o);if(!u||u.session!==e){if(!aM(e,o))return"unknown";return Xg(e,o),"expired"}return e.appendExtension({namespace:bn,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:a,resolvedAt:Date.now()},display:{text:a?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(a?"approved":"denied"),"answered"}function aM(e,o){let a=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==bn)continue;let p=u.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==o)continue;if(u.kind==="requested")a=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return a}function Qo(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${Qg(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function qe(e,o,a="bash"){let u=Ko(e,a);if(!u.at(0))return;let f=Qg(u),h=N.getStore();if(h?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${f}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${Qo(u)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let g=await iM(h,e,f,u,o);if(g==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${f} \u672A\u6267\u884C\uFF1A${g==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}var Ms={assign:0,create:0,clone:0,discard:0,update:0};function oa(e,o,a){return e>=o&&e<=a}function ey(e){return e===8205}function uM(e){return oa(e,55296,56319)}function Yg(e){return oa(e,127462,127487)}function ty(e){return oa(e,65024,65039)}function ry(e){return oa(e,768,879)||oa(e,6832,6911)||oa(e,7616,7679)||oa(e,65056,65071)}function im(e){return e>65535?2:1}function Zg(e,o){while(o<e.length){let a=e.codePointAt(o);if(ry(a)||ty(a))o+=im(a);else break}return o}function Yl(e,o){let a=e.codePointAt(o),u=o+im(a);u=Zg(e,u);while(u<e.length-1&&ey(e.codePointAt(u))){let p=e.codePointAt(u+1);u+=1+im(p),u=Zg(e,u)}if(Yg(a)&&u<e.length&&Yg(e.codePointAt(u)))u+=im(e.codePointAt(u));return u}function ny(e){return e>=768&&(uM(e)||ry(e)||ty(e)||ey(e))}function oy(e){let o=0,a=0;while(a<e.length)a=Yl(e,a),o++;return o}function cM(e,o){let a=0,u=0;while(u<e.length)if(u=Yl(e,u),++a>=o)return!0;return!1}function mM(e,o){let a=0,u=0;while(u<e.length)if(u=Yl(e,u),++a>o)return!1;return!0}function sy(e,o){if(o===0)return!0;if(e.length<o)return!1;let a=0;while(!0){if(ny(e.charCodeAt(a)))return cM(e,o);if(++a>=o)return!0}}function iy(e,o){if(e.length<=o)return!0;let a=0;while(!0){if(ny(e.charCodeAt(a)))return mM(e,o);if(++a>o)return!1}}function He(e){return Array.isArray(e)}function Kr(e){return v(typeof e,"bigint")}function cn(e){return v(typeof e,"boolean")}function Zl(e){if(nr(e)||!Os(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 Os(e){return v(typeof e,"function")}function am(e){return Number.isInteger(e)}function Oo(e){return v(e,null)}function Bt(e){return Number.isFinite(e)}function rs(e){return lt(e)&&!He(e)}function lt(e){return v(typeof e,"object")&&!Oo(e)}function yt(e){return v(typeof e,"string")}function ed(e){return v(typeof e,"symbol")}function nr(e){return v(e,void 0)}function v(e,o){return e===o}function sa(e,o){return e>o}function Mu(e,o){return e<o}function _s(e,o){return e<=o}function Na(e,o){return e>=o}function ay(e,o){if(Kr(e)||Kr(o))return BigInt(e)%BigInt(o)===0n;let a=0.0000000001;if(!Bt(e))return!0;if(am(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<a}function uy(e){if(!lt(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(Oo(o))return!1;return v(typeof o.constructor,"function")&&!(v(o.constructor,globalThis.Object)||v(o.constructor.name,"Object"))}function ia(e){return Kr(e)||cn(e)||Oo(e)||Bt(e)||yt(e)||nr(e)}function lM(e){return oy(e)}function cy(e,o){return iy(e,o)}function my(e,o){return sy(e,o)}function on(e,o,a){return e.every((u,p)=>p<o||a(u,p))}function Dn(e,o,a){let u=!0;return e.forEach((p,f)=>{if(f>=o&&!a(p,f))u=!1}),u}function qa(e,o){return e.some((a,u)=>o(a,u))}function py(e,o){let a=!1;return e.forEach((u,p)=>{if(o(u,p))a=!0}),a}function td(e,o){return e.reduce((a,u,p)=>o(u,p)?++a:a,0)}function bt(e,o,a){return v(e.length,0)?a():o(e[0],e.slice(1))}function Ou(e){return v(e,"__proto__")||v(e,"constructor")||v(e,"prototype")}function se(e,o){return Ou(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function rd(e){return be(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function pn(e){return Object.entries(e)}function be(e){return Object.getOwnPropertyNames(e)}function ly(e){return Object.getOwnPropertySymbols(e)}function nd(e){return Object.values(e)}function dM(e,o){if(!lt(o))return!1;let a=be(e);return v(a.length,be(o).length)&&a.every((u)=>Da(e[u],o[u]))}function fM(e,o){return He(o)&&v(e.length,o.length)&&e.every((a,u)=>Da(e[u],o[u]))}function Da(e,o){return He(e)?fM(e,o):lt(e)?dM(e,o):v(e,o)}var hM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function gM(e){return hM.test(e)}function On(e,o){return`(${e} && ${o})`}function br(e,o){return`(${e} || ${o})`}function zn(e){return`!(${e})`}function um(e){return`Array.isArray(${e})`}function dy(e){return`typeof ${e} === "bigint"`}function yM(e){return`typeof ${e} === "boolean"`}function xM(e){return`Number.isInteger(${e})`}function IM(e){return`${e} === null`}function fy(e){return`Number.isFinite(${e})`}function hy(e){return On(gy(e),zn(um(e)))}function gy(e){return`typeof ${e} === "object" && ${e} !== null`}function yy(e){return`typeof ${e} === "string"`}function EM(e){return`typeof ${e} === "symbol"`}function od(e){return`${e} === undefined`}function bM(e){return`typeof ${e} === "function"`}function SM(e){return`Guard.IsConstructor(${e})`}function Ao(e,o){return`${e} === ${o}`}function xy(e,o){return`${e} > ${o}`}function sd(e,o){return`${e} < ${o}`}function aa(e,o){return`${e} <= ${o}`}function _u(e,o){return`${e} >= ${o}`}function wM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function TM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function Ls(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 RM(e,o,a){return`${e}.some((${o[0]}, ${o[1]}) => ${a})`}function kM(e,o,a){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${a}) result = true }); return result })(${e})`}function cm(e,o,a){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${a}) ? ++result : result, 0)`}function Iy(e){return`Object.entries(${e})`}function ua(e){return`Object.getOwnPropertyNames(${e})`}function ca(e,o){return v(o,'"__proto__"')||v(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function Ey(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function AM(e){return`[${e.join(", ")}]`}function Ti(e,o){return`((${e.join(", ")}) => ${o})`}function Sr(e,o){return`${e}(${o.join(", ")})`}function id(e,o){return`new ${e}(${o.join(", ")})`}function St(e,o){return`${e}${gM(o)?`.${o}`:`[${je(o)}]`}`}function je(e){if(!ia(e))throw Error("Unsupported Constant");return yt(e)?JSON.stringify(e):`${e}`}function PM(e,o,a){return`(${e} ? ${o} : ${a})`}function mm(e){return`{ ${e.join("; ")}; }`}function Zs(e,o){return`const ${e} = ${o}`}function by(e,o){return`if(${e}) { ${o} }`}function pm(e){return`return ${e}`}function Fn(e){return v(e.length,0)?"true":e.reduce((o,a)=>On(o,a))}function ad(e){return v(e.length,0)?"false":e.reduce((o,a)=>br(o,a))}function $M(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function CM(e){return e instanceof Boolean}function vM(e){return e instanceof Number}function MM(e){return e instanceof String}function Sy(e){return globalThis.ArrayBuffer.isView(e)}function wy(e){return e instanceof globalThis.RegExp}function OM(e){return e instanceof globalThis.Date}function _M(e){return e instanceof globalThis.Set}function LM(e){return e instanceof globalThis.Map}var qM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function ns(){return qM}function Ri(e){return ns().immutableTypes?Object.freeze(e):e}function ln(e,o){return Ms.assign+=1,Ri({...e,...o})}function DM(e){return e}function FM(e){return se(e,"~kind")||se(e,"~unsafe")}function jM(e){let o={};for(let a of be(e)){if(Ou(a))continue;let u=Object.getOwnPropertyDescriptor(e,a);if(u.value=ma(u.value),v(u.enumerable,!0))o[a]=u.value;else Object.defineProperty(o,a,u)}return o}function UM(e){let o={};for(let a of be(e)){if(Ou(a))continue;o[a]=ma(e[a])}for(let a of ly(e))o[a]=ma(e[a]);return o}function BM(e){return uy(e)?DM(e):FM(e)?jM(e):UM(e)}function GM(e){return e.map((o)=>ma(o))}function KM(e){return e.slice()}function HM(e){return new RegExp(e.source,e.flags)}function WM(e){return new Map(ma([...e.entries()]))}function zM(e){return new Set(ma([...e.values()]))}function ma(e){return Sy(e)?KM(e):wy(e)?HM(e):LM(e)?WM(e):_M(e)?zM(e):He(e)?GM(e):lt(e)?BM(e):e}function Fa(e){return Ms.clone+=1,ma(e)}function VM(e,o){for(let a of Object.keys(o))Object.defineProperty(e,a,{configurable:!0,writable:!0,enumerable:!1,value:o[a]});return e}function Ty(e,o){return{...e,...o}}function qt(e,o,a={}){Ms.create+=1;let u=Ty(o,a),p=ns().enumerableKind?Ty(u,e):VM(u,e);return Ri(p)}function ss(e,o){Ms.discard+=1;let a={};for(let u of be(e)){if(o.includes(u))continue;let p=Object.getOwnPropertyDescriptor(e,u);p.value=Fa(p.value),Object.defineProperty(a,u,p)}return Ri(a)}function Tt(e,o,a){Ms.update+=1;let u=ns(),p=Fa(e);for(let f of Object.keys(o))Object.defineProperty(p,f,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[f]});for(let f of Object.keys(a))Object.defineProperty(p,f,{configurable:!0,enumerable:!0,writable:!0,value:a[f]});return Ri(p)}function Re(e,o){return lt(e)&&se(e,"~kind")&&v(e["~kind"],o)}function Dr(e){return lt(e)}function Me(e,o,a){return qt({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:a},{})}function ki(e){return Re(e,"Deferred")}function JM(e){return Tt(e,{"~readonly":!0},{})}function Nu(e,o){return Tt(JM(e),{},o)}function Ry(e,o,a,u){let p=pe(e,o,a);return Nu(p,u)}function QM(e){return Tt(e,{"~optional":!0},{})}function qu(e,o){return Tt(QM(e),{},o)}function ky(e,o,a,u){let p=pe(e,o,a);return qu(p,u)}function H(e,o){return qt({"~kind":"Array"},{type:"array",items:e},o)}function Rt(e){return Re(e,"Array")}function ja(e){return ss(e,["~kind","type","items"])}function Ns(e,o,a={}){return qt({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},a)}function Yr(e){return Re(e,"Constructor")}function Ay(e){return ss(e,["~kind","type","parameters","instanceType"])}function qs(e,o,a={}){return qt({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},a)}function Zr(e){return Re(e,"Function")}function Py(e){return ss(e,["~kind","type","parameters","returnType"])}function sn(e,o){return qt({["~kind"]:"Ref"},{$ref:e},o)}function Zt(e){return Re(e,"Ref")}function Ai(e,o){return qt({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Ua(e){return Re(e,"Generic")}function Ba(e){return qt({["~kind"]:"Any"},{},e)}function Fr(e){return Re(e,"Any")}var $y="(?!)";function ir(e){return qt({"~kind":"Never"},{not:{}},e)}function Po(e){return Re(e,"Never")}function Ds(e,o={}){return Me("AddOptional",[e],o)}function pa(e,o={}){return qu(e,o)}function n(e){return pa(e)}function an(e){return Dr(e)&&se(e,"~optional")}function Cy(e){return be(e).filter((o)=>!an(e[o]))}function lm(e){return be(e)}function dm(e){return nd(e)}function l(e,o={}){let a=Cy(e),u=a.length>0?{required:a}:{};return qt({"~kind":"Object"},{type:"object",...u,properties:e},o)}function Je(e){return Re(e,"Object")}function vy(e){return ss(e,["~kind","type","properties","required"])}function Q(e){return qt({["~kind"]:"Unknown"},{},e)}function en(e){return Re(e,"Unknown")}function Fs(e,o,a){let u=be(e).reduce((p,f)=>({...p,[f]:Tt(e[f],{},{$id:f})}),{});return qt({["~kind"]:"Cyclic"},{$defs:u,$ref:o},a)}function cr(e){return Re(e,"Cyclic")}function vr(e){return Tt(e,{["~unsafe"]:null},{})}function fm(e){return rs(e)&&se(e,"~unsafe")&&Oo(e["~unsafe"])}function Ln(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Du(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p,p],1:(u)=>[u,Q(),Q()]});return qt({["~kind"]:"Infer"},{type:"infer",name:o,extends:a},{})}function tn(e){return Re(e,"Infer")}function la(e,o,a,u={}){return qt({"~kind":"Dependent"},{if:e,then:o,else:a},u)}function Hr(e){return Re(e,"Dependent")}function My(e){return ss(e,["~kind","if","then","else"])}function Oy(e){return rs(e)}function _y(e){return be(e).filter((a)=>isNaN(a)).reduce((a,u)=>[...a,e[u]],[])}function Ly(e){return yt(e)||Bt(e)}function Ny(e,o){let a=Oy(e)?_y(e):e;return qt({"~kind":"Enum"},{enum:a},o)}function rn(e){return Re(e,"Enum")}function jn(e,o={}){return qt({"~kind":"Intersect"},{allOf:e},o)}function Ve(e){return Re(e,"Intersect")}function qy(e){return ss(e,["~kind","allOf"])}var ud=void 0;function XM(){try{return Fy("null")(),!0}catch{return!1}}function Dy(){if(nr(ud))ud=XM();return ud&&ns().useAcceleration}function Fy(...e){return new globalThis.Function(...e)}function Wr(){throw Error("Unreachable")}function YM(e){let o=new Set,a=e;while(a&&a!==Object.prototype){for(let u of Reflect.ownKeys(a))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);a=Object.getPrototypeOf(a)}return[...o]}function ZM(e){return typeof e==="number"}var Vn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Vn||(Vn={}));var Ga=BigInt("14695981039346656037"),[eO,tO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],rO=Array.from({length:256}).map((e,o)=>BigInt(o)),Gy=new Float64Array(1),Ky=new DataView(Gy.buffer),Hy=new Uint8Array(Gy.buffer);function Pn(e){Ga=Ga^rO[e],Ga=Ga*eO%tO}function nO(e){Pn(Vn.Array);for(let o of e)Pi(o)}function oO(e){Pn(Vn.BigInt),Ky.setBigInt64(0,e);for(let o of Hy)Pn(o)}function Uy(e){Pn(Vn.Boolean),Pn(e?1:0)}function sO(e){Pn(Vn.Constructor),Pi(e.toString())}function iO(e){Pn(Vn.Date),Pi(e.getTime())}function aO(e){Pn(Vn.Function),Pi(e.toString())}function uO(e){Pn(Vn.Null)}function By(e){Pn(Vn.Number),Ky.setFloat64(0,e,!0);for(let o of Hy)Pn(o)}function cO(e){Pn(Vn.Object);for(let o of YM(e).sort())Pi(o),Pi(e[o])}function mO(e){Pn(Vn.RegExp),cd(e.toString())}var pO=new TextEncoder;function cd(e){Pn(Vn.String);for(let o of pO.encode(e))Pn(o)}function lO(e){Pn(Vn.Symbol),Pi(e.toString())}function dO(e){Pn(Vn.TypeArray);let o=new Uint8Array(e.buffer);for(let a=0;a<o.length;a++)Pn(o[a])}function fO(e){return Pn(Vn.Undefined)}function Pi(e){return Sy(e)?dO(e):OM(e)?iO(e):wy(e)?mO(e):CM(e)?Uy(e.valueOf()):MM(e)?cd(e.valueOf()):vM(e)?By(e.valueOf()):ZM(e)?By(e):He(e)?nO(e):cn(e)?Uy(e):Kr(e)?oO(e):Zl(e)?sO(e):Oo(e)?uO(e):lt(e)?cO(e):yt(e)?cd(e):ed(e)?lO(e):nr(e)?fO(e):Os(e)?aO(e):Wr()}function Wy(e){return Ga=BigInt("14695981039346656037"),Pi(e),Ga}function md(e){return Wy(e).toString(16).padStart(16,"0")}function zy(e){switch(e.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"dependentRequired":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"exclusiveMinimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"format":return`must match format "${e.params.format}"`;case"if":return`must match "${e.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${e.params.limit} items`;case"maxLength":return`must not have more than ${e.params.limit} characters`;case"maxProperties":return`must not have more than ${e.params.limit} properties`;case"maximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"minItems":return`must not have fewer than ${e.params.limit} items`;case"minLength":return`must not have fewer than ${e.params.limit} characters`;case"minProperties":return`must not have fewer than ${e.params.limit} properties`;case"minimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"multipleOf":return`must be multiple of ${e.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${e.params.pattern}"`;case"propertyNames":return`property names ${e.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${e.params.requiredProperties.join(", ")}`;case"type":return typeof e.params.type==="string"?`must be ${e.params.type}`:`must be either ${e.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return e.params.message;default:return"an unknown validation error occurred"}}var hO=zy;function Vy(){return hO}class hm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,a=Qn(o)?(f)=>this.decode(o["~codec"].decode(f)):this.decode,u=Qn(o)?(f)=>o["~codec"].encode(e(f)):e,p={decode:a,encode:u};return Tt(this.type,{"~codec":p},{})}}class gm{constructor(e){this.type=e}Decode(e){return new hm(this.type,e)}}function ym(e){return new gm(e)}function Qy(e,o){return ym(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function Xy(e,o){return ym(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Qn(e){return Dr(e)&&se(e,"~codec")&<(e["~codec"])&&se(e["~codec"],"encode")&&se(e["~codec"],"decode")}function Yy(e){return Ka(e)}function fa(e){return Dr(e)&&se(e,"~immutable")}function js(e,o={}){return Me("AddReadonly",[e],o)}function ha(e,o={}){return Nu(e,o)}function Zy(e){return ha(e)}function ga(e){return Dr(e)&&se(e,"~readonly")}function yO(e,o){let a=xm(e)?[...e["~refine"],o]:[o];return Tt(e,{"~refine":a},{})}function ex(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[p,f,()=>"Refine Error"]});return yO(o,{check:a,error:u})}function xO(e){return rs(e)&&se(e,"check")&&se(e,"error")&&Os(e.check)&&Os(e.error)}function xm(e){return Dr(e)&&se(e,"~refine")&&He(e["~refine"])&&on(e["~refine"],0,(o)=>xO(o))}var tx="-?(?:0|[1-9][0-9]*)n";function Fu(e){return qt({"~kind":"BigInt"},{type:"bigint"},e)}function $o(e){return Re(e,"BigInt")}function D(e){return qt({"~kind":"Boolean"},{type:"boolean"},e)}function xo(e){return Re(e,"Boolean")}function ju(e){return qt({"~kind":"Identifier"},{name:e})}function rx(e){return Re(e,"Identifier")}var Im="-?(?:0|[1-9][0-9]*)";function S(e){return qt({"~kind":"Integer"},{type:"integer"},e)}function In(e){return Re(e,"Integer")}class nx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function IO(e){return Kr(e)?"bigint":cn(e)?"boolean":Bt(e)?"number":yt(e)?"string":(()=>{throw new nx(e)})()}function i(e,o){return qt({"~kind":"Literal"},{type:IO(e),const:e},o)}function Em(e){return Kr(e)||cn(e)||Bt(e)||yt(e)}function ox(e){return It(e)&&Kr(e.const)}function sx(e){return It(e)&&cn(e.const)}function bm(e){return It(e)&&Bt(e.const)}function Sm(e){return It(e)&&yt(e.const)}function It(e){return Re(e,"Literal")}function Un(e){return qt({"~kind":"Null"},{type:"null"},e)}function Us(e){return Re(e,"Null")}var wm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function ne(e){return qt({"~kind":"Number"},{type:"number"},e)}function Lr(e){return Re(e,"Number")}function Ha(e){return qt({"~kind":"Symbol"},{type:"symbol"},e)}function Bs(e){return Re(e,"Symbol")}function ya(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[p,f,f],1:(p)=>[p,Q(),Q()]});return qt({"~kind":"Parameter"},{name:o,extends:a,equals:u},{})}function ix(e){return Re(e,"Parameter")}var Tm=".*";function s(e){return qt({"~kind":"String"},{type:"string"},e)}function nn(e){return Re(e,"String")}function y(e,o={}){return qt({"~kind":"Union"},{anyOf:e},o)}function xe(e){return Re(e,"Union")}function ax(e){return ss(e,["~kind","anyOf"])}function Uu(e){let o=ux(e);return v(o.length,2)?o[0]:[]}function EO(e){return!0}function cx(e){return bt(e,(o,a)=>bO(o)?cx(a):!1,()=>!0)}function mx(e){return v(e.length,0)?!1:cx(e)}function bO(e){return xe(e)?mx(e.anyOf):It(e)?EO(e.const):!1}function Rm(e){return mx(e)}function km(e){return qt({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function px(e,o,a=[]){return bt(e,(u,p)=>px(p,o,[...a,`${u}${o}`]),()=>a)}function SO(e,o){return v(e.length,0)?[`${o}`]:px(e,o)}function lx(e,o,a=[]){return bt(o,(u,p)=>lx(e,p,[...a,...dx(e,u)]),()=>a)}function dx(e,o){return xe(o)?lx(e,o.anyOf):It(o)?SO(e,o.const):Wr()}function fx(e,o){return bt(o,(a,u)=>fx(dx(e,a),u),()=>e)}function wO(e){return e.map((o)=>i(o))}function TO(e){let o=fx([],e),a=wO(o);return y(a)}function RO(e){return v(e.length,0)?Wr():v(e.length,1)&&It(e[0])?e[0]:TO(e)}function pd(e){let o=Uu(e);return v(o.length,0)?s():Rm(o)?RO(o):km(e)}function Bu(e){let o=pd(e);return lr(o)?s():o}function wo(e,o){let u={[e]:o};return qt({["~kind"]:"Record"},{type:"object",patternProperties:u})}function hx(e){return wo(ps,e)}function gx(e){return l({true:e,false:e})}function zr(e,o={}){let[a,u,p]=[e,e.length,!1];return qt({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:a,minItems:u},o)}function ht(e){return Re(e,"Tuple")}function yx(e){return ss(e,["~kind","type","items","minItems","additionalItems"])}function kO(e){return ss(e,["~readonly"])}function ld(e,o){return Tt(kO(e),{},o)}function xx(e,o,a,u){let p=pe(e,o,a);return ld(p,u)}function Ix(e,o={}){return Me("RemoveReadonly",[e],o)}function Ex(e,o={}){return ld(e,o)}function AO(e){return ss(e,["~optional"])}function dd(e,o){return Tt(AO(e),{},o)}function bx(e,o,a,u){let p=pe(e,o,a);return dd(p,u)}function Sx(e,o={}){return Me("RemoveOptional",[e],o)}function Am(e,o={}){return dd(e,o)}function fd(e){return e.reduceRight((a,u,p)=>({[p]:u,...a}),{})}function wx(e){let o=fd(e.items);return l(o)}function hd(e){return Je(e)||ht(e)}function PO(e,o){return ga(e)?ga(o)?!0:!1:!1}function $O(e,o){return an(e)?an(o)?!0:!1:!1}function CO(e,o){let a=PO(e,o),u=$O(e,o),p=Nr([e,o]),f=Ex(Am(p));return a&&u?ha(pa(f)):a&&!u?ha(f):!a&&u?pa(f):f}function vO(e,o,a){return a in e?a in o?CO(e[a],o[a]):e[a]:(a in o)?o[a]:ir()}function MO(e,o){return[...new Set([...be(e),...be(o)])].reduce((p,f)=>({...p,[f]:vO(e,o,f)}),{})}function Tx(e){return Je(e)?e.properties:ht(e)?fd(e.items):{}}function Rx(e,o){let a=Tx(e),u=Tx(o),p=MO(a,u);return l(p)}function OO(e,o){let a=Wa(e,o);return v(a,Ku)?e:v(a,Hu)?o:v(a,Gu)?o:ir()}function _O(e,o){let a=hd(e),u=hd(o);return a&&u?Rx(e,o):a&&!u?e:!a&&u?o:OO(e,o)}function kx(e,o){return Po(e)?e:Fr(e)?e:en(e)?o:Po(o)?o:Fr(o)?o:en(o)?e:_O(e,o)}function LO(e,o){return xe(e)||xe(o)}function NO(e,o){let a=Go(e),u=Go(o);return LO(a,u)?Nr([a,u]):kx(a,u)}function Ax(e,o,a=[]){return bt(o,(u,p)=>Ax(e,p,[...a,NO(u,e)]),()=>v(a.length,0)?[e]:a)}function Px(e,o,a=[]){return bt(e,(u,p)=>Px(p,o,[...a,...Wu([u],o)]),()=>a)}function Wu(e,o=[]){return bt(e,(a,u)=>xe(a)?Wu(u,Px(a.anyOf,o)):Wu(u,Ax(a,o)),()=>o)}function qO(e,o){let a=Nn({},e,o);return Ro(a)?[]:[e]}function $x(e,o,a=[]){return bt(e,(u,p)=>$x(p,o,[...a,...qO(u,o)]),()=>a)}function Pm(e,o){let a=Go(e),u=xe(a)?a.anyOf:[a],p=$x(u,o);return To(p)}function fs(e,o,a){let u=Nr([e,o]),p=Pm(a,e);return To([u,p])}function Io(e,o=[]){return bt(e,(a,u)=>Io(u,[...o,i(a)]),()=>To(o))}function Nr(e){let o=Wu(e),a=gd(o);return To(a)}function Bn(e){let o=Bu(e);return Go(o)}function To(e){let o=gd(e);return Ci(o)}function Go(e){return Hr(e)?fs(e.if,e.then,e.else):rn(e)?Io(e.enum):Ve(e)?Nr(e.allOf):lr(e)?Bn(e.pattern):xe(e)?To(e.anyOf):e}function Ci(e){return v(e.length,1)?e[0]:v(e.length,0)?ir():y(e)}function Cx(e,o){let a=Io(e);return vi(a,o)}function vx(e,o){return wo(Mi,o)}function Mx(e,o){let a=Nr(e);return vi(a,o)}function Ox(e,o){return yt(e)||Bt(e)?l({[e]:o}):v(e,!1)?l({false:o}):v(e,!0)?l({true:o}):l({})}function _x(e,o){return wo(za,o)}function Lx(e,o){return se(e,"pattern")&&(yt(e.pattern)||e.pattern instanceof RegExp)?wo(e.pattern.toString(),o):wo(ps,o)}function Nx(e,o){let a=Uu(e);return Rm(a)?vi(Bn(e),o):wo(e,o)}function DO(e){return xe(e)?xa(e.anyOf):[e]}function xa(e,o=[]){return bt(e,(a,u)=>xa(u,[...o,...DO(a)]),()=>o)}function FO(e){return e.some((o)=>nn(o)||Lr(o)||In(o))}function jO(e,o){return v(FO(e),!0)?wo(ps,o):void 0}function UO(e,o){return e.reduce((a,u)=>It(u)&&(yt(u.const)||Bt(u.const))?{...a,[u.const]:o}:a,{})}function BO(e,o){let a=UO(e,o);return l(a)}function qx(e,o){let a=xa(e),u=jO(a,o);return Dr(u)?u:BO(a,o)}function vi(e,o){return Fr(e)?hx(o):xo(e)?gx(o):rn(e)?Cx(e.enum,o):In(e)?vx(e,o):Ve(e)?Mx(e.allOf,o):It(e)?Ox(e.const,o):Lr(e)?_x(e,o):xe(e)?qx(e.anyOf,o):nn(e)?Lx(e,o):lr(e)?Nx(e.pattern,o):l({})}function yd(e,o,a){return dt([e])?Tt(vi(e,o),{},a):$m(e,o,a)}function Dx(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return yd(f,h,p)}var Mi=`^${Im}$`,za=`^${wm}$`,ps=`^${Tm}$`;function $m(e,o,a={}){return Me("Record",[e,o],a)}function Qe(e,o,a={}){return yd(e,o,a)}function Fx(e,o){return wo(e,o)}function Cm(e){return v(e,ps)?s():v(e,Mi)?S():v(e,za)?ne():pd(e)}function Sn(e){return be(e.patternProperties)[0]}function Oi(e){let o=Sn(e);return Cm(o)}function hr(e){return e.patternProperties[Sn(e)]}function or(e){return Re(e,"Record")}function Ia(e){return qt({"~kind":"Rest"},{type:"rest",items:e},{})}function _i(e){return Re(e,"Rest")}function vm(e){return qt({["~kind"]:"This"},{$ref:"#"},e)}function Mm(e){return Re(e,"This")}function Va(e){return qt({"~kind":"Undefined"},{type:"undefined"},e)}function gs(e){return Re(e,"Undefined")}function Om(e){return qt({"~kind":"Void"},{type:"void"},e)}function Co(e){return Re(e,"Void")}function KO(e,o){return v(e,"Array")?H(o[0]):v(e,"Capitalize")?Lm(o[0]):v(e,"ConstructorParameters")?jm(o[0]):v(e,"Evaluate")?rb(o[0]):v(e,"Exclude")?Um(o[0],o[1]):v(e,"Extract")?Bm(o[0],o[1]):v(e,"Index")?Qu(o[0],o[1]):v(e,"InstanceType")?Gm(o[0]):v(e,"Lowercase")?Nm(o[0]):v(e,"NonNullable")?Km(o[0]):v(e,"Omit")?Hm(o[0],o[1]):v(e,"Parameters")?Wm(o[0]):v(e,"Partial")?zm(o[0]):v(e,"Pick")?Vm(o[0],o[1]):v(e,"Readonly")?Jm(o[0]):v(e,"KeyOf")?Xu(o[0]):v(e,"Record")?$m(o[0],o[1]):v(e,"Required")?Qm(o[0]):v(e,"ReturnType")?Xm(o[0]):v(e,"Uncapitalize")?qm(o[0]):v(e,"Uppercase")?Dm(o[0]):Ju(sn(e),o)}function Ea(){throw Error("Unreachable")}function Kx(e,o=[]){return bt(e,(a,u)=>Kx(u,[...o,a[1]]),()=>o)}function ti(e){return v(e.length,3)?[e[0],...Kx(e[1])]:[]}function Hx(e){return ya(e[0],e[2],e[4])}function Wx(e){return ya(e[0],e[2],e[2])}function zx(e){return ya(e[0],Q(),e[2])}function Vx(e){return ya(e,Q(),Q())}function Jx(e){return e}function Qx(e){return ti(e)}function Xx(e){return e[1]}function Yx(e){return ti(e)}function Zx(e){return e[1]}function eI(e){return KO(e[0],e[1])}function tI(e){return null}function rI(e){return s()}function nI(e){return ne()}function oI(e){return D()}function sI(e){return Va()}function iI(e){return Un()}function aI(e){return S()}function uI(e){return Fu()}function cI(e){return Q()}function mI(e){return Ba()}function pI(e){return l({})}function lI(e){return ir()}function dI(e){return Ha()}function fI(e){return Om()}function hI(e){return vm()}function gI(e){return i(BigInt(e))}function yI(e){return i(v(e,"true"))}function xI(e){return i(parseFloat(e))}function II(e){return i(e)}function EI(e){return e[1]}function bI(e){return i(e)}function SI(e){return v(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function wI(e){return e[1]}function TI(e){return _m(e)}function RI(e){return v(e.length,6)?la(e[1],e[3],e[5]):la(e[1],e[3],Q())}function kI(e){return e.length>0}function AI(e){return e.reduce((o,a)=>v(a.length,3)?[...o,[a[1]]]:[...o,[]],[])}function PI(e){return v(e.length,6)?[e[1],e[3],e[5]]:[]}function $I(e){return He(e)&&v(e.length,3)?e[1]:e}function CI(e){return v(e.length,2)?e[1]:[]}function jx(e,o){return o.reduce((a,u)=>{let p=u;return v(p.length,1)?Qu(a,p[0]):v(p.length,0)?H(a):Ea()},e)}function Ux(e,o){return v(o.length,3)?Fm(e,o[0],o[1],o[2]):e}function HO(e,o){return He(o)&&v(o.length,0)?e:Ym(e,o)}function vI(e){let[o,a,u,p,f]=e;return HO(o?Ux(Xu(jx(a,u)),p):Ux(jx(a,u),p),f)}function xd(e,o){return v(o.length,3)?(()=>{let[a,u,p]=o,f=xd(u,p);if(v(a,"&"))return Ve(f)?jn([e,...f.allOf]):jn([e,f]);if(v(a,"|"))return xe(f)?y([e,...f.anyOf]):y([e,f]);Ea()})():e}function MI(e){return e}function OI(e){let[o,a]=e;return xd(o,a)}function _I(e){return e}function LI(e){let[o,a]=e;return xd(o,a)}function NI(e){return tb(e[1])}function qI(e){return e[1]}function DI(e){return Ai(e[0],e[2])}function FI(e){return v(e.length,4)?Du(e[1],e[3]):v(e.length,2)?Du(e[1],Q()):Ea()}function jI(e){return e}function UI(e){return`${e}`}function BI(e){return e}function GI(e){return e}function KI(e){return In(e[3])?Mi:Lr(e[3])?za:Bs(e[3])?ps:nn(e[3])?ps:Ea()}function HI(e){return e}function WI(e){return e.length>0}function zI(e){return e.length>0}function VI(e){let[o,a,u,p,f]=e;return{[a]:o&&u?js(Ds(f)):o&&!u?js(f):!o&&u?Ds(f):f}}function JI(e){return e}function QI(e){return ti(e)}function XI(e){return e.reduce((o,a)=>se(a,Mi)||se(a,za)||se(a,ps)?[o[0],ln(o[1],a)]:[ln(o[0],a),o[1]],[{},{}])}function YI(e){return XI(e[1])}function ZI(e){let[o,a]=e,u=v(be(a).length,0)?{}:{patternProperties:a};return l(o,u)}function eE(e){return v(e.length,5)?js(Ds(e[4])):v(e.length,3)?e[2]:v(e.length,4)?v(e[2],"readonly")?js(e[3]):Ds(e[3]):Ea()}function tE(e){if(!He(e)||!v(e.length,3))return e;let[o,a,u]=e;return o&&u?js(Ds(a)):o&&!u?js(a):!o&&u?Ds(a):a}function rE(e){return v(e.length,2)?Ia(e[1]):v(e.length,1)?e[0]:Ea()}function nE(e){return ti(e)}function oE(e){return zr(e[1])}function sE(e){return js(Ds(e[4]))}function iE(e){return js(e[3])}function aE(e){return Ds(e[3])}function uE(e){return e[2]}function cE(e){return e}function mE(e){return v(e.length,2)?Ia(e[1]):v(e.length,1)?e[0]:Ea()}function pE(e){return ti(e)}function lE(e){return qs(e[1],e[4])}function dE(e){return Ns(e[2],e[5])}function Bx(e,o){return v(e,"remove")?Ix(o):v(e,"add")?js(o):o}function fE(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 Gx(e,o){return v(e,"remove")?Sx(o):v(e,"add")?Ds(o):o}function hE(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 gE(e){return v(e.length,2)?[e[1]]:[]}function yE(e){return He(e[6])&&v(e[6].length,1)?zu(ju(e[3]),e[5],e[6][0],Bx(e[1],Gx(e[8],e[10]))):zu(ju(e[3]),e[5],sn(e[3]),Bx(e[1],Gx(e[8],e[10])))}function xE(e){return sn(e)}function IE(e){return BigInt(e)}function EE(e){return parseFloat(e)}function bE(e){return v(e,"true")}function SE(e){return e}function wE(e){return null}function TE(e){return}function RE(e){return{[e[0]]:e[2]}}function kE(e){return ti(e)}function WO(e){return e.reduce((o,a)=>ln(o,a),{})}function AE(e){return WO(e[1])}function PE(e){return ti(e)}function $E(e){return e[1]}function CE(e){return e}function vE(e){return Fu()}function ME(e){return s()}function OE(e){return ne()}function _E(e){return S()}function LE(e){return ir()}function NE(e){return i(e)}function qE(e){return e}function DE(e){return y(e[1])}function FE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function jE(e){return[e[0],...e[1]]}function UE(e){return e}function BE(e){return e[1]}function GE(e){return ti(e)}function KE(e){return v(e.length,2)?e[1]:[]}function HE(e){let o=e[2],a=e[3],[u,p]=e[4],f=v(be(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Ai(o,Vu(a,u,f))}}function WE(e){let o=e[2],[a,u]=e[3],p=v(be(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Vu(o,a,p)}}function zE(e){return{[e[1]]:Ai(e[2],e[4])}}function VE(e){return{[e[1]]:e[3]}}function JE(e){return null}function QE(e){return e}function XE(e){return ti(e)}function YE(e){return e[1]}function ZE(e){let[o,a]=[e[0],e[1]];return nb(ln(o,XI(a)[0]))}function eb(e){return e}function Yu(e){return v(e.length,2)}function kt(e,o,a){return Yu(e)?o(e[0],e[1]):a()}function JO(e,o){return v(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Ur(e,o){for(let a=0;a<e.length;a++){let u=JO(e[a],o);if(Yu(u))return u}return[]}function Id(e,o){return Array.from({length:o-e+1},(a,u)=>String.fromCharCode(e+u))}var ob=[...Id(97,122),...Id(65,90)],Ed="0",bd=Id(49,57),Ja=[Ed,...bd],sb=" ",Qa=`
|
|
17
|
-
`;var Li="_",Zm=".",ib="$",ep="-";var ab="//",ub="/*",XO="*/";function cb(e){let o=e.indexOf(XO);return v(o,-1)?"":e.slice(o+2)}function mb(e){let o=e.indexOf(Qa);return v(o,-1)?"":e.slice(o)}function YO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function tp(e){let o=YO(e);return o.startsWith(ub)?tp(cb(o.slice(2))):o.startsWith(ab)?tp(mb(o.slice(2))):o}function $n(e){let o=e.trimStart();return o.startsWith(ub)?$n(cb(o.slice(2))):o.startsWith(ab)?$n(mb(o.slice(2))):o}function rp(e,o){return kt(Ur([e],o),(a,u)=>[a,u],()=>["",o])}function ZO(e,o){return e.includes(o)}function Xa(e,o,a,u=""){return kt(Ur(e,a),(p,f)=>ZO(o,p)?Xa(e,o,f,u):Xa(e,o,f,`${u}${p}`),()=>[u,a])}function e_(e){return Ur(bd,e)}var t_=[...Ja,Li];function r_(e){return Xa(t_,[Li],e)}function n_(e){return kt(Ur([Ed],e),(o,a)=>[o,a],()=>kt(e_(e),(o,a)=>kt(r_(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[]))}function np(e){return n_($n(e))}function o_(e){return rp(ep,e)}function s_(e){return kt(o_(e),(o,a)=>kt(np(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function pb(e){return s_($n(e))}function i_(e){return kt(pb(e),(o,a)=>kt(Ur(["n"],a),(u,p)=>[`${o}`,p],()=>[]),()=>[])}function Sd(e){return i_(e)}function wd(e,o){return Ur([e],o)}function V(e,o){return v(e,"")?["",o]:e.startsWith(Qa)?wd(e,tp(o)):e.startsWith(sb)?wd(e,o):wd(e,$n(o))}var lb=[...ob,Li,ib];function a_(e){return Ur(lb,e)}var u_=[...lb,...Ja];function db(e,o=""){return kt(Ur(u_,e),(a,u)=>db(u,`${o}${a}`),()=>[o,e])}function c_(e){return kt(a_(e),(o,a)=>kt(db(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Vr(e){return c_($n(e))}var m_=[...Ja,Li];function p_(e){return Yu(Ur([Zm],e))}function fb(e){return kt(Xa(m_,[Li],e),(o,a)=>v(o,"")?[]:[o,a],()=>[])}function l_(e){return kt(Ur([Zm],e),(o,a)=>kt(fb(a),(u,p)=>[`0${o}${u}`,p],()=>[]),()=>[])}function d_(e){return kt(np(e),(o,a)=>kt(Ur([Zm],a),(u,p)=>kt(fb(p),(f,h)=>[`${o}${u}${f}`,h],()=>[`${o}`,p]),()=>[`${o}`,a]),()=>[])}function f_(e){return p_(e)?l_(e):d_(e)}function hb(e){return f_($n(e))}function h_(e){return rp(ep,e)}function g_(e){return kt(h_(e),(o,a)=>kt(hb(a),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function op(e){return g_($n(e))}function y_(e){return v(e,"")?[]:[e.slice(0,1),e.slice(1)]}function gb(e,o){return bt(e,(a,u)=>o.startsWith(a)?!0:gb(u,o),()=>!1)}function Ni(e,o,a=""){return kt(y_(o),(u,p)=>gb(e,o)?[a,o]:Ni(e,p,`${a}${u}`),()=>[])}function x_(e,o,a){return kt(Ur([e],a),(u,p)=>kt(Ni([o],p),(f,h)=>kt(Ur([o],h),(g,x)=>[`${f}`,x],()=>[]),()=>[]),()=>[])}function I_(e,o,a){return kt(Ur([e],a),(u,p)=>kt(Ni([Qa,o],p),(f,h)=>kt(Ur([o],h),(g,x)=>[`${f}`,x],()=>[]),()=>[]),()=>[])}function yb(e,o,a,u){return a?x_(e,o,$n(u)):I_(e,o,$n(u))}function E_(e,o){return Ur(e,o)}function b_(e,o){return yb(e,e,!1,o)}function S_(e,o){return kt(E_(e,o),(a,u)=>b_(a,`${a}${u}`),()=>[])}function sp(e,o){return S_(e,$n(o))}function xb(e,o){return kt(Ni(e,o),(a,u)=>v(a,"")?[]:[a,u],()=>[])}var w=(e,o,a=()=>[])=>e.length===2?o(e):a(),T_=(e)=>w(w(Vr(e),([o,a])=>w(V("extends",a),([u,p])=>w(Ft(p),([f,h])=>w(V("=",h),([g,x])=>w(Ft(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[Hx(o),a]),R_=(e)=>w(w(Vr(e),([o,a])=>w(V("extends",a),([u,p])=>w(Ft(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Wx(o),a]),k_=(e)=>w(w(Vr(e),([o,a])=>w(V("=",a),([u,p])=>w(Ft(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[zx(o),a]),A_=(e)=>w(Vr(e),([o,a])=>[Vx(o),a]),bb=(e)=>w(w(T_(e),([o,a])=>[o,a],()=>w(R_(e),([o,a])=>[o,a],()=>w(k_(e),([o,a])=>[o,a],()=>w(A_(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Jx(o),a]),Sb=(e,o=[])=>w(w(V(",",e),([a,u])=>w(bb(u),([p,f])=>[[a,p],f])),([a,u])=>Sb(u,[...o,a]),()=>[o,e]),P_=(e)=>w(w(w(bb(e),([o,a])=>w(Sb(a),([u,p])=>w(w(V(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Qx(o),a]),kd=(e)=>w(w(V("<",e),([o,a])=>w(P_(a),([u,p])=>w(V(">",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Xx(o),a]),wb=(e,o=[])=>w(w(V(",",e),([a,u])=>w(Ft(u),([p,f])=>[[a,p],f])),([a,u])=>wb(u,[...o,a]),()=>[o,e]),$_=(e)=>w(w(w(Ft(e),([o,a])=>w(wb(a),([u,p])=>w(w(V(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Yx(o),a]),C_=(e)=>w(w(V("<",e),([o,a])=>w($_(a),([u,p])=>w(V(">",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[Zx(o),a]),v_=(e)=>w(w(Vr(e),([o,a])=>w(C_(a),([u,p])=>[[o,u],p])),([o,a])=>[eI(o),a]),Tb=(e)=>w(w(w(V(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[tI(o),a]),Rb=(e)=>w(V("string",e),([o,a])=>[rI(o),a]),kb=(e)=>w(V("number",e),([o,a])=>[nI(o),a]),M_=(e)=>w(V("boolean",e),([o,a])=>[oI(o),a]),O_=(e)=>w(V("undefined",e),([o,a])=>[sI(o),a]),__=(e)=>w(V("null",e),([o,a])=>[iI(o),a]),Ab=(e)=>w(V("integer",e),([o,a])=>[aI(o),a]),L_=(e)=>w(V("bigint",e),([o,a])=>[uI(o),a]),N_=(e)=>w(V("unknown",e),([o,a])=>[cI(o),a]),q_=(e)=>w(V("any",e),([o,a])=>[mI(o),a]),D_=(e)=>w(V("object",e),([o,a])=>[pI(o),a]),F_=(e)=>w(V("never",e),([o,a])=>[lI(o),a]),Pb=(e)=>w(V("symbol",e),([o,a])=>[dI(o),a]),j_=(e)=>w(V("void",e),([o,a])=>[fI(o),a]),U_=(e)=>w(V("this",e),([o,a])=>[hI(o),a]),B_=(e)=>w(w(V("${",e),([o,a])=>w(Ft(a),([u,p])=>w(V("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[EI(o),a]),Td=(e)=>w(Ni(["${","`"],e),([o,a])=>[bI(o),a]),$b=(e)=>w(w(w(Td(e),([o,a])=>w(B_(a),([u,p])=>w($b(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(w(Td(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(Td(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[SI(o),a]),Ad=(e)=>w(w(V("`",e),([o,a])=>w($b(a),([u,p])=>w(V("`",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[wI(o),a]),G_=(e)=>w(Ad(e),([o,a])=>[TI(o),a]),K_=(e)=>w(w(w(V("if",e),([o,a])=>w(Ft(a),([u,p])=>w(V("then",p),([f,h])=>w(Ft(h),([g,x])=>w(V("else",x),([I,E])=>w(Ft(E),([k,A])=>[[o,u,f,g,I,k],A])))))),([o,a])=>[o,a],()=>w(w(V("if",e),([o,a])=>w(Ft(a),([u,p])=>w(V("then",p),([f,h])=>w(Ft(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[o,a],()=>[])),([o,a])=>[RI(o),a]),H_=(e)=>w(Sd(e),([o,a])=>[gI(o),a]),W_=(e)=>w(w(V("true",e),([o,a])=>[o,a],()=>w(V("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[yI(o),a]),z_=(e)=>w(op(e),([o,a])=>[xI(o),a]),V_=(e)=>w(sp(["'",'"'],e),([o,a])=>[II(o),a]),J_=(e)=>w(w(w(V("keyof",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kI(o),a]),Cb=(e,o=[])=>w(w(w(V("[",e),([a,u])=>w(Ft(u),([p,f])=>w(V("]",f),([h,g])=>[[a,p,h],g]))),([a,u])=>[a,u],()=>w(w(V("[",e),([a,u])=>w(V("]",u),([p,f])=>[[a,p],f])),([a,u])=>[a,u],()=>[])),([a,u])=>Cb(u,[...o,a]),()=>[o,e]),Q_=(e)=>w(Cb(e),([o,a])=>[AI(o),a]),X_=(e)=>w(w(w(V("extends",e),([o,a])=>w(Ft(a),([u,p])=>w(V("?",p),([f,h])=>w(Ft(h),([g,x])=>w(V(":",x),([I,E])=>w(Ft(E),([k,A])=>[[o,u,f,g,I,k],A])))))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[PI(o),a]),Y_=(e)=>w(w(w(V("(",e),([o,a])=>w(Ft(a),([u,p])=>w(V(")",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(Rb(e),([o,a])=>[o,a],()=>w(kb(e),([o,a])=>[o,a],()=>w(M_(e),([o,a])=>[o,a],()=>w(O_(e),([o,a])=>[o,a],()=>w(__(e),([o,a])=>[o,a],()=>w(Ab(e),([o,a])=>[o,a],()=>w(L_(e),([o,a])=>[o,a],()=>w(N_(e),([o,a])=>[o,a],()=>w(q_(e),([o,a])=>[o,a],()=>w(D_(e),([o,a])=>[o,a],()=>w(F_(e),([o,a])=>[o,a],()=>w(Pb(e),([o,a])=>[o,a],()=>w(j_(e),([o,a])=>[o,a],()=>w(U_(e),([o,a])=>[o,a],()=>w(H_(e),([o,a])=>[o,a],()=>w(W_(e),([o,a])=>[o,a],()=>w(z_(e),([o,a])=>[o,a],()=>w(V_(e),([o,a])=>[o,a],()=>w(G_(e),([o,a])=>[o,a],()=>w(K_(e),([o,a])=>[o,a],()=>w(cL(e),([o,a])=>[o,a],()=>w(lL(e),([o,a])=>[o,a],()=>w(xL(e),([o,a])=>[o,a],()=>w(yL(e),([o,a])=>[o,a],()=>w(SL(e),([o,a])=>[o,a],()=>w(v_(e),([o,a])=>[o,a],()=>w(wL(e),([o,a])=>[o,a],()=>[])))))))))))))))))))))))))))),([o,a])=>[$I(o),a]),Z_=(e)=>w(w(w(V("with",e),([o,a])=>w(zb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[CI(o),a]),vb=(e)=>w(w(J_(e),([o,a])=>w(Y_(a),([u,p])=>w(Q_(p),([f,h])=>w(X_(h),([g,x])=>w(Z_(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[vI(o),a]),Mb=(e)=>w(w(w(V("&",e),([o,a])=>w(vb(a),([u,p])=>w(Mb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[MI(o),a]),Ob=(e)=>w(w(vb(e),([o,a])=>w(Mb(a),([u,p])=>[[o,u],p])),([o,a])=>[OI(o),a]),_b=(e)=>w(w(w(V("|",e),([o,a])=>w(Ob(a),([u,p])=>w(_b(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[_I(o),a]),ip=(e)=>w(w(Ob(e),([o,a])=>w(_b(a),([u,p])=>[[o,u],p])),([o,a])=>[LI(o),a]),eL=(e)=>w(w(V("readonly",e),([o,a])=>w(ip(a),([u,p])=>[[o,u],p])),([o,a])=>[NI(o),a]),tL=(e)=>w(w(V("|",e),([o,a])=>w(ip(a),([u,p])=>[[o,u],p])),([o,a])=>[qI(o),a]),rL=(e)=>w(w(kd(e),([o,a])=>w(V("=",a),([u,p])=>w(Ft(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[DI(o),a]),nL=(e)=>w(w(w(V("infer",e),([o,a])=>w(Vr(a),([u,p])=>w(V("extends",p),([f,h])=>w(ip(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[o,a],()=>w(w(V("infer",e),([o,a])=>w(Vr(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>[])),([o,a])=>[FI(o),a]),Ft=(e)=>w(w(nL(e),([o,a])=>[o,a],()=>w(tL(e),([o,a])=>[o,a],()=>w(eL(e),([o,a])=>[o,a],()=>w(ip(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[jI(o),a]),oL=(e)=>w(op(e),([o,a])=>[UI(o),a]),sL=(e)=>w(Vr(e),([o,a])=>[BI(o),a]),iL=(e)=>w(sp(["'",'"'],e),([o,a])=>[GI(o),a]),aL=(e)=>w(w(V("[",e),([o,a])=>w(Vr(a),([u,p])=>w(V(":",p),([f,h])=>w(w(Ab(h),([g,x])=>[g,x],()=>w(kb(h),([g,x])=>[g,x],()=>w(Rb(h),([g,x])=>[g,x],()=>w(Pb(h),([g,x])=>[g,x],()=>[])))),([g,x])=>w(V("]",x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[KI(o),a]),Lb=(e)=>w(w(oL(e),([o,a])=>[o,a],()=>w(sL(e),([o,a])=>[o,a],()=>w(iL(e),([o,a])=>[o,a],()=>w(aL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[HI(o),a]),Nb=(e)=>w(w(w(V("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[WI(o),a]),qb=(e)=>w(w(w(V("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[zI(o),a]),Db=(e)=>w(w(Nb(e),([o,a])=>w(Lb(a),([u,p])=>w(qb(p),([f,h])=>w(V(":",h),([g,x])=>w(Ft(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[VI(o),a]),ap=(e)=>w(w(w(V(",",e),([o,a])=>w(V(`
|
|
18
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V(";",e),([o,a])=>w(V(`
|
|
19
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V(",",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(V(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(V(`
|
|
20
|
-
`,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))))),([o,a])=>[JI(o),a]),Fb=(e,o=[])=>w(w(ap(e),([a,u])=>w(Db(u),([p,f])=>[[a,p],f])),([a,u])=>Fb(u,[...o,a]),()=>[o,e]),uL=(e)=>w(w(w(Db(e),([o,a])=>w(Fb(a),([u,p])=>w(w(ap(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[QI(o),a]),Pd=(e)=>w(w(V("{",e),([o,a])=>w(uL(a),([u,p])=>w(V("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[YI(o),a]),cL=(e)=>w(Pd(e),([o,a])=>[ZI(o),a]),mL=(e)=>w(w(w(Vr(e),([o,a])=>w(V("?",a),([u,p])=>w(V(":",p),([f,h])=>w(V("readonly",h),([g,x])=>w(Ft(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[o,a],()=>w(w(Vr(e),([o,a])=>w(V(":",a),([u,p])=>w(V("readonly",p),([f,h])=>w(Ft(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[o,a],()=>w(w(Vr(e),([o,a])=>w(V("?",a),([u,p])=>w(V(":",p),([f,h])=>w(Ft(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[o,a],()=>w(w(Vr(e),([o,a])=>w(V(":",a),([u,p])=>w(Ft(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>[])))),([o,a])=>[eE(o),a]),Ib=(e)=>w(w(mL(e),([o,a])=>[o,a],()=>w(w(Nb(e),([o,a])=>w(Ft(a),([u,p])=>w(qb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>[])),([o,a])=>[tE(o),a]),jb=(e)=>w(w(w(V("...",e),([o,a])=>w(Ib(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(Ib(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[rE(o),a]),Ub=(e,o=[])=>w(w(V(",",e),([a,u])=>w(jb(u),([p,f])=>[[a,p],f])),([a,u])=>Ub(u,[...o,a]),()=>[o,e]),pL=(e)=>w(w(w(jb(e),([o,a])=>w(Ub(a),([u,p])=>w(w(V(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[nE(o),a]),lL=(e)=>w(w(V("[",e),([o,a])=>w(pL(a),([u,p])=>w(V("]",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[oE(o),a]),dL=(e)=>w(w(Vr(e),([o,a])=>w(V("?",a),([u,p])=>w(V(":",p),([f,h])=>w(V("readonly",h),([g,x])=>w(Ft(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[sE(o),a]),fL=(e)=>w(w(Vr(e),([o,a])=>w(V(":",a),([u,p])=>w(V("readonly",p),([f,h])=>w(Ft(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[iE(o),a]),hL=(e)=>w(w(Vr(e),([o,a])=>w(V("?",a),([u,p])=>w(V(":",p),([f,h])=>w(Ft(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[aE(o),a]),gL=(e)=>w(w(Vr(e),([o,a])=>w(V(":",a),([u,p])=>w(Ft(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[uE(o),a]),Eb=(e)=>w(w(dL(e),([o,a])=>[o,a],()=>w(fL(e),([o,a])=>[o,a],()=>w(hL(e),([o,a])=>[o,a],()=>w(gL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[cE(o),a]),Bb=(e)=>w(w(w(V("...",e),([o,a])=>w(Eb(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(Eb(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[mE(o),a]),Gb=(e,o=[])=>w(w(V(",",e),([a,u])=>w(Bb(u),([p,f])=>[[a,p],f])),([a,u])=>Gb(u,[...o,a]),()=>[o,e]),Kb=(e)=>w(w(w(Bb(e),([o,a])=>w(Gb(a),([u,p])=>w(w(V(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[pE(o),a]),yL=(e)=>w(w(V("(",e),([o,a])=>w(Kb(a),([u,p])=>w(V(")",p),([f,h])=>w(V("=>",h),([g,x])=>w(Ft(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[lE(o),a]),xL=(e)=>w(w(V("new",e),([o,a])=>w(V("(",a),([u,p])=>w(Kb(p),([f,h])=>w(V(")",h),([g,x])=>w(V("=>",x),([I,E])=>w(Ft(E),([k,A])=>[[o,u,f,g,I,k],A])))))),([o,a])=>[dE(o),a]),IL=(e)=>w(w(w(V("+",e),([o,a])=>w(V("readonly",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V("-",e),([o,a])=>w(V("readonly",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[fE(o),a]),EL=(e)=>w(w(w(V("+",e),([o,a])=>w(V("?",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V("-",e),([o,a])=>w(V("?",a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[hE(o),a]),bL=(e)=>w(w(w(V("as",e),([o,a])=>w(Ft(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[gE(o),a]),SL=(e)=>w(w(V("{",e),([o,a])=>w(IL(a),([u,p])=>w(V("[",p),([f,h])=>w(Vr(h),([g,x])=>w(V("in",x),([I,E])=>w(Ft(E),([k,A])=>w(bL(A),([P,C])=>w(V("]",C),([M,J])=>w(EL(J),([O,B])=>w(V(":",B),([L,X])=>w(Ft(X),([te,j])=>w(Tb(j),([re,ye])=>w(V("}",ye),([Te,ze])=>[[o,u,f,g,I,k,P,M,O,L,te,re,Te],ze]))))))))))))),([o,a])=>[yE(o),a]),wL=(e)=>w(Vr(e),([o,a])=>[xE(o),a]),TL=(e)=>w(Sd(e),([o,a])=>[IE(o),a]),RL=(e)=>w(op(e),([o,a])=>[EE(o),a]),kL=(e)=>w(w(V("true",e),([o,a])=>[o,a],()=>w(V("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[bE(o),a]),AL=(e)=>w(sp(['"',"'"],e),([o,a])=>[SE(o),a]),PL=(e)=>w(V("null",e),([o,a])=>[wE(o),a]),$L=(e)=>w(V("undefined",e),([o,a])=>[TE(o),a]),Hb=(e)=>w(w(Lb(e),([o,a])=>w(V(":",a),([u,p])=>w($d(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[RE(o),a]),Wb=(e,o=[])=>w(w(ap(e),([a,u])=>w(Hb(u),([p,f])=>[[a,p],f])),([a,u])=>Wb(u,[...o,a]),()=>[o,e]),CL=(e)=>w(w(w(Hb(e),([o,a])=>w(Wb(a),([u,p])=>w(w(ap(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kE(o),a]),zb=(e)=>w(w(V("{",e),([o,a])=>w(CL(a),([u,p])=>w(V("}",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[AE(o),a]),Vb=(e,o=[])=>w(w(V(",",e),([a,u])=>w($d(u),([p,f])=>[[a,p],f])),([a,u])=>Vb(u,[...o,a]),()=>[o,e]),vL=(e)=>w(w(w($d(e),([o,a])=>w(Vb(a),([u,p])=>w(w(V(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[PE(o),a]),ML=(e)=>w(w(V("[",e),([o,a])=>w(vL(a),([u,p])=>w(V("]",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[$E(o),a]),$d=(e)=>w(w(TL(e),([o,a])=>[o,a],()=>w(RL(e),([o,a])=>[o,a],()=>w(kL(e),([o,a])=>[o,a],()=>w(AL(e),([o,a])=>[o,a],()=>w(PL(e),([o,a])=>[o,a],()=>w($L(e),([o,a])=>[o,a],()=>w(zb(e),([o,a])=>[o,a],()=>w(ML(e),([o,a])=>[o,a],()=>[])))))))),([o,a])=>[CE(o),a]),OL=(e)=>w(V("-?(?:0|[1-9][0-9]*)n",e),([o,a])=>[vE(o),a]),_L=(e)=>w(V(".*",e),([o,a])=>[ME(o),a]),LL=(e)=>w(V("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,a])=>[OE(o),a]),NL=(e)=>w(V("-?(?:0|[1-9][0-9]*)",e),([o,a])=>[_E(o),a]),qL=(e)=>w(V("(?!)",e),([o,a])=>[LE(o),a]),DL=(e)=>w(xb(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,a])=>[NE(o),a]),FL=(e)=>w(w(OL(e),([o,a])=>[o,a],()=>w(_L(e),([o,a])=>[o,a],()=>w(LL(e),([o,a])=>[o,a],()=>w(NL(e),([o,a])=>[o,a],()=>w(qL(e),([o,a])=>[o,a],()=>w(jL(e),([o,a])=>[o,a],()=>w(DL(e),([o,a])=>[o,a],()=>[]))))))),([o,a])=>[qE(o),a]),jL=(e)=>w(w(V("(",e),([o,a])=>w(Cd(a),([u,p])=>w(V(")",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[DE(o),a]),Jb=(e)=>w(w(w(Rd(e),([o,a])=>w(V("|",a),([u,p])=>w(Jb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w(w(Rd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[]))),([o,a])=>[FE(o),a]),Rd=(e)=>w(w(FL(e),([o,a])=>w(Cd(a),([u,p])=>[[o,u],p])),([o,a])=>[jE(o),a]),Cd=(e)=>w(w(Jb(e),([o,a])=>[o,a],()=>w(Rd(e),([o,a])=>[o,a],()=>[])),([o,a])=>[UE(o),a]),ux=(e)=>w(w(V("^",e),([o,a])=>w(Cd(a),([u,p])=>w(V("$",p),([f,h])=>[[o,u,f],h]))),([o,a])=>[BE(o),a]),Qb=(e,o=[])=>w(w(V(",",e),([a,u])=>w(Ft(u),([p,f])=>[[a,p],f])),([a,u])=>Qb(u,[...o,a]),()=>[o,e]),UL=(e)=>w(w(w(Ft(e),([o,a])=>w(Qb(a),([u,p])=>w(w(V(",",p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[GE(o),a]),Xb=(e)=>w(w(w(V("extends",e),([o,a])=>w(UL(a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[KE(o),a]),BL=(e)=>w(w(V("interface",e),([o,a])=>w(Vr(a),([u,p])=>w(kd(p),([f,h])=>w(Xb(h),([g,x])=>w(Pd(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[HE(o),a]),GL=(e)=>w(w(V("interface",e),([o,a])=>w(Vr(a),([u,p])=>w(Xb(p),([f,h])=>w(Pd(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[WE(o),a]),KL=(e)=>w(w(V("type",e),([o,a])=>w(Vr(a),([u,p])=>w(kd(p),([f,h])=>w(V("=",h),([g,x])=>w(Ft(x),([I,E])=>[[o,u,f,g,I],E]))))),([o,a])=>[zE(o),a]),HL=(e)=>w(w(V("type",e),([o,a])=>w(Vr(a),([u,p])=>w(V("=",p),([f,h])=>w(Ft(h),([g,x])=>[[o,u,f,g],x])))),([o,a])=>[VE(o),a]),WL=(e)=>w(w(w(V("export",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[JE(o),a]),Yb=(e)=>w(w(w(V(";",e),([o,a])=>w(V(`
|
|
21
|
-
`,a),([u,p])=>[[o,u],p])),([o,a])=>[o,a],()=>w(w(V(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(V(`
|
|
22
|
-
`,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[QE(o),a]),Zb=(e,o=[])=>w(w(Yb(e),([a,u])=>w(vd(u),([p,f])=>[[a,p],f])),([a,u])=>Zb(u,[...o,a]),()=>[o,e]),zL=(e)=>w(w(w(vd(e),([o,a])=>w(Zb(a),([u,p])=>w(w(Yb(p),([f,h])=>[[f],h],()=>[[],p]),([f,h])=>[[o,u,f],h]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[XE(o),a]),vd=(e)=>w(w(WL(e),([o,a])=>w(w(BL(a),([u,p])=>[u,p],()=>w(GL(a),([u,p])=>[u,p],()=>w(KL(a),([u,p])=>[u,p],()=>w(HL(a),([u,p])=>[u,p],()=>[])))),([u,p])=>w(Tb(p),([f,h])=>[[o,u,f],h]))),([o,a])=>[YE(o),a]),VL=(e)=>w(w(vd(e),([o,a])=>w(zL(a),([u,p])=>[[o,u],p])),([o,a])=>[ZE(o),a]),eS=(e)=>w(w(VL(e),([o,a])=>[o,a],()=>w(rL(e),([o,a])=>[o,a],()=>w(Ft(e),([o,a])=>[o,a],()=>[]))),([o,a])=>[eb(o),a]);function tS(e){let o=Ad(`\`${e}\``);return v(o.length,2)?o[0]:Wr()}function QL(e){return e.join("|")}function XL(e){return e.slice(1,e.length-1)}function YL(e,o,a){return Di(o,`${a}${e}`)}function ZL(e,o){return Di(e,`${o}${tx}`)}function eN(e,o){return Di(e,`${o}${Im}`)}function tN(e,o){return Di(e,`${o}${wm}`)}function rN(e,o){return Zu(y([i("false"),i("true")]),e,o)}function nN(e,o){return Di(e,`${o}${Tm}`)}function oN(e,o,a){return Di(o,`${a}${XL(e)}`)}function sN(e,o,a){let u=ec(e,{});return Zu(u,o,a)}function iN(e,o,a){let u=Io(e);return Zu(u,o,a)}function rS(e,o,a,u=[]){return bt(e,(p,f)=>rS(f,o,a,[...u,Zu(p,[],"")]),()=>Di(o,`${a}(${QL(u)})`))}function Zu(e,o,a){return rn(e)?iN(e.enum,o,a):In(e)?eN(o,a):It(e)?YL(e.const,o,a):$o(e)?ZL(o,a):xo(e)?rN(o,a):Lr(e)?tN(o,a):nn(e)?nN(o,a):lr(e)?oN(e.pattern,o,a):oS(e)?sN(e.parameters[0],o,a):xe(e)?rS(e.anyOf,o,a):$y}function Di(e,o){return bt(e,(a,u)=>Zu(a,u,o),()=>o)}function aN(e){return`^${Di(e,"")}$`}function nS(e){let o=aN(e);return km(o)}function ec(e,o){return dt(e)?Tt(nS(e),{},o):_m(e,o)}function sS(e,o,a,u){let p=Lo(e,o,a);return ec(p,u)}function _m(e,o={}){return Me("TemplateLiteral",[e],o)}function oS(e){return Dr(e)&&se(e,"action")&&v(e.action,"TemplateLiteral")}function iS(e){return ec(e,{})}function uN(e){let o=tS(e);return iS(o)}function aS(e,o={}){let a=yt(e)?uN(e):iS(e);return Tt(a,{},o)}function lr(e){return Re(e,"TemplateLiteral")}function Md(e){return qt({["~kind"]:"ExtendsUnion"},{inferred:e})}function Od(e){return lt(e)&&se(e,"~kind")&&se(e,"inferred")&&v(e["~kind"],"ExtendsUnion")&<(e.inferred)}function Se(e){return qt({["~kind"]:"ExtendsTrue"},{inferred:e})}function _d(e){return lt(e)&&se(e,"~kind")&&se(e,"inferred")&&v(e["~kind"],"ExtendsTrue")&<(e.inferred)}function et(){return qt({["~kind"]:"ExtendsFalse"},{})}function Ld(e){return lt(e)&&se(e,"~kind")&&v(e["~kind"],"ExtendsFalse")}function Ro(e){return Od(e)||_d(e)}function wr(e,o,a){return Ro(e)?o(e.inferred):a()}function cN(e,o,a,u){return wr(Pt(e,a,u),(p)=>Se(ln(ln(e,p),{[o]:a})),()=>et())}function mN(e,o){return Se(e)}function pN(e,o,a,u,p){return wr(Pt(e,o,a),(f)=>wr(Pt(f,o,u),(h)=>Se(h),()=>et()),()=>wr(Pt(e,o,p),(f)=>Se(f),()=>et()))}function lN(e,o,a){let u=Io(a);return Pt(e,o,u)}function uS(e,o,a){return bt(a,(u,p)=>wr(Pt(e,o,u),(f)=>uS(f,o,p),()=>et()),()=>Se(e))}function dN(e,o,a){let u=Bn(a);return Pt(e,o,u)}function cS(e,o,a){return bt(a,(u,p)=>wr(Pt(e,o,u),(f)=>Se(f),()=>cS(e,o,p)),()=>et())}function Wt(e,o,a){return Fr(a)?mN(e,o):Hr(a)?pN(e,o,a.if,a.then,a.else):rn(a)?lN(e,o,a.enum):tn(a)?cN(e,a.name,o,a.extends):Ve(a)?uS(e,o,a.allOf):lr(a)?dN(e,o,a.pattern):xe(a)?cS(e,o,a.anyOf):en(a)?Se(e):et()}function mS(e,o,a){return tn(a)?Wt(e,o,a):Fr(a)?Se(e):en(a)?Se(e):Md(e)}function fN(e,o){let a=fa(e),u=fa(o);return a&&u?!0:!a&&u?!0:a&&!u?!1:!0}function pS(e,o,a,u){return Rt(u)?fN(o,u)?Pt(e,a,u.items):et():Wt(e,o,u)}function lS(e,o,a){return $o(a)?Se(e):Wt(e,o,a)}function dS(e,o,a){return xo(a)?Se(e):Wt(e,o,a)}function hN(e,o,a,u,p){let f=tn(u)?o:u,h=tn(u)?u:o,g=an(o),x=an(u);return!g&&x?et():wr(Pt(e,f,h),(I)=>tc(I,a,p),()=>et())}function gN(e,o,a,u){return bt(u,(p,f)=>hN(e,o,a,p,f),()=>an(o)?Se(e):et())}function yN(e,o,a){return bt(o,(u,p)=>gN(e,u,p,a),()=>Se(e))}function tc(e,o,a){return yN(e,o,a)}function up(e,o,a){return Co(a)?Se(e):Pt(e,o,a)}function fS(e,o,a,u){return Fr(u)?Se(e):en(u)?Se(e):Yr(u)?wr(tc(e,o,u.parameters),(p)=>up(p,a,u.instanceType),()=>et()):et()}function hS(e,o,a,u,p){return wr(Pt(e,o,p),()=>Pt(e,a,p),()=>Pt(e,u,p))}function gS(e,o,a){let u=Io(o);return Pt(e,u,a)}function yS(e,o,a,u){return Fr(u)?Se(e):en(u)?Se(e):Zr(u)?wr(tc(e,o,u.parameters),(p)=>up(p,a,u.returnType),()=>et()):et()}function xS(e,o,a){return In(a)?Se(e):Lr(a)?Se(e):Wt(e,o,a)}function IS(e,o,a){let u=Nr(o);return Pt(e,u,a)}function cp(e,o,a){return o===a?Se(e):et()}function xN(e,o,a){return It(a)?cp(e,o,a.const):$o(a)?Se(e):Wt(e,i(o),a)}function IN(e,o,a){return It(a)?cp(e,o,a.const):xo(a)?Se(e):Wt(e,i(o),a)}function EN(e,o,a){return It(a)?cp(e,o,a.const):Lr(a)?Se(e):Wt(e,i(o),a)}function bN(e,o,a){return It(a)?cp(e,o,a.const):nn(a)?Se(e):Wt(e,i(o),a)}function ES(e,o,a){return Kr(o.const)?xN(e,o.const,a):cn(o.const)?IN(e,o.const,a):Bt(o.const)?EN(e,o.const,a):yt(o.const)?bN(e,o.const,a):Wr()}function bS(e,o,a){return tn(a)?Wt(e,o,a):Se(e)}function SS(e,o,a){return Us(a)?Se(e):Wt(e,o,a)}function wS(e,o,a){return Lr(a)?Se(e):Wt(e,o,a)}function SN(e,o,a){return an(o)?an(a)?Se(e):et():Se(e)}function wN(e,o,a){return tn(a)&&Po(a.extends)?et():wr(Pt(e,o,a),(u)=>SN(u,o,a),()=>et())}function TN(e,o){return e.reduce((a,u)=>(u in o)?Ro(o[u])?{...a,...o[u].inferred}:Wr():Wr(),{})}function RN(e,o,a){let u={};for(let h of be(a))u[h]=h in o?wN({},o[h],a[h]):an(a[h])?tn(a[h])?Se(ln(e,{[a[h].name]:a[h].extends})):Se(e):et();let p=nd(u).every((h)=>Ro(h)),f=p?TN(be(u),u):{};return p?Se(f):et()}function kN(e,o,a){let u=RN(e,o,a);return Ro(u)?Se(ln(e,u.inferred)):et()}function AN(e,o,a){return kN(e,o,a)}function PN(e,o){return be(o).reduce((a,u)=>({...a,[u]:se(e,u)?xe(a[u])?y([...a[u].anyOf,o[u]]):y([e[u],o[u]]):o[u]}),e)}function TS(e,o,a,u){return bt(o,(p,f)=>wr(Pt({},e[p],a),(h)=>TS(e,f,a,PN(u,h)),()=>et()),()=>Se(u))}function $N(e,o,a,u){let p=be(o);return TS(o,p,u,e)}function RS(e,o,a){return or(a)?$N(e,o,Sn(a),hr(a)):Je(a)?AN(e,o,a.properties):Wt(e,l(o),a)}function CN(e,o){return v(be(o).length,0)?Se(e):et()}function vN(e,o,a,u,p){return Pt(e,a,p)}function kS(e,o,a,u){return or(u)?vN(e,Cm(o),a,Cm(Sn(u)),hr(u)):Je(u)?CN(e,u.properties):Fr(u)?Se(e):en(u)?Se(e):et()}function AS(e,o,a){return nn(a)?Se(e):Wt(e,o,a)}function PS(e,o,a){return Bs(a)?Se(e):Wt(e,o,a)}function $S(e,o,a){let u=Bn(o);return Pt(e,u,a)}function Nd(e,o){return qt({"~kind":"Inferrable"},{name:e,type:o},{})}function rc(e){return lt(e)&&se(e,"~kind")&&se(e,"name")&&se(e,"type")&&v(e["~kind"],"Inferrable")&&yt(e.name)&<(e.type)}function qd(e){return _i(e)?tn(e.items)?Rt(e.items.extends)?Nd(e.items.name,e.items.extends.items):en(e.items.extends)?Nd(e.items.name,e.items.extends):void 0:Wr():void 0}function mp(e){return tn(e)?Nd(e.name,e.extends):void 0}function Dd(e,o,a=[]){return bt(e,(u,p)=>wr(Pt({},u,o),()=>Dd(p,o,[...a,u]),()=>{return}),()=>a)}function CS(e,o,a,u){let p=Dd(a,u);return He(p)?Se(ln(e,{[o]:zr(p)})):et()}function pp(e,o,a,u){let p=Dd(a,u);return He(p)?Se(ln(e,{[o]:y(p)})):et()}function MN(e){return[...e].reverse()}function Fd(e,o){return o?MN(e):e}function ON(e){let o=e.length>0?e[0]:void 0,a=Dr(o)?qd(o):void 0;return Dr(a)}function _N(e,o,a,u,p,f){return wr(Pt(e,a,p),(h)=>vS(h,o,u,f),()=>et())}function LN(e,o,a,u,p){let f=qd(u);return rc(f)?CS(e,f.name,Fd(a,o),f.type):bt(a,(h,g)=>_N(e,o,h,g,u,p),()=>et())}function NN(e,o,a,u){return bt(u,(p,f)=>LN(e,o,a,p,f),()=>v(a.length,0)?Se(e):et())}function vS(e,o,a,u){return NN(e,o,a,u)}function qN(e,o,a){let u=Fi(e,gr([],[]),a),p=ON(u);return vS(e,p,Fd(o,p),Fd(u,p))}function MS(e,o,a){let u=mp(a);return rc(u)?pp(e,u.name,o,u.type):bt(o,(p,f)=>wr(Pt(e,p,a),(h)=>MS(h,f,a),()=>et()),()=>Se(e))}function OS(e,o,a){let u=Fi(e,gr([],[]),o);return ht(a)?qN(e,u,a.items):Rt(a)?MS(e,u,a.items):Wt(e,zr(u),a)}function _S(e,o,a){return Co(a)?Se(e):gs(a)?Se(e):Wt(e,o,a)}function LS(e,o,a){return bt(a,(u,p)=>wr(Pt(e,o,u),(f)=>Se(f),()=>LS(e,o,p)),()=>et())}function jd(e,o,a){return bt(o,(u,p)=>wr(LS(e,u,a),(f)=>jd(f,p,a),()=>et()),()=>Se(e))}function NS(e,o,a){let u=mp(a);return rc(u)?pp(e,u.name,o,u.type):xe(a)?jd(e,o,a.anyOf):jd(e,o,[a])}function qS(e,o,a){return tn(a)?Wt(e,o,a):Fr(a)?Se(e):en(a)?Se(e):et()}function DS(e,o,a){return Co(a)?Se(e):Wt(e,o,a)}function Pt(e,o,a){return Fr(o)?mS(e,o,a):Rt(o)?pS(e,o,o.items,a):$o(o)?lS(e,o,a):xo(o)?dS(e,o,a):Yr(o)?fS(e,o.parameters,o.instanceType,a):Hr(o)?hS(e,o.if,o.then,o.else,a):rn(o)?gS(e,o.enum,a):Zr(o)?yS(e,o.parameters,o.returnType,a):In(o)?xS(e,o,a):Ve(o)?IS(e,o.allOf,a):It(o)?ES(e,o,a):Po(o)?bS(e,o,a):Us(o)?SS(e,o,a):Lr(o)?wS(e,o,a):Je(o)?RS(e,o.properties,a):or(o)?kS(e,Sn(o),hr(o),a):nn(o)?AS(e,o,a):Bs(o)?PS(e,o,a):lr(o)?$S(e,o.pattern,a):ht(o)?OS(e,o.items,a):gs(o)?_S(e,o,a):xe(o)?NS(e,o.anyOf,a):en(o)?qS(e,o,a):Co(o)?DS(e,o,a):et()}function DN(e,o){return Nr([...e,l(o)])}function Ud(e,o,a){return dt(e)?Tt(DN(e,o),{},a):Vu(e,o,a)}function FS(e,o,a,u,p){let f=Lo(e,o,a),h=nc(e,o,u);return Ud(f,h,p)}function Vu(e,o,a={}){return Me("Interface",[e,o],a)}function Ya(e){return Dr(e)&&se(e,"action")&&v(e.action,"Interface")}function jS(e,o,a={}){return Ud(e,o,a)}function FN(e,o,a){return e.includes(a)?!0:oc([...e,a],o,o[a])}function US(e,o,a){let u=dm(a);return ba(e,o,u)}function ba(e,o,a){return bt(a,(u,p)=>oc(e,o,u)?!0:ba(e,o,p),()=>!1)}function oc(e,o,a){return Zt(a)?FN(e,o,a.$ref):Rt(a)?oc(e,o,a.items):Yr(a)?ba(e,o,[...a.parameters,a.instanceType]):Zr(a)?ba(e,o,[...a.parameters,a.returnType]):Ya(a)?US(e,o,a.parameters[1]):Ve(a)?ba(e,o,a.allOf):Je(a)?US(e,o,a.properties):xe(a)?ba(e,o,a.anyOf):ht(a)?ba(e,o,a.items):or(a)?oc(e,o,hr(a)):!1}function BS(e,o,a){return oc(e,o,a)}function jN(e,o){return o.reduce((a,u)=>BS([u],e,e[u])?[...a,u]:a,[])}function GS(e){let o=lm(e);return jN(e,o)}function UN(e,o,a){return a.includes(o)?a:(o in e)?sc(e,e[o],[...a,o]):Wr()}function KS(e,o,a){let u=dm(o);return Za(e,u,a)}function Za(e,o,a){return o.reduce((u,p)=>sc(e,p,u),a)}function sc(e,o,a){return Zt(o)?UN(e,o.$ref,a):Rt(o)?sc(e,o.items,a):Yr(o)?Za(e,[...o.parameters,o.instanceType],a):Zr(o)?Za(e,[...o.parameters,o.returnType],a):Ya(o)?KS(e,o.parameters[1],a):Ve(o)?Za(e,o.allOf,a):Je(o)?KS(e,o.properties,a):xe(o)?Za(e,o.anyOf,a):ht(o)?Za(e,o.items,a):or(o)?sc(e,hr(o),a):a}function HS(e,o,a){return sc(e,a,[o])}function BN(e){return Ba()}function GN(e){return be(e).reduce((o,a)=>({...o,[a]:Sa(e[a])}),{})}function ic(e){return e.reduce((o,a)=>[...o,Sa(a)],[])}function Sa(e){return Zt(e)?BN(e.$ref):Rt(e)?H(Sa(e.items),ja(e)):Yr(e)?Ns(ic(e.parameters),Sa(e.instanceType)):Zr(e)?qs(ic(e.parameters),Sa(e.returnType)):Ve(e)?jn(ic(e.allOf)):Je(e)?l(GN(e.properties)):or(e)?Qe(Oi(e),Sa(hr(e))):xe(e)?y(ic(e.anyOf)):ht(e)?zr(ic(e.items)):e}function KN(e,o){return o in e?Sa(e[o]):Q()}function WS(e){return KN(e.$defs,e.$ref)}function HN(e,o,a){let u=Lo(e,gr([],[]),o),p=nc({},gr([],[]),a);return Nr([...u,l(p)])}function WN(e,o){return be(e).filter((u)=>o.includes(u)).reduce((u,p)=>{let f=e[p],h=Ya(f)?HN(e,f.parameters[0],f.parameters[1]):f;return{...u,[p]:h}},{})}function zS(e,o,a){let u=HS(e,o,a),p=WN(e,u);return Fs(p,o)}function VS(e,o){return o in e?Zt(e[o])?VS(e,e[o].$ref):e[o]:ir()}function Gs(e,o){return VS(e,o)}function JS(e){return cr(e)?WS(e):fm(e)?Q():e}function Nn(e,o,a){let u=JS(o),p=JS(a);return Pt(e,u,p)}var Gu=0,ac=1,Ku=2,Hu=3;function Wa(e,o){let a=[Nn({},e,o),Nn({},o,e)];return Ro(a[0])&&Ro(a[1])?Gu:Ro(a[0])&&Ld(a[1])?Ku:Ld(a[0])&&Ro(a[1])?Hu:ac}function Bd(e,o,a=[],u=o){return bt(o,(p,f)=>{let h=Wa(e,p);return v(h,Ku)||v(h,Gu)?u:v(h,ac)?Bd(e,f,[...a,p],u):Bd(e,f,a,u)},()=>[...a,e])}function zN(e,o,a){let u=Go(e);return Fr(u)?[u]:en(u)?[u]:Po(u)?lp(o,a):Je(u)?lp(o,[...a,u]):lp(o,Bd(u,a))}function lp(e,o=[]){return bt(e,(a,u)=>zN(a,u,o),()=>o)}function gd(e){let o=lp(e);return xa(o)}function Gd(e,o){return Tt(Go(e),{},o)}function QS(e,o,a,u){let p=pe(e,o,a);return Gd(p,u)}function uc(e,o=[]){return ki(e)&&v(e.action,"Conditional")?Zt(e.parameters[0])?uc(e.parameters[2],uc(e.parameters[3],[...o,e.parameters[0].$ref])):uc(e.parameters[2],uc(e.parameters[3],o)):ki(e)&&v(e.action,"Mapped")?ki(e.parameters[1])&&v(e.parameters[1].action,"KeyOf")&&Zt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function VN(e,o){return e.reduce((a,u)=>[...a,o.includes(u.name)],[])}function ZS(e,o,a=[]){return bt(e,(u,p)=>bt(o,(f,h)=>ZS(p,h,[...a,[f,u]]),()=>a),()=>a)}function JN(e){return lr(e)?Bn(e.pattern):rn(e)?Io(e.enum):e}function QN(e){let o=JN(e);return xe(o)?[...o.anyOf]:[o]}function XN(e,o){return e.reduce((a,u)=>[...a,[...u,o]],[])}function XS(e,o){return o.reduce((a,u)=>[...a,...XN(e,u)],[])}function YS(e){return e.reduce((o,a)=>v(a[0],!0)?XS(o,QN(a[1])):XS(o,[a[1]]),[[]])}function ew(e,o,a){let u=uc(a),p=VN(e,u),f=ZS(o,p);return ki(a)&&v(a.action,"Conditional")?YS(f):ki(a)&&v(a.action,"Mapped")?YS(f):[o]}function YN(){return["(not-resolvable)",ir()]}function ZN(){return["(not-generic)",ir()]}function eq(e,o,a){return[e,Ai(o,a)]}function tq(e,o,a){return o in e?tw(e,o,e[o],a):YN()}function tw(e,o,a,u){return Ua(a)?eq(o,a.parameters,a.expression):Zt(a)?tq(e,a.$ref,u):ZN()}function rw(e,o,a){return tw(e,"(anonymous)",o,a)}function rq(e,o,a){if(tn(o)||eu(o)||Ro(Nn({},o,a)))return;let u={parameter:e,expect:a,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function nw(e,o,a,u,p){let f=pe(e,o,p);return rq(a,f,u),ln(e,{[a]:f})}function nq(e,o,a,u,p){let f=pe(e,o,a.extends),h=pe(e,o,a.equals);return bt(p,(g,x)=>Kd(nw(e,o,a.name,f,g),o,u,x),()=>Kd(nw(e,o,a.name,f,h),o,u,[]))}function Kd(e,o,a,u){return bt(a,(p,f)=>nq(e,o,p,f,u),()=>e)}function ow(e,o,a,u){return Kd(e,o,a,u)}var Hd=0,Wd=0;function oq(){if(Mu(Wd,ns().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function sq(){oq(),Wd++,Hd++}function iq(){if(Hd--,v(Hd,0))Wd=0}function aq(e){return sa(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function uq(e,o){return v(aq(e),o)}function cq(e,o,a,u,p,f){sq();try{let h=ow(e,o,u,f),g=pe(h,gr([...o.callstack,a.$ref],o.visited),p);return pe(h,gr([],[]),g)}finally{iq()}}function mq(e,o,a,u,p,f){return f.reduce((h,g)=>{let x=cq(e,o,a,u,p,g);return[...h,x]},[])}function pq(e,o,a,u,p,f){let h=ew(u,f,p),g=mq(e,o,a,u,p,h);return v(g.length,1)?g[0]:To(g)}function dp(e,o,a,u){let p=Lo(e,o,u),f=rw(e,a,u),h=f[0],g=f[1];return Ua(g)?uq(o,h)?Ju(sn(h),p):pq(e,o,sn(h),g.parameters,g.expression,p):Ju(a,p)}function Ju(e,o){return qt({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function sw(e,o){return dp({},gr([],[]),e,o)}function eu(e){return Re(e,"Call")}function lq(e){return ss(e,["~immutable"])}function iw(e,o){return Tt(lq(e),{},o)}function aw(e,o,a,u){let p=pe(e,o,a);return iw(p,u)}function uw(e,o){return e(o)}function cw(e,o){return yt(o)?i(uw(e,o)):i(o)}function mw(e,o){let a=Bn(o);return ni(e,a)}function pw(e,o){let a=o.map((u)=>ni(e,u));return y(a)}function ni(e,o){return It(o)?cw(e,o.const):lr(o)?mw(e,o.pattern):xe(o)?pw(e,o.anyOf):o}function Lm(e,o={}){return Me("Capitalize",[e],o)}function lw(e,o={}){return zd(e,o)}function Nm(e,o={}){return Me("Lowercase",[e],o)}function dw(e,o={}){return Vd(e,o)}function qm(e,o={}){return Me("Uncapitalize",[e],o)}function fw(e,o={}){return Jd(e,o)}function Dm(e,o={}){return Me("Uppercase",[e],o)}function hw(e,o={}){return Qd(e,o)}var dq=(e)=>e[0].toUpperCase()+e.slice(1),fq=(e)=>e.toLowerCase(),hq=(e)=>e[0].toLowerCase()+e.slice(1),gq=(e)=>e.toUpperCase();function zd(e,o){return dt([e])?Tt(ni(dq,e),{},o):Lm(e,o)}function Vd(e,o){return dt([e])?Tt(ni(fq,e),{},o):Nm(e,o)}function Jd(e,o){return dt([e])?Tt(ni(hq,e),{},o):qm(e,o)}function Qd(e,o){return dt([e])?Tt(ni(gq,e),{},o):Dm(e,o)}function gw(e,o,a,u){let p=pe(e,o,a);return zd(p,u)}function yw(e,o,a,u){let p=pe(e,o,a);return Vd(p,u)}function xw(e,o,a,u){let p=pe(e,o,a);return Jd(p,u)}function Iw(e,o,a,u){let p=pe(e,o,a);return Qd(p,u)}function Fm(e,o,a,u,p={}){return Me("Conditional",[e,o,a,u],p)}function Ew(e,o,a,u,p={}){return Xd({},gr([],[]),e,o,a,u,p)}function yq(e,o,a,u,p,f){let h=Nn(e,a,u);return Od(h)?y([pe(h.inferred,o,p),pe(e,o,f)]):_d(h)?pe(h.inferred,o,p):pe(e,o,f)}function Xd(e,o,a,u,p,f,h){return dt([a,u])?Tt(yq(e,o,a,u,p,f),{},h):Fm(a,u,p,f,h)}function bw(e,o,a,u,p,f,h){let g=pe(e,o,a),x=pe(e,o,u);return Xd(e,o,g,x,p,f,h)}function jm(e,o={}){return Me("ConstructorParameters",[e],o)}function Sw(e,o={}){return Yd(e,o)}function xq(e){let o=Yr(e)?e.parameters:[],a=Fi({},gr([],[]),o);return zr(a)}function Yd(e,o){return dt([e])?Tt(xq(e),{},o):jm(e,o)}function ww(e,o,a,u){let p=pe(e,o,a);return Yd(p,u)}function Um(e,o,a={}){return Me("Exclude",[e,o],a)}function Tw(e,o,a={}){return cc(e,o,a)}function cc(e,o,a){return dt([e,o])?Tt(Pm(e,o),{},a):Um(e,o,a)}function Rw(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return cc(f,h,p)}function Bm(e,o,a={}){return Me("Extract",[e,o],a)}function kw(e,o,a={}){return Zd(e,o,a)}function Iq(e,o){let a=Nn({},e,o);return Ro(a)?[e]:[]}function Aw(e,o,a=[]){return bt(e,(u,p)=>Aw(p,o,[...a,...Iq(u,o)]),()=>a)}function Pw(e,o){let a=Go(e),u=xe(a)?a.anyOf:[a],p=Aw(u,o);return To(p)}function Zd(e,o,a){return dt([e,o])?Tt(Pw(e,o),{},a):Bm(e,o,a)}function $w(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return Zd(f,h,p)}function Eq(e){return e.reduce((o,a)=>Em(a)?[...o,i(a)]:o,[])}function tu(e){let o=Eq(e);return y(o)}function Qu(e,o,a={}){return Me("Index",[e,o],a)}function Cw(e,o,a={}){let u=He(o)?tu(o):o;return ef(e,u,a)}function vw(e,o){let a=Gs(e,o);return No(a)}function Mw(e,o,a){let u=fs(e,o,a);return No(u)}function bq(e,o){let a=be(e).filter((E)=>!se(o,E)),u=be(o).filter((E)=>!se(e,E)),p=be(e).filter((E)=>se(o,E)),f=a.reduce((E,k)=>({...E,[k]:e[k]}),{}),h=u.reduce((E,k)=>({...E,[k]:o[k]}),{}),g=p.reduce((E,k)=>({...E,[k]:Nr([e[k],o[k]])}),{}),x=ln(f,h);return ln(x,g)}function Ow(e){return e.reduce((o,a)=>bq(o,No(a)),{})}function _w(e){return e}function Lw(e){let o=wx(zr(e));return No(o)}function Sq(e,o){return be(e).filter((p)=>(p in o)).reduce((p,f)=>({...p,[f]:To([e[f],o[f]])}),{})}function Nw(e,o){return bt(e,(a,u)=>Nw(u,Sq(o,No(a))),()=>o)}function qw(e){return bt(e,(o,a)=>Nw(a,No(o)),()=>Wr())}function No(e){return cr(e)?vw(e.$defs,e.$ref):Hr(e)?Mw(e.if,e.then,e.else):Ve(e)?Ow(e.allOf):xe(e)?qw(e.anyOf):ht(e)?Lw(e.items):Je(e)?_w(e.properties):{}}function ru(e){let o=No(e);return l(o)}var wq=new RegExp("^(?:0|[1-9][0-9]*)$");function nu(e){let o=`${e}`;return wq.test(o)?parseInt(o):e}function Tq(e){return i(nu(e))}function Dw(e){return e.map((o)=>Fw(o))}function Fw(e){return Ve(e)?jn(Dw(e.allOf)):xe(e)?y(Dw(e.anyOf)):It(e)?Tq(e.const):e}function jw(e,o){let a=Fw(o),u=Nn({},a,ne());return Ro(u)?e:It(o)&&v(o.const,"length")?ne():ir()}function Uw(e,o){let a=Gs(e,o);return vo(a)}function Bw(e,o,a){let u=fs(e,o,a);return vo(u)}function Gw(e){let o=Io(e);return vo(o)}function Kw(e){let o=Nr(e);return vo(o)}function Hw(e){return[`${e}`]}function Ww(e){let o=Bn(e);return vo(o)}function zw(e){return e.reduce((o,a)=>[...o,...vo(a)],[])}function vo(e){return cr(e)?Uw(e.$defs,e.$ref):Hr(e)?Bw(e.if,e.then,e.else):rn(e)?Gw(e.enum):Ve(e)?Kw(e.allOf):It(e)?Hw(e.const):lr(e)?Ww(e.pattern):xe(e)?zw(e.anyOf):[]}function ou(e){return vo(e)}function mc(e,o){return o.map((a)=>pc(e,a))}function pc(e,o){return Rt(o)?H(pc(e,o.items)):Yr(o)?Ns(mc(e,o.parameters),pc(e,o.instanceType)):Zr(o)?qs(mc(e,o.parameters),pc(e,o.returnType)):ht(o)?zr(mc(e,o.items)):xe(o)?y(mc(e,o.anyOf)):Ve(o)?jn(mc(e,o.allOf)):Mm(o)?l(e):o}function Vw(e,o){return pc(e,o)}function Rq(e,o){let a=o in e?e[o]:ir();return Vw(e,a)}function Jw(e,o){return o.reduce((a,u)=>[...a,Rq(e,u)],[])}function kq(e,o){let a=ou(o),u=Jw(e,a);return To(u)}var Aq=new RegExp(Mi);function Pq(e){return e.filter((a)=>Aq.test(a))}function $q(e){let o=lm(e),a=Pq(o),u=Jw(e,a);return To(u)}function Qw(e,o){return Lr(o)?$q(e):kq(e,o)}function Cq(e){return i(nu(e))}function Xw(e){return e.map((o)=>tf(o))}function tf(e){return Ve(e)?jn(Xw(e.allOf)):xe(e)?y(Xw(e.anyOf)):It(e)?Cq(e.const):e}function vq(e,o){return e.reduceRight((a,u,p)=>{let f=Nn({},i(p),o);return Ro(f)?[u,...a]:a},[])}function Mq(e,o){let a=tf(o),u=vq(e,a);return Ci(u)}function Oq(e){return Ci(e)}function Yw(e,o){return It(o)&&v(o.const,"length")?i(e.length):Lr(o)||In(o)?Oq(e):Mq(e,o)}function Zw(e,o){return Rt(e)?jw(e.items,o):Je(e)?Qw(e.properties,o):ht(e)?Yw(e.items,o):ir()}function _q(e){return cr(e)||Hr(e)||Ve(e)||xe(e)?ru(e):e}function ef(e,o,a){return dt([e,o])?Tt(Zw(_q(e),o),{},a):Qu(e,o,a)}function eT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return ef(f,h,p)}function Gm(e,o={}){return Me("InstanceType",[e],o)}function tT(e,o={}){return rf(e,o)}function Lq(e){return Yr(e)?e.instanceType:ir()}function rf(e,o){return dt([e])?Tt(Lq(e),{},o):Gm(e,o)}function rT(e,o,a,u={}){let p=pe(e,o,a);return rf(p,u)}function Xu(e,o={}){return Me("KeyOf",[e],o)}function nT(e,o={}){return nf(e,o)}function oT(){return y([ne(),s(),Ha()])}function sT(e){return ne()}function Nq(e){return e.reduce((a,u)=>Em(u)?[...a,i(nu(u))]:Wr(),[])}function iT(e){let o=be(e),a=Nq(o);return Ci(a)}function aT(e){return Oi(e)}function uT(e){let o=e.map((a,u)=>i(u));return Ci(o)}function cT(e){return Fr(e)?oT():Rt(e)?sT(e.items):Je(e)?iT(e.properties):or(e)?aT(e):ht(e)?uT(e.items):ir()}function qq(e){return cr(e)||Hr(e)||Ve(e)||xe(e)?ru(e):e}function nf(e,o){return dt([e])?Tt(cT(qq(e)),{},o):Xu(e,o)}function mT(e,o,a,u){let p=pe(e,o,a);return nf(p,u)}function zu(e,o,a,u,p={}){return Me("Mapped",[e,o,a,u],p)}function pT(e,o,a,u,p={}){return of({},gr([],[]),e,o,a,u,p)}function Dq(e){let o=Bn(e);return fp(o)}function Fq(e){return e.reduce((o,a)=>[...o,...fp(a)],[])}function jq(e){let o=Io(e);return fp(o)}function Uq(e){return Bt(e)?[i(`${e}`)]:[i(e)]}function fp(e){return rn(e)?jq(e.enum):It(e)?Uq(e.const):lr(e)?Dq(e.pattern):xe(e)?Fq(e.anyOf):[e]}function lT(e){return fp(e)}function Bq(e){return lr(e)?Bn(e.pattern):e}function Gq(e,o,a,u,p,f){let h=ln(e,{[a.name]:u}),g=pe(h,o,p),x=Bq(g),I=pe(h,o,f);return bm(x)||Sm(x)?{[x.const]:I}:{}}function Kq(e,o,a,u,p,f){return u.reduce((h,g)=>[...h,Gq(e,o,a,g,p,f)],[])}function Hq(e){return e.reduce((o,a)=>[...o,l(a)],[])}function dT(e,o,a,u,p,f){let h=lT(u),g=Kq(e,o,a,h,p,f),x=Hq(g);return Nr(x)}function of(e,o,a,u,p,f,h){return dt([u])?Tt(dT(e,o,a,u,p,f),{},h):zu(a,u,p,f,h)}function fT(e,o,a,u,p,f,h){let g=pe(e,o,u);return of(e,o,a,g,p,f,h)}function Wq(e,o,a){let u=ln(e,o);return be(o).filter((f)=>a.includes(f)).reduce((f,h)=>({...f,[h]:zS(u,h,o[h])}),{})}function zq(e,o,a){let u=ln(e,o);return be(o).filter((f)=>!a.includes(f)).reduce((f,h)=>({...f,[h]:pe(u,gr([],[]),o[h])}),{})}function Vq(e,o,a){let u=GS(o),p=Wq(e,o,u),f=zq(e,o,u),h={...p,...f};return Tt(h,{},a)}function hp(e,o,a,u){return Vq(e,a,u)}function Km(e,o={}){return Me("NonNullable",[e],o)}function hT(e,o={}){return sf(e,o)}function Jq(e){let o=y([Un(),Va()]);return cc(e,o,{})}function sf(e,o){return dt([e])?Tt(Jq(e),{},o):Km(e,o)}function gT(e,o,a,u){let p=pe(e,o,a);return sf(p,u)}function Hm(e,o,a={}){return Me("Omit",[e,o],a)}function yT(e,o,a={}){let u=He(o)?tu(o):o;return af(e,u,a)}function gp(e){let o=ru(e);return Je(o)?o.properties:Wr()}function Qq(e,o){return be(e).reduce((u,p)=>o.includes(p)?u:{...u,[p]:e[p]},{})}function xT(e,o){let a=gp(e),u=ou(o),p=Qq(a,u);return l(p)}function af(e,o,a){return dt([e,o])?Tt(xT(e,o),{},a):Hm(e,o,a)}function IT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return af(f,h,p)}function Wm(e,o={}){return Me("Parameters",[e],o)}function ET(e,o={}){return uf(e,o)}function Xq(e){let o=Zr(e)?e.parameters:[],a=Fi({},gr([],[]),o);return zr(a)}function uf(e,o){return dt([e])?Tt(Xq(e),{},o):Wm(e,o)}function bT(e,o,a,u){let p=pe(e,o,a);return uf(p,u)}function zm(e,o={}){return Me("Partial",[e],o)}function ST(e,o={}){return cf(e,o)}function wT(e,o){let a=Gs(e,o),u=Ks(a);return Fs(ln(e,{[o]:u}),o)}function TT(e,o,a){let u=fs(e,o,a);return Ks(u)}function RT(e){let o=Nr(e);return Ks(o)}function kT(e){let o=e.map((a)=>Ks(a));return y(o)}function AT(e){let o=be(e).reduce((u,p)=>({...u,[p]:pa(e[p])}),{});return l(o)}function Ks(e){return cr(e)?wT(e.$defs,e.$ref):Hr(e)?TT(e.if,e.then,e.else):Ve(e)?RT(e.allOf):xe(e)?kT(e.anyOf):Je(e)?AT(e.properties):l({})}function cf(e,o){return dt([e])?Tt(Ks(e),{},o):zm(e,o)}function PT(e,o,a,u){let p=pe(e,o,a);return cf(p,u)}function Vm(e,o,a={}){return Me("Pick",[e,o],a)}function $T(e,o,a={}){let u=He(o)?tu(o):o;return mf(e,u,a)}function Yq(e,o){return be(e).reduce((u,p)=>o.includes(p)?ln(u,{[p]:e[p]}):u,{})}function CT(e,o){let a=gp(e),u=ou(o),p=Yq(a,u);return l(p)}function mf(e,o,a){return dt([e,o])?Tt(CT(e,o),{},a):Vm(e,o,a)}function vT(e,o,a,u,p){let f=pe(e,o,a),h=pe(e,o,u);return mf(f,h,p)}function Jm(e,o={}){return Me("ReadonlyObject",[e],o)}function pf(e,o={}){return lf(e,o)}var MT=pf;function OT(e){return Ka(H(e))}function _T(e,o){let a=Gs(e,o),u=Hs(a);return Fs(ln(e,{[o]:u}),o)}function LT(e,o,a){let u=fs(e,o,a);return Hs(u)}function NT(e){let o=Nr(e);return Hs(o)}function qT(e){let o=be(e).reduce((u,p)=>({...u,[p]:ha(e[p])}),{});return l(o)}function DT(e){return Ka(zr(e))}function FT(e){let o=e.map((a)=>Hs(a));return y(o)}function Hs(e){return Rt(e)?OT(e.items):cr(e)?_T(e.$defs,e.$ref):Hr(e)?LT(e.if,e.then,e.else):Ve(e)?NT(e.allOf):Je(e)?qT(e.properties):ht(e)?DT(e.items):xe(e)?FT(e.anyOf):e}function lf(e,o){return dt([e])?Tt(Hs(e),{},o):Jm(e)}function jT(e,o,a,u){let p=pe(e,o,a);return lf(p,u)}function UT(e,o,a,u){return o.visited.includes(u)?a:(u in e)?pe(e,gr(o.callstack,[...o.visited,u]),e[u]):a}function BT(e,o){let a=Gs(e,o),u=Ws(a);return Fs(ln(e,{[o]:u}),o)}function GT(e,o,a){let u=fs(e,o,a);return Ws(u)}function KT(e){let o=Nr(e);return Ws(o)}function HT(e){let o=e.map((a)=>Ws(a));return y(o)}function WT(e){let o=be(e).reduce((u,p)=>({...u,[p]:Am(e[p])}),{});return l(o)}function Ws(e){return cr(e)?BT(e.$defs,e.$ref):Hr(e)?GT(e.if,e.then,e.else):Ve(e)?KT(e.allOf):xe(e)?HT(e.anyOf):Je(e)?WT(e.properties):l({})}function Qm(e,o={}){return Me("Required",[e],o)}function zT(e,o={}){return df(e,o)}function df(e,o){return dt([e])?Tt(Ws(e),{},o):Qm(e,o)}function VT(e,o,a,u){let p=pe(e,o,a);return df(p,u)}function Xm(e,o={}){return Me("ReturnType",[e],o)}function JT(e,o={}){return ff(e,o)}function Zq(e){return Zr(e)?e.returnType:ir()}function ff(e,o){return dt([e])?Tt(Zq(e),{},o):Xm(e,o)}function QT(e,o,a,u={}){let p=pe(e,o,a);return ff(p,u)}function Ym(e,o){return Me("With",[e,o],{})}function yp(e,o){return hf(e,o)}function hf(e,o){return dt([e])?Tt(e,{},o):Ym(e,o)}function XT(e,o,a,u){let p=pe(e,o,a);return hf(p,u)}function eD(e){return _i(e)?ht(e.items)?gf(e.items.items):tn(e.items)?[e]:Zt(e.items)?[e]:[ir()]:[e]}function gf(e){return e.reduce((a,u)=>[...a,...eD(u)],[])}function gr(e,o){return{callstack:e,visited:o}}function dt(e){return bt(e,(o,a)=>Zt(o)?!1:dt(a),()=>!0)}function nc(e,o,a){return be(a).reduce((u,p)=>({...u,[p]:pe(e,o,a[p])}),{})}function Fi(e,o,a){let u=Lo(e,o,a);return gf(u)}function Lo(e,o,a){return a.map((u)=>pe(e,o,u))}function tD(e,o){let a=an(e)?qu(o,{}):o,u=ga(e)?Nu(a,{}):a;return fa(e)?lc(u,{}):u}function rD(e,o,a,u,p){return v(a,"AddImmutable")?YT(e,o,u[0],p):v(a,"RemoveImmutable")?aw(e,o,u[0],p):v(a,"AddReadonly")?Ry(e,o,u[0],p):v(a,"RemoveReadonly")?xx(e,o,u[0],p):v(a,"AddOptional")?ky(e,o,u[0],p):v(a,"RemoveOptional")?bx(e,o,u[0],p):v(a,"Capitalize")?gw(e,o,u[0],p):v(a,"Conditional")?bw(e,o,u[0],u[1],u[2],u[3],p):v(a,"ConstructorParameters")?ww(e,o,u[0],p):v(a,"Evaluate")?QS(e,o,u[0],p):v(a,"Exclude")?Rw(e,o,u[0],u[1],p):v(a,"Extract")?$w(e,o,u[0],u[1],p):v(a,"Index")?eT(e,o,u[0],u[1],p):v(a,"InstanceType")?rT(e,o,u[0],p):v(a,"Interface")?FS(e,o,u[0],u[1],p):v(a,"KeyOf")?mT(e,o,u[0],p):v(a,"Lowercase")?yw(e,o,u[0],p):v(a,"Mapped")?fT(e,o,u[0],u[1],u[2],u[3],p):v(a,"Module")?hp(e,o,u[0],p):v(a,"NonNullable")?gT(e,o,u[0],p):v(a,"Pick")?vT(e,o,u[0],u[1],p):v(a,"Parameters")?bT(e,o,u[0],p):v(a,"Partial")?PT(e,o,u[0],p):v(a,"Omit")?IT(e,o,u[0],u[1],p):v(a,"ReadonlyObject")?jT(e,o,u[0],p):v(a,"Record")?Dx(e,o,u[0],u[1],p):v(a,"Required")?VT(e,o,u[0],p):v(a,"ReturnType")?QT(e,o,u[0],p):v(a,"TemplateLiteral")?sS(e,o,u[0],p):v(a,"Uncapitalize")?xw(e,o,u[0],p):v(a,"Uppercase")?Iw(e,o,u[0],p):v(a,"With")?XT(e,o,u[0],u[1]):Me(a,u,p)}function nD(e,o,a){let u=Zt(a)?UT(e,o,a,a.$ref):Rt(a)?H(pe(e,o,a.items),ja(a)):eu(a)?dp(e,o,a.target,a.arguments):Yr(a)?Ns(Lo(e,o,a.parameters),pe(e,o,a.instanceType),Ay(a)):Zr(a)?qs(Lo(e,o,a.parameters),pe(e,o,a.returnType),Py(a)):Hr(a)?la(pe(e,o,a.if),pe(e,o,a.then),pe(e,o,a.else),My(a)):Ve(a)?jn(Lo(e,o,a.allOf),qy(a)):Je(a)?l(nc(e,o,a.properties),vy(a)):or(a)?Fx(Sn(a),pe(e,o,hr(a))):_i(a)?Ia(pe(e,o,a.items)):ht(a)?zr(Fi(e,o,a.items),yx(a)):xe(a)?y(Lo(e,o,a.anyOf),ax(a)):a;return tD(a,u)}function pe(e,o,a){return ki(a)?rD(e,o,a.action,a.parameters,a.options):nD(e,o,a)}function Ho(e,o){return pe(e,gr([],[]),o)}function oD(e){return Tt(e,{"~immutable":!0},{})}function lc(e,o){return Tt(oD(e),{},o)}function YT(e,o,a,u){let p=pe(e,o,a);return lc(p,u)}function tb(e,o={}){return Me("AddImmutable",[e],o)}function Ka(e,o={}){return lc(e,o)}function rb(e,o={}){return Me("Evaluate",[e],o)}function qn(e,o={}){return Gd(e,o)}function nb(e,o={}){return Me("Module",[e],o)}function ZT(e,o={}){return hp({},gr([],[]),e,o)}function sD(e,o){let a=Wa(e,o);return v(a,Hu)?1:v(a,ac)?1:0}function eR(e,o,a=[]){return bt(o,(u,p)=>v(sD(e,u),1)?eR(e,p,[...a,u]):[...a,e,...o],()=>[...a,e])}function tR(e,o=[]){return bt(e,(a,u)=>tR(u,eR(a,o)),()=>o)}function rR(e){return tR(e)}function nR(...e){let[o,a,u]=Ln(e,{2:(h,g)=>yt(h)?[{},h,g]:[h,g,{}],3:(h,g,x)=>[h,g,x],1:(h)=>[{},h,{}]}),p=eS(a),f=He(p)&&v(p.length,2)?pe(o,gr([],[]),p[0]):ir();return Tt(f,{},u)}function iD(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function aD(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function uD(e){return{type:"toolCall",id:e.id,name:e.name,arguments:structuredClone(e.arguments),...e.thoughtSignature===void 0?{}:{thoughtSignature:e.thoughtSignature},...e.namespace===void 0?{}:{namespace:e.namespace}}}function cD(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function dc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function su(e){dc(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function xf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var mD=xf(z(""));function If(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,p)=>If(u,o[p]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let a=o;return Object.entries(e).every(([u,p])=>Object.hasOwn(a,u)&&If(p,a[u]))}class oR{started=!1;terminal=!1;blocks=new Map;encode(e){if(this.terminal)throw Error(`Assistant message event ${e.type} follows a terminal event`);switch(e.type){case"start":if(this.started)throw Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:cD(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=su(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:iD(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=su(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=su(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:aD(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=su(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=su(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let a=xf(o.arguments),u=a===mD;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":a}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:uD(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let a=z(o.catchupJson);if(xf(a)!==o.snapshotArguments){let p=z(o.snapshotArguments);if(!If(p,a))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=su(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(dc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){dc(e);let a=this.blocks.get(e);if(a===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(a.kind!==o)throw Error(`Assistant message block ${e} is ${a.kind}, not ${o}`);return a}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,a){let u=this.block(e,a);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let p=u.deltaChars;u.deltaChars+=o.length;let f=Math.max(0,u.coveredChars-p);if(f>=o.length)return;let h=f===0?o:o.slice(f);return a==="text"?{type:"text_delta",contentIndex:e,delta:h}:{type:"thinking_delta",contentIndex:e,delta:h}}}function yf(e,o,a,u,p){if(dc(a),a!==e.content.length){let f=a<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${a}: ${f}`)}e.content.push(structuredClone(u)),o.set(a,p)}function wa(e,o,a,u,p){dc(a);let f=o.get(a),h=e.content[a];if(!f||!h)throw Error(`${p} frame has no started block at index ${a}`);if(f.kind!==u||h.type!==u)throw Error(`${p} frame expected ${u} block at index ${a}, found ${h.type}`);if(f.ended)throw Error(`${p} frame follows the end of block at index ${a}`);return{block:h,state:f}}function pD(e){let o,a,u=new Map;for(let p of e){if(p.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(a!==void 0)throw Error(`${a} frame appears before the start frame`);o=structuredClone(p.partial);continue}if(!o){a??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);yf(o,u,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:f}=wa(o,u,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");f.text+=p.delta;break}case"text_end":{let{block:f,state:h}=wa(o,u,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");if(f.text=p.content,delete f.textSignature,p.textSignature!==void 0)f.textSignature=p.textSignature;h.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);yf(o,u,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:f}=wa(o,u,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");f.thinking+=p.delta;break}case"thinking_end":{let{block:f,state:h}=wa(o,u,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");if(f.thinking=p.content,delete f.thinkingSignature,delete f.redacted,p.thinkingSignature!==void 0)f.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)f.redacted=p.redacted;h.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);yf(o,u,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:f,state:h}=wa(o,u,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||h.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");h.json=p.json,f.arguments=z(p.json);break}case"toolcall_delta":{let{block:f,state:h}=wa(o,u,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||h.kind!=="toolCall")throw Error("Unreachable tool-call frame state");h.json+=p.delta;break}case"toolcall_end":{let{block:f,state:h}=wa(o,u,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(f.id=p.id,f.name=p.name,f.arguments=structuredClone(p.arguments),delete f.thoughtSignature,delete f.namespace,p.thoughtSignature!==void 0)f.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)f.namespace=p.namespace;h.ended=!0;break}}}if(!o)return;for(let[p,f]of u){if(f.kind!=="toolCall"||f.ended||f.json.length===0)continue;let h=o.content[p];if(h?.type!=="toolCall")throw Error("Unreachable tool-call frame state");h.arguments=z(f.json)}return o}var sR=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],lD=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,dD=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Ta(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!dD.some((u)=>u.test(e.errorMessage))){if(sR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&lD.test(e.errorMessage))return!0}}if(o&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>o)return!0}if(o&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=o*0.99)return!0}return!1}function fD(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function hD(){return[...sR]}function iR(e){return new RegExp(e.join("|"),"i")}var gD=iR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),yD=iR(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),aR=60000;function uR(e,o){let a=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??aR)}class xp extends Error{constructor(){super("Aborted")}}function xD(e,o){return new Promise((a,u)=>{if(o?.aborted){u(new xp);return}let p=setTimeout(a,e);o?.addEventListener("abort",()=>{clearTimeout(p),u(new xp)},{once:!0})})}async function ID(e,o,a,u){let p=o?.enabled?o.maxRetries:0,f=0,h;for(;;){let g=await e();if(g.stopReason==="aborted"){if(h)await u?.onRetryFinished?.(!1,h.attempt);return g}if(g.stopReason!=="error"){if(h)await u?.onRetryFinished?.(!0,h.attempt);return g}if(f>=p||!cR(g)){if(h)await u?.onRetryFinished?.(!1,h.attempt,g.errorMessage);return g}f++,h={attempt:f,errorMessage:g.errorMessage||"Unknown error"};let x=uR(o,f);await u?.onRetryScheduled?.(f,p,x,h.errorMessage);try{await xD(x,a)}catch(I){if(await u?.onRetryFinished?.(!1,f,h.errorMessage),I instanceof xp){let{errorMessage:E,...k}=g;return{...k,stopReason:"aborted"}}throw I}await u?.onRetryAttemptStart?.()}}function cR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(gD.test(o))return!1;return yD.test(o)}function ED(e,o){return vr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function fc(e){return se(e,"~refine")&&He(e["~refine"])&&on(e["~refine"],0,(o)=>lt(o)&&se(o,"check")&&se(o,"error")&&Os(o.check)&&Os(o.error))}function Tn(e){return lt(e)&&!He(e)}function ii(e){return cn(e)}function Ye(e){return Tn(e)||ii(e)}function iu(e){return se(e,"additionalItems")&&Ye(e.additionalItems)}function Wo(e){return se(e,"additionalProperties")&&Ye(e.additionalProperties)}function hc(e){return se(e,"allOf")&&He(e.allOf)&&e.allOf.every((o)=>Ye(o))}function gc(e){return se(e,"$anchor")&&yt(e.$anchor)}function yc(e){return se(e,"anyOf")&&He(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function Ip(e){return se(e,"const")}function zs(e){return se(e,"contains")&&Ye(e.contains)}function qo(e){return se(e,"default")}function xc(e){return se(e,"dependencies")&<(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||He(o)&&o.every((a)=>yt(a)))}function Ic(e){return se(e,"dependentRequired")&<(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>He(o)&&o.every((a)=>yt(a)))}function au(e){return se(e,"dependentSchemas")&<(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function mi(e){return se(e,"$dynamicAnchor")&&yt(e.$dynamicAnchor)}function Ec(e){return se(e,"$dynamicRef")&&yt(e.$dynamicRef)}function bc(e){return se(e,"else")&&Ye(e.else)}function Ep(e){return se(e,"enum")&&He(e.enum)}function Sc(e){return se(e,"exclusiveMaximum")&&(Bt(e.exclusiveMaximum)||Kr(e.exclusiveMaximum))}function ys(e){return se(e,"exclusiveMinimum")&&(Bt(e.exclusiveMinimum)||Kr(e.exclusiveMinimum))}function Ra(e){return se(e,"format")&&yt(e.format)}function Do(e){return se(e,"$id")&&yt(e.$id)}function wc(e){return se(e,"if")&&Ye(e.if)}function pi(e){return se(e,"items")&&(Ye(e.items)||He(e.items)&&e.items.every((o)=>Ye(o)))}function Tc(e){return pi(e)&&He(e.items)}function Rc(e){return se(e,"maximum")&&(Bt(e.maximum)||Kr(e.maximum))}function kc(e){return se(e,"maxContains")&&Bt(e.maxContains)}function uu(e){return se(e,"maxItems")&&Bt(e.maxItems)}function Ac(e){return se(e,"maxLength")&&Bt(e.maxLength)}function Pc(e){return se(e,"maxProperties")&&Bt(e.maxProperties)}function xs(e){return se(e,"minimum")&&(Bt(e.minimum)||Kr(e.minimum))}function di(e){return se(e,"minContains")&&Bt(e.minContains)}function ji(e){return se(e,"minItems")&&Bt(e.minItems)}function ka(e){return se(e,"minLength")&&Bt(e.minLength)}function Aa(e){return se(e,"minProperties")&&Bt(e.minProperties)}function $c(e){return se(e,"multipleOf")&&(Bt(e.multipleOf)||Kr(e.multipleOf))}function Cc(e){return se(e,"not")&&Ye(e.not)}function vc(e){return se(e,"oneOf")&&He(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function Pa(e){return se(e,"pattern")&&(yt(e.pattern)||e.pattern instanceof RegExp)}function fi(e){return se(e,"patternProperties")&<(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function Is(e){return se(e,"prefixItems")&&He(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function hi(e){return se(e,"properties")&<(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function cu(e){return se(e,"propertyNames")&&(lt(e.propertyNames)||Ye(e.propertyNames))}function bD(e){return se(e,"$recursiveAnchor")&&cn(e.$recursiveAnchor)}function Mc(e){return bD(e)&&v(e.$recursiveAnchor,!0)}function Oc(e){return se(e,"$recursiveRef")&&yt(e.$recursiveRef)}function _c(e){return se(e,"$ref")&&yt(e.$ref)}function Ss(e){return se(e,"required")&&He(e.required)&&e.required.every((o)=>yt(o))}function Lc(e){return se(e,"then")&&Ye(e.then)}function Nc(e){return se(e,"type")&&(yt(e.type)||He(e.type)&&e.type.every((o)=>yt(o)))}function Ui(e){return se(e,"uniqueItems")&&cn(e.uniqueItems)}function Bi(e){return se(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function zi(e){return se(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function SD(e){return Bi(e)||zi(e)||qa(be(e),(o)=>bp(e[o]))}function wD(e){return qa(e,(o)=>bp(o))}function bp(e){return He(e)?wD(e):lt(e)?SD(e):!1}function mR(e,o){return bp(o)||qa(be(e),(a)=>bp(e[a]))}class Ef{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Sr(St("context","Push"),[])}Pop(){return Sr(St("context","Pop"),[])}AddIndex(e){return Sr(St("context","AddIndex"),[e])}AddKey(e){return Sr(St("context","AddKey"),[e])}Merge(e){return Sr(St("context","Merge"),[e])}}class Kn{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((a)=>this.GetIndices().add(a)),o.GetKeys().forEach((a)=>this.GetKeys().add(a));return!0}}class Hn extends Kn{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=ns().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var Sp={identifier:"External",variables:[]};function zo(e){let o=`External[${Sp.variables.length}]`;return Sp.variables.push(e),o}function pR(){Sp.variables=[]}function lR(){return{...Sp}}function dR(e,o,a,u){let p=zo(a["~refine"].map((f)=>f));return Ls(p,je(0),["refinement","_"],Sr(St("refinement","check"),[u]))}function fR(e,o,a,u){return on(a["~refine"],0,(p,f)=>p.check(u))}function hR(e,o,a,u,p,f){return Dn(p["~refine"],0,(h,g)=>h.check(f)||o.AddError({keyword:"~refine",schemaPath:a,instancePath:u,params:{index:g,message:h.error(f)}}))}var TD=0;function ar(){return`var_${TD++}`}function bf(e){return pi(e)&&He(e.items)}function RD(e,o,a,u){let[p,f]=[ar(),ar()],h=Eo(e,o,a.additionalItems,p),g=sd(f,je(a.items.length)),x=o.AddIndex(f);return Ls(u,je(0),[p,f],br(g,On(h,x)))}function kD(e,o,a,u){let[p,f]=[ar(),ar()],h=Eo(e,o,a.additionalItems,p),g=sd(f,je(a.items.length));return Ls(u,je(0),[p,f],br(g,h))}function gR(e,o,a,u){if(!bf(a))return je(!0);return o.UseUnevaluated()?RD(e,o,a,u):kD(e,o,a,u)}function yR(e,o,a,u){if(!bf(a))return!0;return on(u,0,(f,h)=>Mu(h,a.items.length)||Fo(e,o,a.additionalItems,f)&&o.AddIndex(h))}function xR(e,o,a,u,p,f){if(!bf(p))return!0;return on(f,0,(g,x)=>{let I=`${a}/additionalItems`,E=`${u}/${x}`;return Mu(x,p.items.length)||jo(e,o,I,E,p.additionalItems,g)&&o.AddIndex(x)})}function ws(e){return new RegExp(e,"u")}function AD(e,o){return!e.UseUnevaluated()&&(v(o,!0)||lt(o)&&v(be(o).length,0))}function PD(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Sf(e){let o=[];if(fi(e))o.push(...be(e.patternProperties));if(hi(e))o.push(...be(e.properties).map(PD));return v(o.length,0)?"(?!)":`(${o.join("|")})`}function $D(e,o,a){return Ss(o)&&hi(o)&&!fi(o)&&v(o.additionalProperties,!1)&&v(be(o.properties).length,o.required.length)}function CD(e,o,a){return Ao(St(Sr(St("Object","getOwnPropertyNames"),[a]),"length"),je(o.required.length))}function vD(e,o,a,u){let[p,f]=[ar(),ar()],h=zo(ws(Sf(a))),g=Eo(e,o,a.additionalProperties,`${u}[${p}]`),x=Sr(St(h,"test"),[p]),I=o.AddKey(p),E=o.UseUnevaluated()?br(x,On(g,I)):br(x,g);return Ls(ua(u),je(0),[p,f],E)}function IR(e,o,a,u){if(AD(o,a.additionalProperties))return je(!0);return $D(o,a,u)?CD(o,a,u):vD(e,o,a,u)}function ER(e,o,a,u){let p=ws(Sf(a));return on(be(u),0,(h,g)=>p.test(h)||Fo(e,o,a.additionalProperties,u[h])&&o.AddKey(h))}function bR(e,o,a,u,p,f){let h=ws(Sf(p)),g=[];return Dn(be(f),0,(I,E)=>{let k=`${a}/additionalProperties`,A=`${u}/${I}`,P=h.test(I)||jo(e,o,k,A,p.additionalProperties,f[I])&&o.AddKey(I);if(!P)g.push(I);return P})||o.AddError({keyword:"additionalProperties",schemaPath:a,instancePath:u,params:{additionalProperties:g}})}function Vi(e,o,a,u,p){let f=Zs("results","[]"),h=a.map((E,k)=>Zs(`context_${k}`,id("CheckContext",[]))),g=a.map((E,k)=>Zs(`condition_${k}`,Sr(Ti(["context"],Ht(e,o,E,u)),[`context_${k}`]))),x=a.map((E,k)=>by(`condition_${k}`,Sr(St("results","push"),[`context_${k}`]))),I=pm(On(p,o.Merge("results")));return Sr(Ti([],mm([f,...h,...g,...x,I])),[])}function MD(e,o,a,u){return Vi(e,o,a.allOf,u,Ao(St("results","length"),je(a.allOf.length)))}function OD(e,o,a,u){return Fn(a.allOf.map((p)=>Ht(e,o,p,u)))}function SR(e,o,a,u){return o.UseUnevaluated()?MD(e,o,a,u):OD(e,o,a,u)}function wR(e,o,a,u){let p=a.allOf.reduce((f,h)=>{let g=new Kn;return $t(e,g,h,u)?[...f,g]:f},[]);return v(p.length,a.allOf.length)&&o.Merge(p)}function TR(e,o,a,u,p,f){let h=[],g=p.allOf.reduce((I,E,k)=>{let A=`${a}/allOf/${k}`,P=new Hn,C=dr(e,P,A,u,E,f);if(!C)h.push(P);return C?[...I,P]:I},[]),x=v(g.length,p.allOf.length)&&o.Merge(g);if(!x)h.forEach((I)=>I.GetErrors().forEach((E)=>o.AddError(E)));return x}function _D(e,o,a,u){return Vi(e,o,a.anyOf,u,xy(St("results","length"),je(0)))}function LD(e,o,a,u){return ad(a.anyOf.map((p)=>Ht(e,o,p,u)))}function RR(e,o,a,u){return o.UseUnevaluated()?_D(e,o,a,u):LD(e,o,a,u)}function kR(e,o,a,u){let p=a.anyOf.reduce((f,h)=>{let g=new Kn;return $t(e,g,h,u)?[...f,g]:f},[]);return sa(p.length,0)&&o.Merge(p)}function AR(e,o,a,u,p,f){let h=[],g=p.anyOf.reduce((I,E,k)=>{let A=new Hn,P=`${a}/anyOf/${k}`,C=dr(e,A,P,u,E,f);if(!C)h.push(A);return C?[...I,A]:I},[]),x=sa(g.length,0)&&o.Merge(g);if(!x)h.forEach((I)=>I.GetErrors().forEach((E)=>o.AddError(E)));return x||o.AddError({keyword:"anyOf",schemaPath:a,instancePath:u,params:{}})}function PR(e,o,a,u){return a?je(!0):je(!1)}function wf(e,o,a,u){return a}function $R(e,o,a,u,p,f){return wf(e,o,p,f)||o.AddError({keyword:"boolean",schemaPath:a,instancePath:u,params:{}})}function CR(e,o,a,u){return ia(a.const)?Ao(u,je(a.const)):Ey(u,zo(a.const))}function Tf(e,o,a,u){return ia(a.const)?v(u,a.const):Da(u,a.const)}function vR(e,o,a,u,p,f){return Tf(e,o,p,f)||o.AddError({keyword:"const",schemaPath:a,instancePath:u,params:{allowedValue:p.const}})}function MR(e){return!(di(e)&&v(e.minContains,0))}function ND(e,o,a,u){let[p,f]=[ar(),ar()],h=zn(Ao(St(u,"length"),je(0))),g=kM(u,[p,f],On(Ht(e,o,a.contains,p),o.AddIndex(f)));return On(h,g)}function qD(e,o,a,u){let[p]=[ar()],f=zn(Ao(St(u,"length"),je(0))),h=RM(u,[p,"_"],Ht(e,o,a.contains,p));return On(f,h)}function OR(e,o,a,u){if(!MR(a))return je(!0);return o.UseUnevaluated()?ND(e,o,a,u):qD(e,o,a,u)}function Rf(e,o,a,u){if(!MR(a))return!0;return!v(u.length,0)&&py(u,(p,f)=>$t(e,o,a.contains,p)&&o.AddIndex(f))}function _R(e,o,a,u,p,f){return Rf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:1}})}function LR(e,o,a,u){let p=Ao(St(ua(u),"length"),je(0)),f=Fn(pn(a.dependencies).map(([h,g])=>{let x=zn(ca(u,je(h))),I=Ht(e,o,g,u),E=(k)=>Fn(k.map((A)=>ca(u,je(A))));return br(x,He(g)?E(g):I)}));return br(p,f)}function NR(e,o,a,u){let p=v(be(u).length,0),f=on(pn(a.dependencies),0,([h,g])=>!se(u,h)||(He(g)?g.every((x)=>se(u,x)):$t(e,o,g,u)));return p||f}function qR(e,o,a,u,p,f){let h=v(be(f).length,0),g=Dn(pn(p.dependencies),0,([x,I])=>{let E=`${a}/dependencies/${x}`;return!se(f,x)||(He(I)?I.every((k)=>se(f,k)||o.AddError({keyword:"dependencies",schemaPath:a,instancePath:u,params:{property:x,dependencies:I}})):dr(e,o,E,u,I,f))});return h||g}function DR(e,o,a,u){let p=Ao(St(ua(u),"length"),je(0)),f=Fn(pn(a.dependentRequired).map(([h,g])=>{let x=zn(ca(u,je(h))),I=Fn(g.map((E)=>ca(u,je(E))));return br(x,I)}));return br(p,f)}function FR(e,o,a,u){let p=v(be(u).length,0),f=on(pn(a.dependentRequired),0,([h,g])=>!se(u,h)||g.every((x)=>se(u,x)));return p||f}function jR(e,o,a,u,p,f){let h=v(be(f).length,0),g=Dn(pn(p.dependentRequired),0,([x,I])=>!se(f,x)||Dn(I,0,(E)=>se(f,E)||o.AddError({keyword:"dependentRequired",schemaPath:a,instancePath:u,params:{property:x,dependencies:I}})));return h||g}function UR(e,o,a,u){let p=Ao(St(ua(u),"length"),je(0)),f=Fn(pn(a.dependentSchemas).map(([h,g])=>{let x=zn(ca(u,je(h))),I=Ht(e,o,g,u);return br(x,I)}));return br(p,f)}function BR(e,o,a,u){let p=v(be(u).length,0),f=on(pn(a.dependentSchemas),0,([h,g])=>!se(u,h)||$t(e,o,g,u));return p||f}function GR(e,o,a,u,p,f){let h=v(be(f).length,0),g=Dn(pn(p.dependentSchemas),0,([x,I])=>{let E=`${a}/dependentSchemas/${x}`;return!se(f,x)||dr(e,o,E,u,I,f)});return h||g}function KR(e,o,a,u){let p=e.DynamicRef(a)??!1;return gi(e,o,p,u)}function HR(e,o,a,u){let p=e.DynamicRef(a)??!1;return Ye(p)&&$t(e,o,p,u)}function WR(e,o,a,u,p,f){let h=e.DynamicRef(p)??!1;return Ye(h)&&dr(e,o,"#",u,h,f)}function zR(e,o,a,u){return ad(a.enum.map((p)=>{if(ia(p))return Ao(u,je(p));let f=zo(p);return Ey(u,f)}))}function Af(e,o,a,u){return qa(a.enum,(p)=>ia(p)?v(u,p):Da(u,p))}function VR(e,o,a,u,p,f){return Af(e,o,p,f)||o.AddError({keyword:"enum",schemaPath:a,instancePath:u,params:{allowedValues:p.enum}})}function JR(e,o,a,u){return sd(u,je(a.exclusiveMaximum))}function Pf(e,o,a,u){return Mu(u,a.exclusiveMaximum)}function QR(e,o,a,u,p,f){return Pf(e,o,p,f)||o.AddError({keyword:"exclusiveMaximum",schemaPath:a,instancePath:u,params:{comparison:"<",limit:p.exclusiveMaximum}})}function XR(e,o,a,u){return xy(u,je(a.exclusiveMinimum))}function $f(e,o,a,u){return sa(u,a.exclusiveMinimum)}function YR(e,o,a,u,p,f){return $f(e,o,p,f)||o.AddError({keyword:"exclusiveMinimum",schemaPath:a,instancePath:u,params:{comparison:">",limit:p.exclusiveMinimum}})}var DD=[0,31,28,31,30,31,30,31,31,30,31,30,31],FD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function jD(e){return e%4===0&&(e%100!==0||e%400===0)}function pu(e){let o=FD.exec(e);if(!o)return!1;let a=+o[1],u=+o[2],p=+o[3];return u>=1&&u<=12&&p>=1&&p<=(u===2&&jD(a)?29:DD[u])}var UD=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function lu(e,o=!0){let a=UD.exec(e);if(!a)return!1;if(o&&!a[4]&&!a[5])return!1;let u=+a[1],p=+a[2],f=+a[3];if(u>23||p>59||f>60)return!1;if(a[5]){let E=+a[6],k=+a[7];if(E>23||k>59)return!1}if(f<60)return!0;let h=a[5]==="-"?-1:1,g=+(a[6]||0),x=+(a[7]||0);return((u*60+p-h*(g*60+x))%1440+1440)%1440===1439}function wp(e){let o=e.split(/T/i);return o.length===2&&pu(o[0])&&lu(o[1])}var BD=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Tp(e){return BD.test(e)}var GD=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function Rp(e){return GD.test(e)}var ZR=/^(?!-).*(?<!-)$/,ek=/^(?!..--)/,tk=/^[a-zA-Z0-9-]*$/;var du=/[^\p{ASCII}]/u;var KD=/[0-9]/,rk=/[\u{0660}-\u{0669}]/u,HD=/[\u{06f0}-\u{06f9}]/u,WD=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,zD=/[\u{002d}\u{002b}]/u,Cf=/\p{Mn}/u,VD=/\p{Mc}/u;var nk=/[\p{Mn}\p{Mc}\p{Me}]/u,vf=/\p{L}/u,JD=/\p{Nd}/u,ok=/\p{Script=Greek}/u,kp=/\p{Script=Hebrew}/u,sk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,ik=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Mf=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,ak=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,QD=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,XD=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,uk=new RegExp([KD,HD].map((e)=>e.source).join("|"),"u"),ck=new RegExp([vf,zD,WD,JD,Cf,VD,QD,XD].map((e)=>e.source).join("|"),"u");function mk(e){return ZR.test(e)&&ek.test(e)&&tk.test(e)}var Rs=36,Dc=1,Fc=26,ZD=38,eF=700,lk=72,dk=128;function Of(){throw null}function Ap(e){return e.toLowerCase().startsWith("xn--")}function fk(e,o,a){e=a?Math.floor(e/eF):e>>1,e+=Math.floor(e/o);let u=0;while(e>(Rs-Dc)*Fc>>1)e=Math.floor(e/(Rs-Dc)),u+=Rs;return u+Math.floor((Rs-Dc+1)*e/(e+ZD))}function Pp(e){let o=[],a=dk,u=0,p=lk,f=e.lastIndexOf("-");if(f>0)for(let g=0;g<f;g++){let x=e.charCodeAt(g);if(x>=128)Of();o.push(x)}let h=f<0?0:f+1;while(h<e.length){let g=u,x=1,I=Rs;while(!0){if(h>=e.length)Of();let k=e.charCodeAt(h++),A;if(k>=97&&k<=122)A=k-97;else if(k>=48&&k<=57)A=k-48+26;else Of();u+=A*x;let P=I<=p?Dc:I>=p+Fc?Fc:I-p;if(A<P)break;x*=Rs-P,I+=Rs}let E=o.length+1;p=fk(u-g,E,g===0),a+=Math.floor(u/E),u%=E,o.splice(u,0,a),u++}return String.fromCodePoint(...o)}function pk(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var tF=new RegExp(du.source,"gu");function hk(e){let o=e.replace(tF,""),a=o.length,u=a>0?[o,"-"]:[],p=Array.from(e,(I)=>I.codePointAt(0)),f=dk,h=0,g=lk,x=a;while(x<p.length){let I=1/0;for(let E of p)if(E>=f&&E<I)I=E;h+=(I-f)*(x+1),f=I;for(let E of p){if(E<f)h++;if(E===f){let k=h;for(let A=Rs;;A+=Rs){let P=A<=g?Dc:A>=g+Fc?Fc:A-g;if(k<P)break;let C=P+(k-P)%(Rs-P);u.push(pk(C)),k=Math.floor((k-P)/(Rs-P))}u.push(pk(k)),g=fk(h,x+1,x===a),h=0,x++}}h++,f++}return u.join("")}var rF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,gk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,nF=/^(?:R|AL|AN)$/;function yk(e){if(Ap(e))try{return $p(Pp(e.slice(4).toLowerCase()))}catch{return!1}return $p(e)}function xk(e){let o=String.fromCodePoint(e);return uk.test(o)?"EN":rk.test(o)?"AN":Cf.test(o)?"NSM":kp.test(o)?"R":ik.test(o)?"AL":vf.test(o)?"L":"ON"}function $p(e){for(let o of e)if(nF.test(xk(o.codePointAt(0))))return!0;return!1}function Cp(e){let o=!1,a=gk,u=!1,p=!1,f=!0;for(let h of e){let g=xk(h.codePointAt(0));if(f){if(g!=="L"&&g!=="R"&&g!=="AL")return!1;o=g==="R"||g==="AL",a=o?rF:gk,f=!1}if(!a.test(g))return!1;if(g==="EN")u=!0;else if(g==="AN")p=!0}if(o&&u&&p)return!1;return!0}function oF(e){return du.test(e)&&hk(e).length+4>63}function sF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function vp(e){if(oF(e))return!1;if($p(e)&&!Cp(e))return!1;let o=[...e],a=o.map((f)=>f.codePointAt(0)),u=a.length;if(sF(o))return!1;if(nk.test(o[0]))return!1;let p=!1;for(let f=0;f<u;f++){let h=a[f],g=o[f];if(ak.test(g))return!1;if(!ck.test(g))return!1;if(sk.test(g))p=!0;let x=a[f-1],I=a[f+1];switch(h){case 183:if(x!==108||I!==108)return!1;break;case 885:if(!I||!ok.test(o[f+1]))return!1;break;case 1523:case 1524:if(!x||!kp.test(o[f-1]))return!1;break;case 8204:if(!x||x<128&&!Mf.test(o[f-1]))return!1;break;case 8205:if(!x||!Mf.test(o[f-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function Mp(e){if(!Ap(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let a=Pp(o);if(!du.test(a))return!1;return vp(a)}catch{return!1}}function iF(e){return e.length>0&&e.length<=63}function aF(e){return iF(e)&&(Mp(e)||mk(e))}function Sk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>aF(o))}function uF(e){return e.length>0&&e.length<=63}function cF(e){return uF(e)&&(Mp(e)||vp(e))}function mF(e){return e.replace(/[\uff01-\uff5e]/g,(o)=>String.fromCharCode(o.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function wk(e){if(e.length===0||e.includes(" "))return!1;let o=mF(e);if(o.length>253)return!1;let a=o.split("."),u=a.some((p)=>yk(p));return a.every((p)=>cF(p)&&(!u||Cp(p)))}function Op(e){return Sk(e)}var pF=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function _p(e){return pF.test(e.normalize("NFC"))}function Lp(e){return wk(e)}var lF=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Np(e){return lF.test(e)}var dF=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function qp(e){return dF.test(e)}var fF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,hF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Dp(e){return!fF.test(e)&&!hF.test(e)&&URL.canParse(e,"http://example.com")}var gF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,yF=/[\x00-\x20<>\^`{|}\\]/,xF=/%(?![0-9a-fA-F]{2})/;function IF(e){return e.length<2048?e.replace(gF,"[::1]"):e}function Fp(e){if(yF.test(e))return!1;if(xF.test(e))return!1;return URL.canParse(IF(e))}var EF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function jp(e){return EF.test(e)}var bF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Up(e){return bF.test(e)}function Bp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var SF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Gp(e){return SF.test(e)}var wF=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Kp(e){return wF.test(e)}var TF=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Hp(e){return TF.test(e)}var RF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Wp(e){return RF.test(e)}function zp(e){return URL.canParse(e)}var kF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Vp(e){return kF.test(e)}var Rr=new Map;function Rk(){Rr.clear()}function AF(){return[...Rr.entries()]}function PF(e,o){Rr.set(e,o)}function $F(e){return Rr.has(e)}function CF(e){return Rr.get(e)}function kk(e,o){return Rr.get(e)?.(o)??!0}function Ak(){Rk(),Rr.set("date-time",wp),Rr.set("date",pu),Rr.set("duration",Tp),Rr.set("email",Rp),Rr.set("hostname",Op),Rr.set("idn-email",_p),Rr.set("idn-hostname",Lp),Rr.set("ipv4",Np),Rr.set("ipv6",qp),Rr.set("iri-reference",Dp),Rr.set("iri",Fp),Rr.set("json-pointer-uri-fragment",jp),Rr.set("json-pointer",Up),Rr.set("regex",Bp),Rr.set("relative-json-pointer",Gp),Rr.set("time",lu),Rr.set("uri-reference",Kp),Rr.set("uri-template",Hp),Rr.set("uri",Wp),Rr.set("url",zp),Rr.set("uuid",Vp)}Ak();function Pk(e,o,a,u){return Sr(St("Format","Test"),[je(a.format),u])}function Lf(e,o,a,u){return kk(a.format,u)}function $k(e,o,a,u,p,f){return Lf(e,o,p,f)||o.AddError({keyword:"format",schemaPath:a,instancePath:u,params:{format:p.format}})}function Ck(e,o,a,u){let p=Lc(a)?a.then:!0,f=bc(a)?a.else:!0;return PM(Ht(e,o,a.if,u),Ht(e,o,p,u),Ht(e,o,f,u))}function vk(e,o,a,u){let p=Lc(a)?a.then:!0,f=bc(a)?a.else:!0;return $t(e,o,a.if,u)?$t(e,o,p,u):$t(e,o,f,u)}function Mk(e,o,a,u,p,f){let h=Lc(p)?p.then:!0,g=bc(p)?p.else:!0,x=new Hn,I=dr(e,x,`${a}/if`,u,p.if,f)?dr(e,x,`${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(I)o.Merge([x]);return I}function vF(e,o,a,u){return Fn(a.items.map((p,f)=>{let h=aa(St(u,"length"),je(f)),g=Eo(e,o,p,`${u}[${f}]`),x=o.AddIndex(je(f));return br(h,On(g,x))}))}function MF(e,o,a,u){return Fn(a.items.map((p,f)=>{let h=aa(St(u,"length"),je(f)),g=Eo(e,o,p,`${u}[${f}]`);return br(h,g)}))}function OF(e,o,a,u){return o.UseUnevaluated()?vF(e,o,a,u):MF(e,o,a,u)}function _F(e,o,a,u){return on(a.items,0,(p,f)=>_s(u.length,f)||Fo(e,o,p,u[f])&&o.AddIndex(f))}function LF(e,o,a,u,p,f){return Dn(p.items,0,(h,g)=>{let x=`${a}/items/${g}`,I=`${u}/${g}`;return _s(f.length,g)||jo(e,o,x,I,h,f[g])&&o.AddIndex(g)})}function NF(e,o,a,u){let p=Is(a)?a.prefixItems.length:0,f=Eo(e,o,a.items,"element"),h=o.AddIndex("index");return Ls(u,je(p),["element","index"],On(f,h))}function qF(e,o,a,u){let p=Is(a)?a.prefixItems.length:0,f=Eo(e,o,a.items,"element");return Ls(u,je(p),["element","index"],f)}function DF(e,o,a,u){return o.UseUnevaluated()?NF(e,o,a,u):qF(e,o,a,u)}function FF(e,o,a,u){let p=Is(a)?a.prefixItems.length:0;return on(u,p,(f,h)=>Fo(e,o,a.items,f)&&o.AddIndex(h))}function jF(e,o,a,u,p,f){let h=Is(p)?p.prefixItems.length:0;return Dn(f,h,(g,x)=>{let I=`${a}/items`,E=`${u}/${x}`;return jo(e,o,I,E,p.items,g)&&o.AddIndex(x)})}function Ok(e,o,a,u){return Tc(a)?OF(e,o,a,u):DF(e,o,a,u)}function _k(e,o,a,u){return Tc(a)?_F(e,o,a,u):FF(e,o,a,u)}function Lk(e,o,a,u,p,f){return Tc(p)?LF(e,o,a,u,p,f):jF(e,o,a,u,p,f)}function Nk(e){return zs(e)}function qk(e,o,a,u){if(!Nk(a))return je(!0);let[p]=[ar()],f=cm(u,[p,"_"],Ht(e,o,a.contains,p));return aa(f,je(a.maxContains))}function Nf(e,o,a,u){if(!Nk(a))return!0;let p=td(u,(f)=>$t(e,o,a.contains,f));return _s(p,a.maxContains)}function Dk(e,o,a,u,p,f){let h=di(p)?p.minContains:1;return Nf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:h,maxContains:p.maxContains}})}function Fk(e,o,a,u){return aa(u,je(a.maximum))}function qf(e,o,a,u){return _s(u,a.maximum)}function jk(e,o,a,u,p,f){return qf(e,o,p,f)||o.AddError({keyword:"maximum",schemaPath:a,instancePath:u,params:{comparison:"<=",limit:p.maximum}})}function Uk(e,o,a,u){return aa(St(u,"length"),je(a.maxItems))}function Df(e,o,a,u){return _s(u.length,a.maxItems)}function Bk(e,o,a,u,p,f){return Df(e,o,p,f)||o.AddError({keyword:"maxItems",schemaPath:a,instancePath:u,params:{limit:p.maxItems}})}function Gk(e,o,a,u){return TM(u,je(a.maxLength))}function Ff(e,o,a,u){return cy(u,a.maxLength)}function Kk(e,o,a,u,p,f){return Ff(e,o,p,f)||o.AddError({keyword:"maxLength",schemaPath:a,instancePath:u,params:{limit:p.maxLength}})}function Hk(e,o,a,u){return aa(St(ua(u),"length"),je(a.maxProperties))}function jf(e,o,a,u){return _s(be(u).length,a.maxProperties)}function Wk(e,o,a,u,p,f){return jf(e,o,p,f)||o.AddError({keyword:"maxProperties",schemaPath:a,instancePath:u,params:{limit:p.maxProperties}})}function zk(e){return zs(e)}function UF(e,o,a,u){let[p,f]=[ar(),ar()],h=cm(u,[p,f],On(Ht(e,o,a.contains,p),o.AddIndex(f)));return _u(h,je(a.minContains))}function BF(e,o,a,u){let[p]=[ar()],f=cm(u,[p,"_"],Ht(e,o,a.contains,p));return _u(f,je(a.minContains))}function Vk(e,o,a,u){if(!zk(a))return je(!0);return o.UseUnevaluated()?UF(e,o,a,u):BF(e,o,a,u)}function Uf(e,o,a,u){if(!zk(a))return!0;let p=td(u,(f,h)=>$t(e,o,a.contains,f)&&o.AddIndex(h));return Na(p,a.minContains)}function Jk(e,o,a,u,p,f){return Uf(e,o,p,f)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:p.minContains}})}function Qk(e,o,a,u){return _u(u,je(a.minimum))}function Bf(e,o,a,u){return Na(u,a.minimum)}function Xk(e,o,a,u,p,f){return Bf(e,o,p,f)||o.AddError({keyword:"minimum",schemaPath:a,instancePath:u,params:{comparison:">=",limit:p.minimum}})}function Yk(e,o,a,u){return _u(St(u,"length"),je(a.minItems))}function Gf(e,o,a,u){return Na(u.length,a.minItems)}function Zk(e,o,a,u,p,f){return Gf(e,o,p,f)||o.AddError({keyword:"minItems",schemaPath:a,instancePath:u,params:{limit:p.minItems}})}function eA(e,o,a,u){return wM(u,je(a.minLength))}function Kf(e,o,a,u){return my(u,a.minLength)}function tA(e,o,a,u,p,f){return Kf(e,o,p,f)||o.AddError({keyword:"minLength",schemaPath:a,instancePath:u,params:{limit:p.minLength}})}function rA(e,o,a,u){return _u(St(ua(u),"length"),je(a.minProperties))}function Hf(e,o,a,u){return Na(be(u).length,a.minProperties)}function nA(e,o,a,u,p,f){return Hf(e,o,p,f)||o.AddError({keyword:"minProperties",schemaPath:a,instancePath:u,params:{limit:p.minProperties}})}function oA(e,o,a,u){return $M(u,je(a.multipleOf))}function Wf(e,o,a,u){return ay(u,a.multipleOf)}function sA(e,o,a,u,p,f){return Wf(e,o,p,f)||o.AddError({keyword:"multipleOf",schemaPath:a,instancePath:u,params:{multipleOf:p.multipleOf}})}function GF(e,o,a,u){return Vi(e,o,[a.not],u,zn(Ao(St("results","length"),je(1))))}function KF(e,o,a,u){return zn(Ht(e,o,a.not,u))}function iA(e,o,a,u){return o.UseUnevaluated()?GF(e,o,a,u):KF(e,o,a,u)}function zf(e,o,a,u){let p=new Kn;return!$t(e,p,a.not,u)&&o.Merge([p])}function aA(e,o,a,u,p,f){return zf(e,o,p,f)||o.AddError({keyword:"not",schemaPath:a,instancePath:u,params:{}})}function HF(e,o,a,u){return Vi(e,o,a.oneOf,u,Ao(St("results","length"),je(1)))}function WF(e,o,a,u){let[p]=[ar()],f=AM(a.oneOf.map((g)=>Ht(e,o,g,u))),h=cm(f,[p,"_"],Ao(p,je(!0)));return Ao(h,je(1))}function uA(e,o,a,u){return o.UseUnevaluated()?HF(e,o,a,u):WF(e,o,a,u)}function cA(e,o,a,u){let p=a.oneOf.reduce((f,h)=>{let g=new Kn;return $t(e,g,h,u)?[...f,g]:f},[]);return v(p.length,1)&&o.Merge(p)}function mA(e,o,a,u,p,f){let h=[],g=[],x=p.oneOf.reduce((E,k,A)=>{let P=new Hn,C=`${a}/oneOf/${A}`,M=dr(e,P,C,u,k,f);if(M)g.push(A);if(!M)h.push(P);return M?[...E,P]:E},[]),I=v(x.length,1)&&o.Merge(x);if(!I&&v(g.length,0))h.forEach((E)=>E.GetErrors().forEach((k)=>o.AddError(k)));return I||o.AddError({keyword:"oneOf",schemaPath:a,instancePath:u,params:{passingSchemas:g}})}function pA(e,o,a,u){let p=zo(yt(a.pattern)?ws(a.pattern):a.pattern);return Sr(St(p,"test"),[u])}function Vf(e,o,a,u){return(yt(a.pattern)?ws(a.pattern):a.pattern).test(u)}function lA(e,o,a,u,p,f){return Vf(e,o,p,f)||o.AddError({keyword:"pattern",schemaPath:a,instancePath:u,params:{pattern:p.pattern}})}function dA(e,o,a,u){return Fn(pn(a.patternProperties).map(([p,f])=>{let[h,g]=[ar(),ar()],x=zo(ws(p)),I=zn(Sr(St(x,"test"),[h])),E=Eo(e,o,f,g),k=o.AddKey(h),A=o.UseUnevaluated()?br(I,On(E,k)):br(I,E);return Ls(Iy(u),je(0),[`[${h}, ${g}]`,"_"],A)}))}function fA(e,o,a,u){return on(pn(a.patternProperties),0,([p,f])=>{let h=ws(p);return on(pn(u),0,([g,x])=>!h.test(g)||Fo(e,o,f,x)&&o.AddKey(g))})}function hA(e,o,a,u,p,f){return Dn(pn(p.patternProperties),0,([h,g])=>{let x=`${a}/patternProperties/${h}`,I=ws(h);return Dn(pn(f),0,([E,k])=>{let A=`${u}/${E}`;return!I.test(E)||jo(e,o,x,A,g,k)&&o.AddKey(E)})})}function gA(e,o,a,u){return Fn(a.prefixItems.map((p,f)=>{let h=aa(St(u,"length"),je(f)),g=Eo(e,o,p,`${u}[${f}]`),x=o.AddIndex(je(f)),I=o.UseUnevaluated()?On(g,x):g;return br(h,I)}))}function yA(e,o,a,u){return v(u.length,0)||on(a.prefixItems,0,(p,f)=>_s(u.length,f)||Fo(e,o,p,u[f])&&o.AddIndex(f))}function xA(e,o,a,u,p,f){return v(f.length,0)||Dn(p.prefixItems,0,(h,g)=>{let x=`${a}/prefixItems/${g}`,I=`${u}/${g}`;return _s(f.length,g)||jo(e,o,x,I,h,f[g])&&o.AddIndex(g)})}function Jp(e,o){return e.includes(o)||ns().exactOptionalPropertyTypes}function IA(e,o){return od(St(e,o))}function Jf(e,o){return nr(e[o])}function EA(e,o,a,u){let p=Ss(a)?a.required:[],f=pn(a.properties).map(([h,g])=>{let x=zn(ca(u,je(h))),I=Eo(e,o,g,St(u,h)),E=o.AddKey(je(h)),k=o.UseUnevaluated()?On(I,E):I,A=p.includes(h)?k:br(x,k);return Jp(p,h)?A:br(IA(u,h),A)});return Fn(f)}function bA(e,o,a,u){let p=Ss(a)?a.required:[];return on(pn(a.properties),0,([h,g])=>{let x=!se(u,h)||Fo(e,o,g,u[h])&&o.AddKey(h);return Jp(p,h)?x:Jf(u,h)||x})}function SA(e,o,a,u,p,f){let h=Ss(p)?p.required:[];return Dn(pn(p.properties),0,([x,I])=>{let E=`${a}/properties/${x}`,k=`${u}/${x}`,A=()=>!se(f,x)||jo(e,o,E,k,I,f[x])&&o.AddKey(x);return Jp(h,x)?A():Jf(f,x)||A()})}function wA(e,o,a,u){let[p,f]=[ar(),ar()];return Ls(ua(u),je(0),[p,f],Ht(e,o,a.propertyNames,p))}function TA(e,o,a,u){return on(be(u),0,(p,f)=>$t(e,o,a.propertyNames,p))}function RA(e,o,a,u,p,f){let h=[];return Dn(be(f),0,(x,I)=>{let E=`${u}/${x}`,k=`${a}/propertyNames`,A=dr(e,o,k,E,p.propertyNames,x);if(!A)h.push(x);return A})||o.AddError({keyword:"propertyNames",schemaPath:a,instancePath:u,params:{propertyNames:h}})}function kA(e,o,a,u){let p=e.RecursiveRef(a)??!1;return gi(e,o,p,u)}function AA(e,o,a,u){let p=e.RecursiveRef(a)??!1;return Ye(p)&&$t(e,o,p,u)}function PA(e,o,a,u,p,f){let h=e.RecursiveRef(p)??!1;return Ye(h)&&dr(e,o,"#",u,h,f)}function zF(e,o,a,u){let p=Ti(["context","value"],gi(e,o,a,"value")),f=Ti(["context","value"],mm([Zs("nextContext",id("CheckContext",[])),Zs("result",Sr(p,["nextContext","value"])),by("result",o.Merge("[nextContext]")),pm("result")]));return Sr(f,["context",u])}function VF(e,o,a,u){return gi(e,o,a,u)}function $A(e,o,a,u){let p=e.Ref(a)??!1;return o.UseUnevaluated()?zF(e,o,p,u):VF(e,o,p,u)}function CA(e,o,a,u){let p=e.Ref(a)??!1,f=new Kn,h=Ye(p)&&$t(e,f,p,u);if(h)o.Merge([f]);return h}function vA(e,o,a,u,p,f){let h=e.Ref(p)??!1,g=new Hn,x=Ye(h)&&dr(e,g,"#",u,h,f);if(x)o.Merge([g]);if(!x)g.GetErrors().forEach((I)=>o.AddError(I));return x}function MA(e,o,a,u){return Fn(a.required.map((p)=>ca(u,je(p))))}function OA(e,o,a,u){return on(a.required,0,(p)=>se(u,p))}function _A(e,o,a,u,p,f){let h=[];return Dn(p.required,0,(x)=>{let I=se(f,x);if(!I)h.push(x);return I})||o.AddError({keyword:"required",schemaPath:a,instancePath:u,params:{requiredProperties:h}})}function LA(e,o,a,u){return v(a,"object")?hy(u):v(a,"array")?um(u):v(a,"boolean")?yM(u):v(a,"integer")?xM(u):v(a,"number")?fy(u):v(a,"null")?IM(u):v(a,"string")?yy(u):v(a,"bigint")?dy(u):v(a,"constructor")?SM(u):v(a,"function")?bM(u):v(a,"symbol")?EM(u):v(a,"undefined")?od(u):v(a,"void")?od(u):je(!0)}function Qf(e,o,a,u,p){return v(a,"object")?rs(p):v(a,"array")?He(p):v(a,"boolean")?cn(p):v(a,"integer")?am(p):v(a,"number")?Bt(p):v(a,"null")?Oo(p):v(a,"string")?yt(p):v(a,"bigint")?Kr(p):v(a,"constructor")?Zl(p):v(a,"function")?Os(p):v(a,"symbol")?ed(p):v(a,"undefined")?nr(p):v(a,"void")?nr(p):!0}function JF(e,o,a,u){return ad(a.map((p)=>LA(e,o,p,u)))}function NA(e,o,a,u,p){return qa(a,(f)=>Qf(e,o,f,u,p))}function qA(e,o,a,u){return He(a.type)?JF(e,o,a.type,u):LA(e,o,a.type,u)}function DA(e,o,a,u){return He(a.type)?NA(e,o,a.type,a,u):Qf(e,o,a.type,a,u)}function FA(e,o,a,u,p,f){return(He(p.type)?NA(e,o,p.type,p,f):Qf(e,o,p.type,p,f))||o.AddError({keyword:"type",schemaPath:a,instancePath:u,params:{type:p.type}})}function jA(e,o,a,u){let[p,f]=[ar(),ar()],h=Sr(St("context","GetIndices"),[]),g=Sr(St("indices","has"),[p]),x=Ht(e,o,a.unevaluatedItems,f),I=Sr(St("context","AddIndex"),[p]),E=Ls(u,je(0),[f,p],On(br(g,x),I));return Sr(Ti(["context"],mm([Zs("indices",h),pm(E)])),["context"])}function UA(e,o,a,u){let p=o.GetIndices();return on(u,0,(f,h)=>(p.has(h)||$t(e,o,a.unevaluatedItems,f))&&o.AddIndex(h))}function BA(e,o,a,u,p,f){let h=o.GetIndices(),g=[];return Dn(f,0,(I,E)=>{let k=new Hn,A=(h.has(E)||dr(e,k,a,u,p.unevaluatedItems,I))&&o.AddIndex(E);if(!A)g.push(E);return A})||o.AddError({keyword:"unevaluatedItems",schemaPath:a,instancePath:u,params:{unevaluatedItems:g}})}function GA(e,o,a,u){let[p,f]=[ar(),ar()],h=Sr(St("context","GetKeys"),[]),g=Sr(St("keys","has"),[p]),x=Sr(St("context","AddKey"),[p]),I=Ht(e,o,a.unevaluatedProperties,f),E=Ls(Iy(u),je(0),[`[${p}, ${f}]`,"_"],br(g,On(I,x)));return Sr(Ti(["context"],mm([Zs("keys",h),pm(E)])),["context"])}function KA(e,o,a,u){let p=o.GetKeys();return on(pn(u),0,([f,h])=>p.has(f)||$t(e,o,a.unevaluatedProperties,h)&&o.AddKey(f))}function HA(e,o,a,u,p,f){let h=o.GetKeys(),g=[];return Dn(pn(f),0,([I,E])=>{let k=new Hn,A=h.has(I)||dr(e,k,a,u,p.unevaluatedProperties,E)&&o.AddKey(I);if(!A)g.push(I);return A})||o.AddError({keyword:"unevaluatedProperties",schemaPath:a,instancePath:u,params:{unevaluatedProperties:g}})}function Xf(e){return!v(e.uniqueItems,!1)}function WA(e,o,a,u){if(!Xf(a))return je(!0);let p=St(id("Set",[Sr(St(u,"map"),[St("Hashing","Hash")])]),"size"),f=St(u,"length");return Ao(p,f)}function zA(e,o,a,u){if(!Xf(a))return!0;let p=new Set(u.map(md)).size,f=u.length;return v(p,f)}function VA(e,o,a,u,p,f){if(!Xf(p))return!0;let h=new Set,g=f.reduce((I,E,k)=>{let A=md(E);if(h.has(A))return[...I,k];return h.add(A),I},[]);return v(g.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:a,instancePath:u,params:{duplicateItems:g}})}function jc(e,o){return Nc(e)&&(He(e.type)&&sa(e.type.length,0)&&on(e.type,0,(a)=>v(a,o))||v(e.type,o))}function QF(e){return jc(e,"object")}function XF(e){return Tn(e)&&(Wo(e)||xc(e)||Ic(e)||au(e)||hi(e)||fi(e)||cu(e)||Aa(e)||Pc(e)||Ss(e)||zi(e))}function YF(e){return jc(e,"array")}function ZF(e){return Tn(e)&&(iu(e)||pi(e)||zs(e)||kc(e)||uu(e)||di(e)||ji(e)||Is(e)||Bi(e)||Ui(e))}function e1(e){return jc(e,"string")}function t1(e){return Tn(e)&&(ka(e)||Ac(e)||Ra(e)||Pa(e))}function r1(e){return jc(e,"number")||jc(e,"bigint")}function n1(e){return Tn(e)&&(xs(e)||Rc(e)||Sc(e)||ys(e)||$c(e))}function Eo(e,o,a,u){return o.UseUnevaluated()?On(On(o.Push(),Ht(e,o,a,u)),o.Pop()):Ht(e,o,a,u)}function Ht(e,o,a,u){e.Push(a);let p=[];if(ii(a))return PR(e,o,a,u);if(Nc(a))p.push(qA(e,o,a,u));if(XF(a)){let h=[];if(Ss(a))h.push(MA(e,o,a,u));if(Wo(a))h.push(IR(e,o,a,u));if(xc(a))h.push(LR(e,o,a,u));if(Ic(a))h.push(DR(e,o,a,u));if(au(a))h.push(UR(e,o,a,u));if(fi(a))h.push(dA(e,o,a,u));if(hi(a))h.push(EA(e,o,a,u));if(cu(a))h.push(wA(e,o,a,u));if(Aa(a))h.push(rA(e,o,a,u));if(Pc(a))h.push(Hk(e,o,a,u));let g=Fn(h),x=br(zn(hy(u)),g);p.push(QF(a)?g:x)}if(ZF(a)){let h=[];if(iu(a))h.push(gR(e,o,a,u));if(zs(a))h.push(OR(e,o,a,u));if(pi(a))h.push(Ok(e,o,a,u));if(kc(a))h.push(qk(e,o,a,u));if(uu(a))h.push(Uk(e,o,a,u));if(di(a))h.push(Vk(e,o,a,u));if(ji(a))h.push(Yk(e,o,a,u));if(Is(a))h.push(gA(e,o,a,u));if(Ui(a))h.push(WA(e,o,a,u));let g=Fn(h),x=br(zn(um(u)),g);p.push(YF(a)?g:x)}if(t1(a)){let h=[];if(Ac(a))h.push(Gk(e,o,a,u));if(ka(a))h.push(eA(e,o,a,u));if(Ra(a))h.push(Pk(e,o,a,u));if(Pa(a))h.push(pA(e,o,a,u));let g=Fn(h),x=br(zn(yy(u)),g);p.push(e1(a)?g:x)}if(n1(a)){let h=[];if(Sc(a))h.push(JR(e,o,a,u));if(ys(a))h.push(XR(e,o,a,u));if(Rc(a))h.push(Fk(e,o,a,u));if(xs(a))h.push(Qk(e,o,a,u));if($c(a))h.push(oA(e,o,a,u));let g=Fn(h),x=br(zn(br(fy(u),dy(u))),g);p.push(r1(a)?g:x)}if(_c(a))p.push($A(e,o,a,u));if(Oc(a))p.push(kA(e,o,a,u));if(Ec(a))p.push(KR(e,o,a,u));if(Ip(a))p.push(CR(e,o,a,u));if(Ep(a))p.push(zR(e,o,a,u));if(wc(a))p.push(Ck(e,o,a,u));if(Cc(a))p.push(iA(e,o,a,u));if(hc(a))p.push(SR(e,o,a,u));if(yc(a))p.push(RR(e,o,a,u));if(vc(a))p.push(uA(e,o,a,u));if(Bi(a))p.push(br(zn(um(u)),jA(e,o,a,u)));if(zi(a))p.push(br(zn(gy(u)),GA(e,o,a,u)));if(fc(a))p.push(dR(e,o,a,u));let f=Fn(p);return e.Pop(a),f}function Fo(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=ii(a)?wf(e,o,a,u):(!Nc(a)||DA(e,o,a,u))&&(!(lt(u)&&!He(u))||(!Ss(a)||OA(e,o,a,u))&&(!Wo(a)||ER(e,o,a,u))&&(!xc(a)||NR(e,o,a,u))&&(!Ic(a)||FR(e,o,a,u))&&(!au(a)||BR(e,o,a,u))&&(!fi(a)||fA(e,o,a,u))&&(!hi(a)||bA(e,o,a,u))&&(!cu(a)||TA(e,o,a,u))&&(!Aa(a)||Hf(e,o,a,u))&&(!Pc(a)||jf(e,o,a,u)))&&(!He(u)||(!iu(a)||yR(e,o,a,u))&&(!zs(a)||Rf(e,o,a,u))&&(!pi(a)||_k(e,o,a,u))&&(!kc(a)||Nf(e,o,a,u))&&(!uu(a)||Df(e,o,a,u))&&(!di(a)||Uf(e,o,a,u))&&(!ji(a)||Gf(e,o,a,u))&&(!Is(a)||yA(e,o,a,u))&&(!Ui(a)||zA(e,o,a,u)))&&(!yt(u)||(!Ac(a)||Ff(e,o,a,u))&&(!ka(a)||Kf(e,o,a,u))&&(!Ra(a)||Lf(e,o,a,u))&&(!Pa(a)||Vf(e,o,a,u)))&&(!(Bt(u)||Kr(u))||(!Sc(a)||Pf(e,o,a,u))&&(!ys(a)||$f(e,o,a,u))&&(!Rc(a)||qf(e,o,a,u))&&(!xs(a)||Bf(e,o,a,u))&&(!$c(a)||Wf(e,o,a,u)))&&(!_c(a)||CA(e,o,a,u))&&(!Oc(a)||AA(e,o,a,u))&&(!Ec(a)||HR(e,o,a,u))&&(!Ip(a)||Tf(e,o,a,u))&&(!Ep(a)||Af(e,o,a,u))&&(!wc(a)||vk(e,o,a,u))&&(!Cc(a)||zf(e,o,a,u))&&(!hc(a)||wR(e,o,a,u))&&(!yc(a)||kR(e,o,a,u))&&(!vc(a)||cA(e,o,a,u))&&(!Bi(a)||(!He(u)||UA(e,o,a,u)))&&(!zi(a)||(!lt(u)||KA(e,o,a,u)))&&(!fc(a)||fR(e,o,a,u));return e.Pop(a),p}function jo(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=ii(p)?$R(e,o,a,u,p,f):!!(+(!Nc(p)||FA(e,o,a,u,p,f))&+(!(lt(f)&&!He(f))||!!(+(!Ss(p)||_A(e,o,a,u,p,f))&+(!Wo(p)||bR(e,o,a,u,p,f))&+(!xc(p)||qR(e,o,a,u,p,f))&+(!Ic(p)||jR(e,o,a,u,p,f))&+(!au(p)||GR(e,o,a,u,p,f))&+(!fi(p)||hA(e,o,a,u,p,f))&+(!hi(p)||SA(e,o,a,u,p,f))&+(!cu(p)||RA(e,o,a,u,p,f))&+(!Aa(p)||nA(e,o,a,u,p,f))&+(!Pc(p)||Wk(e,o,a,u,p,f))))&+(!He(f)||!!(+(!iu(p)||xR(e,o,a,u,p,f))&+(!zs(p)||_R(e,o,a,u,p,f))&+(!pi(p)||Lk(e,o,a,u,p,f))&+(!kc(p)||Dk(e,o,a,u,p,f))&+(!uu(p)||Bk(e,o,a,u,p,f))&+(!di(p)||Jk(e,o,a,u,p,f))&+(!ji(p)||Zk(e,o,a,u,p,f))&+(!Is(p)||xA(e,o,a,u,p,f))&+(!Ui(p)||VA(e,o,a,u,p,f))))&+(!yt(f)||!!(+(!Ac(p)||Kk(e,o,a,u,p,f))&+(!ka(p)||tA(e,o,a,u,p,f))&+(!Ra(p)||$k(e,o,a,u,p,f))&+(!Pa(p)||lA(e,o,a,u,p,f))))&+(!(Bt(f)||Kr(f))||!!(+(!Sc(p)||QR(e,o,a,u,p,f))&+(!ys(p)||YR(e,o,a,u,p,f))&+(!Rc(p)||jk(e,o,a,u,p,f))&+(!xs(p)||Xk(e,o,a,u,p,f))&+(!$c(p)||sA(e,o,a,u,p,f))))&+(!_c(p)||vA(e,o,a,u,p,f))&+(!Oc(p)||PA(e,o,a,u,p,f))&+(!Ec(p)||WR(e,o,a,u,p,f))&+(!Ip(p)||vR(e,o,a,u,p,f))&+(!Ep(p)||VR(e,o,a,u,p,f))&+(!wc(p)||Mk(e,o,a,u,p,f))&+(!Cc(p)||aA(e,o,a,u,p,f))&+(!hc(p)||TR(e,o,a,u,p,f))&+(!yc(p)||AR(e,o,a,u,p,f))&+(!vc(p)||mA(e,o,a,u,p,f))&+(!Bi(p)||(!He(f)||BA(e,o,a,u,p,f)))&+(!zi(p)||(!lt(f)||HA(e,o,a,u,p,f))))&&(!fc(p)||hR(e,o,a,u,p,f));return e.Pop(p),h}var JA=[0],Qp=new Map,Uc=new Map;function o1(){return`${JA[0]++}`}function s1(e,o){if(!Qp.has(e))Qp.set(e,new Map);let a=Qp.get(e);if(a.has(o))return a.get(o);let u=o1();return a.set(o,u),u}function i1(e,o,a,u){return e.UseUnevaluated()?Sr(`check_${a}`,["context",u]):Sr(`check_${a}`,[u])}function a1(e,o,a,u){let p=Ht(e,o,a,"value");return o.UseUnevaluated()?Zs(`check_${u}`,Ti(["context","value"],p)):Zs(`check_${u}`,Ti(["value"],p))}function QA(){JA[0]=0,Qp.clear(),Uc.clear()}function XA(){return[...Uc.values()]}function gi(e,o,a,u){let p=s1(a,e.LexicalBaseURL()),f=i1(o,a,p,u);if(Uc.has(p))return f;return Uc.set(p,""),Uc.set(p,a1(e,o,a,p)),f}function u1(e,o){return lt(o)&&!Ou(e)?o[e]:void 0}function c1(e,o){return e.reduce((a,u)=>u1(u,a),o)}function m1(e){if(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 p1(e,o){let a=m1(o);return c1(a,e)}var Yp="https://json-schema.org";function ZA(e,o){if(lt(e)&&mi(e)&&v(e.$dynamicAnchor,o))return e;if(lt(e))for(let a of be(e)){let u=ZA(e[a],o);if(u)return u}return}function Yf(e,o,a){if(v(e,a))return o.href;let u=Tn(e)&&Do(e)?new URL(e.$id,o.href):o;if(He(e))for(let p of e){let f=Yf(p,u,a);if(!nr(f))return f}else if(lt(e))for(let p of be(e)){let f=Yf(e[p],u,a);if(!nr(f))return f}return}function l1(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("#")?eP(e,a):e;return}function d1(e,o,a){let u=new URL(`#${e.$anchor}`,o.href),p=new URL(a.href,o.href);return v(u.href,p.href)?e:void 0}function f1(e,o,a){let u=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(a.href,o.href);return v(u.href,p.href)?e:void 0}function eP(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let a=decodeURIComponent(o.hash.slice(1));if(!a.startsWith("/"))return;return p1(e,a)}function h1(e,o,a){if(Do(e)){let u=l1(e,o,a);if(!nr(u))return u}if(gc(e)){let u=d1(e,o,a);if(!nr(u))return u}if(mi(e)){let u=f1(e,o,a);if(!nr(u))return u}return eP(e,a)}function g1(e,o,a){return e.reduce((u,p)=>{let f=Zp(p,o,a);return!nr(f)?f:u},void 0)}function y1(e){return v(e,"const")||v(e,"enum")}function x1(e,o,a){return be(e).reduce((u,p)=>{if(y1(p))return u;let f=Zp(e[p],o,a);return!nr(f)?f:u},void 0)}function Zp(e,o,a){let u=Tn(e)&&Do(e)?new URL(e.$id,o.href):o;if(Tn(e)){let p=h1(e,u,a);if(!nr(p))return p}if(He(e))return g1(e,u,a);if(lt(e))return x1(e,u,a);return}function I1(e,o,a){return Yf(e,new URL(o||".",Yp),a)}function E1(e,o,a,u){let p=el(e,o,a,u,!1);return Tn(p)&&Do(p)?p:void 0}function YA(e){return e.href.split("#")[0]}function b1(e,o){return se(e,o)?e[o]:void 0}function S1(e,o,a){return Zp(e,o,a)}function w1(e,o,a){let u=YA(a);if(v(u,YA(o)))return;if(!se(e,u))return;let p=e[u],f=Tn(p)&&Do(p)?new URL(p.$id,u):new URL(u);return v(a.hash,"")?p:Zp(p,f,a)}function T1(e,o,a,u,p){if(!u.$ref.startsWith("#"))return;if(se(e,"$schema"))return;let f=I1(o,a,p);if(nr(f)||v(f,a))return;return{target:p,base:f,root:o}}function R1(e,o,a){let u=e[o];if(!Tn(u))return;return{target:a,base:o,root:u}}function k1(e,o,a,u,p){let f=p?R1(e.context,u,a):void 0;if(!nr(f))return f;return T1(e.root,e.lexicalSchema,e.referenceBase,o,a)}function A1(e,o,a,u,p,f){if(Do(p))return;let h=E1(e,o,a,u);if(!h||f.includes(h))return;return{target:p,resource:h}}function el(e,o,a,u,p=!0){let f=new URL(a||".",Yp),h=p&&Do(o)?new URL(o.$id,f):f,g=new URL(u,h.href);return b1(e,u)??S1(o,h,g)??w1(e,h,g)}function P1(e,o,a,u,p,f){let h=new URL(a||".",Yp),g=p.$dynamicRef.startsWith("#")?u:o,x=el(e,g,a,p.$dynamicRef,!1);if(nr(x)){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))??ZA(o,A)}return}if(!Tn(x)||!mi(x))return x;if(new URL(p.$dynamicRef,h).hash.startsWith("#/"))return x;return f.find((k)=>v(k.$dynamicAnchor,x.$dynamicAnchor))??x}function $1(e,o){let a=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:a,p=el(e.context,u,e.referenceBase,o.$ref,!1);if(!p||!Tn(p))return{schema:p};let f=new URL(o.$ref,e.referenceBase).href.split("#")[0],h=!v(f,e.resourceBase),g=k1(e,o,p,f,h),x=h?A1(e.context,e.root,e.referenceBase,f,p,e.ids):void 0;return{schema:p,retrievedResource:g,resolvedResource:x}}function C1(e,o){let a=Mc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return el(e.context,a,e.lexicalBase,o.$recursiveRef,!1)}function v1(e,o){return P1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var Br=function(e,o,a,u){if(a==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?u:a==="a"?u.call(e):u?u.value:o.get(e)},$r,rl,iP,rh,tl,tP,rP,nP,oP,eh,th,nh,oh,sP,aP;class Yi{constructor(e,o){$r.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return Br(this,$r,"m",rh).call(this,this.ids)}Push(e){if(!Tn(e))return;if(Do(e))Br(this,$r,"m",nh).call(this,e);if(gc(e))this.anchors.push(e);if(Mc(e))this.recursiveAnchors.push(e);if(mi(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!Tn(e))return;if(Do(e))Br(this,$r,"m",oh).call(this,e);if(gc(e))this.anchors.pop();if(Mc(e))this.recursiveAnchors.pop();if(mi(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Br(this,$r,"m",aP).call(this,e)}Ref(e){let o=$1(Br(this,$r,"m",rl).call(this),e);return Br(this,$r,"m",iP).call(this,o),o.schema}RecursiveRef(e){let o=C1(Br(this,$r,"m",rl).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=v1(Br(this,$r,"m",rl).call(this),e);if(o)this.pendingResource=!0;return o}}$r=new WeakSet,rl=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Br(this,$r,"m",rP).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Br(this,$r,"m",tP).call(this),resourceBase:Br(this,$r,"m",tl).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},iP=function(o){if(!nr(o.schema))this.pendingResource=!0;if(!nr(o.resolvedResource))Br(this,$r,"m",sP).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!nr(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},rh=function(o){let a=this.retrievedFrames[this.retrievedFrames.length-1],u=a?new URL(a.base):new URL(Yp);return(a?o.slice(a.idDepth):o).reduce((f,h)=>new URL(h.$id,f),u).href},tl=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return Br(this,$r,"m",rh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((a,u)=>new URL(u.$id,a),new URL(o.base)).href},tP=function(){if(this.retrievedFrames.length>0)return Br(this,$r,"m",tl).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return Br(this,$r,"m",tl).call(this)},rP=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(o)return this.ids.length>o.idDepth?this.ids[this.ids.length-1]:o.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},nP=function(o){o.forEach((a)=>Br(this,$r,"m",eh).call(this,a,!1))},oP=function(o){o.forEach((a)=>Br(this,$r,"m",th).call(this,a,!1))},eh=function e(o,a=!0){if(ii(o))return;if(He(o))return Br(this,$r,"m",nP).call(this,o);if(!Tn(o))return;let u=o;if(!a&&Do(u))return;if(!a&&mi(u))this.dynamicAnchors.push(u);for(let p of be(u))Br(this,$r,"m",e).call(this,u[p],!1)},th=function e(o,a=!0){if(ii(o))return;if(He(o))return Br(this,$r,"m",oP).call(this,o);if(!Tn(o))return;let u=o;if(!a&&Do(u))return;if(!a&&mi(u))this.dynamicAnchors.pop();for(let p of be(u))Br(this,$r,"m",e).call(this,u[p],!1)},nh=function(o){this.ids.push(o);let a=this.pendingResource;if(this.pendingResource=!1,a)this.resourceIds.push(o);Br(this,$r,"m",eh).call(this,o,!0)},oh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&v(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();Br(this,$r,"m",th).call(this,o,!0)},sP=function(o,a){Br(this,$r,"m",nh).call(this,a),this.resolvedResources.set(o,a)},aP=function(o){if(!this.resolvedResources.has(o))return;let a=this.resolvedResources.get(o);Br(this,$r,"m",oh).call(this,a),this.resolvedResources.delete(o)};function M1(e){let o=e.Functions().join(`;
|
|
23
|
-
`),a=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${a.join("; ")} }`}function O1(e,o){return Fy("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Kn,_,fu,da,e.External().variables)}function _1(e){let o=new Yi(e.Context(),e.Schema()),a=new Kn;return(u)=>$t(o,a,e.Schema(),u)}function L1(e,o){return Dy()?O1(e,o):_1(e)}class uP{constructor(e,o,a){this.isAccelerated=e,this.code=o,this.check=a}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class cP{constructor(e,o,a,u,p,f){this.context=e,this.schema=o,this.external=a,this.functions=u,this.entry=p,this.useUnevaluated=f}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=M1(this),o=L1(this,e);return new uP(Dy(),e,o)}}function nl(...e){let[o,a]=Ln(e,{2:(x,I)=>[x,I],1:(x)=>[{},x]});pR(),QA();let u=new Yi(o,a),p=new Ef(mR(o,a)),f=gi(u,p,a,"value"),h=XA(),g=lR();return new cP(o,a,g,h,f,p.UseUnevaluated())}function ol(...e){let[o,a,u]=Ln(e,{3:(E,k,A)=>[E,k,A],2:(E,k)=>[{},E,k]}),p=new Yi(o,a),f=new Hn,h=dr(p,f,"#","",a,u),g=f.GetErrors(),x=Vy(),I=g.map((E)=>({...E,message:x(E)}));return[h,I]}function ih(...e){let[o,a,u]=Ln(e,{3:(h,g,x)=>[h,g,x],2:(h,g)=>[{},h,g]}),p=new Yi(o,a),f=new Kn;return $t(p,f,a,u)}function mr(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return ih(o,a,u)}function Vs(...e){let[o,a,u]=Ln(e,{3:(h,g,x)=>[h,g,x],2:(h,g)=>[{},h,g]}),[p,f]=ol(o,a,u);return f}class $a extends Error{constructor(e,o,a){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:a,value:o},writable:!1,configurable:!1,enumerable:!1})}}function mP(e,o,a){if(!He(a))return a;return a.map((u)=>Rn(e,o.items,u))}function pP(e,o,a){return Rn({...e,...o.$defs},sn(o.$ref),a)}function D1(e,o){let a=se(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Ho(e,o),p=qn(u);return Je(p)?yp(p,a):p}function lP(e,o,a){let u=D1(e,o);return Rn(e,u,a)}function sl(e){return se(e,"additionalProperties")?e.additionalProperties:void 0}function dP(e,o,a){if(!lt(a)||He(a))return a;let u=sl(o);for(let p of be(a)){if(se(o.properties,p)){a[p]=Rn(e,o.properties[p],a[p]);continue}if(cn(u)&&v(u,!0)||Dr(u)&&mr(e,u,a[p])){a[p]=Rn(e,u,a[p]);continue}delete a[p]}return a}function fP(e,o,a){if(!lt(a))return a;let u=sl(o),[p,f]=[new RegExp(Sn(o)),hr(o)];for(let h of be(a)){if(p.test(h)){a[h]=Rn(e,f,a[h]);continue}if(cn(u)&&v(u,!0)||Dr(u)&&mr(e,u,a[h])){a[h]=Rn(e,u,a[h]);continue}delete a[h]}return a}function hP(e,o,a){return se(e,o.$ref)?Rn(e,e[o.$ref],a):a}function gP(e,o,a){if(!He(a))return a;let u=Math.min(a.length,o.items.length);for(let p=0;p<u;p++)a[p]=Rn(e,o.items[p],a[p]);return sa(a.length,u)?a.slice(0,u):a}function Jr(e){return Fa(e)}function yP(e,o,a){for(let u of o.anyOf){let p=Rn(e,u,Jr(a));if(mr(e,u,p))return p}return a}function Rn(e,o,a){return Rt(o)?mP(e,o,a):cr(o)?pP(e,o,a):Ve(o)?lP(e,o,a):Je(o)?dP(e,o,a):or(o)?fP(e,o,a):Zt(o)?hP(e,o,a):ht(o)?gP(e,o,a):xe(o)?yP(e,o,a):a}function F1(e,o){for(let a of be(e)){if(se(o,a))continue;o[a]=e[a]}return o}function j1(e){let o={};for(let a of be(e))o[a]=Bc(e[a]);return o}function U1(e){return ah(rR(e))}function ah(e){return e.map((o)=>Bc(o))}function Bc(e){let o=Rt(e)?H(Bc(e.items),ja(e)):Ve(e)?jn(ah(e.allOf)):xe(e)?y(U1(e.anyOf)):Je(e)?l(j1(e.properties)):or(e)?Qe(Oi(e),Bc(hr(e))):ht(e)?zr(ah(e.items)):e;return F1(e,o)}function hu(e){return Bc(e)}function Vo(...e){let[o,a,u]=Ln(e,{3:(f,h,g)=>[f,h,g],2:(f,h)=>[{},f,h]}),p=ns().unionPrioritySort?hu(a):a;return Rn(o,p,u)}function Mo(e){return lt(e)&&se(e,"value")}function We(e){return{value:e}}function Mr(){return}function B1(e){return He(e)?We(e):We([e])}function G1(e){return v(e,!0)?We(BigInt(1)):We(BigInt(0))}var K1=/^-?(0|[1-9]\d*)n$/,H1=/^-?(0|[1-9]\d*)\.\d+$/,W1=/^-?(0|[1-9]\d*)$/;function z1(e){return K1.test(e)}function V1(e){return H1.test(e)}function J1(e){return W1.test(e)}function Q1(e){let o=e.toLowerCase();return z1(e)?We(BigInt(e.slice(0,e.length-1))):V1(e)?We(BigInt(e.split(".")[0])):J1(e)?We(BigInt(e)):v(o,"false")?We(BigInt(0)):v(o,"true")?We(BigInt(1)):Mr()}function il(e){return Kr(e)?We(e):cn(e)?G1(e):Bt(e)?We(BigInt(Math.trunc(e))):Oo(e)?We(BigInt(0)):yt(e)?Q1(e):nr(e)?We(BigInt(0)):Mr()}function X1(e){return v(e,BigInt(0))?We(!1):v(e,BigInt(1))?We(!0):Mr()}function Y1(e){return v(e,0)?We(!1):v(e,1)?We(!0):Mr()}function Z1(e){return v(e.toLowerCase(),"false")?We(!1):v(e.toLowerCase(),"true")?We(!0):v(e,"0")?We(!1):v(e,"1")?We(!0):Mr()}function xP(e){return Kr(e)?X1(e):cn(e)?We(e):Bt(e)?Y1(e):Oo(e)?We(!1):yt(e)?Z1(e):nr(e)?We(!1):Mr()}function ej(e){return v(e,BigInt(0))?We(null):Mr()}function tj(e){return v(e,!1)?We(null):Mr()}function rj(e){return v(e,0)?We(null):Mr()}function nj(e){let o=e.toLowerCase();return v(o,"undefined")||v(o,"null")||v(e,"")||v(e,"0")?We(null):Mr()}function oj(e){return Kr(e)?ej(e):cn(e)?tj(e):Bt(e)?rj(e):Oo(e)?We(null):yt(e)?nj(e):nr(e)?We(null):Mr()}var IP=BigInt(Number.MAX_SAFE_INTEGER),EP=BigInt(Number.MIN_SAFE_INTEGER);function sj(e){return e<=IP&&e>=EP?We(Number(e)):Mr()}function ij(e){return We(e?1:0)}function aj(e){let o=+e;if(Bt(o))return We(o);let a=e.toLowerCase();if(v(a,"false"))return We(0);if(v(a,"true"))return We(1);let u=il(e);if(Mo(u))return u.value<=IP&&u.value>=EP?We(Number(u.value)):Mr();return Mr()}function uh(e){return Kr(e)?sj(e):cn(e)?ij(e):Bt(e)?We(e):Oo(e)?We(0):yt(e)?aj(e):nr(e)?We(0):Mr()}function bP(e){return Kr(e)?We(e.toString()):cn(e)?We(e.toString()):Bt(e)?We(e.toString()):Oo(e)?We("null"):yt(e)?We(e):nr(e)?We(""):Mr()}function uj(e){return v(e,BigInt(0))?We(void 0):Mr()}function cj(e){return v(e,!1)?We(void 0):Mr()}function mj(e){return v(e,0)?We(void 0):Mr()}function pj(e){let o=e.toLowerCase();return v(o,"undefined")||v(o,"null")||v(e,"")||v(e,"0")?We(void 0):Mr()}function SP(e){return Kr(e)?uj(e):cn(e)?cj(e):Bt(e)?mj(e):Oo(e)?We(void 0):yt(e)?pj(e):nr(e)?We(e):Mr()}function wP(e,o,a){return B1(a).value.map((p)=>Qr(e,o.items,p))}function TP(e,o,a){let u=il(a);return Mo(u)?u.value:a}function RP(e,o,a){let u=xP(a);return Mo(u)?u.value:a}function kP(e,o,a){return Qr({...e,...o.$defs},sn(o.$ref),a)}function AP(e,o,a){return Qr(e,qn(o),a)}function PP(e,o,a){let u=uh(a);return Mo(u)?Math.trunc(u.value):a}function $P(e,o,a){let u=Ho(e,o),p=qn(u);return Qr(e,p,a)}function lj(e,o,a){let u=il(a);return Mo(u)&&v(o.const,u.value)?u.value:a}function dj(e,o,a){let u=xP(a);return Mo(u)&&v(o.const,u.value)?u.value:a}function fj(e,o,a){let u=uh(a);return Mo(u)&&v(o.const,u.value)?u.value:a}function hj(e,o,a){let u=bP(a);return Mo(u)&&v(o.const,u.value)?u.value:a}function CP(e,o,a){if(v(o.const,a))return a;return ox(o)?lj(e,o,a):sx(o)?dj(e,o,a):bm(o)?fj(e,o,a):Sm(o)?hj(e,o,a):Wr()}function vP(e,o,a){let u=oj(a);return Mo(u)?u.value:a}function MP(e,o,a){let u=uh(a);return Mo(u)?u.value:a}function al(e,o,a,u){let p=be(u);for(let[f,h]of o)for(let g of p)if(!f.test(g))u[g]=Qr(e,a,u[g]);return u}function Gc(e,o,a){return an(e)&&nr(a[o])}function gj(e,o,a){let u=rd(o.properties),p=be(a);for(let[f,h]of u)for(let g of p){if(!f.test(g)||Gc(h,g,a))continue;a[g]=Qr(e,h,a[g])}return se(o,"additionalProperties")&<(o.additionalProperties)?al(e,u,o.additionalProperties,a):a}function OP(e,o,a){return rs(a)?gj(e,o,a):a}function yj(e,o,a){let u=rd(o.patternProperties),p=be(a);for(let[f,h]of u)for(let g of p)if(f.test(g))a[g]=Qr(e,h,a[g]);return se(o,"additionalProperties")&<(o.additionalProperties)?al(e,u,o.additionalProperties,a):a}function _P(e,o,a){return rs(a)?yj(e,o,a):a}function LP(e,o,a){return se(e,o.$ref)?Qr(e,e[o.$ref],a):a}function NP(e,o,a){let u=bP(a);return Mo(u)?u.value:a}function qP(e,o,a){return Qr(e,qn(o),a)}function DP(e,o,a){if(!He(a))return a;for(let u=0;u<Math.min(o.items.length,a.length);u++)a[u]=Qr(e,o.items[u],a[u]);return a}function FP(e,o,a){let u=SP(a);return Mo(u)?u.value:a}function jP(e,o,a){if(o.anyOf.some((h)=>mr(e,h,a)))return a;let f=o.anyOf.map((h)=>Qr(e,h,Jr(a))).find((h)=>mr(e,o,h));return nr(f)?a:f}function UP(e,o,a){let u=SP(a);return Mo(u)?void 0:a}function Qr(e,o,a){return Rt(o)?wP(e,o,a):$o(o)?TP(e,o,a):xo(o)?RP(e,o,a):cr(o)?kP(e,o,a):rn(o)?AP(e,o,a):In(o)?PP(e,o,a):Ve(o)?$P(e,o,a):It(o)?CP(e,o,a):Us(o)?vP(e,o,a):Lr(o)?MP(e,o,a):Je(o)?OP(e,o,a):or(o)?_P(e,o,a):Zt(o)?LP(e,o,a):nn(o)?NP(e,o,a):lr(o)?qP(e,o,a):ht(o)?DP(e,o,a):gs(o)?FP(e,o,a):xe(o)?jP(e,o,a):Co(o)?UP(e,o,a):a}function Cs(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return Qr(o,a,u)}function BP(e,o,a){if(!He(a))return a;for(let u=0;u<a.length;u++)a[u]=kn(e,o.items,a[u]);return a}function GP(e,o,a){return kn({...e,...o.$defs},sn(o.$ref),a)}function KP(e,o){if(!nr(o))return o;return Os(e.default)?e.default():Jr(e.default)}function HP(e,o,a){let u=Ho(e,o),p=qn(u);return kn(e,p,a)}function WP(e,o,a){if(!lt(a))return a;let u=be(o.properties);for(let p of u){let f=kn(e,o.properties[p],a[p]);if(nr(f)&&(an(o.properties[p])||!se(o.properties[p],"default")))continue;a[p]=f}if(!Wo(o)||cn(o.additionalProperties))return a;for(let p of be(a)){if(u.includes(p))continue;a[p]=kn(e,o.additionalProperties,a[p])}return a}function zP(e,o,a){if(!lt(a))return a;let[u,p]=[new RegExp(Sn(o)),hr(o)];for(let f of be(a)){if(!(u.test(f)&&qo(p)))continue;a[f]=kn(e,p,a[f])}if(!Wo(o))return a;for(let f of be(a)){if(u.test(f))continue;a[f]=kn(e,o.additionalProperties,a[f])}return a}function VP(e,o,a){return se(e,o.$ref)?kn(e,e[o.$ref],a):a}function JP(e,o,a){if(!He(a))return a;let[u,p]=[o.items,Math.max(o.items.length,a.length)];for(let f=0;f<p;f++)if(f<u.length)a[f]=kn(e,u[f],a[f]);return a}function QP(e,o,a){for(let u of o.anyOf){let p=kn(e,u,Jr(a));if(mr(e,u,p))return p}return a}function kn(e,o,a){let u=qo(o)?KP(o,a):a;return Rt(o)?BP(e,o,u):cr(o)?GP(e,o,u):Ve(o)?HP(e,o,u):Je(o)?WP(e,o,u):or(o)?zP(e,o,u):Zt(o)?VP(e,o,u):ht(o)?JP(e,o,u):xe(o)?QP(e,o,u):u}function yi(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return kn(o,a,u)}function gu(e){return(...o)=>{let[a,u,p]=Ln(o,{3:(f,h,g)=>[f,h,g],2:(f,h)=>[{},f,h]});return e.reduce((f,h)=>h(a,u,f),p)}}function xj(e,o,a){return o["~codec"].decode(a)}function Ij(e,o,a){return o["~codec"].encode(a)}function Or(e,o,a,u){if(!Qn(a))return u;return v(e,"Decode")?xj(o,a,u):Ij(o,a,u)}function Ej(e,o,a,u){if(!He(u))return u;for(let p=0;p<u.length;p++)u[p]=qr(e,o,a.items,u[p]);return Or(e,o,a,u)}function bj(e,o,a,u){let p=Or(e,o,a,u);if(!He(p))return p;for(let f=0;f<p.length;f++)p[f]=qr(e,o,a.items,p[f]);return p}function XP(e,o,a,u){return v(e,"Decode")?Ej(e,o,a,u):bj(e,o,a,u)}function YP(e,o,a,u){return u=qr(e,{...o,...a.$defs},sn(a.$ref),u),Or(e,o,a,u)}function ZP(e){return e.reduce((o,a)=>({...o,...a}),{})}function e$(e,o){for(let a of o)if(!Da(e,a))return a;return e}function Sj(e,o,a,u){if(v(a.allOf.length,0))return Or(e,o,a,u);let p=a.allOf.map((g)=>qr(e,o,g,Vo(g,Jr(u)))),h=p.every((g)=>lt(g))?ZP(p):e$(u,p);return Or(e,o,a,h)}function wj(e,o,a,u){if(v(a.allOf.length,0))return Or(e,o,a,u);let p=Or(e,o,a,u),f=a.allOf.map((g)=>qr(e,o,g,Vo(g,Jr(p))));if(f.every((g)=>lt(g)))return ZP(f);return e$(p,f)}function t$(e,o,a,u){return v(e,"Decode")?Sj(e,o,a,u):wj(e,o,a,u)}function Tj(e,o,a,u){if(!rs(u))return u;for(let p of be(a.properties)){if(!se(u,p)||Gc(a.properties[p],p,u))continue;u[p]=qr(e,o,a.properties[p],u[p])}return Or(e,o,a,u)}function Rj(e,o,a,u){let p=Or(e,o,a,u);if(!rs(p))return p;for(let f of be(a.properties)){if(!se(p,f)||Gc(a.properties[f],f,p))continue;p[f]=qr(e,o,a.properties[f],p[f])}return p}function r$(e,o,a,u){return v(e,"Decode")?Tj(e,o,a,u):Rj(e,o,a,u)}function kj(e,o,a,u){if(!rs(u))return u;let p=new RegExp(Sn(a));for(let f of be(u)){if(!p.test(f))continue;u[f]=qr(e,o,hr(a),u[f])}return Or(e,o,a,u)}function Aj(e,o,a,u){let p=Or(e,o,a,u);if(!rs(p))return p;let f=new RegExp(Sn(a));for(let h of be(p)){if(!f.test(h))continue;p[h]=qr(e,o,hr(a),p[h])}return p}function n$(e,o,a,u){return v(e,"Decode")?kj(e,o,a,u):Aj(e,o,a,u)}function o$(e,o,a,u){return se(o,a.$ref)?qr(e,o,o[a.$ref],u):u}function s$(e,o,a,u){return v(e,"Decode")?Or(e,o,a,o$(e,o,a,u)):o$(e,o,a,Or(e,o,a,u))}function Pj(e,o,a,u){if(!He(u))return u;for(let p=0;p<Math.min(a.items.length,u.length);p++)u[p]=qr(e,o,a.items[p],u[p]);return Or(e,o,a,u)}function $j(e,o,a,u){let p=Or(e,o,a,u);if(!He(p))return u;for(let f=0;f<Math.min(a.items.length,p.length);f++)p[f]=qr(e,o,a.items[f],p[f]);return p}function i$(e,o,a,u){return v(e,"Decode")?Pj(e,o,a,u):$j(e,o,a,u)}function Cj(e,o,a,u){for(let p of a.anyOf){if(!mr(o,p,u))continue;let f=qr(e,o,p,u);return Or(e,o,a,f)}return u}function vj(e,o,a,u){let p=Or(e,o,a,u);for(let f of a.anyOf){let h=qr(e,o,f,Jr(p));if(!mr(o,f,h))continue;return h}return p}function a$(e,o,a,u){return v(e,"Decode")?Cj(e,o,a,u):vj(e,o,a,u)}function qr(e,o,a,u){return Rt(a)?XP(e,o,a,u):cr(a)?YP(e,o,a,u):Ve(a)?t$(e,o,a,u):Je(a)?r$(e,o,a,u):or(a)?n$(e,o,a,u):Zt(a)?s$(e,o,a,u):ht(a)?i$(e,o,a,u):xe(a)?a$(e,o,a,u):Or(e,o,a,u)}class u$ extends $a{constructor(e,o){super("Decode",e,o)}}function Mj(e,o,a){if(!mr(e,o,a))throw new u$(a,Vs(e,o,a));return a}function Oj(e,o,a){let u=ns().unionPrioritySort?hu(o):o;return qr("Decode",e,u,a)}var _j=gu([(e,o,a)=>Jr(a),(e,o,a)=>yi(e,o,a),(e,o,a)=>Cs(e,o,a),(e,o,a)=>Vo(e,o,a),(e,o,a)=>Mj(e,o,a),(e,o,a)=>Oj(e,o,a)]);function ch(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return _j(o,a,u)}class c$ extends $a{constructor(e,o){super("Encode",e,o)}}function Lj(e,o,a){if(!mr(e,o,a))throw new c$(a,Vs(e,o,a));return a}function Nj(e,o,a){let u=ns().unionPrioritySort?hu(o):o;return qr("Encode",e,u,a)}var qj=gu([(e,o,a)=>Jr(a),(e,o,a)=>Nj(e,o,a),(e,o,a)=>yi(e,o,a),(e,o,a)=>Cs(e,o,a),(e,o,a)=>Vo(e,o,a),(e,o,a)=>Lj(e,o,a)]);function mh(...e){let[o,a,u]=Ln(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return qj(o,a,u)}function Dj(e,o){return Qn(o)||Zi(e,o.items)}function Fj(e,o){return Qn(o)||m$({...e,...o.$defs},sn(o.$ref))}function jj(e,o){return Qn(o)||o.allOf.some((a)=>Zi(e,a))}function Uj(e,o){return Qn(o)||be(o.properties).some((a)=>Zi(e,o.properties[a]))}function Bj(e,o){return Qn(o)||Zi(e,hr(o))}function m$(e,o){if(ph.has(o.$ref))return!1;return ph.add(o.$ref),Qn(o)||se(e,o.$ref)&&Zi(e,e[o.$ref])}function Gj(e,o){return Qn(o)||o.items.some((a)=>Zi(e,a))}function Kj(e,o){return Qn(o)||o.anyOf.some((a)=>Zi(e,a))}function Zi(e,o){return Rt(o)?Dj(e,o):cr(o)?Fj(e,o):Ve(o)?jj(e,o):Je(o)?Uj(e,o):or(o)?Bj(e,o):Zt(o)?m$(e,o):ht(o)?Gj(e,o):xe(o)?Kj(e,o):Qn(o)}var ph=new Set;function lh(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return ph.clear(),Zi(o,a)}class vs extends Error{constructor(e,o){super(o);this.type=e}}function p$(e,o){return Os(o.default)?o.default(o):lt(o.default)?Jr(o.default):o.default}function l$(e,o){if(Ui(o)&&!qo(o))throw new vs(o,"Arrays with uniqueItems constraints must specify a default annotation");let a=ji(o)?o.minItems:0;return Array.from({length:a},()=>Xr(e,o.items))}function d$(e,o){return ys(o)?BigInt(o.exclusiveMinimum)+BigInt(1):xs(o)?BigInt(o.minimum):BigInt(0)}function f$(e,o){return!1}function h$(e,o){let a=Xr(e,o.instanceType);return class{constructor(){Object.assign(this,a)}}}function g$(e,o){return Xr({...e,...o.$defs},sn(o.$ref))}function y$(e,o){return Xr(e,qn(o))}function x$(e,o){let a=Xr(e,o.returnType);return()=>a}function I$(e,o){return ys(o)&&Bt(o.exclusiveMinimum)?o.exclusiveMinimum+1:xs(o)?o.minimum:0}function E$(e,o){let a=Ho(e,o),u=qn(a);return Xr(e,u)}function b$(e,o){return o.const}function S$(e,o){throw new vs(o,"Cannot create TNever types")}function w$(e,o){return null}function T$(e,o){return ys(o)&&Bt(o.exclusiveMinimum)?o.exclusiveMinimum+1:xs(o)?o.minimum:0}function R$(e,o){return(nr(o.required)?[]:o.required).reduce((u,p)=>({...u,[p]:Xr(e,o.properties[p])}),{})}function k$(e,o){if(Aa(o)&&!qo(o))throw new vs(o,"Record with the minProperties constraint must have a default annotation");return{}}function A$(e,o){return se(e,o.$ref)?Xr(e,e[o.$ref]):(()=>{throw new vs(o,"Unable to deref Ref")})()}function P$(e,o){if((Pa(o)||Ra(o))&&!qo(o))throw Error("Strings with format or pattern constraints must specify default");let u=ka(o)?o.minLength:0;return"".padEnd(u)}function $$(e,o){return Symbol()}function C$(e,o){let a=Bu(o.pattern);if(nn(a))throw new vs(o,"Unable to create TemplateLiteral due to infinite type expansion");return Xr(e,a)}function v$(e,o){return Array.from({length:o.minItems},(a,u)=>Xr(e,o.items[u]))}function M$(e,o){return}function O$(e,o){if(v(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Xr(e,o.anyOf[0])}function _$(e,o){return}function Xr(e,o){return qo(o)?p$(e,o):Rt(o)?l$(e,o):$o(o)?d$(e,o):xo(o)?f$(e,o):Yr(o)?h$(e,o):cr(o)?g$(e,o):rn(o)?y$(e,o):Zr(o)?x$(e,o):In(o)?I$(e,o):Ve(o)?E$(e,o):It(o)?b$(e,o):Po(o)?S$(e,o):Us(o)?w$(e,o):Lr(o)?T$(e,o):Je(o)?R$(e,o):or(o)?k$(e,o):Zt(o)?A$(e,o):nn(o)?P$(e,o):Bs(o)?$$(e,o):lr(o)?C$(e,o):ht(o)?v$(e,o):gs(o)?M$(e,o):xe(o)?O$(e,o):Co(o)?_$(e,o):void 0}function Js(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Xr(o,a)}class ul extends $a{constructor(e,o){super("Parse",e,o)}}function Hj(e,o,a){if(!mr(e,o,a))throw new ul(a,Vs(e,o,a));return a}var L$=gu([(e,o,a)=>Jr(a),(e,o,a)=>yi(e,o,a),(e,o,a)=>Cs(e,o,a),(e,o,a)=>Vo(e,o,a),(e,o,a)=>Hj(e,o,a)]);var zj=l({type:i("insert"),path:s(),value:Q()}),Vj=Object({type:i("update"),path:s(),value:Q()}),Jj=l({type:i("delete"),path:s()}),GMe=y([zj,Vj,Jj]);class cl{constructor(e,o){this.hasCodec=lh(e,o),this.buildResult=nl(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(ns().correctiveParse)return L$(this.Context(),this.Type(),e);throw new ul(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Vs(this.Context(),this.Type(),e)}Clean(e){return Vo(this.Context(),this.Type(),e)}Convert(e){return Cs(this.Context(),this.Type(),e)}Create(){return Js(this.Context(),this.Type())}Default(e){return yi(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?ch(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?mh(this.Context(),this.Type(),e):this.Parse(e)}}function fh(...e){let[o,a]=Ln(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return new cl(o,a)}var q$=new WeakMap,Yj=Symbol.for("TypeBox.Kind");function Zj(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function eU(e,o){switch(o){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function hh(e){try{return F$(e)}catch{return}}function tU(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isFinite(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isInteger(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function rU(e,o){let a=o.properties,u=new Set(a?Object.keys(a):[]);if(a)for(let[p,f]of Object.entries(a)){if(!(p in e))continue;e[p]=va(e[p],f)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[p,f]of Object.entries(e)){if(u.has(p))continue;e[p]=va(f,o.additionalProperties)}}function nU(e,o){if(Array.isArray(o.items)){for(let a=0;a<e.length;a++){let u=o.items[a];if(!u)continue;e[a]=va(e[a],u)}return}if(o.items&&typeof o.items==="object")for(let a=0;a<e.length;a++)e[a]=va(e[a],o.items)}function D$(e,o){for(let a of o)if(hh(a)?.Check(e))return e;for(let a of o){let u=structuredClone(e),p=va(u,a);if(hh(a)?.Check(p))return p}return e}function va(e,o){let a=e;if(Array.isArray(o.allOf))for(let f of o.allOf)a=va(a,f);if(Array.isArray(o.anyOf))a=D$(a,o.anyOf);if(Array.isArray(o.oneOf))a=D$(a,o.oneOf);let u=Zj(o),p=u.length>1&&u.some((f)=>eU(a,f));if(u.length>0&&!p)for(let f of u){let h=tU(a,f);if(h!==a){a=h;break}}if(u.includes("object")&&typeof a==="object"&&a!==null&&!Array.isArray(a))rU(a,o);if(u.includes("array")&&Array.isArray(a))nU(a,o);return a}function ml(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)ml(e[p],f)}else if(o.items)for(let p of e)ml(p,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let a=e,u=new Set(o.required??[]);for(let[p,f]of Object.entries(o.properties)){if(!(p in a))continue;if(a[p]===null&&!u.has(p)&&typeof f.$ref!=="string"&&hh(f)?.Check(null)===!1)delete a[p];else ml(a[p],f)}}function F$(e){let o=e,a=q$.get(o);if(a)return a;let u=fh(e);return q$.set(o,u),u}function oU(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function sU(e,o){let a=e.find((u)=>u.name===o.name);if(!a)throw Error(`Tool "${o.name}" not found`);return yu(a,o)}function yu(e,o){let a=structuredClone(o.arguments);ml(a,e.parameters),Cs(e.parameters,a);let u=F$(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Yj)){let h=va(a,e.parameters);if(h!==a)if(typeof a==="object"&&a!==null&&typeof h==="object"&&h!==null){for(let g of Object.keys(a))delete a[g];Object.assign(a,h)}else return u.Check(h)?h:a}if(u.Check(a))return a;let p=u.Errors(a).map((h)=>` - ${oU(h)}: ${h.message}`).join(`
|
|
24
|
-
`)||"Unknown validation error",f=`Validation failed for tool "${o.name}":
|
|
25
|
-
${p}
|
|
26
|
-
|
|
27
|
-
Received arguments:
|
|
28
|
-
${JSON.stringify(o.arguments,null,2)}`;throw Error(f)}var j$;function Kc(){if(!j$)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return j$}async function U$(e,o,a,u,p,f){let h=K$(o,e),g=[...h],x={...o,messages:[...o.messages,...h]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let I of h)await u({type:"message_start",message:I}),await u({type:"message_end",message:I});return await G$(x,g,a,p,u,f??Kc()),g}async function B$(e,o,a,u,p){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let f=[],h={...e};return await a({type:"agent_start"}),await a({type:"turn_start"}),await G$(h,f,o,u,a,p??Kc()),f}async function G$(e,o,a,u,p,f){let h=e,g=a,x,I=!1,E=await g.getSteeringMessages?.()||[];while(!0){let k=!0;while(k||E.length>0){let P=[];if(x){let L=await g.prepareNextTurn?.(x);if(L)h=L.context??h,P=L.messages??[],g={...g,model:L.model??g.model,reasoning:L.thinkingLevel===void 0?g.reasoning:L.thinkingLevel==="off"?void 0:L.thinkingLevel};if(E.length===0)E=await g.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let L of K$(h,[...P,...E]))await p({type:"message_start",message:L}),await p({type:"message_end",message:L}),h.messages.push(L),o.push(L);E=[];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 aU(h,g,u,p,f);if(o.push(M),M.stopReason==="error"||M.stopReason==="aborted"){x={message:M,toolResults:[],context:h,newMessages:o},await g.finishTurn?.(x,u),await p({type:"turn_end",message:M,toolResults:[]}),await p({type:"agent_end",messages:o});return}let J=M.content.filter((L)=>L.type==="toolCall"),O=[];if(k=!1,J.length>0){let L=M.stopReason==="length"?await uU(J,p):await cU(h,M,g,u,p);O.push(...L.messages),k=!L.terminate;for(let X of O)h.messages.push(X),o.push(X)}x={message:M,toolResults:O,context:h,newMessages:o};let B=await g.finishTurn?.(x,u);if(await p({type:"turn_end",message:M,toolResults:O}),B?.action==="end"){await p({type:"agent_end",messages:o});return}if(I=B?.action==="continue",E=await g.getSteeringMessages?.()||[],k||E.length>0)I=!1}let A=await g.getFollowUpMessages?.()||[];if(A.length>0){I=!1,E=A;continue}if(I){I=!1;continue}break}await p({type:"agent_end",messages:o})}function K$(e,o){let a=-1;for(let E=o.length-1;E>=0;E--)if(o[E].role==="system"){a=E;break}let u=o[a],p=u?o.map((E,k)=>k===a?gh(u,iU):E):o,f=ui(ce([...e.messages,...p]),(e.tools??[]).map(pt)),h=f.toolsAdded.length===0&&f.toolsRemoved.length===0;if(u){if(h&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return p.map((E,k)=>k===a?gh(u,f):E)}if(h)return o;let g=gh({role:"system",content:"",timestamp:Date.now()},f),x=o.findIndex((E)=>E.role!=="system"),I=x===-1?o.length:x;return[...o.slice(0,I),g,...o.slice(I)]}var iU={toolsAdded:[],toolsRemoved:[]};function gh(e,{toolsAdded:o,toolsRemoved:a}){let{toolsAdded:u,toolsRemoved:p,...f}=e;return{...f,...o.length>0?{toolsAdded:o}:{},...a.length>0?{toolsRemoved:a}:{}}}async function aU(e,o,a,u,p){let f=e.messages;if(o.transformContext)f=await o.transformContext(f,a);let h=await o.convertToLlm(f),g=At({messages:h}),x=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,I=await p(o.model,g,{...o,apiKey:x,signal:a}),E=async()=>Object.assign(await I.result(),{thinkingLevel:o.reasoning??"off"}),k=null,A=!1;for await(let C of I)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 E();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 E();if(A)e.messages[e.messages.length-1]=P;else e.messages.push(P),await u({type:"message_start",message:{...P}});return await u({type:"message_end",message:P}),P}async function uU(e,o){let a=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let p={toolCall:u,result:Ii(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Hc(p,o);let f=yh(p);await xh(f,o),a.push(f)}return{messages:a,terminate:!1}}async function cU(e,o,a,u,p){let f=o.content.filter((g)=>g.type==="toolCall"),h=f.some((g)=>e.tools?.find((x)=>x.name===g.name)?.executionMode==="sequential");if(a.toolExecution==="sequential"||h)return mU(e,o,f,a,u,p);return pU(e,o,f,a,u,p)}async function mU(e,o,a,u,p,f){let h=[],g=[];for(let x of a){await f({type:"tool_execution_start",toolCallId:x.id,toolName:x.name,args:x.arguments});let I=await W$(e,o,x,u,p),E;if(I.kind==="immediate")E={toolCall:x,result:I.result,isError:I.isError};else{let A=await V$(I,p,z$(x,f));E=await J$(e,o,I,A,u,p)}await Hc(E,f);let k=yh(E);if(await xh(k,f),h.push(E),g.push(k),p?.aborted)break}return{messages:g,terminate:H$(h)}}async function pU(e,o,a,u,p,f){let h=[];for(let I of a){await f({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let E=await W$(e,o,I,u,p);if(E.kind==="immediate"){let k={toolCall:I,result:E.result,isError:E.isError};if(await Hc(k,f),h.push(k),p?.aborted)break;continue}if(h.push(async()=>{if(p?.aborted){let P={toolCall:I,result:Ii("Operation aborted"),isError:!0};return await Hc(P,f),P}let k=await V$(E,p,z$(I,f)),A=await J$(e,o,E,k,u,p);return await Hc(A,f),A}),p?.aborted)break}let g=await Promise.all(h.map((I)=>typeof I==="function"?I():Promise.resolve(I))),x=[];for(let I of g){let E=yh(I);await xh(E,f),x.push(E)}return{messages:x,terminate:H$(g)}}function H$(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function lU(e,o){if(!e.prepareArguments)return o;let a=e.prepareArguments(o.arguments);if(a===o.arguments)return o;return{...o,arguments:a}}async function W$(e,o,a,u,p,f=e.tools??[]){let h=f.find((g)=>g.name===a.name);if(!h)return{kind:"immediate",result:Ii(`Tool ${a.name} not found`),isError:!0};try{let g=lU(h,a),x=yu(h,g);if(u.beforeToolCall){let I=await u.beforeToolCall({assistantMessage:o,toolCall:a,args:x,context:e},p);if(p?.aborted)return{kind:"immediate",result:Ii("Operation aborted"),isError:!0};if(I?.block){let E=Ii(I.reason||"Tool execution was blocked");if(I.terminate===!0)E.terminate=!0;return{kind:"immediate",result:E,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Ii("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:a,tool:h,args:x}}catch(g){return{kind:"immediate",result:Ii(g instanceof Error?g.message:String(g)),isError:!0}}}function z$(e,o){return(a)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:a})}async function V$(e,o,a){let u=[],p=!0,f=performance.now(),h=()=>Math.round(performance.now()-f);try{let g=await e.tool.execute(e.toolCall.id,e.args,o,(I)=>{if(!p)return;u.push(Promise.resolve(a(I)))}),x=h();return p=!1,await Promise.all(u),{result:g,isError:g.isError===!0,durationMs:x}}catch(g){let x=h();return p=!1,await Promise.all(u),{result:Ii(g instanceof Error?g.message:String(g)),isError:!0,durationMs:x}}finally{p=!1}}async function J$(e,o,a,u,p,f){let{result:h,isError:g}=u;if(p.afterToolCall)try{let x=await p.afterToolCall({assistantMessage:o,toolCall:a.toolCall,args:a.args,result:h,isError:g,context:e},f);if(x){let I=x.structuredContent??(x.content?void 0:h.structuredContent);if(h={...h,content:x.content??h.content,details:x.details??h.details,usage:x.usage??h.usage,terminate:x.terminate??h.terminate},I===void 0)delete h.structuredContent;else h.structuredContent=I;g=x.isError??g}}catch(x){h=Ii(x instanceof Error?x.message:String(x)),g=!0}return{toolCall:a.toolCall,result:h,isError:g,durationMs:u.durationMs}}function Ii(e){return{content:[{type:"text",text:e}],details:{}}}async function Hc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function yh(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs},timestamp:Date.now()}}async function xh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function dU(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var fU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},hU={id:"unknown",name:"unknown",api:"unknown",provider:"unknown",baseUrl:"",reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function gU(e){let o=e?.tools?.slice()??[],a=e?.messages?.slice()??[],u=ho(e?.systemPrompt,o.map(pt));if(a[0]?.role!=="system"&&u)a.unshift(u);return{get systemPrompt(){return ci(a)},model:e?.model??hU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(p){o=p.slice()},get messages(){return a},set messages(p){a=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Ih{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class Eh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let o=e??{};this._state=gU(o.initialState),this.convertToLlm=o.convertToLlm??dU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Kc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new Ih(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Ih(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=An(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let a=this.normalizePromptInput(e,o);await this.runPromptMessages(a)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let a=this.followUpQueue.drain();if(a.length>0){await this.runPromptMessages(a);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let a=[{type:"text",text:e}];if(o&&o.length>0)a.push(...o);return[{role:"user",content:a,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(a)=>{await U$(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),a,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await B$(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(a)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(a,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,a=()=>{},u=new Promise((p)=>{a=p});this.activeRun={promise:u,resolve:a,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(p){await this.handleRunFailure(p,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let a={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:fU,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:a}),await this.processEvents({type:"message_end",message:a}),await this.processEvents({type:"turn_end",message:a,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[a]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let a=new Set(this._state.pendingToolCalls);a.add(e.toolCallId),this._state.pendingToolCalls=a;break}case"tool_execution_end":{let a=new Set(this._state.pendingToolCalls);a.delete(e.toolCallId),this._state.pendingToolCalls=a;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let a of this.listeners)await a(e,o)}}var pl=Symbol("basalt.rebind-fetch");function ve(e,...o){return Object.assign(e,{aliases:o})}function Ma(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function yU(e){let o=[],a="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(a)o.push(a);a="";continue}if(u>="A"&&u<="Z"&&a&&!/[A-Z]$/.test(a))o.push(a),a="";a+=u}if(a)o.push(a);return o}function Q$(e,o){if(e.some((C)=>C.name===o))return o;let a=e.map((C)=>C.name),u=(C)=>a.filter((M)=>Ma(M)===C),p=u(Ma(o));if(p.length===1&&p[0])return p[0];if(p.length>1)return o;let f=o.split(/[.:/]/).pop()??o,h=f===o?[]:u(Ma(f));if(h.length===1&&h[0])return h[0];let g=new Map;for(let C of e)for(let M of C.aliases??[]){let J=Ma(M);g.set(J,(g.get(J)??new Set).add(C.name))}let x=(C)=>[...new Set([...u(C),...g.get(C)??[]])],I=x(Ma(f));if(I.length===1&&I[0])return I[0];if(I.length>1)return o;let E=yU(f),k=new Set;E.forEach((C,M)=>{k.add(Ma(C));let J=E[M+1];if(J)k.add(Ma(C+J))});let A=new Set;for(let C of k)for(let M of x(C))A.add(M);let P=[...A];return P.length===1&&P[0]?P[0]:o}function T(e){return e}function Cn(e,o){let a=o.indexOf("/");if(a<=0)return;return e.getModel(o.slice(0,a),o.slice(a+1))}function Mt(e){return`${e.provider}/${e.id}`}function Z$(e,o,a){let u=async(f,h)=>{try{if(o){let x=f instanceof Request?f:void 0;o({at:Date.now(),method:h?.method??x?.method??"GET",url:typeof f==="string"?f:f instanceof URL?f.toString():f.url,headers:X$(h?.headers??x?.headers),body:xU(h?.body!==void 0?h.body:x?.body??void 0)})}}catch{}let g=await e(f,h);if(a)try{let x=Date.now(),{status:I,statusText:E}=g,k=X$(g.headers);if(!g.body)return a({at:x,status:I,statusText:E,headers:k,body:""}),g;let A="",P=new TextDecoder,C=new TransformStream({transform(O,B){B.enqueue(O),A+=P.decode(O,{stream:!0}),a({at:x,status:I,statusText:E,headers:k,body:A})},flush(){A+=P.decode(),a({at:x,status:I,statusText:E,headers:k,body:A})}}),M=g.body.pipeThrough(C),J=new Response(M,g);try{Object.defineProperty(J,"url",{value:g.url})}catch{}return J}catch{}return g},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:p,[pl]:(f)=>Z$(f,o,a)})}function X$(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,p)=>{o[p]=u}),o;let a=Array.isArray(e)?e:Object.entries(e);for(let u of a)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function xU(e){if(e===void 0||e===null)return"";if(typeof e==="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e))return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));return`<${typeof e==="object"&&typeof e.constructor==="function"?e.constructor.name:typeof e}: \u975E\u6587\u672C\u8BF7\u6C42\u4F53\uFF0C\u672A\u8BB0\u5F55\u539F\u6587>`}function IU(e,o){return Q$(e,o)}function EU(e,o,a){let u=Date.now(),p=new WeakSet,f=(x)=>{if(!x||typeof x!=="object"||!("role"in x)||x.role!=="assistant")return;let I=Date.now(),E=Math.max(10,I-u);x.generationMs=E},h=async(x)=>{if(!a||!x||typeof x!=="object"||!("role"in x)||x.role!=="assistant")return;if(f(x),p.has(x))return;p.add(x),Object.assign(x,await a(x))},g=(x)=>{let I=x?.content;if(!Array.isArray(I))return;for(let E of I)if(E&&E.type==="toolCall"&&typeof E.name==="string")E.name=IU(o(),E.name)};return{async*[Symbol.asyncIterator](){for await(let x of e){let{partial:I,message:E}=x;g(I),await h(E),g(E),yield x}},result:async()=>{let x=await e.result();return f(x),await h(x),g(x),x}}}function Wc(e,o){let a=(o??[]).filter((g)=>g.kind==="path").map((g)=>`<file path=${JSON.stringify(g.data)} />`),u=(o??[]).filter((g)=>g.kind==="text").map((g)=>`<file name=${JSON.stringify(g.name)}>
|
|
29
|
-
${g.data}
|
|
30
|
-
</file>`),p=(o??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),f=(o??[]).filter((g)=>g.kind==="image"&&g.id).map((g)=>`<image id=${JSON.stringify(g.id)} name=${JSON.stringify(g.name)} />`);return{merged:[...a,...u,...f,...e.trim()?[e]:[]].join(`
|
|
31
|
-
|
|
32
|
-
`),images:p}}function bh(e,o){let{merged:a,images:u}=Wc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:a},...u]:a,timestamp:Date.now()}}var Y$=!1;function eC(e){let o=new Set;for(let g of e.tools){let x=g.name.toLowerCase();if(o.has(x))throw Error(`Tool names collide ignoring case: ${g.name}`);o.add(x)}let a=new Eh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(g,x,I)=>{let{captureRequest:E,captureResponse:k}=e,A=E||k?{...I,fetch:Z$(I?.fetch??globalThis.fetch,E?(C)=>E({...C,model:Mt(g)}):void 0,k?(C)=>k({...C,model:Mt(g)}):void 0)}:I,P=g.api==="openai-completions"||g.api==="openai-responses"?{...g,compat:{...g.compat,supportsDeveloperRole:!1}}:g;return EU(e.models.streamSimple(P,x,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:x})=>{let I=g.messages.findIndex((P)=>P.role!=="system"),E=g.messages.slice(0,I===-1?g.messages.length:I),k=e.hooks.prepare,A=e.hooks.tools?.()??g.tools;if(A){a.state.tools=A;let P=E[0];if(P?.role==="system")E[0]={...P,toolsAdded:A.map(pt),toolsRemoved:void 0}}return{context:{...g,tools:A,messages:await k(E,A,x)}}}:void 0}),u=new Map,p=new Map,f=new WeakSet,h;return a.subscribe((g)=>{if(g.type==="message_update"&&g.message.role==="assistant"){p.clear(),e.hooks.draft(tC(g.message));return}if(g.type==="tool_execution_update"){let I=u.get(g.toolCallId)??Ne(g.toolName,g.args),E=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:I.name,input:I.input,...I.source?{source:I.source}:{},output:E}),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 x=g.message.role==="user"&&h?{type:"user",text:h.text,...h.attachments?.length?{attachments:h.attachments}:{}}:bU(g.message);if(g.message.role==="user")h=void 0;if(x?.type==="assistant"){for(let I of x.parts)if(I.type==="tool_call")u.set(I.id,I)}if(x?.type==="tool_result"){let I=u.get(x.callID);if(I?.source)Object.assign(x,{name:I.name,source:I.source})}if(x)e.hooks.message(x,g.message);if(g.message.role==="assistant")e.hooks.draft(null)}),{agent:a,prompt:(g,x)=>{h={text:g,attachments:x};let{merged:I,images:E}=Wc(g,x);return a.prompt(I,E.length>0?E: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 I=a.steeringQueue?.messages;if(!Array.isArray(I)){if(!Y$)Y$=!0,console.warn("pi Agent.steeringQueue.messages is missing; steering messages cannot be recalled");return!1}let E=I.indexOf(g);if(E<0){let A=JSON.stringify(g);E=I.findIndex((P)=>JSON.stringify(P)===A)}if(E<0)return!1;let[k]=I.splice(E,1);if(k)f.delete(k);return!0},abort:()=>a.abort()}}function Sh(e){if(e?.role!=="assistant")return{reason:"done"};if(e.stopReason==="aborted")return{reason:"aborted"};if(e.stopReason==="error")return{reason:"error",error:e.errorMessage};return{reason:"done"}}function ll(e,o="\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"){let{name:a,source:u}=Ne(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:a,...u?{source:u}:{},output:o,isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:o}],isError:!0,timestamp:Date.now()}}}function tC(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...Ne(o.name,o.arguments)}})}function bU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:tC(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((a)=>a.type==="image").map((a)=>({mimeType:a.mimeType,data:a.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((a)=>a.type==="text"?a.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class tt extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function R(e){return e}import{createHash as rC}from"crypto";import{existsSync as SU}from"fs";import{readFile as nC,realpath as dl}from"fs/promises";import{dirname as wU,isAbsolute as oC,relative as sC,resolve as iC,sep as aC}from"path";var uC=[...Ki];class fl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class hl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let a=wU(iC(e)),u=iC(a,o??"web.tsx");if(!o&&!SU(u))return;let p=sC(await dl(a),await dl(u));if(oC(p)||p===".."||p.startsWith(`..${aC}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let a=this.pending.get(e);if(a)return a;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let a=this.cache.get(e);if(a){let I=!0;for(let[E,k]of a.inputs){let A=await nC(E).catch(()=>{return});if(!A||rC("sha256").update(A).digest("hex")!==k){I=!1;break}}if(I)return a.source;this.cache.delete(e)}let u=await dl(o),p=new Map,f=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:uC,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(I){I.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(E)=>{if(!uC.includes(E.path))throw Error(`Unsupported shared web import: ${E.path}`);return{path:E.path,external:!0}}),I.onLoad({filter:/.*/},async(E)=>{let k=sC(u,await dl(E.path));if(oC(k)||k===".."||k.startsWith(`..${aC}`))throw Error("Plugin web imports must stay inside its plugin directory");let A=await nC(E.path);p.set(E.path,rC("sha256").update(A).digest("hex"));return})}}]}).catch((I)=>{let k=(I instanceof AggregateError?I.errors:[I]).map((A)=>A instanceof Error?A.message:String(A));throw Error(`Plugin web build failed: ${k.join("; ")}`,{cause:I})});if(!f.success)throw new fl(f.logs.filter((I)=>I.level==="error").map((I)=>({file:I.position?.file??null,line:I.position?.line??null,message:I.message})));let h=f.outputs.find((I)=>I.kind==="entry-point"&&I.path.endsWith(".js")),g=f.outputs.find((I)=>I.path.endsWith(".css"));if(!h||f.outputs.some((I)=>I!==h&&I!==g))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let x=await h.text();return this.cache.set(e,{source:x,css:await g?.text(),inputs:p}),x}}function es(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Qs(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 gl(e){return e.content.flatMap((a)=>a.type==="text"&&a.text.trim()?[a.text.trim()]:[]).join(`
|
|
33
|
-
|
|
34
|
-
`)}function xu(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function Iu(e){return e.role==="assistant"&&e.content.length>0}function Ge(e){let o=[],a=new Map,u=0;for(let p of e){let f=p.raw;if(f.role==="assistant"){if(Iu(f))u++;for(let h of f.content){if(h.type!=="toolCall")continue;let g={call:h,step:u,message:f};o.push(g),a.set(h.id,g)}}else if(f.role==="toolResult"){let h=a.get(f.toolCallId);if(h)h.result=f}}return o}var yl=new Set(["edit","write"]),cC=new Set(["grep","glob"]);function ko(e,o){let a=Ne(e.name,e.arguments).input?.[o];return typeof a==="string"?a:void 0}function mC(e){return[...new Set(Ge(e).flatMap((o)=>yl.has(Ne(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&ko(o.call,"path")?[ko(o.call,"path")]:[]))]}function wh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function xl(e){let o=[{source:"ASSISTANT_TOOL",text:`${Ne(e.call.name,e.call.arguments).name}(${es(Ne(e.call.name,e.call.arguments).input)}) [${wh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:xu(e.result)});return o}function F(e){let o=0,a=0,u=0;for(let p of e){let f=p.codePointAt(0);if(f<=127)o++;else if(f>=19968&&f<=40959||f>=12288&&f<=12351||f>=65280&&f<=65519||f>=131072&&f<=173791)a++;else u++}return Math.max(0,Math.ceil(o/4+a+u/2))}var Th=8192;function G(e){let o=e,a=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let p of o.content)if(p.type==="text")u+=p.text;else a++;else if(o.role==="assistant")for(let p of o.content)if(p.type==="text")u+=p.text;else if(p.type==="thinking")u+=p.thinking;else u+=`${p.name}${es(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")u+=p.text;else a++;else u=es(e);return F(u)+16+a*Th}function Lt(e=[]){return e.reduce((o,a)=>o+F(a.name+a.description+es(a.parameters))+16,0)}function Wn(e,o){let a=e.replace(/\s+/g," ").trim();if(F(a)<=o)return a;let u=Math.min(a.length,o*4);while(u>0&&F(a.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${a.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Uo(e,o,a=Number.POSITIVE_INFINITY){if(F(e)<=o&&e.length<=a)return e;let u=`
|
|
35
|
-
[... omitted; use history tools for the full text ...]
|
|
36
|
-
`,p=Math.floor((o-F(u))/2);if(p<=0)return"";let f=(h)=>{let g=0,x=Math.max(0,Math.min(e.length,p*4,Math.floor((a-u.length)/2)));while(g<x){let I=Math.ceil((g+x)/2),E=h?e.slice(-I):e.slice(0,I);if(F(E)<=p)g=I;else x=I-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 Il(e,o){if(F(e.join(`
|
|
37
|
-
`))<=o)return e;let a=(E)=>`- [... ${E} steps omitted; use history tools for the full text ...]`,u=o-F(a(e.length)),p=[],f=[],h=0,g=0,x=e.length-1;while(g<=x){let E=p.length<=f.length,k=E?e[g]:e[x],A=F(`${k}
|
|
38
|
-
`);if(h+A>u)break;if(h+=A,E)p.push(e[g++]);else f.unshift(e[x--])}let I=x-g+1;return[...p,...I>0?[a(I)]:[],...f]}function rt(e){let o=[],a;for(let u of e){let p=u.entry;if(p.type==="run"&&p.state==="start"){a={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(a);continue}if(p.type==="run"&&p.state==="end"){if(a)a.end=p.seq,a.status=TU(p.reason,a.records);a=void 0;continue}if(p.type==="extension"||!u.raw)continue;if(!a&&p.type==="user"&&p.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!a)a={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(a);a.records.push(u)}for(let u of o)u.records=Xo(u.records);return o}function Xo(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 x=f.raw.content?.filter((I)=>I.type==="toolCall")??[];if(x.length>0)for(let I of x)u.add(I.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((x)=>x.raw?.role==="assistant");if(u.size>0||g){a.push(f);continue}o.push(f);continue}o.push(f)}if(a.length>0)o.push(...a);return o}function TU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let a=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return a?.stopReason==="error"&&Ta(a)?"interrupted":"failed";if(!a)return"completed";switch(a.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return Ta(a)?"interrupted":"failed";default:return"interrupted"}}function wt(e){for(let o=e.length-1;o>=0;o--){let a=e[o]?.entry;if(a?.type==="compaction")return a.through}return 0}function El(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((a)=>a.entry.seq<=o)}function Rh(e,o){return e.find((a)=>a.start<o&&!El(a,o)&&a.records.some((u)=>u.entry.seq<=o))}function _r(e){let o=wt(e),u=rt(e).findLast((p)=>p.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function Xn(e){let o=wt(e);return Rh(rt(e),o)?.end}function dn(e,o){let a=wt(e),u=rt(e).at(-1);if(!u||u.end!==void 0)return;let p=u.records.filter((E)=>E.entry.seq>a),f=[],h=new Set;for(let E of p){let k=E.raw,A=G(E.raw);if(k.role==="assistant"){for(let P of k.content)if(P.type==="toolCall")h.add(P.id)}else if(k.role==="toolResult")h.delete(k.toolCallId);if(Iu(k)||!f.length||k.role==="user"&&f.at(-1)?.assistant)f.push({end:E.entry.seq,tokens:A,assistant:Iu(k),pending:h.size});else{let P=f.at(-1);P.end=E.entry.seq,P.tokens+=A,P.pending=h.size}}let g=f.findLastIndex((E)=>E.assistant),x=0,I;for(let E=f.length-1;E>=0;E--){let k=f[E];if(E<g&&k.assistant&&k.pending===0&&(x<=o||I===void 0))I=k.end;if(x+=k.tokens,x>o&&I!==void 0)break}if(x<=o)return;return I}var pC=2000;function Ot(e,o){let a=F(o);if(a<=pC)return o;let u=new TextEncoder().encode(o).length,p=o.split(`
|
|
39
|
-
`).length,f=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${p} lines, approximately ${a} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
|
|
40
|
-
`),h="</user-text-reference>",g=pC-F(`${f}
|
|
41
|
-
|
|
42
|
-
${h}`);if(g<=0)return o;let x=`${f}
|
|
43
|
-
${Uo(o,g,o.length-f.length-h.length-3)}
|
|
44
|
-
${h}`;return x.length<o.length&&F(x)<a?x:o}function lC(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let p=Ot(e.entry.seq,o.content);return p===o.content?o:{...o,content:p}}let a=!1,u=o.content.map((p)=>{if(p.type!=="text")return p;let f=Ot(e.entry.seq,p.text);if(f!==p.text)a=!0;return f===p.text?p:{...p,text:f}});return a?{...o,content:u}:o}function kh(e,o=!1){let a=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),u=a.flatMap((P)=>{let 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?Uo(a.map((C)=>Qs(C.raw)).join(`
|
|
45
|
-
|
|
46
|
-
`),600):a.map((C,M)=>`<user-message sequence="${M+1}">
|
|
47
|
-
${Ot(C.entry.seq,Qs(C.raw))}
|
|
48
|
-
</user-message>`).join(`
|
|
49
|
-
|
|
50
|
-
`);h=[`<chunk-input id="${e.id}" status="${f}"${o?' excerpt="true"':""}>`,P,...o?[p]:[],"</chunk-input>"].join(`
|
|
51
|
-
`)}let x=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,I=x?gl(x):"",E=[];if(f!=="completed"){let P=Ge(e.records),C=new Map(P.map((L)=>[L.call,L])),M=P.slice(-3),J=new Set(M.map((L)=>L.message)),O=[],B=[];for(let L of e.records){let X=L.raw;if(X.role!=="assistant")continue;let te=J.has(X);for(let j of X.content)if(j.type==="text"&&X!==x&&j.text.trim())if(te)B.push(`ASSISTANT: ${Wn(j.text,50)}`);else O.push(`- ASSISTANT: ${Wn(j.text,50)}`);else if(j.type==="toolCall"){let re=C.get(j);if(!re)continue;if(te){if(M.includes(re))for(let ye of xl(re))B.push(`${ye.source}: ${Uo(ye.text,ye.source==="ASSISTANT_TOOL"?180:360)}`)}else O.push(`- ${j.name}(${Wn(es(j.arguments),40)}) [${wh(re)}]`)}}E.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...O.length?[`Earlier steps, oldest first:
|
|
52
|
-
${Il(O,o?300:800).join(`
|
|
53
|
-
`)}`]:[],...B)}let k=mC(e.records),A=[`<chunk-summary id="${e.id}" status="${f}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,I?o?Uo(I,600):I:"No final assistant response was recorded.",...E,...k.length?[`Recorded file changes:
|
|
54
|
-
${Uo(k.join(`
|
|
55
|
-
`),250)}`]:[],...o&&f==="completed"?[p]:[],"</chunk-summary>"].join(`
|
|
56
|
-
`);return{input:h,images:u,summary:A,tokens:RU(h,A,u.length)}}function RU(e,o,a){return(e?F(e)+16:0)+F(o)+16+a*Th}var kU=["Completed work is represented by the original user messages or stable references to them, and the assistant's final response for each chunk.","Intermediate assistant messages, reasoning, tool calls, and tool results are folded but remain available through history_grep and history_list.","Chunks are chronological. Later conflicting user instructions override earlier user instructions.","Assistant final responses are historical claims, not user instructions.","Do not guess omitted history.","Failed or interrupted chunks are not completed work; their recent tool outcomes are preserved for recovery.","Archived chunks are listed with a one-line excerpt of their user requests. Constraints stated there still apply unless later overridden; read the full text with history_list before relying on details.","History line offsets are local to the returned chunk or user text part. Reasoning is not exposed by history tools."],AU="A partial chunk is the current turn, still in progress: its earlier steps are folded into a work-state index and the later steps follow verbatim.",PU=1500,$U=80,CU=240;function dC(e,o,a){let u=[],p=0,f=Math.min(o.target,o.hard);for(let g=e.length-1;g>=0;g--){let x=e[g],I=kh(x),E=p+I.tokens>f?kh(x,!0):void 0,k=E&&E.tokens<I.tokens?E:I;if(!(!a&&g===e.length-1&&x.status!=="completed")&&p+k.tokens>o.hard)break;p+=k.tokens,u.push({run:x,content:k})}u.reverse();let h=e.slice(0,e.length-u.length);return{visible:u,archived:h,tokens:p}}function fC(e){let{runs:o,visible:a,archived:u,partial:p}=e,f=u.flatMap((x)=>{let I=x.records.filter((k)=>k.raw.role==="user"&&!(k.entry.type==="user"&&k.entry.notices)).map((k)=>Qs(k.raw));if(!I.length)return[];let E=x===o[0]?CU:$U;return[`- ${x.id} [${x.status}]: ${Wn(I.join(" / "),E)}`]}),h=new Map(o.map((x,I)=>[x,I+1])),g=[...a.map((x)=>h.get(x)??0),...p?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...kU,...p?[AU]:[],"",`visible chunks: ${a.length+(p?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((x)=>x.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:",Uo(f.join(`
|
|
57
|
-
`),PU)]:[],"</conversation-checkpoint>"].join(`
|
|
58
|
-
`)}function hC(e,o){let a=e.split(`
|
|
59
|
-
`),u=o.split(`
|
|
60
|
-
`),p=new Set(a),f=new Set(u),h=[...a.filter((x)=>x.trim()&&!f.has(x)).map((x)=>`- ${Wn(x,40)}`),...u.filter((x)=>x.trim()&&!p.has(x)).map((x)=>`+ ${Wn(x,40)}`)],g=a.find((x)=>x.trim()&&f.has(x));return[...h.slice(0,6),...h.length>6?[`\u2026 ${h.length-6} more changed lines`]:[],...g&&h.every((x)=>x.startsWith("+"))?[`@ ${Wn(g,40)}`]:[]]}function bl(e,o){if(!o)return e;let a=o.endsWith("/")?o:`${o}/`;return e.startsWith(a)?e.slice(a.length):e}function vU(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((a)=>{let u=a&&typeof a==="object"?a.path:void 0;return typeof u==="string"?[u]:[]})}function MU(e,o){let a=ko(e,"path");if(yl.has(e.name)&&a)return`file:${bl(a,o)}`;let u=ko(e,"command");if(u)return`command:${u}`;return`${e.name}:${es(e.arguments)}`}function OU(e,o){let a={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let f of Ge(e)){let h=u.get(f.step)??[];h.push(f),u.set(f.step,h)}let p=new Map;for(let f of e){let h=f.raw;if(!Iu(h))continue;let g=++a.steps,x=gl(h);if(x)a.narration.push({step:g,text:Wn(x,60)});for(let{call:I,result:E}of u.get(g)??[]){if(!E)continue;let k=Ne(I.name,I.arguments),A={...I,name:k.name,arguments:k.input},P=MU(A,o),C=xu(E);if(E.isError){let X=ko(A,"command"),te=X?`${A.name} \`${Wn(X,40)}\``:`${A.name} ${P.startsWith("file:")?P.slice(5):Wn(es(A.arguments),40)}`,j={step:g,key:P,what:te,detail:Uo(C.trim().split(`
|
|
61
|
-
`).slice(0,8).join(`
|
|
62
|
-
`),200)};a.errors.push(j);let re=p.get(P)??[];re.push(j),p.set(P,re);continue}for(let X of p.get(P)??[])X.resolved=g;p.delete(P);let M=ko(A,"path");if(yl.has(A.name)&&M){let X=bl(M,o),te=a.files.get(X)??{count:0,first:g,last:g,diffs:[]};if(te.count++,te.last=g,te.diffs.push({step:g,lines:A.name==="edit"?ko(A,"old_string")!==void 0?hC(ko(A,"old_string")??"",ko(A,"new_string")??""):[]:hC("",ko(A,"content")??"")}),te.diffs.length>3)te.diffs.shift();a.files.set(X,te);continue}let J=A.name==="read"?[...M?[M]:[],...vU(A)]:[];if(J.length){for(let X of J){let te=bl(X,o),j=a.reads.get(te)??[];j.push(g),a.reads.set(te,j)}continue}if(cC.has(A.name)){let X=M?` in ${bl(M,o)}`:"",te=A.name==="grep"&&ko(A,"glob")?` (${ko(A,"glob")})`:"",j=`${A.name} ${ko(A,"pattern")??""}${X}${te}`.replace(/\s+/g," "),re=a.searches.get(j)??{steps:[],head:""};re.steps.push(g),re.head=Wn(C.trim().split(`
|
|
63
|
-
`)[0]??"",25),a.searches.set(j,re);continue}let O=ko(A,"command");if(O){let X=C.trim().split(`
|
|
64
|
-
`);a.commands.push({step:g,command:Wn(O,40),exit:"0",lines:X.length,tail:X.slice(-3).map((te)=>Wn(te,40))});continue}let B=`${A.name} ${Wn(es(A.arguments),40)}`,L=a.other.get(B)??[];L.push(g),a.other.set(B,L)}}return a}function gC(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function zc(e,o,a){let u=(I,E)=>E===void 0||!I.length?I:Il(I,E),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(([I,E],k)=>{if(p.push(`- ${I}: ${E.count} change${E.count>1?"s":""} (step ${E.first}${E.last!==E.first?`-${E.last}`:""})`),k<f.length-a.diffFiles)return;for(let A of E.diffs)p.push(` step ${A.step}:`,...A.lines.map((P)=>` ${P}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((I)=>I.resolved?`- step ${I.step} ${I.what} (resolved at step ${I.resolved})${a.lists===void 0?`: ${I.detail.replace(/\n/g,`
|
|
65
|
-
`)}`:""}`:`- step ${I.step} ${I.what} (UNRESOLVED): ${I.detail.replace(/\n/g,`
|
|
66
|
-
`)}`)),p.push("","## Steps",...u(e.narration.map((I)=>`- ${I.step}. ${I.text}`),a.narration));let h=[...e.reads].map(([I,E])=>`- ${I} @ ${E.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(([I,E])=>`- ${I} \u2192 ${E.head||"(no output)"} (${gC(E.steps)})`);p.push("",`## Searches (${g.length})`,...u(g,a.lists));let x=e.commands.map((I)=>[`- ${I.step}. \`${I.command}\` exit=${I.exit}, ${I.lines} output lines, last ${I.tail.length}:`,...I.tail.map((E)=>` ${E}`)].join(`
|
|
67
|
-
`));if(p.push("",`## Commands (${x.length})`,...u(x,a.lists)),e.other.size){let I=[...e.other].map(([E,k])=>`- ${E} (${gC(k)})`);p.push("",`## Other tool calls (${I.length})`,...u(I,a.lists))}return p.push("</work-state>"),p.join(`
|
|
68
|
-
`)}function Yn(e,o,a,u){let p=OU(e,u),f=zc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(F(f)<=a)return f;let h={...p,narration:[]};for(let I of[Number.POSITIVE_INFINITY,20,10,5]){let E=F(zc(h,o,{diffFiles:I}));if(E>a*0.7)continue;return zc(p,o,{narration:Math.max(500,a-E),diffFiles:I})}let g=Math.max(300,Math.floor(a*0.1)),x=F(zc(h,o,{diffFiles:0,lists:g}));return zc(p,o,{narration:Math.max(500,a-x),diffFiles:0,lists:g})}function Vc(e){return{role:"user",content:e,timestamp:0}}function Ah(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function yC(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:Vc(e.input)}function Eu(e){let o=[];for(let a of e){let u=o.at(-1),p=a;if(u?.role==="user"&&p.role==="user"){let f=(h)=>typeof h.content==="string"?[{type:"text",text:h.content}]:h.content;o[o.length-1]={...p,content:[...f(u),{type:"text",text:`
|
|
69
|
-
|
|
70
|
-
`},...f(p)],timestamp:Math.max(u.timestamp,p.timestamp)};continue}o.push(a)}return o}function xC(e){let o=[],a=new Map;for(let u of e){let p=u;if(p.role==="toolResult"){if(!a.has(p.toolCallId))continue;let f=a.get(p.toolCallId);if(f===void 0)a.set(p.toolCallId,o.length),o.push(u);else o[f]=u;continue}if(p.role==="assistant"){if(p.content.length===0)continue;if(a=new Map,p.stopReason!=="error"&&p.stopReason!=="aborted"){for(let f of p.content)if(f.type==="toolCall")a.set(f.id,void 0)}}else if(p.role==="user")a=new Map;o.push(u)}return o}function _U(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Ce(e,o,a,u={}){let p=wt(e),f=rt(e),h=f.filter((he)=>El(he,p)),g=Rh(f,p),x=[],I=[],E=0;for(let he of f){if(El(he,p))continue;let we=[];for(let Ee of he.records){if(he===g&&Ee.entry.seq<=p)continue;let ft=Ee.raw.role==="user"?lC(Ee):Ee.raw;E+=G(ft),x.push(ft),we.push(ft)}if(u.inspect&&we.length)I.push({id:`recent-${he.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${he.id}`,tokens:we.reduce((Ee,ft)=>Ee+G(ft),0),detail:JSON.stringify(we,_U,2)})}if(!h.length&&!g)return{items:I,messages:Eu(x),visible:0,archived:0,open:E,tokens:E,untrimmed:E};let k=dC(h,a,!!g),{visible:A,archived:P}=k,C=k.tokens,M=[],J="",O="";if(g){let he=g.records.filter((Ee)=>Ee.entry.seq<=p),we=he.filter((Ee)=>Ee.entry.type==="user"&&!Ee.entry.notices&&Ee.raw.role==="user");if(we.length){J=[`<chunk-input id="${g.id}" status="partial">`,...we.map((ft,ke)=>`<user-message sequence="${ke+1}">
|
|
71
|
-
${Ot(ft.entry.seq,Qs(ft.raw))}
|
|
72
|
-
</user-message>`),"</chunk-input>"].join(`
|
|
73
|
-
`);let Ee=we.flatMap((ft)=>{let ke=ft.raw.content;return typeof ke==="string"?[]:ke.filter((Le)=>Le.type==="image")});M.push(Ee.length?{role:"user",content:[{type:"text",text:J},...Ee],timestamp:0}:Vc(J))}O=Yn(he,g,a.index,u.cwd),M.push(Ah(O,o))}let B=e.flatMap((he)=>{let we=he.raw;if(he.entry.seq>p||we?.role!=="toolResult"||we.toolName!=="skill")return[];return[Vc(we.content.filter((Ee)=>Ee.type==="text").map((Ee)=>Ee.text).join(`
|
|
74
|
-
`))]}),L=LU(e,p),X=L?[Vc(L)]:[],te="",j=e.findLast((he)=>he.entry.type==="compaction")?.entry.time??0,re=()=>{te=fC({runs:h,visible:A.map((we)=>we.run),archived:P,partial:!!g,tokens:C,budget:a});let he=[Vc(te)];for(let{content:we}of A){if(we.input)he.push(yC(we));he.push(Ah(we.summary,o))}return[...he,...B,...X,...M].map((we)=>({...we,timestamp:j}))},ye=(he)=>he.reduce((we,Ee)=>we+G(Ee),0),Te=re(),ze=ye(Te)+E,Y=ze,{trim:me}=u;while(me&&me.fixed+ze>me.limit){let he=g||A.at(-1)?.run.status==="completed"?A:A.slice(0,-1);if(!he.length)break;let we=0,Ee=0;for(let ft of he)if(Ee++,we+=ft.content.tokens,we>=me.fixed+ze-me.limit)break;P=[...P,...A.slice(0,Ee).map((ft)=>ft.run)],A=A.slice(Ee),C-=we,Te=re(),ze=ye(Te)+E}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:G(Te[0]),detail:te},...A.map(({run:he,content:we})=>({id:he.id,label:`Chunk ${he.id}`,state:"sealed",tokens:(we.input?G(yC(we)):0)+G(Ah(we.summary,o)),detail:[we.input,we.summary].filter(Boolean).join(`
|
|
75
|
-
|
|
76
|
-
`)})),...P.map((he)=>({id:he.id,label:`Chunk ${he.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"})),...X.map((he)=>({id:"todos",label:"\u5F85\u529E\u6E05\u5355",tokens:G(he),detail:L})),...g?[{id:g.id,label:`Chunk ${g.id}`,state:"folded",tokens:ye(M),detail:[J,O].filter(Boolean).join(`
|
|
77
|
-
|
|
78
|
-
`)}]:[],...I]:[],messages:Eu([...Te,...x]),visible:A.length,archived:P.length,open:E,tokens:ze,untrimmed:Y}}function LU(e,o){let a=new Map,u;for(let p of e){let f=p.raw;if(f?.role==="assistant"){for(let g of f.content)if(g.type==="toolCall"&&g.name==="todo")a.set(g.id,g.arguments)}if(f?.role!=="toolResult"||f.toolName!=="todo"||f.isError)continue;let h=NU(a.get(f.toolCallId));if(h)u={seq:p.entry.seq,todos:h}}if(!u||u.seq>o||u.todos.every((p)=>p.status==="completed"))return"";return["<todo-list>","Your current todo list. You set it with the todo tool earlier; that call was folded out of your context, and the user still sees this list. Continue the work from it and keep it updated with the todo tool.",...u.todos.map((p)=>`- [${p.status}] ${p.content}`),"</todo-list>"].join(`
|
|
79
|
-
`)}function NU(e){let o=e&&typeof e==="object"&&"todos"in e?e.todos:void 0;if(!Array.isArray(o))return;return o.flatMap((a)=>{if(!a||typeof a!=="object"||!("content"in a)||!("status"in a))return[];let u=ao.find((p)=>p===a.status);return typeof a.content==="string"&&u?[{content:a.content,status:u}]:[]})}function de(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Ph=0.97,qU=0.97,IC=0.5,DU=0.05,FU=20000,jU=24000;function mn(e){return{target:FU,hard:jU,index:Math.floor(de(e)*DU)}}function $h(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class hn{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,a=()=>{return}){this.records=e;this.fold=o;this.cwd=a}budget(e){return mn(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(de(e)*Ph/this.ratio)}prepare(e,o,a,u){let p=de(a),f=mn(a),h=e.reduce((j,re)=>j+G(re),0)+Lt(o),g=this.records().at(-1)?.entry.seq??0,x=()=>u?[...u,...this.records().filter((j)=>j.entry.seq>g)]:this.records(),I=()=>Ce(x(),a,f,{cwd:this.cwd(),trim:{fixed:h,limit:Math.floor(p*Ph/this.ratio)}}),E=x().findLast((j)=>j.raw?.role==="assistant"),k=E?x().filter((j)=>j.entry.seq>E.entry.seq&&j.raw):[],A=E?.raw,P=()=>E!==void 0&&(E.entry.seq===this.reshapedAfter||x().some((j)=>j.entry.type==="compaction"&&j.entry.seq>E.entry.seq)),C=this.dueSeal(a);if(C!==void 0)this.fold(C,!1),this.reshapedAfter=E?.entry.seq??-1;let M=I(),J=k.reduce((j,re)=>j+G(re.raw),0);if(this.lastEstimate===0&&E&&A&&!P()){let j=A.usage.input+A.usage.cacheRead+A.usage.cacheWrite,re=h+M.untrimmed-G(A)-J;if(j>0&&re>0)this.ratio=Math.min(2,Math.max(0.5,j/re))}let B=((j)=>{let re=h+j.untrimmed,ye=h+j.tokens;return((E&&A&&!P()&&$h(A)>0?$h(A)+Math.round(this.ratio*J):void 0)??Math.round(re*this.ratio))-Math.round((re-ye)*this.ratio)})(M);if(B>p*qU){let j=B-M.open*this.ratio,re=Math.max(1000,Math.floor((p*IC-j-f.index)/this.ratio)),ye=E?.entry.seq??-1,Te=x().findLast((he)=>he.entry.type==="compaction"&&he.entry.partial)?.entry.seq??-1,ze=Math.max(this.lastFoldSeq,Te),me=(ze>0?x().filter((he)=>he.entry.seq>ze&&he.raw?.role==="assistant").length:999)<=1;if(!me||this.consecutivePartialFolds<2){let he=dn(x(),re);if(he!==void 0)this.fold(he,!0),this.reshapedAfter=ye,this.lastFoldSeq=ye,this.consecutivePartialFolds=me?this.consecutivePartialFolds+1:1,M=I()}}else this.consecutivePartialFolds=0;this.lastEstimate=h+M.tokens;let L=M.messages,X=h+M.tokens;if(Math.round(X*this.ratio)>p)L=UU(L,Math.max(0,Math.floor(p/this.ratio-h))),X=h+L.reduce((j,re)=>j+G(re),0);return this.lastEstimate=X,{messages:Eu([...e,...L]),estimate:X,calibratedEstimate:Math.round(X*this.ratio)}}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,x)=>g+G(x.raw),0);if(p||!u||$h(u)+h<Math.floor(de(e)*Ph))return}return _r(o)}recover(e){let o=de(e),a=mn(e),u=Ce(this.records(),e,a,{cwd:this.cwd()}),p=Math.floor((o*IC-(o-u.open*this.ratio)-a.index)/this.ratio),f=dn(this.records(),p);if(f===void 0)return!1;return this.fold(f,!0),this.reshapedAfter=this.records().findLast((h)=>h.raw?.role==="assistant")?.entry.seq??-1,!0}}var Ch=500;function UU(e,o){let a=[...e],u=a.map((f)=>G(f)),p=u.reduce((f,h)=>f+h,0);while(p>o){let f=-1;for(let[k,A]of a.entries()){if(A.role!=="toolResult"||(u[k]??0)<=Ch)continue;if(f<0||(u[k]??0)>(u[f]??0))f=k}if(f<0)break;let h=a[f],g=u[f]??0,x=Math.max(Ch,Math.floor(g/2)),I={...h,content:h.content.map((k)=>k.type==="text"?{...k,text:Uo(k.text,x)}:k)},E=G(I);u[f]=E<g?E:Ch,a[f]=I,p-=g-E}return a}var BU=2000;function bu(e,o){let a=[];for(let u of o.replace(/\r\n/g,`
|
|
80
|
-
`).split(`
|
|
81
|
-
`))for(let p=0;p<Math.max(u.length,1);){let f=Math.min(u.length,p+BU);if(f<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(f-1)))f--;a.push({source:e,text:u.slice(p,f)}),p=f>p?f:p+1}return a}function Ar(e){let o=[],a=Ge(e.records),u=new Map(a.map((f)=>[f.call,f])),p=new Set(a.flatMap((f)=>f.result?[f.result]:[]));for(let f of e.records){let h=f.raw;if(h.role==="user")o.push(...bu(f.entry.type==="user"&&f.entry.notices?"NOTICE":"USER",Qs(h)));else if(h.role==="assistant"){for(let g of h.content)if(g.type==="text"&&g.text.trim())o.push(...bu("ASSISTANT",g.text));else if(g.type==="toolCall"){let x=u.get(g);if(x)for(let I of xl(x))o.push(...bu(I.source,I.text))}}else if(h.role==="toolResult"&&!p.has(h))o.push(...bu(h.isError?"TOOL_ERROR":"TOOL_OUTPUT",xu(h)))}return o.map((f,h)=>({chunk:e.id,line:h,...f}))}function Zn(e,o){let a=e.find((u)=>u.entry.seq===o);if(a?.entry.type!=="user"||a.entry.notices||!a.raw||a.raw.role!=="user")return;return bu("USER",Qs(a.raw)).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function eo(e,o){let a=e.find((u)=>u.entry.seq===o)?.entry;if(a?.type!=="extension"||!a.display)return;return bu("EXTENSION",a.display.text).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function fn(e,o=""){return e.map((a,u)=>{let p=e[u-1],f=p&&p.source===a.source&&p.chunk===a.chunk&&p.line===a.line-1;return`${o}${f?`${a.line}:`:`${a.line} ${a.source}:`} ${a.text}`}).join(`
|
|
82
|
-
`)}import{AsyncLocalStorage as GU}from"async_hooks";import{chmodSync as wC,existsSync as KU,mkdirSync as HU,readFileSync as WU,renameSync as zU,writeFileSync as VU}from"fs";import{dirname as JU,join as QU}from"path";function EC(){let e=Bun.version.split(".").map(Number);if(!((e[0]??0)>1||e[0]===1&&(e[1]??0)>4||e[0]===1&&e[1]===4&&(e[2]??0)>=3))throw Error("\u4EE3\u7406\u4F20\u8F93\u9700\u8981 Bun 1.4.3 \u6216\u66F4\u65B0\u7248\u672C\uFF0C\u8BF7\u5148\u5347\u7EA7 Bun")}function bC(e=process.env){let o={...e};for(let a of["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY"])delete o[a],delete o[a.toLowerCase()];return o}function Jc(e){let o=e.hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1]??o;return u==="localhost"||u.endsWith(".localhost")||u==="::1"||u==="::"||/^(?:0\.|127\.)/.test(u)}function SC(e,o){let a=async(p,f,h)=>{let g=await e(p,{...f,...o.proxy?{proxy:o.proxy}:{proxy:!1},...o.tls==="insecure"?{tls:{rejectUnauthorized:!1}}:{},redirect:"manual"});if(![301,302,303,307,308].includes(g.status))return g;let x=g.headers.get("location");if(!x)return g;if(h>=10)throw Error("\u4EE3\u7406\u8BF7\u6C42\u91CD\u5B9A\u5411\u6B21\u6570\u8FC7\u591A");let I=p instanceof Request?p:void 0,E=new URL(I?.url??String(p)),k=new URL(x,E);if(k.protocol!=="http:"&&k.protocol!=="https:")throw Error("\u62D2\u7EDD\u91CD\u5B9A\u5411\u5230\u975E HTTP \u5730\u5740");if(Jc(k)&&!Jc(E))throw Error("\u62D2\u7EDD\u4ECE\u516C\u7F51\u91CD\u5B9A\u5411\u5230\u56DE\u73AF\u5730\u5740");let A=new Headers(I?.headers);if(new Headers(f?.headers).forEach((M,J)=>{A.set(J,M)}),E.origin!==k.origin)A.delete("authorization"),A.delete("cookie"),A.delete("proxy-authorization");let P=(f?.method??I?.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&&I?.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 vh=Ji,RC=Cr,TC=new GU;class Wi{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;EC(),this.path=QU(e,"proxy.json");let a=async(u,p)=>{let f=TC.getStore();if(!f)return this.baseFetch(u,p);return this.createFetch(f)(u,p)};globalThis.fetch=Object.assign(a,{preconnect:o.preconnect})}load(){if(!KU(this.path))return;this.config=this.validate(JSON.parse(WU(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{HU(JU(this.path),{recursive:!0});let a=`${this.path}.tmp-${process.pid}`;VU(a,`${JSON.stringify(o,null,2)}
|
|
83
|
-
`,{mode:384}),wC(a,384),zU(a,this.path),wC(this.path,384)}catch(a){throw Error("\u4FDD\u5B58\u4EE3\u7406\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:a})}return this.config=o,this.settings()}createFetch(e,o=this.baseFetch){let a=(p,f="verify")=>SC(o,{proxy:p,tls:f});return Object.assign(async(p,f)=>{let h=p instanceof Request?p.url:String(p),x=this.profileFor(e)?.noProxy?.some((E)=>ZU(h,E))??!1;if(Jc(new URL(h))||x)return a()(p,f);let I=this.proxyURL(e);return a(I,this.profileFor(e)?.tls)(p,f)},{preconnect:o.preconnect})}models(e){return new kC(e,this)}providerOptions(e,o,a){let u=Object.assign({},e),p=e?.fetch,h=p?.[pl]?.call(p,this.baseFetch)??p??this.baseFetch;u.fetch=this.createFetch(o,h);let g=bC({...process.env,...e?.env}),x=!1;if(a)try{x=Jc(new URL(a))}catch{}let I=x?void 0:this.proxyURL(o),E=this.profileFor(o);return u.env={...g,...I?{HTTP_PROXY:I,HTTPS_PROXY:I,ALL_PROXY:I}:{},...E?.noProxy?.length?{NO_PROXY:E.noProxy.join(",")}:{}},u}run(e,o){return TC.run(e,o)}wrapProvider(e){let o=jt(e.id),a={...e.auth},u=e.auth.oauth;if(u){let E=e.id==="openai"||e.id===vt?vh:o;a.oauth={...u,login:(k,A)=>this.run(E,()=>u.login(k,A)),refresh:(k,A)=>this.run(E,()=>u.refresh(k,A)),toAuth:(k)=>this.run(E,()=>u.toAuth(k))}}let p={...e,auth:a},f=e.refreshModels;if(f)p.refreshModels=(E)=>this.run(o,()=>f(E));p.stream=(E,k,A)=>this.run(o,()=>e.stream(E,k,this.providerOptions(A,o,E.baseUrl))),p.streamSimple=(E,k,A)=>this.run(o,()=>e.streamSimple(E,k,this.providerOptions(A,o,E.baseUrl)));let h=e.fetchDeferred;if(h)p.fetchDeferred=(E,k,A)=>this.run(o,()=>h(E,k,this.providerOptions(A,o,E.baseUrl)));let g=e.cancelDeferred;if(g)p.cancelDeferred=(E,k,A)=>this.run(o,()=>g(E,k,this.providerOptions(A,o,E.baseUrl)));let x=e.generateImages;if(x)p.generateImages=(E,k,A)=>this.run(o,()=>x(E,k,this.providerOptions(A,o,E.baseUrl)));let I=e.classify;if(I)p.classify=(E,k,A)=>this.run(o,()=>I(E,k,this.providerOptions(A,o,E.baseUrl)));return p}proxyURL(e){let o=this.profileFor(e);if(!o)return;let a=ri(o.address),u=o.username?`${encodeURIComponent(o.username)}:${encodeURIComponent(o.password??"")}@`:"",p=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return`${a.protocol}://${u}${p}:${a.port}`}profileFor(e){let o=e?this.config.routes[e]:this.config.defaultProfileID,a=e&&o!==void 0?o:this.config.defaultProfileID;if(!a)return;let u=this.config.profiles.find((p)=>p.id===a);if(!u)throw Error(`\u4EE3\u7406\u7EBF\u8DEF ${a} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u9875\u91CD\u65B0\u9009\u62E9`);return u}validate(e){let o=Mh(e);if(o?.version!==1)throw new t("\u4EE3\u7406\u914D\u7F6E\u7248\u672C\u65E0\u6548");let u=(Array.isArray(o.profiles)?o.profiles:[]).map(XU),p=new Set(u.map((x)=>x.id));if(p.size!==u.length)throw new t("\u4EE3\u7406\u914D\u7F6E ID \u4E0D\u80FD\u91CD\u590D");let f=YU(o.defaultProfileID);if(f&&!p.has(f))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let h=Mh(o.routes)??{},g={};for(let[x,I]of Object.entries(h)){if(x!==vh&&x!==RC&&!Xi(x))throw new t(`\u4EE3\u7406\u7528\u9014\u65E0\u6548\uFF1A${x}`);if(I!==null&&(typeof I!=="string"||!p.has(I)))throw new t(`\u7528\u9014 ${x} \u7684\u7EBF\u8DEF\u4E0D\u5B58\u5728`);g[x]=I}return{version:1,defaultProfileID:f,routes:g,profiles:u}}}class kC{source;manager;wrapped=new Map;constructor(e,o){this.source=e;this.manager=o;for(let a of e.getProviders())this.install(a)}getProviders(){return this.source.getProviders().map((e)=>this.wrap(e))}getProvider(e){let o=this.source.getProvider(e);return o?this.wrap(o):void 0}getModels(...e){return this.source.getModels(...e)}getModel(...e){return this.source.getModel(...e)}getModelsOfType(e,o){return this.source.getModelsOfType(e,o)}getModelOfType(e,o,a){return this.source.getModelOfType(e,o,a)}getAllModels(...e){return this.source.getAllModels(...e)}refresh(...e){return this.source.refresh(...e)}checkAuth(...e){return this.source.checkAuth(...e)}getAvailable(...e){return this.source.getAvailable(...e)}getAvailableOfType(e,o,a){return this.source.getAvailableOfType(e,o,a)}getAllAvailable(...e){return this.source.getAllAvailable(...e)}getAuth(e,o){if(typeof e==="string")return this.source.getAuth(e,o);return this.source.getAuth(e,o)}login(...e){return this.source.login(...e)}logout(...e){return this.source.logout(...e)}stream(e,o,a){return this.source.stream(e,o,a)}complete(e,o,a){return this.source.complete(e,o,a)}streamSimple(...e){return this.source.streamSimple(...e)}completeSimple(...e){return this.source.completeSimple(...e)}streamDeferred(...e){return this.source.streamDeferred(...e)}fetchDeferred(...e){return this.source.fetchDeferred(...e)}cancelDeferred(...e){return this.source.cancelDeferred(...e)}generateImages(...e){return this.source.generateImages(...e)}classify(...e){return this.source.classify(...e)}setProvider(e){this.install(e)}deleteProvider(e){this.source.deleteProvider(e),this.wrapped.delete(e)}clearProviders(){this.source.clearProviders(),this.wrapped.clear()}wrap(e){return this.wrapped.get(e.id)??this.install(e)}install(e){if(this.wrapped.get(e.id)===e)return this.source.setProvider(e),e;let o=this.manager.wrapProvider(e);return this.wrapped.set(e.id,o),this.source.setProvider(o),o}}function jt(e){return`${Qi}${e}`}function As(e){return[{id:vh,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:RC,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:jt(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function XU(e){let o=Mh(e);if(!o)throw new t("\u4EE3\u7406\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof o.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(o.id))throw new t("\u4EE3\u7406\u914D\u7F6E ID \u65E0\u6548");let a;try{a=ri(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 YU(e){if(e===void 0||e===null||e==="")return;if(typeof e!=="string")throw new t("\u4EE3\u7406\u7EBF\u8DEF ID \u65E0\u6548");return e}function Mh(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function ZU(e,o){try{let a=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/^\./,"");return a===u||a.endsWith(`.${u}`)}catch{return!1}}import{join as Sg}from"path";import{existsSync as HC}from"fs";import{realpath as WC}from"fs/promises";import{dirname as zC,isAbsolute as gB,join as VC,relative as yB,resolve as Fh,sep as xB}from"path";import{existsSync as eB,watch as tB}from"fs";import{readdir as rB,stat as nB}from"fs/promises";import{basename as Oh,dirname as oB,join as AC,resolve as sB}from"path";class _h{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,a,u=150){this.host=e;this.slots=o;this.watching=a;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let a=[],u=[];for(let g of[...new Set(e)]){let x;try{x=await rB(g)}catch(I){if(I instanceof Error&&"code"in I&&I.code==="ENOENT")continue;throw I}for(let I of x.sort()){let E=AC(g,I),k=(await nB(E)).isDirectory()?AC(E,"index.ts"):E;if(!k.endsWith(".ts")||k.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(k),path:k})}catch(A){let P=Oh(k)==="index.ts"?Oh(oB(k)):Oh(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((x)=>x.definition.id===g.definition.id)),f=[...p,...u],h=this.order(f.map(({definition:g})=>g));for(let g of h){let x=f.find((E)=>E.definition===g)?.path,I=p.some((E)=>E.definition===g);try{await this.host.install(g,x,I)}catch(E){this.slots.set(g.id,{definition:g,path:x,builtin:I,enabled:!0,error:E instanceof Error?E.message:String(E)})}}if(this.watching())for(let g of[...f,...a]){if(!eB(g.path))continue;let x=tB(g.path,()=>{let I=g.definition.id,E=this.debounceTimers.get(I);if(E)clearTimeout(E);let k=setTimeout(()=>{this.debounceTimers.delete(I),this.host.reload(I).catch((A)=>{let P=this.slots.get(I);if(P)P.error=A instanceof Error?A.message:String(A)})},this.debounceMs);k.unref?.(),this.debounceTimers.set(I,k)});x.on("error",(I)=>{let E=this.slots.get(g.definition.id);if(E)E.error=I.message,this.host.changed()}),this.watchers.push(x)}}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 x of g.deps??[]){let I=a.get(x);if(I)h(I);else if(!this.slots.has(x))throw Error(`Missing plugin dependency: ${x}`)}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(`${sB(e)}?v=${++this.revision}`);if(!o.default)throw Error("Plugin module must export a default definition");return this.validate(o.default),o.default}}async function PC(e,o,a=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,p;try{return await Promise.race([a?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((f,h)=>{p=setTimeout(()=>{u.abort(),h(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as iB}from"async_hooks";import{isDeepStrictEqual as $C}from"util";var Oa=new iB;function Xs(){let e=Oa.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function Su(e){let o=structuredClone(e),a=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let p of Object.values(u))a(p)};return a(o),o}function CC(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let x of["seq","time","session_id","raw"])if(x in o)throw Error(`Entry replacement contains protected field: ${x}`);let a=JSON.parse(JSON.stringify(o,(x,I)=>{if(typeof I==="function"||typeof I==="symbol"||typeof I==="number"&&!Number.isFinite(I))throw Error("Entry replacement must contain JSON values");return I}));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 x of new Set([...Object.keys(e),...Object.keys(u)])){if(!p.includes(x)&&!$C(f[x],u[x]))throw Error(`Entry replacement changed protected field: ${x}`);if(["seq","time","session_id","raw"].includes(x))throw Error(`Entry replacement contains protected field: ${x}`)}let h=(x)=>x===void 0||typeof x==="string",g=!0;switch(e.type){case"user":g=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((x)=>x&&typeof x.name==="string"&&typeof x.mimeType==="string"&&lo.includes(x.kind)&&typeof x.data==="string"));break;case"assistant":g=h(u.error)&&Array.isArray(u.parts)&&u.parts.every((x)=>x&&(["text","thinking"].includes(x.type)&&typeof x.text==="string"||x.type==="tool_call"&&typeof x.id==="string"&&typeof x.name==="string"&&("input"in x)));break;case"tool_result":g=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((x)=>x&&typeof x.mimeType==="string"&&typeof x.data==="string"));break;case"extension":{let x=u.display;g="payload"in u&&(x===void 0||x!==null&&typeof x==="object"&&("text"in x)&&typeof x.text==="string"&&(!("title"in x)||h(x.title)));break}case"notice_pending":{let I=["text"],E=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(E),...Object.keys(A)]))if(I.includes(P)){if(typeof A[P]!=="string")g=!1}else if(!$C(E[P],A[P]))g=!1;break}case"run":g=h(u.error);break;case"compaction":break}if(!g)throw Error("Invalid entry replacement content");return a}function vC(e,o,a,u,p,f){let h=u;for(let g of a.generations)for(let x of g.hooks.get("entry.before_append")??[]){if(g.disabled)break;let I={phase:"before",violated:!1};try{let E=Oa.run(I,()=>{let k=Su(h),A=performance.now(),P=x(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:CC(h,P);if(I.violated)throw Error("entry.before_append attempted a database write");return{validated:C,slow:performance.now()-A>e}});if(E.validated&&JSON.stringify(E.validated)!==JSON.stringify(h))h=E.validated;if(E.slow)throw Error("entry.before_append exceeded budget");g.beforeFailures=0,g.failures=0}catch(E){g.failures=g.beforeFailures++,o(g,E)}}return h}function aB(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return Su(o);return structuredClone(o)}async function MC(e,o,a,u,p,f,h,g,x="end"){let I=f;for(let E of u){if(E.disabled)continue;let k=E.hooks.get(p)??[];for(let A of k){if(E.disabled)break;let P=E.hookOptions.get(A);if(p==="prompt.fragments"&&(P?.promptPosition??"end")!==x)continue;let C=p==="prompt.fragments"?JSON.stringify([h?.id,I]):void 0,M=C===void 0?void 0:E.promptCache.get(A)?.get(C);try{let J=aB(p,I),O=P?.timeoutMs,B=typeof O==="function"?O({runtime:e.runtime,session:h,connection:g}):O,L=await o((X)=>A(J,{runtime:e.runtime,session:h,connection:g,signal:X}),B);if(C!==void 0){let X=L===void 0?I:L;if(!Array.isArray(X)||X.some((j)=>typeof j!=="string"))throw Error("Prompt fragments must be strings");if(P?.promptMutable!==!0&&M&&JSON.stringify(M)!==JSON.stringify(X))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let te=E.promptCache.get(A)??new Map;te.set(C,[...X]),E.promptCache.set(A,te)}if(E.failures=0,L!==void 0&&p!=="entry.after_append")I=L}catch(J){if(M)I=structuredClone(M);if(a(E,J),P?.errorMode==="propagate")throw J}}}return I}class Qc{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 uB}from"fs";import{dirname as cB,resolve as OC}from"path";var Lh=new WeakMap;function _C(e){return[...e].map((o)=>{let a=Boolean(o.path&&(Boolean(o.definition.webEntry)||uB(OC(cB(OC(o.path)),"web.tsx"))));if(o.current&&!Lh.has(o.current))Lh.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:a,webRevision:o.current?Lh.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class Nh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,a){this.host=e;this.deadline=o;this.fail=a}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,a){let u=this.host.pin(),p=(async()=>{try{let f=[];for(let h of u.generations){if(h.disabled)continue;for(let g of h.hooks.get(e)??[]){let x=h.hookOptions.get(g)?.timeoutMs,I=typeof x==="function"?x({runtime:this.host.runtime,session:o,connection:a}):x;f.push(this.deadline((E)=>g(o,{runtime:this.host.runtime,session:o,connection:a,signal:E}),I,!0).catch((E)=>this.fail(h,E)))}}await Promise.all(f)}finally{await u.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,o,a){let u=a===void 0?void 0:Su(a),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Oa.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,p),this.pending.add(p);let f=()=>{if(this.pending.delete(p),this.entryQueues.get(o)===p)this.entryQueues.delete(o)};p.then(f,f)}}function LC(e){return e.replace(/(?:(?:request[- ]?)?headers?)["']?\s*[=:][\s\S]*/gi,"[headers redacted]").replace(/\b(?:api[-_ ]?key|authorization|cookie|password|secret|access[-_ ]?token)\b[^\n]*/gi,"[redacted]").replace(/\bBearer\s+[^\s"',}]+/gi,"[redacted]").replace(/(?:authorization|[\w-]*api[-_]?key|password|secret|cookie|[\w-]*token|key)["']?\s*[=:][^\n]*/gi,"[redacted]").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi,"[address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[address]").replace(/\blocalhost(?::\d+)?\b/gi,"[address]").replace(/\b(?:sk|key)-[\w-]+/gi,"[redacted]").replace(/[\r\n\t]+/g," ").slice(0,300)}function mB(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 pB(e,o){let a=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!a)throw Error("Completion session not found");let u=o.model??a?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=Cn(e.options.models,u);if(!p&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!p){let f=(await e.models()).models.filter((g)=>g.available===!0),h=p?Mt(p):u;if(!f.some((g)=>g.id===h)){let g=f[0];if(g)p=Cn(e.options.models,g.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function NC(e,o){mB(o);let a=await pB(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 x of g){if(o.signal?.aborted)throw Error("cancelled");if(x.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${LC(x.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(x.type==="text_delta")p+=x.delta;if(x.type==="done"){if(x.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(x.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${x.reason}\uFF09`);f=!0}}}catch(h){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${LC(h instanceof Error?h.message:String(h))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!f)throw Error("Model completion ended without a stop response; retry");return{text:p,model:Mt(a)}}var lB=["active","archived","all"];function qC(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function dB(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&&!lB.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 fB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function DC(e){function o(a,u={}){let{types:p,bodies:f}=u;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let h=qC(u.limit),g=u.after??0;if(!Number.isSafeInteger(g)||g<0)throw Error("sessions after must be a non-negative integer");let x=(e.get(a)?.entries(g,p,f!==!1)??[]).slice(0,h);return structuredClone(f===!1?x.map(fB):x)}return{list(a={}){dB(a);let u=a.limit===void 0?void 0:qC(a.limit),p=e.list(a.children??!1,{archive:a.archive}).filter((f)=>a.projectID===void 0||f.projectID===a.projectID).filter((f)=>a.since===void 0||f.created>=a.since);return structuredClone(u===void 0?p:p.slice(0,u))},get(a){return structuredClone(e.get(a)?.info())},entries:o}}async function FC(e,o,a,u,p,f){let h={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},g=e.runtime.store.db,x=new Map,I=!1,E=!0,k=()=>{if(!E||h.disposed)throw Error("Plugin registration scope is closed")},A=(O,B)=>{if(k(),!I){x.set(O,B);return}if(B===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,O);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,O,B)},P={get:(O)=>{k();let B=x.has(O)?x.get(O):g.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,O)?.value;return B==null?void 0:JSON.parse(B)},set:(O,B)=>{let L=JSON.stringify(B);if(L===void 0)throw Error("Plugin KV values must be JSON serializable");A(O,L)},delete:(O)=>A(O,null)},C=()=>{if(k(),I)throw Error("Register resources during setup only")},M=[...o.migrations??[]].sort((O,B)=>O.version-B.version),J=new Set;try{for(let O of M){if(!Number.isSafeInteger(O.version)||O.version<1||J.has(O.version))throw Error("Plugin migration versions must be unique positive integers");if(J.add(O.version),g.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,O.version))continue;g.transaction(()=>{if(O.sql!==void 0)g.run(O.sql);else O.up({...P,db:g});for(let[B,L]of x)if(L===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,B);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,B,L);g.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,O.version)})(),e.runtime.store.invalidateEntryCache(),x.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:DC(e.runtime),complete:(O)=>NC(e.runtime,O),kv:P,database:g,broadcast:(O)=>{e.runtime.emitEvent(O)},registerInputGate:(O)=>{C(),h.gates.push(O)},registerNoticeSource:(O,B)=>{if(C(),!O||!Number.isSafeInteger(B.textLimit)||B.textLimit<1||!Number.isSafeInteger(B.summaryLimit)||B.summaryLimit<1)throw Error("Notice source limits must be positive integers");h.noticeSources.set(O,{...B})},provide:(O,B)=>{if(C(),O.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(h.services.has(O.name))throw Error(`Duplicate plugin service: ${O.name}`);if(!O.validate(B))throw Error(`Invalid plugin service: ${O.name}`);h.services.set(O.name,B)},on:(O,B,L)=>{if(C(),(L?.promptPosition||L?.promptMutable)&&O!=="prompt.fragments")throw Error("promptPosition and promptMutable only apply to prompt.fragments");let X=h.hooks.get(O)??[];if(X.push(B),h.hooks.set(O,X),L)h.hookOptions.set(B,L)},registerHistoryResolver:(O)=>{C(),h.historyResolvers.push(O)},registerTool:(O,B)=>{if(C(),!O.name||["toolsearch","tool_search","tool_call"].includes(O.name.toLowerCase())||hB(e,p,o.id).has(O.name.toLowerCase())||h.tools.some((X)=>X.name.toLowerCase()===O.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${O.name}`);let L=a?"always":"defer";if(typeof B?.defer==="boolean")L=B.defer?"defer":"always";else if(B?.defer!==void 0)L=B.defer;h.tools.push({...O,defer:L,source:`plugin:${o.id}`,group:B?.group,aliases:B?.aliases,builtin:a})},registerRoute:(O)=>{if(C(),!(O.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((B)=>O.path===B||O.path.startsWith(`${B}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(O.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(h.routes.some((B)=>B.path===O.path&&B.method===O.method))throw Error("Duplicate plugin route");h.routes.push(O)},registerWebSocket:(O)=>{if(C(),!O.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(h.websockets.some((B)=>B.path===O.path))throw Error("Duplicate plugin WebSocket route");h.websockets.push(O)},registerCommand:(O)=>{C(),h.commands.push(O)},registerWebContribution:(O)=>{C(),h.web.push(O)},registerToolPolicy:(O,B)=>{C(),h.policies.set(O,B)},appendExtension:(O,B)=>{if(Xs(),k(),!I)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(O,B)},onDeactivate:(O)=>{C(),h.deactivators.push(O)},onDispose:(O)=>{C(),h.disposers.push(O)}})),g.transaction(()=>{for(let[O,B]of x)if(B===null)g.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,O);else g.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,O,B)})(),x.clear(),I=!0,h}catch(O){throw E=!1,await f(h),O}}function hB(e,o,a){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,f]of o){if(p===a)continue;for(let h of f.current?.tools??[])u.add(h.name.toLowerCase())}return u}class qh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function jC(e,o,a,u){for(let p of o){let f=p.current;if(!f||f.disabled||f.retired)continue;let h=f.websockets.find((g)=>g.path===u);if(!h)continue;return{connect:(g)=>{let x=!1;f.references++,f.connections.add(g);let I={send:(k)=>{if(x||f.retired||f.disabled)return;g.send(k)},close:(k,A)=>g.close(k,A)},E=async(k)=>{if(x||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:()=>E(()=>h.open?.(I)),message:(k)=>E(()=>h.message(I,k)),close:async()=>{if(x)return;x=!0,f.connections.delete(g);try{await a(()=>h.close?.(I))}catch(k){f.error=k instanceof Error?k.message:String(k)}finally{f.references--,await e.collect(f)}}}}}}return}function Dh(e,o){let a=e.split("/"),u=new URL(o.url).pathname.split("/");if(a.length!==u.length)return;let p={};return a.every((h,g)=>{let x=u[g];if(x===void 0)return!1;if(!h.startsWith(":"))return x===h;try{p[h.slice(1)]=decodeURIComponent(x)}catch{return!1}return x.length>0})?p:void 0}async function UC(e,o,a,u,p){let f=e.pin();try{let h=f.generations.find((g)=>g.definition.id===a)?.commands.find((g)=>g.id===u);if(!h)throw new m("Plugin command is unavailable");return await o(()=>h.execute(p))}finally{await f.release()}}function BC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((p)=>p.method===o.method&&Dh(p.path,o)!==void 0))}finally{a.release()}}function GC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((p)=>p.public===!0&&p.method===o.method&&Dh(p.path,o)!==void 0))}finally{a.release()}}async function KC(e,o,a){let u=e.pin(),p=!0;try{for(let f of u.generations)for(let h of f.routes){if(h.method!==a.method)continue;let g=Dh(h.path,a);if(g){let x=await o(()=>h.handler(a,g),h.timeoutMs);if(!x)return;if(x.body&&x.body instanceof ReadableStream){p=!1;let I=!1,E=()=>{if(I)return;I=!0,u.release()},k=x.body.getReader(),A=new ReadableStream({async pull(P){try{let{done:C,value:M}=await k.read();if(C)P.close(),E();else P.enqueue(M)}catch(C){P.error(C),E()}},async cancel(P){try{await k.cancel(P)}finally{E()}}});return new Response(A,{status:x.status,statusText:x.statusText,headers:x.headers})}return x}}return}finally{if(p)await u.release()}}class jh{runtime;options;slots=new Map;retirement=new qh(this.deadline.bind(this));observers=new Nh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new hl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,o={}){this.runtime=e;this.options=o;if(o.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(o.beforeAppendBudgetMs)||o.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new _h(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new m(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let a=o.current.services.get(e.name);if(!e.validate(a))throw new m(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return a}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((a)=>a(e)))}noticeSource(e){return[...this.slots.values()].findLast((a)=>a.enabled&&a.current&&!a.current.disabled&&a.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let a=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==a)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let a of e)this.directories.add(Fh(a));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await WC(e),a=[...this.directories,VC(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>VC(u.directory,".basalt","plugins"))];for(let u of a){if(!HC(u))continue;let p=yB(await WC(u),o);if(p&&p!==".."&&!p.startsWith(`..${xB}`)&&!gB(p)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),a=await this.checkEntry(o);if(!a.ok)throw new tt(a.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((a)=>a.level==="error").map((a)=>({file:a.position?.file??null,line:a.position?.line??null,column:a.position?.column??null,message:a.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,a=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,a)})}async installDefinition(e,o,a=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:o,builtin:a,enabled:u?.enabled!==0};if(p.enabled)p.current=await this.stage(e,a);this.slots.set(e.id,p)}reload(e){return this.exclusive(async()=>{let o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let g=await this.checkEntry(o.path);if(!g.ok)throw new tt(g.errors)}let a=o.builtin&&!HC(o.path)?o.definition:await this.catalog.read(o.path);if(a.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((g)=>g.definition.id===e?a:g.definition),!0),p=await this.stage(a),f=o.current;o.definition=a,o.current=p,o.error=void 0,o.discoveryFailed=!1;let h=new Map(this.slots);this.slots.clear();for(let g of u){let x=h.get(g.id);if(x)this.slots.set(g.id,x)}if(f)await this.retirement.retire(f)}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}})}setEnabled(e,o){return this.exclusive(async()=>{let a=this.require(e);if(o===a.enabled&&(!o||a.current&&!a.current.disabled))return;if(!o){for(let h of this.slots.values())if(h.enabled&&h.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${h.definition.id}`)}let u=o&&a.discoveryFailed&&a.path?await this.catalog.read(a.path):a.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let p=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let f=a.current;if(a.definition=u,o)a.discoveryFailed=!1;if(a.enabled=o,a.current=p,a.error=void 0,f)await this.retirement.retire(f)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let a of e.deps??[])if(a===e.id||!this.slots.get(a)?.current||this.slots.get(a)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${a}`);return FC(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,a){this.observers.notify(e,o,a)}resolveHistory(e,o){for(let a of this.slots.values()){if(!a.enabled||!a.current||a.current.disabled)continue;for(let u of a.current.historyResolvers){let p=u(e,o);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Qc(this,e)}async invoke(e,o,a,u,p,f="end"){return MC(this,this.deadline.bind(this),this.fail.bind(this),e,o,a,u,p,f)}pinEntry(e){if(Oa.getStore()?.phase==="after")return;let o;for(let a of this.slots.values()){let u=a.current;if(!a.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Qc(this,o)}beforeEntry(e,o,a,u){return vC(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,a,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let a of e.connections)a.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,a){this.observers.finishEntry(e,o,a)}deadline(e,o=this.timeoutMs,a=!1){return PC(e,o,a)}appendExtension(e,o){return Xs(),new Promise((a)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),a(p)})}list(){return _C(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(a&&o.path)await this.webBuilder.build(a,zC(Fh(o.path)));return{ok:!0}}catch(o){if(o instanceof fl)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!a)return;return this.webBuilder.build(a,zC(Fh(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);return a?this.webBuilder.cache.get(a)?.css:void 0}command(e,o,a){return UC(this,this.deadline.bind(this),e,o,a)}hasRoute(e){return BC(this,e)}isPublicRoute(e){return GC(this,e)}route(e){return KC(this,this.deadline.bind(this),e)}websocket(e){return jC(this,this.slots.values(),this.deadline.bind(this),e)}collect(e){return this.retirement.collect(e)}async close(){this.catalog.close(),await this.serial,await this.idle(),this.closed=!0;for(let e of this.slots.values())if(e.current)await this.retirement.retire(e.current);await this.retirement.collectRetired()}}import{statSync as JC}from"fs";import{join as IB}from"path";var EB=500,bB=1000,SB=3600000,QC=5000,wB=2000,TB=3,RB=1073741824;class Uh{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;pauseQueue=Promise.resolve();constructor(e){this.options=e;if(this.indexPath=IB(e.dataDir,cs),this.features={...us(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,a=o?.backfill;if(!o||!a)return{...e,state:"backfilling"};if(a.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(a.total,a.done),indexed:a.done,state:a.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=JC(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=JC(this.options.store.path).size}catch{}return Math.max(RB,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(),yo(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.pauseQueue.then(async()=>{let a=this.worker;if(!a)return e();Atomics.store(this.flags,Xe,1);try{a.postMessage({type:"pause"});let u=Date.now()+QC;while(Atomics.load(this.flags,Et)===0){if(this.worker!==a)throw Error("\u641C\u7D22\u7D22\u5F15\u5DF2\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6574\u7406");if(Date.now()>=u)throw Error("\u641C\u7D22\u7D22\u5F15\u6B63\u5FD9\uFF0C\u6682\u505C\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6574\u7406");await new Promise((p)=>setTimeout(p,10))}if(this.worker!==a)throw Error("\u641C\u7D22\u7D22\u5F15\u5DF2\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6574\u7406");return e()}finally{Atomics.store(this.flags,Xe,0),Atomics.notify(this.flags,Xe);let u=Date.now()+QC;while(this.worker===a&&Atomics.load(this.flags,Et)!==0){if(Date.now()>=u){await this.stopWorker();break}await new Promise((p)=>setTimeout(p,10))}}});return this.pauseQueue=o.then(()=>{},()=>{}),o}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=ds(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,Xe,0),Atomics.store(this.flags,Et,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,a=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),a&&this.restarts<TB&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.worker=void 0,this.stopping=(async()=>{Atomics.store(this.flags,Xe,0),Atomics.notify(this.flags,Xe);let o=new Promise((a)=>{this.stopped=a});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(wB)]),e.terminate(),this.stopped=void 0,this.closeReader(),this.resolveFlushes(),this.prune()})();try{await this.stopping}finally{this.stopping=void 0}}resolveFlushes(){for(let e of this.flushes.values())e();this.flushes.clear()}closeReader(){this.reader?.close(),this.reader=void 0}schedulePrune(){if(this.pruneTimer)return;let e=Math.max(0,EB-(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)yo(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),SB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch(e){let o=e instanceof Error?e.message:String(e);if(/closed|busy|locked/i.test(o))return;console.error("search queue cleanup failed:",e)}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,bB-(performance.now()-this.lastPush)),a=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),p=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(u)};if(o===0)a();else this.statusTimer=setTimeout(a,o),this.statusTimer.unref?.()}}import{closeSync as MB,existsSync as Ru,mkdirSync as OB,openSync as _B,readdirSync as o0,readFileSync as YC,readSync as LB,realpathSync as Bh,statSync as Rl,writeFileSync as Gh}from"fs";import{dirname as Tl,isAbsolute as Kh,relative as s0,resolve as NB}from"path";import{existsSync as Xc}from"fs";import{dirname as CB,join as Tu}from"path";import{mkdirSync as kB,writeFileSync as AB}from"fs";import{tmpdir as PB}from"os";import{join as XC}from"path";var Sl=2000,Pe=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function wu(e,o){return e.map((a,u)=>{let p=a.length>Sl?`${a.slice(0,Sl)}\u2026 [line truncated]`:a;return`${String(o+u).padStart(6)} ${p}`}).join(`
|
|
84
|
-
`)}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(`
|
|
85
|
-
`).length-1;return`${e.slice(0,a)}
|
|
86
|
-
|
|
87
|
-
\u2026 [${p} characters, ~${f} lines omitted] \u2026
|
|
88
|
-
|
|
89
|
-
${e.slice(-u)}`}var $B=0;function nt(e,o,a){if(e.length<=o)return e;let u=le(e,o);try{let p=a?ei(a):XC(PB(),"basalt-output");kB(p,{recursive:!0});let f=XC(p,`${process.pid}-${Date.now().toString(36)}-${$B++}.txt`);return AB(f,e),`${u}
|
|
90
|
-
[Full output saved to ${f}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var Er=120000,Tr=600000,_a;function vB(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function Pr(){if(_a!==void 0)return _a||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let p=Tu(u,"bash.exe");if(vB(p))continue;if(Xc(p))return _a=p,p}for(let u of o){let p=Tu(u,"git.exe");if(Xc(p)){let f=CB(u),h=Tu(f,"bin","bash.exe");if(Xc(h))return _a=h,h;let g=Tu(f,"usr","bin","bash.exe");if(Xc(g))return _a=g,g}}let a=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?Tu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?Tu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of a)if(Xc(u))return _a=u,u;_a="";return}class to{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let a=0;while(a<o.length){if(o[a]<128){a+=1;continue}let p=o[a+1];if(p===void 0)break;let f=p>=48&&p<=57?4:2;if(a+f>o.length)break;a+=f}return this.gbkPending=o.slice(a),this.gbk.decode(o.subarray(0,a))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let a=new Uint8Array(this.sniffPending.length+e.length);if(a.set(this.sniffPending),a.set(e,this.sniffPending.length),a.length<2)return this.sniffPending=a,"";this.sniffPending=void 0;let u=a[0]===255&&a[1]===254,p=!1;for(let f=1;f<a.length;f+=2)if(a[f]===0){p=!0;break}this.isUtf16=u||p,o=a}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Nt(e,o){let a=process.platform==="win32",u=o??"auto";if(!a)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash"||u==="auto"){let p=Pr();if(p||u==="bash")return{argv:[p??"bash","-c",e],shellName:"bash",isWindows:!0}}return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}function Yo(e,o){let a=process.platform==="win32";return{...process.env,...qi(e),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...a?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o?{[Object.keys(process.env).find((u)=>u.toLowerCase()==="path")??"PATH"]:o}:{}}}function Vt(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128)e.kill()}else process.kill(-e.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}async function Kt(e,o){let{argv:a,isWindows:u,shellName:p}=Nt(e,o.shell),f=await qe(e,o.signal,p);if(f)return{output:f,code:126,timedOut:!1};if(o.signal?.aborted)return{output:"[aborted before the command started]",code:null,timedOut:!1};let h=Bun.spawn(a,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!u,windowsHide:!0,env:Yo(o.cwd,o.extraPath)}),g=!1,x,I=()=>{try{Vt(h)}catch(re){x=re}},E=setTimeout(()=>{g=!0,I()},o.timeout);o.signal?.addEventListener("abort",I,{once:!0});let k=Pe*2,A="",P="",C=0,M=0,J=!1,O="",B=(re=!1)=>{let ye=C-A.length-P.length,Te=ye>0?`${A}
|
|
91
|
-
\u2026 [${ye} characters omitted] \u2026
|
|
92
|
-
${P}`:A+P;if(!re)return le(Te,Pe);return nt(O.length===C?O:Te,Pe,o.cwd)},L=()=>{let re=new to;return async(ye)=>{for await(let ze of ye){let Y=re.decode(ze);if(C+=Y.length,O.length<4000000)O+=Y;if(A.length<k)A+=Y;else P=(P+Y).slice(-k);if(o.onOutput&&!J){let me=performance.now();if(me-M>=80){M=me;try{o.onOutput(B())}catch{J=!0}}}}let Te=re.flush();if(Te){if(C+=Te.length,O.length<4000000)O+=Te;if(A.length<k)A+=Te;else P=(P+Te).slice(-k)}}},X=Promise.all([L()(h.stdout),L()(h.stderr)]),te=await h.exited;if(clearTimeout(E),o.signal?.removeEventListener("abort",I),await Promise.race([X.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))P+=`
|
|
93
|
-
[background processes are still running; their later output is not captured]`;if(x)P+=`
|
|
94
|
-
[failed to kill the process tree: ${String(x)}]`;return{output:B(!0),code:g?null:te,timedOut:g}}class Hh{seen=new Map;mark(e,o=Rl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Rl(e).mtimeMs!==o?"changed":void 0}}var ZC=2000,qB=500,DB=10485760,e0=67108864,wl=20,FB=6,jB=40000,UB=80000;function t0(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return}function i0(e,o,a=[],u){let p=(C)=>Kh(C)?C:NB(e,C),f=(C)=>{let M=s0(e,C);return M&&!M.startsWith("..")&&!Kh(M)?M:C},h=(C)=>{let M=C;while(!Ru(M)&&Tl(M)!==M)M=Tl(M);let J=Bh(M);if(a.some((O)=>Ru(O)&&n0(Bh(O),J))&&!n0(Bh(e),J))throw Error("External directories are read-only")},g=(C,M,J)=>{let O=p(C);if(!Ru(O))throw Error(`No such file or directory: ${O}${HB(O)}`);let B=Rl(O);if(B.isDirectory()){let me=o0(O,{withFileTypes:!0}).map((Ee)=>Ee.isDirectory()?`${Ee.name}/`:Ee.name).sort(),he=me.slice(0,qB),we=me.length-he.length;return c(`${he.join(`
|
|
95
|
-
`)}${we>0?`
|
|
96
|
-
\u2026 and ${we} more entries`:""}`||"(empty directory)").content}if(B.size>DB){let me=Buffer.alloc(8192),he=_B(O,"r"),we=0;try{we=LB(he,me,0,me.length,0)}finally{MB(he)}if(t0(me.subarray(0,we)))throw Error(`${O} exceeds the 10 MB image limit (${B.size} bytes)`);if(B.size>e0)throw Error(`${O} is too large to read (${B.size} bytes, limit ${e0}); inspect it with head, tail or grep instead`)}let L=YC(O),X=t0(L);if(X)return o.mark(O),[{type:"text",text:`Read image ${f(O)} (${X}, ${B.size} bytes)`},{type:"image",data:L.toString("base64"),mimeType:X}];if(L.subarray(0,8192).includes(0))throw Error(`${O} looks like a binary file (${B.size} bytes)`);o.mark(O);let te=L.toString("utf8");if(!te)return c("(empty file)").content;let j=te.replace(/\r?\n$/,"").split(/\r?\n/),re=(M??1)-1;if(re>=j.length)throw Error(`offset ${M} is past the end of the file (${j.length} lines)`);let ye=Math.min(j.length,re+(J??ZC)),Te=0,ze=re;while(ze<ye){let me=j[ze]?.length??0;if(ze>re&&Te+me>jB)break;Te+=me,ze++}let Y=wu(j.slice(re,ze),re+1);if(ze<ye)Y+=`
|
|
97
|
-
|
|
98
|
-
(Showing lines ${re+1}-${ze} of ${j.length} (truncated at line ${ze} due to safety budget). Use offset/limit to read specific windows.)`;else if(re>0||ze<j.length)Y+=`
|
|
99
|
-
|
|
100
|
-
(Showing lines ${re+1}-${ze} of ${j.length}. Use offset/limit to read other parts.)`;return c(Y).content},x=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.
|
|
101
|
-
- path may be absolute or relative to the working directory.
|
|
102
|
-
- By default reads up to ${ZC} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
|
|
103
|
-
- Lines longer than ${Sl} characters are truncated.
|
|
104
|
-
- Reading a directory lists its entries (directories end with /).
|
|
105
|
-
- Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
|
|
106
|
-
- To read several files at once, give paths instead of path (up to ${wl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
|
|
107
|
-
- Always read a file before editing or overwriting it.`,parameters:l({path:n(s({description:"File or directory path"})),offset:n(S({minimum:1,description:"1-based line number to start from"})),limit:n(S({minimum:1,description:"Maximum number of lines to return"})),paths:n(H(l({path:s({description:"File or directory path"}),offset:n(S({minimum:1,description:"1-based line number to start from"})),limit:n(S({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:wl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(C,M){let J=[...M.path!==void 0?[{path:M.path,offset:M.offset,limit:M.limit}]:[],...M.paths??[]];if(J.length===0)throw Error("Give path, or paths to read several files");if(J.length===1){let te=J[0];return{content:g(te.path,te.offset,te.limit),details:void 0}}if(J.length>wl)throw Error(`Read at most ${wl} paths per call`);let O=[],B=[],L=0,X=(te)=>{let j=O.at(-1);if(te.type==="text"&&j?.type==="text")j.text+=`
|
|
108
|
-
|
|
109
|
-
${te.text}`;else O.push(te)};for(let te of J){let j=`==> ${f(p(te.path))} <==`;if(L>=UB){X({type:"text",text:`${j}
|
|
110
|
-
(Skipped due to total read safety budget; read in separate calls)`});continue}try{let re=g(te.path,te.offset,te.limit);for(let ye=0;ye<re.length;ye++){let Te=re[ye];if(!Te)continue;if(Te.type==="text")L+=Te.text.length,X(ye===0?{...Te,text:`${j}
|
|
111
|
-
${Te.text}`}:Te);else X(Te)}}catch(re){let ye=re instanceof Error?re.message:String(re);B.push(ye),X({type:"text",text:`${j}
|
|
112
|
-
Error: ${ye}`})}}if(B.length===J.length)throw Error(B.join(`
|
|
113
|
-
`));return{content:O,details:void 0}}}),I=async(C,M,J,O)=>{let B=O?.update,L=await Kt(C,{cwd:e,timeout:120000,signal:J,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:B?(ye)=>B(c(`${O.prefix}
|
|
114
|
-
|
|
115
|
-
$ ${C}
|
|
116
|
-
${ye.trimEnd()}`)):void 0}),X=L.output.trimEnd()||"(no output)",te=L.timedOut?"killed after 120s timeout":L.code===0?"exit code 0":`exit code ${L.code}`,j=L.timedOut||L.code!==0,re=j?`
|
|
117
|
-
${M}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
|
|
118
|
-
|
|
119
|
-
$ ${C}
|
|
120
|
-
${X}
|
|
121
|
-
[${te}]${re}`,failed:j}},E=(C,M=!1)=>{let J=o.check(C);if(J==="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(J==="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.
|
|
122
|
-
- An existing file is replaced whole, including changes made since you last read it.
|
|
123
|
-
- Prefer the edit tool for changing existing files; use write for new files or full rewrites.
|
|
124
|
-
- 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.
|
|
125
|
-
- 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,J,O){let B=p(M.path);h(B);let L=Ru(B),X;if(L){if(Rl(B).isDirectory())throw Error(`${B} is a directory`);X=E(B,!0)}OB(Tl(B),{recursive:!0}),Gh(B,M.content),o.mark(B);let te=M.content?M.content.split(`
|
|
126
|
-
`).length:0,j=`${L?"Overwrote":"Created"} ${f(B)} (${te} lines)${X?`
|
|
127
|
-
${X}`:""}`;if(M.then_run){let re=await I(M.then_run,`${f(B)} was written as given`,J,{prefix:j,update:O});if(j+=re.out,re.failed)return{...c(j),isError:!0}}return c(j)}}),A=(C,M,J,O)=>{let B=p(C);if(!Ru(B))throw Error(`File not found: ${B} (use write to create it)`);h(B);let L=E(B),X=YC(B,"utf8"),te=X,j=te.includes(`\r
|
|
128
|
-
`),re=[],ye=[],Te=0,ze=0;return M.forEach((Y,me)=>{let he=O?`edits[${J+me}]: `:"";try{if(Y.old_string===Y.new_string)throw Error(`${he}old_string and new_string are identical`);if(!Y.old_string)throw Error(`${he}old_string is empty (use write to create or replace a whole file)`);let we=j&&!Y.old_string.includes(`\r
|
|
129
|
-
`),Ee=we?Y.old_string.replace(/\n/g,`\r
|
|
130
|
-
`):Y.old_string,ft=we?Y.new_string.replace(/\n/g,`\r
|
|
131
|
-
`):Y.new_string,ke=BB(te,Ee).map((Ct)=>[Ct,Ct+Ee.length]);if(ke.length===0)ke=GB(te,Ee);if(ke.length===0)throw Error(`${he}old_string not found in ${f(B)}; read the relevant lines and copy the exact text.${KB(te,Ee)}`);if(ke.length>1&&!Y.replace_all){let Ct=ke.map(([at])=>r0(te,at)).join(", ");throw Error(`${he}old_string occurs ${ke.length} times (lines ${Ct}); add surrounding lines to make it unique, or set replace_all.`)}let Le=r0(te,ke[0][0]),zt=Y.replace_all?ke:[ke[0]],gt="",Ut=0;for(let[Ct,at]of zt)gt+=te.slice(Ut,Ct)+ft,Ut=at;te=gt+te.slice(Ut),Te++,ze+=zt.length;let xr=te.split(/\r?\n/),fr=Le+ft.split(/\r?\n/).length-1,rr=Math.max(1,Le-1),st=Math.min(xr.length,fr+1);if(st-rr+1<=FB+2)re.push(wu(xr.slice(rr-1,st),rr));else re.push(`${wu(xr.slice(rr-1,Le+1),rr)}
|
|
132
|
-
\u2026 (${fr-Le-3} lines as given)
|
|
133
|
-
${wu(xr.slice(fr-2,st),fr-1)}`)}catch(we){ye.push(we instanceof Error?we.message:String(we))}}),{path:B,original:X,content:te,echoes:re,applied:Te,total:ze,count:M.length,note:L,failed:ye}},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.
|
|
134
|
-
- No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
|
|
135
|
-
- 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.
|
|
136
|
-
- 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.
|
|
137
|
-
- 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.
|
|
138
|
-
- To create a file use write; to delete or move files use bash.
|
|
139
|
-
- 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.
|
|
140
|
-
- Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(s({description:"File path (the default for edits items without their own path)"})),old_string:n(s({description:"The exact text to replace (only when edits is absent)"})),new_string:n(s({description:"The replacement text (only when edits is absent)"})),replace_all:n(D({description:"Replace every occurrence (default false)"})),edits:n(H(l({path:n(s({description:"The file of this replacement, when it is not path"})),old_string:s({description:"The exact text to replace"}),new_string:s({description:"The replacement text"}),replace_all:n(D({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(s({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(C,M,J,O){let B=M.edits&&M.edits.length>0?M.edits.map((Y)=>({path:Y.path??M.path,step:Y})):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(B.length===0)throw Error("Give old_string and new_string, or edits");let L=B.length>1,X=new Map;B.forEach((Y,me)=>{if(!Y.path)throw Error(`${L?`edits[${me}]: `:""}path is required`);let he=p(Y.path),we=X.get(he)??{raw:Y.path,steps:[],offset:me};we.steps.push(Y.step),X.set(he,we)});let te=[],j=[];for(let Y of X.values())try{let me=A(Y.raw,Y.steps,Y.offset,L);if(me.applied>0)te.push(me);j.push(...me.failed)}catch(me){let he=me instanceof Error?me.message:String(me);j.push(`${L?`edits[${Y.offset}]: `:""}${he}`)}if(te.length===0)throw Error(j.join(`
|
|
141
|
-
`));let re=[];try{for(let Y of te)Gh(Y.path,Y.content),re.push(Y)}catch(Y){for(let me of re)Gh(me.path,me.original);throw Y}for(let Y of te)o.mark(Y.path);let Te=te.map((Y)=>{let me=Y.total===1?"1 occurrence":`${Y.total} occurrences`,he=Y.note?`
|
|
142
|
-
${Y.note}`:"";if(!L)return`Edited ${f(Y.path)} (${me}).${he}
|
|
143
|
-
${Y.echoes[0]}`;let we=Y.failed.length>0?`, ${Y.failed.length} failed`:"";return`Edited ${f(Y.path)} (${Y.applied} edits${we}, ${me}). Regions are shown as they were right after each edit; later edits may shift line numbers.${he}
|
|
144
|
-
${Y.echoes.map((Ee,ft)=>`--- edit ${ft+1}
|
|
145
|
-
${Ee}`).join(`
|
|
146
|
-
`)}`}).join(`
|
|
147
|
-
|
|
148
|
-
`),ze=!1;if(M.then_run){let Y=await I(M.then_run,"The edits above were applied",J,{prefix:Te,update:O});if(Te+=Y.out,Y.failed)ze=!0}if(j.length>0)Te+=`
|
|
149
|
-
|
|
150
|
-
${j.length===1?"1 edit":`${j.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
|
|
151
|
-
- ${j.join(`
|
|
152
|
-
- `)}`,ze=!0;return ze?{...c(Te),isError:!0}:c(Te)}});return[ve(x,"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 BB(e,o){let a=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))a.push(u);return a}function r0(e,o){let a=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)a++;return a}function GB(e,o){let a=o.replace(/\r?\n$/,"").split(/\r?\n/).map((x)=>x.trimEnd()),u=[],p=e.split(`
|
|
153
|
-
`),f=0;for(let x of p)u.push(f),f+=x.length+1;let h=p.map((x)=>x.replace(/\r$/,"").trimEnd()),g=[];for(let x=0;x+a.length<=h.length;x++)if(a.every((I,E)=>h[x+E]===I)){let I=x+a.length-1,E=u[I]+p[I].replace(/\r$/,"").length,k=o.endsWith(`
|
|
154
|
-
`)&&E<e.length?e[E]==="\r"?2:1:0;g.push([u[x],E+k]),x+=a.length-1}return g}function KB(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(`
|
|
155
|
-
`))===u)return` A match ignoring whitespace exists at line ${g+1}; copy the exact indentation and line breaks from the read output:
|
|
156
|
-
${le(wu(p.slice(g,g+f),g+1),4000)}`;let h=o.split(/\r?\n/).find((g)=>g.trim())?.trim();if(h){let g=p.findIndex((x)=>x.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 HB(e){let o=Tl(e);if(!Ru(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let p=o0(o).filter((f)=>{let h=f.toLowerCase().replace(/\.[^.]*$/,"");return h&&(h.includes(u)||u.includes(h))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function n0(e,o){let a=s0(e,o);return a===""||!a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&a!==".."&&!Kh(a)}var Wh=20,zh=80,WB=5,zB=(e)=>e!==void 0&&e>0?e:void 0;function a0(e,o){let a=Zn(e,o)??eo(e,o);if(!a)throw Error(`No user message with seq ${o}`);return a}function kl(e,o){let a=(h)=>{if(o)return o(h);if(h.source&&h.source!=="self"||h.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(h)=>{let g=a(h),x=zB(h.seq);return{scope:g,seq:x,runs:()=>rt(g.records),reference:`session_id=${g.sessionID}`,both:x!==void 0&&h.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
157
|
-
`:""}},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; searches each line including its source label (e.g. "ASSISTANT:", "USER:", "TOOL_OUTPUT:"). Every line has its label for searching, even when repeated labels are omitted in displayed output. "also" adds more strings that must be on the same line.
|
|
158
|
-
- 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).
|
|
159
|
-
- Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),pattern:s({minLength:1,description:"Text to search for"}),also:n(H(s({minLength:1}),{maxItems:WB,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(S({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(D({description:"Default false"})),head_limit:n(S({minimum:1,maximum:Wh,description:`Hits to return (default ${Wh})`})),offset:n(S({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(h,g){let{scope:x,seq:I,runs:E,reference:k,both:A}=u(g),P;if(I!==void 0)P=[a0(x.records,I)];else{let re=E(),ye=g.chunk_id?re.filter((Te)=>Te.id===g.chunk_id):re;if(g.chunk_id&&!ye.length)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);P=ye.map(Ar)}let C=(re)=>g.case_sensitive?re:re.toLowerCase(),M=[g.pattern,...(g.also??[]).filter(Boolean)].map(C),J=g.head_limit??Wh,O=g.offset??0,B=[],L=new Map,X=0;for(let re of P)re.forEach((ye,Te)=>{let ze=C(`${ye.source}: ${ye.text}`);if(!M.every((me)=>ze.includes(me)))return;if(L.set(ye.chunk,(L.get(ye.chunk)??0)+1),X++,X<=O||B.length>=J)return;let Y=re.slice(Math.max(0,Te-2),Te+3);B.push(`${k} chunk ${ye.chunk} line ${ye.line}:
|
|
160
|
-
${fn(Y," ")}`)});if(!X)return c(`${A}No matches`);if(!B.length)return c(`${A}No matches at offset ${O} (total ${X})`);let te=X-O-B.length,j=L.size>1?` (all matches by chunk: ${[...L].map(([re,ye])=>`${re} ${ye}`).join(", ")})`:"";return c(`${A}${B.join(`
|
|
161
|
-
|
|
162
|
-
`)}${te>0?`
|
|
163
|
-
|
|
164
|
-
\u2026 ${te} more matches${j}; continue with offset=${O+B.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(S({description:"User message to read (from a user-text-reference)"})),offset:n(S({minimum:0,description:"First line (default 0)"})),limit:n(S({minimum:1,maximum:zh,description:`Lines to return (default ${zh})`}))}),async execute(h,g){let{scope:x,seq:I,runs:E,reference:k,both:A}=u(g),P;if(I!==void 0)P=a0(x.records,I);else if(g.chunk_id){let O=E().find((B)=>B.id===g.chunk_id);if(!O)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);P=Ar(O)}else{let O=E().map((B)=>`${k} ${B.id} (${B.status}, ${Ar(B).length} lines)`);return c(O.length?`Pass chunk_id or seq. Chunks in this session:
|
|
165
|
-
${O.join(`
|
|
166
|
-
`)}`:"This session has no history yet")}let C=g.offset??0,M=P.slice(C,C+(g.limit??zh));if(!M.length)return c(`No lines at offset ${C} (total ${P.length})`);let J=P.length-C-M.length;return c(`${A}${k} ${I!==void 0?`seq=${I}`:g.chunk_id}
|
|
167
|
-
${fn(M)}${J>0?`
|
|
168
|
-
|
|
169
|
-
\u2026 ${J} more lines; continue with offset=${C+M.length}`:""}`)}});return[p,f]}import{existsSync as VB,statSync as u0}from"fs";import{isAbsolute as c0,relative as JB,resolve as m0}from"path";var Al=200,QB=30000,Pl=Bun.which("rg");async function Vh(e,o,a){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:a,windowsHide:!0}),[p,f,h]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(h>1)throw Error(f.trim()||`${e[0]} exited with ${h}`);return p}function p0(e){let o=(f)=>f?c0(f)?f:m0(e,f):e,a=(f)=>{let h=JB(e,f);return h&&!h.startsWith("..")&&!c0(h)?h:f},u=T({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
|
|
170
|
-
- Respects .gitignore and skips .git. Use it instead of find or ls -R.
|
|
171
|
-
- 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 x=o(h.path),I=!1;try{I=u0(x).isDirectory()}catch{}if(!I)throw Error(`Directory not found: ${a(x)}`);let E;if(Pl)E=(await Vh([Pl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",h.pattern],x,g)).split(`
|
|
172
|
-
`).filter(Boolean);else{E=[];for await(let C of new Bun.Glob(h.pattern).scan({cwd:x,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(C))E.push(C)}if(!E.length)return c("No files found");let k=E.map((C)=>{let M=m0(x,C);try{return{path:M,time:u0(M).mtimeMs}}catch{return{path:M,time:0}}});k.sort((C,M)=>M.time-C.time);let A=k.slice(0,Al).map((C)=>a(C.path)),P=E.length-A.length;return c(`${A.join(`
|
|
173
|
-
`)}${P>0?`
|
|
174
|
-
\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.
|
|
175
|
-
- output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
|
|
176
|
-
- Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
|
|
177
|
-
- Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
|
|
178
|
-
- 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(S({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(f,h,g){let x=o(h.path);if(!VB(x))throw Error(`Path not found: ${a(x)}`);let I=h.output??"files",E;if(Pl){let P=[Pl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(h.ignore_case)P.push("-i");if(h.glob)P.push("--glob",h.glob);if(I==="files")P.push("-l");else if(I==="count")P.push("-c");else if(P.push("-n","--no-heading"),h.context)P.push("-C",String(h.context));P.push("--",h.pattern,x),E=await Vh(P,e,g)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(h.ignore_case)P.push("-i");if(h.glob)P.push(`--include=${h.glob}`);if(I==="files")P.push("-l");else if(I==="count")P.push("-c");else if(P.push("-n"),h.context)P.push(`-C${h.context}`);P.push("--",h.pattern,x),E=await Vh(P,e,g)}let k=`${e}/`,A=E.split(`
|
|
179
|
-
`).filter(Boolean).map((P)=>P.startsWith(k)?P.slice(k.length):P).filter((P)=>I!=="count"||!P.endsWith(":0"));if(!A.length)return c("No matches");if(I==="files"&&A.length>Al)return c(`${A.slice(0,Al).join(`
|
|
180
|
-
`)}
|
|
181
|
-
\u2026 ${A.length-Al} more files; narrow the search`);return c(nt(A.join(`
|
|
182
|
-
`),QB,e))}});return[ve(u,"find","find_files","list_files","file_search","ls","list","list_dir"),ve(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function l0(e){return ve(T({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
|
|
183
|
-
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.
|
|
184
|
-
- Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
|
|
185
|
-
- 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.
|
|
186
|
-
- Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:H(l({content:s({minLength:1,description:"What to do, in imperative form"}),status:y(ao.map((o)=>i(o)))}))}),async execute(o,a){let u=a.todos.map((h)=>({content:h.content,status:h.status}));e(u);let p=u.filter((h)=>h.status==="completed").length,f=u.find((h)=>h.status==="in_progress");return c(`Todo list updated (${p}/${u.length} completed${f?`; in progress: ${f.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function d0(e){let o=de(e);return{target:o,hard:o,index:o}}class $l{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},a){this.records=e;this.cwd=o;if(a)this.defaultPolicy=new hn(e,a,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??d0(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??de(e)}prepare(e,o,a,u,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,a,u);let f=e.reduce((I,E)=>I+G(E),0)+Lt(o),h=Math.max(0,de(a)*this.recoveryRatio-f),g=Ce(u??this.records(),a,d0(a),{cwd:this.cwd()}).messages,x=g.reduce((I,E)=>I+G(E),0);if(p&&x>h)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(x>h&&g.length>1){let I=g.shift();if(I)x-=G(I);while(g[0]?.role==="toolResult"){let E=g.shift();if(E)x-=G(E)}}if(x>h){let I=g.at(-1),E=I&&"content"in I&&typeof I.content==="string"?I.content:"[Context omitted: use history tools to retrieve earlier messages.]";g.length=0;let k=E;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});x=g.reduce((A,P)=>A+G(P),0)}return this.lastMessageCount=g.length,{messages:[...e,...g],estimate:f+x}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as Qh,readFileSync as XB}from"fs";import{homedir as YB}from"os";import{dirname as f0,join as Xh,resolve as ZB}from"path";var eG=`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.
|
|
187
|
-
|
|
188
|
-
# How to work
|
|
189
|
-
|
|
190
|
-
- 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.
|
|
191
|
-
- 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.
|
|
192
|
-
- 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.
|
|
193
|
-
- 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.
|
|
194
|
-
|
|
195
|
-
# Making changes
|
|
196
|
-
|
|
197
|
-
- 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.
|
|
198
|
-
- 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.
|
|
199
|
-
- 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.
|
|
200
|
-
- 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).
|
|
201
|
-
- Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
|
|
202
|
-
- 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.
|
|
203
|
-
|
|
204
|
-
# Verifying
|
|
205
|
-
|
|
206
|
-
- 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.
|
|
207
|
-
- 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.
|
|
208
|
-
- 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.
|
|
209
|
-
- 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.
|
|
210
|
-
- 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.
|
|
211
|
-
|
|
212
|
-
# Tools
|
|
213
|
-
|
|
214
|
-
- Tool calls are the only way to act; describing an action does not perform it.
|
|
215
|
-
- 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.
|
|
216
|
-
- 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.
|
|
217
|
-
- 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.
|
|
218
|
-
- 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.
|
|
219
|
-
- 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.
|
|
220
|
-
- 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 &&.
|
|
221
|
-
- 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.
|
|
222
|
-
|
|
223
|
-
# Honesty
|
|
224
|
-
|
|
225
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
226
|
-
- Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
|
|
227
|
-
- When the user asks you to run something, run it, even when you can predict the result.
|
|
228
|
-
- If a step failed, was skipped or could not be verified, say which one and why.
|
|
229
|
-
|
|
230
|
-
# Safety
|
|
231
|
-
|
|
232
|
-
- 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.
|
|
233
|
-
- 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.
|
|
234
|
-
- 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.
|
|
235
|
-
- Never print, log or commit secrets such as API keys, tokens or passwords.
|
|
236
|
-
|
|
237
|
-
# Communication
|
|
238
|
-
|
|
239
|
-
- Reply in the same language the user writes in.
|
|
240
|
-
- 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.
|
|
241
|
-
- 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.
|
|
242
|
-
- Do not use emojis unless the user does or asks for them.
|
|
243
|
-
- 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.
|
|
244
|
-
- Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,tG=`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.
|
|
245
|
-
|
|
246
|
-
# Tools
|
|
247
|
-
|
|
248
|
-
- 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.
|
|
249
|
-
- 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.
|
|
250
|
-
- Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
|
|
251
|
-
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
|
|
252
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
253
|
-
|
|
254
|
-
# Communication
|
|
255
|
-
|
|
256
|
-
- Reply in the same language the user writes in.
|
|
257
|
-
- Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
|
|
258
|
-
- Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,rG=["AGENTS.md","CLAUDE.md"],nG=20000;function h0(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?eG:tG}],a=[];if(e.globalInstructions?.trim())a.push(Jh("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of oG(e.project.directory))a.push(Jh(u.path,u.content));if(e.project.instructions.trim())a.push(Jh(`Project "${e.project.name}" instructions`,e.project.instructions))}if(a.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
|
|
259
|
-
|
|
260
|
-
# Instructions from the user and project
|
|
261
|
-
|
|
262
|
-
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.
|
|
263
|
-
|
|
264
|
-
${a.join(`
|
|
265
|
-
|
|
266
|
-
`)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
|
|
267
|
-
|
|
268
|
-
${sG(e)}`}),o}function Jh(e,o){return`<instructions source="${e}">
|
|
269
|
-
${le(o.trim(),nG)}
|
|
270
|
-
</instructions>`}function oG(e){let o=[],a=e;for(let u=0;u<20;u++){for(let f of rG){let h=Xh(a,f);if(Qh(h))try{o.unshift({path:h,content:XB(h,"utf8")});break}catch(g){let x=g instanceof Error?g.message:String(g);o.unshift({path:h,content:`(This instruction file could not be read: ${x})`})}}if(Qh(Xh(a,".git"))||a===YB())break;let p=f0(a);if(p===a)break;a=p}return o}function sG(e){let o=e.now??new Date,a=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:f}=Nt("",e.shell),h=[`Working directory: ${p}`,`Shell: ${f}`,`Date: ${a} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)h.push(e.git??"Git: not a git repository");return`<environment>
|
|
271
|
-
${h.join(`
|
|
272
|
-
`)}
|
|
273
|
-
</environment>`}function iG(e){let o=ZB(e);while(!0){if(Qh(Xh(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let a=f0(o);if(a===o)return!1;o=a}}async function g0(e,o){if(o?.aborted||iG(e))return;let a=async(...x)=>{try{let I=Bun.spawn(["git",...x],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[E,k]=await Promise.all([new Response(I.stdout).text(),I.exited]);return k===0?E.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(`
|
|
274
|
-
`):[],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?`
|
|
275
|
-
${g.join(`
|
|
276
|
-
`)}`:" clean"}`,f?`Recent commits:
|
|
277
|
-
${f}`:"Recent commits: none"].join(`
|
|
278
|
-
`)}function Qt(e){let a=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?kl(e.records,e.history):[],u=e.directory??process.cwd();return[...i0(u,new Hh,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...p0(u),l0(e.onTodos),...a]}class ea{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!is.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!os.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let a=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete a[u];else a[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let p=u,f=p.source??"core",h=u.name.toLowerCase(),g=p.defer??"always",x="suggestion";if(o.global)g=o.global,x="global";if(Object.hasOwn(o.sources,f))g=o.sources[f]??g,x="source";if(Object.hasOwn(o.tools,h))g=o.tools[h]??g,x="tool";if(f==="core"||p.builtin&&p.defer!=="defer")g="always",x="suggestion";return{name:u.name,source:f,mode:g,origin:x,deferred:g==="defer"}})}}function Yh(e){return{name:e.name,description:e.description,parameters:e.parameters}}function Zh(e,o){if(!o)return e;let a=Array.isArray(o.type)?o.type:[o.type],u=e;if(a.includes("number")||a.includes("integer")){let p=typeof u==="string"&&u.trim()?Number(u):u;if(typeof p!=="number"||!Number.isFinite(p))return u;let f=p;if(typeof o.maximum==="number"&&f>o.maximum)f=o.maximum;if(typeof o.minimum==="number"&&f<o.minimum)f=o.minimum;return f===p?u:f}if(typeof u==="string"&&(a.includes("object")||a.includes("array")))try{let p=JSON.parse(u),f=Array.isArray(p);if(typeof p==="object"&&p!==null&&!f&&a.includes("object")||f&&a.includes("array"))u=p}catch{}if(Array.isArray(u)){let p=o.items;if(!p||typeof p!=="object"||Array.isArray(p))return u;return u.map((f)=>Zh(f,p))}if(typeof u==="object"&&u!==null&&o.properties){let p={...u};for(let[f,h]of Object.entries(o.properties))if(f in p)p[f]=Zh(p[f],h);return p}return u}function aG(e){let o=e.prepareArguments;return{...e,prepareArguments:(a)=>{let u=Zh(a,e.parameters);return o?o(u):u}}}function uG(e,o,a){let u=e.prepareArguments?e.prepareArguments(a):a;return yu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class eg{retrieved=new Map;stub(e,o){let a=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${a}
|
|
279
|
-
(Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,p,f,h)=>{let g=JSON.stringify(Yh(e)),x;try{x=uG(e,u,p??{})}catch(k){return{...c(`Invalid arguments for ${e.name}: ${String(k)}
|
|
280
|
-
Schema: ${g}`),isError:!0}}let I=await e.execute(u,x,f,h),E=I.content.map((k)=>k.type==="text"?{...k,text:nt(k.text,Pe,o)}:k);return{...I,content:E}}}}assemble(e,o,a,u){let p=e.map(aG),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,x)=>g.name<x.name?-1:g.name>x.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(S({minimum:1,maximum:100}))}),execute:async(g,x)=>{let I=x.query.trim().toLowerCase(),E=I.startsWith("select:")?I.slice(7).split(",").map((A)=>A.trim()):void 0,k=h.filter((A)=>a(A.name)&&(E?E.includes(A.name.toLowerCase()):`${A.name} ${A.description}`.toLowerCase().includes(I))).slice(0,x.max_results??5);return c(JSON.stringify(k.map((A)=>{let P=JSON.stringify(Yh(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}),Yh(A)})))}}),"tool_search")]}}async function Cl(e,o,a,u){let p=await o.setup(e,u),f=a?.has("projection.policy")?await a.invoke("projection.policy",void 0,e):void 0;if(e.context.use(f),!a)return p;if(a.has("session.setup"))p=await a.invoke("session.setup",p,e);if(a.has("tools.configure"))p=await a.invoke("tools.configure",p,e);let h=p.systemPrompt,g=p.systemParts?.at(-1);if(g?.label==="\u8FD0\u884C\u73AF\u5883"&&a.has("prompt.fragments","before-environment")){let k=await a.invoke("prompt.fragments",[],e,void 0,"before-environment"),A=h.length-g.detail.length;h=h.slice(0,A)+k.join("")+g.detail}let x=await a.invoke("prompt.fragments",[],e),I=[...p.tools,...a.tools()],E=a.has("tools.visible")?await a.invoke("tools.visible",I,e):I;return{...p,systemPrompt:h+x.join(""),tools:E}}var cG=3,y0={attempts:10,delayMs:2000},mG=/\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 pG(e,o){if(e.stopReason!=="error")return!1;if(Ta(e,o))return!1;return!mG.test(e.errorMessage??"")}function x0(e,o,a){if(Ta(e,o))return!0;if(a?.preserveHistory!==!0)return!1;return e.errorMessage===(a.overflowError??"Context exceeds the request budget")}var I0="\u4E0A\u4E0B\u6587\u5DF2\u6EE1\uFF0C\u6A21\u578B\u6CA1\u6709\u5269\u4F59\u7684\u8F93\u51FA\u7A7A\u95F4\uFF0C\u56DE\u590D\u88AB\u622A\u65AD\uFF1B\u8BF7\u538B\u7F29\u4F1A\u8BDD\u6216\u6362\u7528\u4E0A\u4E0B\u6587\u66F4\u5927\u7684\u6A21\u578B";function E0(e){if(e.stopReason!=="length")return!1;return!e.content.some((o)=>o.type==="text"&&o.text.trim()||o.type==="toolCall")}function lG(e,o){return new Promise((a,u)=>{if(o.aborted)return u(o.reason);let p=setTimeout(()=>{o.removeEventListener("abort",f),a()},e),f=()=>{clearTimeout(p),u(o.reason)};o.addEventListener("abort",f,{once:!0})})}async function b0(e,o,a,u,p,f,h,g,x=!1){let I=x?void 0:await o?.invoke("run.start",{text:f},e);if(I)f=I.text;if(g.throwIfAborted(),f===void 0)await u.resume();else await u.prompt(f,h);let E=0,k=0;while(E<cG){let M=e.records.findLast((O)=>O.raw?.role==="assistant")?.raw;if(M&&E0(M)){if(!e.context.recover(p))throw Error(I0);g.throwIfAborted(),E++,await u.retry();continue}if(M?.stopReason!=="error")return;if(!x0(M,p.contextWindow,a)){if(!pG(M,p.contextWindow)||k>=y0.attempts)return;k++,await lG(y0.delayMs,g),await u.retry();continue}if(!e.context.recover(p)){if(a?.preserveHistory===!0)throw Error(a.overflowError??"Context exceeds the request budget");return}g.throwIfAborted(),E++,await u.retry()}let P=e.records.findLast((C)=>C.raw?.role==="assistant")?.raw;if(P&&E0(P))throw Error(I0);if(a?.preserveHistory===!0&&P?.stopReason==="error"&&x0(P,p.contextWindow,a))throw Error(a.overflowError??"Context exceeds the request budget")}async function S0(e,o,a,u,p,f){f.throwIfAborted();let h,g;try{g=await Promise.race([Cl(e,o,a(),f),new Promise((A,P)=>{h=()=>P(f.reason),f.addEventListener("abort",h,{once:!0})})])}finally{if(h)f.removeEventListener("abort",h)}f.throwIfAborted();let x=a(),I=(A)=>{if(!x)return A;return{...A,execute:async(P,C,M,J)=>{let O=u()??g.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),B=O?x.policy(O):void 0;if(O&&!B?.(A.name,e))throw Error(`Tool ${A.name} is unavailable under tool policy ${O}`);let L=await x.invoke("tool.before_call",{name:A.name,callID:P,args:C},e);if(L.block)throw Error(L.block);let X=await N.run(e,()=>A.execute(P,L.args,M,J));return x.invoke("tool.after_result",X,e)}}};if(x)g.tools=g.tools.map(I);let E=g.tools,k=()=>{if(!E.some((P)=>P.name==="history_grep")){if(e.records.some((C)=>C.entry.type==="compaction")){let M=kl(()=>e.records,(J)=>e.resolveHistory(J)).map(I);for(let J of M)if(!E.some((O)=>O.name===J.name))E.push(J)}}let A=new ea(o.store).partition(E);return g.tools=p.assemble(E,A,(P)=>e.permitsTool(P),g.cwd),g.tools};return g.tools=k(),{setup:g,executionTools:E,assemble:k}}function w0(e,o,a,u,p,f,h){return{response:async(g)=>{let x=await o()?.invoke("model.after_response",g,e)??g;if(x.role==="assistant")for(let I of x.content){if(I.type!=="toolCall"||I.name.toLowerCase()!=="tool_call")continue;let E=I.arguments.name;if(typeof E==="string"){let k=h.find((A)=>A.name.toLowerCase()===E.toLowerCase());I.arguments.name=k?.name??E}}return x},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 I of g?.notices??[])e.notice(I);await f.work;let x=await f.flushNotices();if(x&&!p())e.agent?.steer(x)},prepare:async(g,x,I)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let E=await o()?.invoke("model.check",{},e);if(E?.error)throw Error(E.error);let k=await o()?.invoke("step.before",{notices:[]},e);for(let X of k?.notices??[])e.notice(X);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],x,I,A,a()?.preserveHistory===!0),M=C.calibratedEstimate??C.estimate,J=de(I),O=a()?.preserveHistory===!0&&M>J;if(e.appendExtension({namespace:"session",kind:"request_budget",schemaVersion:1,payload:{model:`${I.provider}/${I.id}`,contextWindow:I.contextWindow,maxTokens:I.maxTokens,usable:J,localEstimate:C.estimate,calibratedEstimate:M,calibrationRatio:e.context.calibrationRatio,messageCount:C.messages.length,prefixMessageCount:P.length,blocked:O}}),O)throw Error(a()?.overflowError??"Context exceeds the request budget");let B=C.messages,L=await o()?.invoke("projection.after",B,e)??B;return Eu(xC(L))}}}async function T0(e,o,a){let u=o.store.pendingNotices(e.id);if(!u.length)return;let p=u,f=o.plugins?.pin();try{if(f){let P=await f.invoke("notice.deliver",u,e);p=u.map((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(`
|
|
281
|
-
`),g=p.map((P)=>o.plugins?.noticeSource(P.sourceKind)),x=Math.max(800,...g.map((P)=>P?.summaryLimit??800)),I=h.length>x?`
|
|
282
|
-
[\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]"}
|
|
283
|
-
${h.slice(0,x)}${I}`,A={role:"user",content:k,timestamp:Date.now()};return a({type:"user",text:k,notices:u.map(({text:P,...C})=>C)},A),A}class tg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,a,u,p,f,h,g){this.session=e;this.context=o;this.isStopped=a;this.isRunning=u;this.waiting=p;this.start=f;this.invalidateAgent=h;this.append=g}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let a of e){if(a.recovery!=="discard")continue;this.append({type:"extension",namespace:so,kind:"discarded",schemaVersion:1,payload:{dedupeKey:a.dedupeKey,sourceKind:a.sourceKind,sourceID:a.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((a)=>a.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((a)=>{this.failure=a}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=T0(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((o)=>o.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var dG=new Set(["authorization","proxy-authorization","x-api-key","api-key","x-goog-api-key","x-auth-token","x-amz-security-token","cookie","set-cookie"]);function rg(e){let o={};for(let[a,u]of Object.entries(e)){if(!dG.has(a.toLowerCase())){o[a]=u;continue}let p=/^bearer\s+/i.exec(u)?.[0];o[a]=p?`${p}***`:"***"}return o}function R0(e,o,a,u){let f=(a.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:a.systemPrompt}]).map((j,re)=>({id:`system-${re}`,label:j.label,detail:j.detail,tokens:F(j.detail)+(re===0?16:0)})),h=a.tools.map((j)=>{let re=j,ye=re.defer==="defer"||j.description.includes("(Parameters not inlined: use toolsearch");return{name:j.name,description:j.description,group:re.group??"\u5185\u7F6E",schema:j.parameters,deferred:ye}});f.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Lt(a.tools),detail:JSON.stringify(h,null,2)});let g=f.reduce((j,re)=>j+re.tokens,0),x=u!==void 0?e.records.filter((j)=>j.entry.seq<=u):e.records,I=Ce(x,o,e.context.budget(o),{inspect:!0,cwd:a.cwd,trim:{fixed:g,limit:e.context.previewLimit(o)}}),E,k=0,A=0;for(let j of x){if(j.raw?.role!=="assistant")continue;let re=j.raw.usage;E??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},E.input+=re.input,E.output+=re.output,E.cacheRead+=re.cacheRead,E.cacheWrite+=re.cacheWrite,E.cost+=re.cost.total;let ye=j.entry.generationMs??j.raw.generationMs;if(typeof ye==="number"&&ye>0&&re.output>0)k+=ye,A+=re.output}if(E){let j=E.input+E.cacheRead+E.cacheWrite;if(j>0)E.cacheHitRate=E.cacheRead/j}if(E&&k>0&&A>0)E.generationMs=k,E.tps=Number((A/(k/1000)).toFixed(1));let P=g+I.tokens,C=e.context.calibrationRatio??1,M=Math.round(P*C),J=x.findLast((j)=>j.raw?.role==="assistant"),O=J?.raw,L=(J?x.filter((j)=>j.entry.seq>J.entry.seq&&j.raw):x.filter((j)=>j.raw)).length>0,X,te;if(O){let j=O.usage,re=j.input+j.cacheRead+j.cacheWrite;if(re>0)X=re,te=j.cacheRead/re}return{contextWindow:o.contextWindow,usableWindow:de(o),items:[...f,...I.items],calibratedTokens:M,calibrationRatio:C,lastInputTokens:X,lastCacheHitRate:te,hasPendingOutput:L,tools:h,usage:E}}class ot extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class Z extends Error{constructor(e="session"){super(`${e} is busy`)}}var ng="medium",fG=1e6;class vl{row;ctx;events;notices;lease;policyID;discovery=new eg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Cl(this,this.ctx,e);return new ea(this.ctx.store).partition(o.tools).filter((a)=>this.permitsTool(a.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new Z;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;steerWaiter;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,a){this.row=e;this.ctx=o;this.events=a;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new tg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let p=this.entries(0,["extension","run"],!1),f=p.findLast((g)=>g.type==="extension"&&g.namespace==="session"&&g.kind==="stop_requested"),h=p.findLast((g)=>g.type==="run"&&g.state==="start");if(f&&f.seq>(h?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let g=this.entries(u.seq,["user"],!1).length>0,x=o.store.pendingNotices(e.id).some((I)=>I.wake&&I.recovery!=="discard");if(!this.stopped&&(g||x))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new $l(()=>this.records,()=>this.cwd,(g,x)=>this.appendCompaction(g,x)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=Cn(this.ctx.models,this.row.model);if(!e)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");return e}lastModelRequest(){let e=this.lastRequestSnapshot;return e?{...e,headers:rg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:rg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??ng}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get runningTools(){return this.agent?.agent.state.pendingToolCalls.size??0}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:a,model:u,thinking:p,metadata:f,created:h,updated:g,todos:x}=this.row;return{id:e,title:o,projectID:a,model:u,thinking:p??ng,metadata:f,created:h,updated:g,archivedAt:this.row.archivedAt,status:this.status,todos:x,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,fG);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let a=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,a,e)}entriesAround(e,o,a){return this.ctx.store.entriesAround(this.row.id,e,o,a)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,a=!0){return this.ctx.store.entries(this.row.id,e,o,a)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let a=Cn(this.ctx.models,this.row.model);if(!a)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),p;try{p=this.setup??await Cl(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new ea(this.ctx.store).partition(p.tools),(h)=>this.permitsTool(h),p.cwd);let f=R0(this,a,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:f};return f})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new ot}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!Cn(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,Hl(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let a=Hl(o),u=bh(e,a),p=this.append({type:"user",text:e,...a?.length?{attachments:a}:{}},u);if(this.recallableSteers.set(p.seq,u),this.steerWaiter?.abort(Error("user steered")),this.steerWaiter=void 0,this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}userSteered(){if(this.recallableSteers.size>0)return AbortSignal.abort(Error("user steered"));return this.steerWaiter??=new AbortController,this.steerWaiter.signal}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((f)=>f.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let a=o.raw,u=this.pendingSteers.indexOf(a);if(u<0){let f=JSON.stringify(a);u=this.pendingSteers.findIndex((h)=>JSON.stringify(h)===f)}let p=!1;if(u>=0)this.pendingSteers.splice(u,1),p=!0;else p=this.agent?.unsteer(a)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,a]of this.recallableSteers){if(a!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,a){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&a===void 0)throw new Z;if(e!==void 0)this.stopped=!1;let u=Cn(this.ctx.models,this.row.model);if(!u&&a===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let p=new AbortController;if(this.starting=p,!this.row.title&&e!==void 0)this.row={...this.row,title:hG(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),x=g.filter((k)=>k.entry.type==="user"&&!k.raw);if(x.length>1)return{reason:"interrupted"};let I=x[0];if(I?.entry.type==="user"){if(g.some((k)=>k.entry.seq>I.entry.seq&&k.raw?.role==="assistant"))return{reason:"interrupted"};e=I.entry.text,o=I.entry.attachments,this.pendingUserSeq=I.entry.seq}for(let k of Ge(g.filter((A)=>A.raw))){if(k.result)continue;let A=k.message.stopReason;if(A==="error"||A==="aborted")continue;let{body:P,raw:C}=ll(k.call);this.append(P,C)}if(!I&&this.waitingForInput())return{reason:"waiting_user"};let E=this.records.findLast((k)=>k.entry.seq>f&&k.raw)?.raw;if(!I&&E?.role==="assistant")return Sh(E);if(!I&&!E&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let h=await this.prepareAgent(u,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let g=this.pendingSteers.shift();if(g)h.steer(g)}return await b0(this,this.lease,this.setup,h,u,e,o,p.signal,a!==void 0&&e===void 0),Sh(this.records.findLast((g)=>g.entry.seq>f&&g.raw?.role==="assistant")?.raw)}).then((h)=>p.signal.aborted?{reason:"aborted"}:h,(h)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(h)}).then(async(h)=>{try{if(!this.suspended&&h.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())h={reason:"waiting_user"};if(h.reason!=="interrupted")h=await this.lease?.invoke("run.end",{reason:h.reason,error:h.error},this)??h}}catch(g){h={reason:"error",error:String(g)}}finally{try{await this.lease?.release()}catch(g){h={reason:"error",error:String(g)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...h});let g=Cn(this.ctx.models,this.row.model);if(g)this.context.settle(g)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:a,executionTools:u,assemble:p}=await S0(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=a,this.row.parentID&&(!a.toolPolicy||!this.lease?.policy(a.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=a.cwd,this.agent=eC({models:this.ctx.models,model:e,systemPrompt:a.systemPrompt,tools:a.tools,history:this.records.filter((f)=>!this.pendingSteers.includes(f.raw)).flatMap((f)=>f.raw?[f.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??ng,captureRequest:(f)=>{this.lastRequestSnapshot=f},captureResponse:(f)=>{this.lastResponseSnapshot=f},steerConsumed:(f)=>this.markSteerConsumed(f),hooks:{tools:p,...w0(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(f,h)=>{if(this.suspended&&h.role==="assistant"&&(h.stopReason==="aborted"||h.stopReason==="error"))return;if(h.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,h);let g=this.loaded?.find((x)=>x.entry.seq===this.pendingUserSeq);if(g)g.raw=h;this.pendingUserSeq=void 0;return}if(h.role==="assistant")this.context.calibrate(h);this.append(f,h)},draft:(f)=>{this.draftParts=f,this.events.draft(f)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let a=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...a?{saved:a}:{}})}measureCompactionSavings(e,o){let a=Cn(this.ctx.models,this.row.model);if(!a)return;let u=this.context.budget(a),p=Ce(this.records,a,u,{cwd:this.cwd}).tokens,f={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},h=Ce([...this.records,f],a,u,{cwd:this.cwd}).tokens;return{before:p,after:h}}compact(){this.assertWritable();let e=_r(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}compactAt(e){if(this.assertWritable(),this.status==="busy")throw new Z;let o=rt(this.records).findLast((a)=>a.end!==void 0&&a.end<e)?.end;if(o===void 0)throw new t("\u8FD9\u6761\u6D88\u606F\u4E4B\u524D\u6CA1\u6709\u53EF\u6298\u53E0\u7684\u5DF2\u7ED3\u675F\u8F6E\u6B21");if(o<=wt(this.records))throw new t("\u8BE5\u5904\u4E4B\u524D\u7684\u5185\u5BB9\u5DF2\u5728\u6298\u53E0\u8303\u56F4\u5185");return this.appendCompaction(o,!1),this.reset(),this.info()}uncompact(e){if(this.assertWritable(),this.status==="busy")throw new Z;let o=this.records.findLast((a)=>a.entry.type==="compaction")?.entry;if(o?.type!=="compaction")throw new t("\u4F1A\u8BDD\u6CA1\u6709\u53EF\u64A4\u56DE\u7684\u6298\u53E0");if(o.seq!==e)throw new t("\u53EA\u80FD\u64A4\u56DE\u6700\u8FD1\u4E00\u6B21\u6298\u53E0");return this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.reset(),this.events.entryRemoved(e),this.events.changed(),this.info()}append(e,o){this.refreshEntries();let a=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(a.type==="user"&&!(("notices"in a)&&a.notices))this.row={...this.row,updated:a.time};return this.refreshEntries(),a}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function hG(e,o){let u=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
|
|
284
|
-
`)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var A0=new Set(["user","assistant","tool_result","run","compaction"]),gG=new Set(["user","assistant","toolResult"]);function P0(e,o,a){return{format:si,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...a?{project:a}:{},records:o.filter((u)=>A0.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function ro(e){if(!yr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===si)return yG(e);if(yr(e.info)&&Array.isArray(e.messages))return IG(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 yG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!yr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let a=0,u=e.records.flatMap((p,f)=>{let h=`records[${f}]`;if(!yr(p)||!yr(p.entry))throw new t(`${h} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let g=p.entry;if(g.type==="notice_pending"||g.type==="extension")return[];if(typeof g.type!=="string"||!A0.has(g.type))throw new t(`${h} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(g.type)}`);let{seq:x,time:I}=g;if(typeof x!=="number"||!Number.isSafeInteger(x)||x<=a)throw new t(`${h} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof I!=="number"||!Number.isFinite(I))throw new t(`${h} \u7F3A\u5C11\u6709\u6548\u7684 time`);a=x,xG(g,h);let E=p.raw;if(E!==void 0&&!(yr(E)&&typeof E.role==="string"&&gG.has(E.role)))throw new t(`${h} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:g,...E===void 0?{}:{raw:E}}]});return{title:Gr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(C0):[],created:Ei(o.created)??Date.now(),updated:Ei(o.updated)??Date.now(),needsRaw:!1,records:u}}function xG(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"&&Gi.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 IG(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(EG),f=[],h=0,g=0,x=(J,O)=>{g=Math.max(g,O??g),h+=1,f.push({entry:{...J,seq:h,time:g}})},I=!1,E=(J,O)=>{if(!I)return;I=!1,x({type:"run",state:"end",reason:J,...O?{error:O}:{}},void 0)};for(let J of p){let O=yr(J.info)?J.info:{},B=Array.isArray(J.parts)?J.parts.filter(yr):[],L=Ei(yr(O.time)?O.time.created:void 0);if(O.role==="user"){E("done");let X=bG(B);if(!X)continue;x({type:"run",state:"start"},L),x(X,L),I=!0}else if(O.role==="assistant"){if(!I)x({type:"run",state:"start"},L),I=!0;TG(O,B,x);let X=$0(O.error);if(X)E(X.aborted?"aborted":"error",X.aborted?void 0:X.message)}}E("done");let k=p.findLast((J)=>yr(J.info)&&J.info.role==="assistant"),A=yr(k?.info)?k.info:void 0,P=Gr(u?.providerID)||Gr(A?.providerID),C=Gr(u?.id)||Gr(A?.modelID),M=P&&C?`${P}/${C}`:void 0;return{title:Gr(o.title),model:M,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(C0):[],created:Ei(a.created)??f[0]?.entry.time??Date.now(),updated:Ei(a.updated)??f.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:f}}function EG(e,o){let a=(p)=>(yr(p.info)&&yr(p.info.time)?Ei(p.info.time.created):void 0)??0,u=(p)=>yr(p.info)?Gr(p.info.id):"";return a(e)-a(o)||u(e).localeCompare(u(o))}function bG(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Gr(u.text)).join(`
|
|
285
|
-
|
|
286
|
-
`),a=e.flatMap((u)=>u.type==="file"?SG(u):[]);if(!o.trim()&&a.length===0)return;return{type:"user",text:o,...a.length?{attachments:a}:{}}}function SG(e){let o=Gr(e.mime)||"application/octet-stream",a=Gr(e.filename)||"file",u=Gr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(p){let f=p[3]??"";if(o.startsWith("image/"))return[{name:a,mimeType:o,kind:"image",data:p[2]?f:btoa(f)}];if(o.startsWith("text/")||o==="application/json"){let h=p[2]?new TextDecoder().decode(Uint8Array.from(atob(f),(g)=>g.charCodeAt(0))):f;return[{name:a,mimeType:o,kind:"text",data:h}]}return[]}if(u.startsWith("file://"))try{return[{name:a,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function wG(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 TG(e,o,a){let u=`${Gr(e.providerID)}/${Gr(e.modelID)}`,p=$0(e.error),f=wG(o);f.forEach((h,g)=>{let x=h.flatMap((k)=>{if(k.type==="reasoning")return Gr(k.text).trim()?[{type:"thinking",text:Gr(k.text)}]:[];if(k.type==="text")return k.ignored!==!0&&Gr(k.text).trim()?[{type:"text",text:Gr(k.text)}]:[];return[{type:"tool_call",id:k0(k.callID),name:Gr(k.tool),input:yr(k.state)&&yr(k.state.input)?k.state.input:{}}]}),I=g===f.length-1,E=RG(h);a({type:"assistant",parts:x,model:u,...I&&p&&!p.aborted?{error:p.message}:{}},E);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?[Gr(A.output),Gr(A.error)].filter(Boolean).join(`
|
|
287
|
-
`):C?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Gr(A.output);a({type:"tool_result",callID:k0(k.callID),name:Gr(k.tool),output:M,isError:P||C},Ei(yr(A.time)?A.time.end:void 0))}})}function k0(e){return Gr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function $0(e){if(!yr(e))return;let o=yr(e.data)?e.data:{};return{message:Gr(o.message)||Gr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function RG(e){for(let o of e){let a=yr(o.time)?Ei(o.time.start):yr(o.state)?kG(o.state):void 0;if(a!==void 0)return a}return}function kG(e){return yr(e.time)?Ei(e.time.start):void 0}function C0(e){if(!yr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function v0(e,o){let a={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let p=u.time;switch(u.type){case"user":return{entry:u,raw:AG(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:PG(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 AG(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)}>
|
|
288
|
-
${f.data}
|
|
289
|
-
</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(`
|
|
290
|
-
|
|
291
|
-
`);return{role:"user",content:u.length?[{type:"text",text:p},...u]:p,timestamp:o}}function yr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Gr(e){return typeof e==="string"?e:""}function Ei(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function PG(e){return yr(e)?e:{}}function Jt(e,o){let a=e.at(-1)?.entry.seq??0,u,p,f;for(let{entry:I}of e){if(I.type==="run"&&I.state==="start")u=I.seq;if(I.seq===o)if(I.type==="user"&&!I.notices)a=(u??I.seq)-1;else p=u;if(I.type==="run"&&I.state==="end"){if(p!==void 0&&u===p)f=I.seq;u=void 0}}let h=e.find((I)=>I.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:I})=>I.type==="run"&&I.state==="end")?.entry.seq??0;let g=e.filter(({entry:I})=>I.seq<=a&&(I.type!=="compaction"||I.through<=a)),x=new Map(g.map(({entry:I},E)=>[I.seq,E+1]));return g.map((I,E)=>{let k=structuredClone(I);if(k.entry.seq=E+1,k.entry.type==="compaction"){let A=k.entry.through,P=g.findLast(({entry:C})=>C.seq<=A);k.entry.through=P?x.get(P.entry.seq)??0:0}return k})}function Xt(e){let o=new Map,a=[];for(let u of e){if(u.type==="assistant"){for(let h of u.parts)if(h.type==="tool_call"&&h.name==="todo")o.set(h.id,h.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let p=o.get(u.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let f=[];for(let h of p.todos){if(!h||typeof h!=="object"||!("content"in h)||typeof h.content!=="string"||!("status"in h)||h.status!=="pending"&&h.status!=="in_progress"&&h.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");f.push({content:h.content,status:h.status})}a=f}return a}import{Buffer as _0}from"buffer";import{createHash as $G}from"crypto";import{isDeepStrictEqual as Ml}from"util";var Ol="@blob:";function ku(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function M0(e,o,a){if(typeof e!=="string"||e.length<256||e.startsWith(Ol))return;let u=_0.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let p=$G("sha256").update(u).digest("hex");return a.put(p,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Ol}${p}`}function O0(e,o){if(typeof e!=="string"||!e.startsWith(Ol))return;let a=o.get(e.slice(Ol.length));if(a===void 0)return;return _0.from(a.buffer,a.byteOffset,a.byteLength).toString("base64")}function _l(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let f=M0(p.data,p.mimeType,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((p)=>{let f=M0(p.data,p.mimeType,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,images:u}}return e}function bi(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let f=O0(p.data,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((p)=>{let f=O0(p.data,o);if(f===void 0)return p;return a=!0,{...p,data:f}});if(!a)return e;return{...e,images:u}}return e}function Yc(e,o){if(!ku(o))return o;if(e.type==="user"){let{merged:a,images:u}=Wc(e.text,e.attachments),p=u.length>0?[{type:"text",text:a},...u]:a,f=Object.keys(o),{role:h,timestamp:g,content:x}=o;if(f.length===3&&h==="user"&&typeof g==="number"&&"content"in o&&Ml(x,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 x=[{type:"text",text:e.output},...(e.images??[]).map((B)=>({type:"image",mimeType:B.mimeType,data:B.data}))];if("details"in o?!Ml(o.details,e.meta):e.meta!==void 0)return o;let{role:E,toolCallId:k,toolName:A,content:P,details:C,isError:M,timestamp:J,...O}=o;if(Ml(g,x))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...O,timestamp:h};if(Array.isArray(g)){let B=e.images??[],L=0,X=!0,te=g.map((j)=>{if(ku(j)&&j.type==="image"){let re=B[L++],ye=Object.keys(j);if(re&&ye.length===3&&j.mimeType===re.mimeType&&j.data===re.data)return{type:"image",mimeType:j.mimeType};X=!1}return j});if(X&&L===B.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:te,...O,timestamp:h}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let p=!1,f=u.map((h,g)=>{let x=e.parts[g];if(ku(h)){if(h.type==="text"&&x?.type==="text"&&h.text===x.text){p=!0;let I={...h};return delete I.text,I}if(h.type==="thinking"&&x?.type==="thinking"&&h.thinking===x.text){p=!0;let I={...h};return delete I.thinking,I}if(h.type==="toolCall"&&x?.type==="tool_call"&&h.id===x.id&&h.name===x.name&&"arguments"in h&&Ml(h.arguments,x.input)){p=!0;let I={...h};return delete I.id,delete I.name,delete I.arguments,I}}return h});if(!p)return o;return{...o,content:f}}return o}function og(e,o){if(!ku(o))return o;if(e.type==="user"){let{role:a,timestamp:u}=o;if(a==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:p,images:f}=Wc(e.text,e.attachments);return{role:"user",content:f.length>0?[{type:"text",text:p},...f]:p,timestamp:u}}return o}if(e.type==="tool_result"){let{role:a,timestamp:u}=o;if(a==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:f,toolName:h,content:g,timestamp:x,...I}=o,E;if(Array.isArray(g)){let k=e.images??[],A=0;E=g.map((P)=>{if(ku(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 E=[{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:E,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...I,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 x=e.parts[g];if(ku(h)){if(h.type==="text"&&!("text"in h)&&x?.type==="text"){p=!0;let{type:I,...E}=h;return{type:I,text:x.text,...E}}if(h.type==="thinking"&&!("thinking"in h)&&x?.type==="thinking"){p=!0;let{type:I,...E}=h;return{type:I,thinking:x.text,...E}}if(h.type==="toolCall"&&!("arguments"in h)&&x?.type==="tool_call"){p=!0;let{type:I,...E}=h;return{type:I,id:x.id,name:x.name,arguments:structuredClone(x.input),...E}}}return h});if(!p)return o;return{...o,content:f}}return o}function L0(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),a=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(x,I,E){o.run(x,I,E)},get(x){return a.get(x)?.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 x of p){let I;try{I=JSON.parse(x.body)}catch{continue}let E=bi(I,u),k=_l(E,u),A=k===I?x.body:JSON.stringify(k),P=x.raw;if(x.raw!==null)try{let C=JSON.parse(x.raw),M=og(E,C),J=Yc(E,M);P=JSON.stringify(J)}catch{P=x.raw}if(A!==x.body)f.run(A,P,x.session_id,x.seq),g++;else if(P!==x.raw)h.run(P,x.session_id,x.seq),g++}})(),g}import{Database as CG}from"bun:sqlite";import{chmodSync as N0,existsSync as vG,mkdirSync as MG}from"fs";import{dirname as OG}from"path";var sg=[`
|
|
292
|
-
CREATE TABLE projects (
|
|
293
|
-
id TEXT PRIMARY KEY,
|
|
294
|
-
name TEXT NOT NULL,
|
|
295
|
-
directory TEXT NOT NULL UNIQUE,
|
|
296
|
-
instructions TEXT NOT NULL DEFAULT '',
|
|
297
|
-
created INTEGER NOT NULL,
|
|
298
|
-
updated INTEGER NOT NULL
|
|
299
|
-
);
|
|
300
|
-
CREATE TABLE automations (
|
|
301
|
-
id TEXT PRIMARY KEY,
|
|
302
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
303
|
-
name TEXT NOT NULL,
|
|
304
|
-
prompt TEXT NOT NULL,
|
|
305
|
-
schedule TEXT NOT NULL,
|
|
306
|
-
model TEXT NOT NULL,
|
|
307
|
-
enabled INTEGER NOT NULL,
|
|
308
|
-
created INTEGER NOT NULL,
|
|
309
|
-
updated INTEGER NOT NULL,
|
|
310
|
-
next_run INTEGER,
|
|
311
|
-
last_run INTEGER,
|
|
312
|
-
last_session_id TEXT
|
|
313
|
-
);
|
|
314
|
-
CREATE TABLE sessions (
|
|
315
|
-
id TEXT PRIMARY KEY,
|
|
316
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
317
|
-
automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
|
|
318
|
-
title TEXT NOT NULL DEFAULT '',
|
|
319
|
-
model TEXT NOT NULL,
|
|
320
|
-
todos TEXT NOT NULL DEFAULT '[]',
|
|
321
|
-
created INTEGER NOT NULL,
|
|
322
|
-
updated INTEGER NOT NULL
|
|
323
|
-
);
|
|
324
|
-
CREATE INDEX sessions_project ON sessions(project_id);
|
|
325
|
-
CREATE TABLE entries (
|
|
326
|
-
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
327
|
-
seq INTEGER NOT NULL,
|
|
328
|
-
time INTEGER NOT NULL,
|
|
329
|
-
body TEXT NOT NULL,
|
|
330
|
-
raw TEXT,
|
|
331
|
-
PRIMARY KEY (session_id, seq)
|
|
332
|
-
) WITHOUT ROWID;
|
|
333
|
-
`,"","","",`
|
|
334
|
-
ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
|
|
335
|
-
ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
|
|
336
|
-
ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
|
|
337
|
-
CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
|
|
338
|
-
ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
|
|
339
|
-
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,
|
|
340
|
-
PRIMARY KEY (namespace, key));
|
|
341
|
-
CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
|
|
342
|
-
PRIMARY KEY (namespace, version));
|
|
343
|
-
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);
|
|
344
|
-
CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
|
|
345
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
346
|
-
END;
|
|
347
|
-
CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
|
|
348
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
|
|
349
|
-
END;
|
|
350
|
-
CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
|
|
351
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
352
|
-
END;
|
|
353
|
-
CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
|
|
354
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
355
|
-
END;
|
|
356
|
-
CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
|
|
357
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
358
|
-
END;
|
|
359
|
-
CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
|
|
360
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
|
|
361
|
-
END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
|
|
362
|
-
WHERE json_extract(body,'$.type')='compaction';
|
|
363
|
-
CREATE TABLE IF NOT EXISTS blobs (
|
|
364
|
-
hash TEXT PRIMARY KEY,
|
|
365
|
-
mime TEXT NOT NULL,
|
|
366
|
-
data BLOB NOT NULL
|
|
367
|
-
) WITHOUT ROWID;
|
|
368
|
-
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 _G=[20,50,100,200,400,800];function LG(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function ig(e){let o=0;while(!0)try{return e()}catch(a){let u=_G[o];if(u===void 0||!LG(a))throw a;o++,Bun.sleepSync(u)}}function q0(e,o){if(e!==":memory:")MG(OG(e),{recursive:!0});let a=new CG(e,{create:!0,strict:!0}),u=(f,h=!0)=>new Proxy(function(...g){return Reflect.apply(f,this,g)},{apply(g,x,I){Xs();let E=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,I):Reflect.apply(g,x,I);return C=!0,M}finally{o.pop();let M=o.at(-1);if(C&&M)M.push(...P);else for(let J of P)if(C)J.commit();else J.rollback()}};return E?ig(A):A()},get(g,x){let I=Reflect.get(f,x);if(["deferred","immediate","exclusive"].includes(String(x))&&typeof I==="function")return u(I,!1);return I}}),p=new Proxy(a,{get(f,h){let g=Reflect.get(f,h,f);if(typeof g!=="function")return g;return(...x)=>{Xs();let k=(h==="run"||h==="exec")&&o.length===0&&!a.inTransaction?ig(()=>Reflect.apply(g,f,x)):Reflect.apply(g,f,x);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(...J)=>{Xs();let L=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!a.inTransaction?ig(()=>Reflect.apply(M,A,J)):Reflect.apply(M,A,J);return L===A?C:L}}})}}});if(e!==":memory:")N0(e,384);if(p.run("PRAGMA journal_mode = WAL"),p.run("PRAGMA synchronous = FULL"),p.run("PRAGMA foreign_keys = ON"),p.run("PRAGMA busy_timeout = 10000"),p.run("PRAGMA mmap_size = 268435456"),NG(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(vG(h))N0(h,384)}return p}function NG(e,o=sg){let{user_version:a}=e.query("PRAGMA user_version").get();if(a>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${a} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=a;u<o.length;u++)e.transaction(()=>{let p=o[u]??"",f=Array.isArray(p)?p:u>=4?qG(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 qG(e){let o=[],a=0,u=0,p=[],f=!1,h=0,g=(x)=>{let I=e.slice(a,x).trim();if(I)o.push(I);a=x+1,p=[],f=!1,h=0};while(u<e.length){let x=e[u];if(x==="'"||x==='"'||x==="`"||x==="["){let I=x==="["?"]":x;u++;while(u<e.length)if(e[u]===I)if(I!=="]"&&e[u+1]===I)u+=2;else break;else u++;u++;continue}if(x==="-"&&e[u+1]==="-"){let I=e.indexOf(`
|
|
369
|
-
`,u);u=I===-1?e.length:I+1;continue}if(x==="/"&&e[u+1]==="*"){let I=e.indexOf("*/",u+2);u=I===-1?e.length:I+2;continue}if(/[A-Za-z_]/.test(x)){let I=u+1;while(I<e.length&&/[A-Za-z0-9_$]/.test(e[I]))I++;let E=e.slice(u,I).toUpperCase();if(p.length<3)p.push(E),f=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(f){if(E==="BEGIN"||E==="CASE"&&h>0)h++;else if(E==="END"&&h>0)h--}u=I;continue}if(x===";"&&h===0)g(u);u++}return g(e.length),o}var Ll=({position:e,closed_at:o,...a})=>({...a,closedAt:o??null}),D0=new Set,Nl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch(a){if(!D0.has(e.id))D0.add(e.id),console.warn(`session ${e.id} metadata is not valid JSON and was ignored:`,a)}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var ql=new Set(["user","run","extension","notice_pending","compaction"]);class Dl{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=q0(e,this.entryTransactions),this.blobs={put:(o,a,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,a,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Ll)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Ll(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Ll(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[a,u]of e.entries())o.run(a,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){let o=this.sessionIDs(e);for(let a of o)this.invalidateEntryCache(a);this.db.transaction(()=>{let a=new Set;for(let u of o)for(let p of this.collectSessionBlobHashes(u))a.add(p);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(a)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(Nl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(Nl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(Nl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,a){this.insertSessionWithRecords(o,Jt(this.records(e),a))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let a=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:p}of o){let{seq:f,time:h,...g}=u,x=g,I=_l(x,this.blobs),E=p===void 0?null:JSON.stringify(Yc(x,p));a.run(e.id,f,h,JSON.stringify(I),E)}})()}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){Xs();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),I=(f&&p?p.beforeEntry(f,a,e,g):void 0)??a,E=JSON.stringify(I),k=f?JSON.parse(E):I,A={...k,seq:g,time:Date.now()},P=_l(k,this.blobs),C=P===k&&!f?E:JSON.stringify(P),M=u===void 0?null:JSON.stringify(Yc(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)},x=this.entryTransactions.at(-1);if(x)x.push(g);else g.commit()}}}setEntryRaw(e,o,a){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let p=bi(JSON.parse(u.body),this.blobs),f=Yc(p,a);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(f),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,a,u=!0){if(a&&a.length===0)return[];let p=a?.every((h)=>ql.has(h))?this.cachedEntries(e):void 0;if(p&&a)return p.filter((g)=>g.seq>o&&a.includes(g.type)).map((g)=>({...u?bi(g,this.blobs):g}));return(a?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...a):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((h)=>({...bi(JSON.parse(h.body),u?this.blobs:void 0),seq:h.seq,time:h.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let a=[...ql],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...a).map((p)=>({...JSON.parse(p.body),seq:p.seq,time:p.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,a){let u=this.smallEntries.get(e);if(!u||!ql.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(a),seq:o.seq,time:o.time})}entriesRange(e,o,a=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,a).map((u)=>({...bi(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let a=this.lastSeq(e),u=(x)=>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,x),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),x=Math.max(1,p-a+1,Math.min(h,g));return this.alignToUser(e,x<g?Math.min(g,this.budgetStart(e,x,u)):x)}budgetStart(e,o,a){let u=this.db.query("SELECT seq, length(body) AS size FROM entries WHERE session_id = ? AND seq >= ? ORDER BY seq DESC").all(e,o),p=0;for(let f of u)if(p+=f.size,p>a)return f.seq+1;return o}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((a)=>{let u=bi(JSON.parse(a.body),this.blobs);return{entry:{...u,seq:a.seq,time:a.time},...a.raw===null?{}:{raw:og(u,JSON.parse(a.raw))}}})}lastEntry(e,o){if(ql.has(o)){let u=this.cachedEntries(e);if(u){let p=u.findLast((f)=>f.type===o);return p?{...bi(p,this.blobs)}:void 0}}let a=this.db.query("SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return a?{...bi(JSON.parse(a.body),this.blobs),seq:a.seq,time:a.time}:void 0}async enqueueNotice(e,o){let a=this.truncationEpoch(e),u=o;if(this.plugins){let p=this.plugins.pin();try{let f=await p.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(f===null)return!1;o={...f,dedupeKey:u.dedupeKey,wake:u.wake&&f.wake,recovery:u.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==a)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((g)=>g.type==="notice_pending"&&g.notice.dedupeKey===o.dedupeKey||g.type==="user"&&g.notices?.some((x)=>x.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,a=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let f of a)if(f.type==="user"&&f.notices)for(let h of f.notices)u.add(h.dedupeKey);else if(f.type==="extension"&&f.namespace===so&&f.kind==="discarded"&&f.payload&&typeof f.payload==="object"&&"dedupeKey"in f.payload&&typeof f.payload.dedupeKey==="string")u.add(f.payload.dedupeKey);let p=[];for(let f of a)if(f.type==="notice_pending"&&!u.has(f.notice.dedupeKey))p.push(f.notice);return p}}function oe(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as DG,readdirSync as U0,statSync as B0}from"fs";import{join as G0}from"path";function Zc(e){try{return B0(e).size}catch{return 0}}function K0(e){try{return Math.round(B0(e).mtimeMs)}catch{return}}function H0(e){let o=0,a=0;try{let u=U0(e,{withFileTypes:!0});for(let p of u){let f=G0(e,p.name);if(p.isDirectory()){let h=H0(f);o+=h.bytes,a+=h.files}else if(p.isFile())o+=Zc(f),a+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:a}}function FG(e){if(!DG(e))return[];try{return U0(e,{withFileTypes:!0}).flatMap((o)=>{let a=G0(jG(e),o.name),u=K0(a);if(o.isDirectory()){let p=H0(a);return[{name:o.name,kind:"directory",bytes:p.bytes,files:p.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Zc(a),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,a)=>a.bytes-o.bytes||o.name.localeCompare(a.name))}catch{return[]}}function jG(e){return e}function Si(e,o){let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return 0;let u=Object.values(a)[0];return typeof u==="number"?u:0}function F0(e,o){try{let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return;let u=Object.values(a)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var UG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},BG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function GG(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 x=h.slice(17),I=x.lastIndexOf("_");if(I>0)h=x.slice(0,I)}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 KG(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,a=e.db.query(`SELECT
|
|
370
|
-
count(*) AS total,
|
|
371
|
-
sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
|
|
372
|
-
sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
|
|
373
|
-
sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
|
|
374
|
-
sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
|
|
375
|
-
FROM sessions`).get(),u=e.db.query(`SELECT
|
|
376
|
-
count(*) AS total,
|
|
377
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
378
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
|
|
379
|
-
min(time) AS oldest_time,
|
|
380
|
-
max(time) AS newest_time
|
|
381
|
-
FROM entries`).get(),f=e.db.query(`SELECT
|
|
382
|
-
coalesce(json_extract(body, '$.type'), 'unknown') AS type,
|
|
383
|
-
count(*) AS count,
|
|
384
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
385
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes
|
|
386
|
-
FROM entries
|
|
387
|
-
GROUP BY type
|
|
388
|
-
ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((x)=>({type:String(x.type||"unknown"),count:Number(x.count)||0,bodyBytes:Number(x.body_bytes)||0,rawBytes:Number(x.raw_bytes)||0})),h=f.find((x)=>x.type==="compaction")?.count??0,g=[];try{let x=new Map,I=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let A of I)x.set(A.namespace,Number(A.max_ver)||0);let E=e.db.query(`SELECT
|
|
389
|
-
namespace,
|
|
390
|
-
count(*) AS keys,
|
|
391
|
-
coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
|
|
392
|
-
FROM plugin_kv
|
|
393
|
-
GROUP BY namespace
|
|
394
|
-
ORDER BY bytes DESC, keys DESC`).all(),k=new Set;for(let A of E){k.add(A.namespace);let P=x.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 x.entries())if(!k.has(A))g.push({namespace:A,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:o,mainSessionCount:Number(a?.main_count)||0,subSessionCount:Number(a?.sub_count)||0,forkedSessionCount:Number(a?.forked_count)||0,automationSessionCount:Number(a?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:h,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:f,pluginNamespaces:g}}function Fl(e,o){let a=Si(e,"page_size"),u=Si(e,"page_count"),p=Si(e,"freelist_count"),f=e.db.query("PRAGMA journal_mode").get(),h=e.db.query("SELECT sqlite_version() AS v").get(),g=Si(e,"synchronous"),x=Si(e,"auto_vacuum"),I=Si(e,"cache_size"),E=I<0?Math.abs(I)*1024:I*a,k=Si(e,"foreign_keys")===1,A=Si(e,"busy_timeout"),P=F0(e,"encoding")??"UTF-8",C=F0(e,"quick_check(1)")??"ok",M=e.path!==":memory:"?K0(e.path):void 0,J=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),O=GG(e),B=FG(o);return{dataDir:o,databasePath:e.path,dataBytes:B.reduce((L,X)=>L+X.bytes,0),database:{size:Zc(e.path),walSize:Zc(`${e.path}-wal`),shmSize:Zc(`${e.path}-shm`),sqliteVersion:h?.v??"unknown",journalMode:f?.journal_mode??"unknown",synchronous:UG[g]??String(g),foreignKeys:k,busyTimeout:A,encoding:P,autoVacuum:BG[x]??String(x),cacheSizeBytes:E,pageSize:a,pageCount:u,freelistCount:p,reclaimableBytes:p*a,schemaVersion:Si(e,"user_version"),...M!==void 0?{lastModified:M}:{},integrity:C},analytics:KG(e),entries:B,tables:J.map(({name:L,sql:X})=>{let te=L.replaceAll('"','""'),j=e.db.query(`SELECT count(*) AS count FROM "${te}"`).get().count,re=e.db.query(`PRAGMA table_info("${te}")`).all().map((Y)=>Y.name),ye=e.db.query(`PRAGMA index_list("${te}")`).all().length,Te=Boolean(X&&/WITHOUT\s+ROWID/i.test(X)),ze=O.get(L);return{name:L,rows:j,...ze?{bytes:ze.bytes,pages:ze.pages}:{},indexes:ye,columns:re,withoutRowid:Te}})}}function j0(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let a=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let f of a)for(let h of f.body.matchAll(/@blob:([0-9a-f]{64})/g)){let g=h[1];if(g)u.add(g)}let p=[];for(let f of o)if(!u.has(f.hash))p.push(f.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let f=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let h of p)f.run(h)})()}catch{return 0}return p.length}function W0(e,o,a){let u=Fl(e,o);if(a.vacuum)L0(e.db),e.invalidateEntryCache(),j0(e),e.db.run("VACUUM");else if(a.checkpoint)j0(e);if(a.checkpoint||a.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Fl(e,o)}}var HG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class jl{plugins;builtinNames;registered=new Map;constructor(e,o){this.plugins=e;this.builtinNames=o}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let o=e.name.trim().toLowerCase();if(!o)throw Error("Tool name cannot be empty");if(HG.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function z0(e,o){let a=En(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:a.length>0?a:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function V0(e,o){let a=e.options.visibleModelProviders?.(),p=(await e.options.models.getAvailable().catch(()=>[])).filter((h)=>!a||a.includes(h.provider)).map((h)=>({...z0(Mt(h),h),available:!0})),f=new Set(p.map((h)=>h.id));for(let h of[o,...e.list(!0,{archive:"all"}).map((g)=>g.model)]){if(f.has(h))continue;let g=Cn(e.options.models,h);if(!g||a&&!a.includes(g.provider))continue;f.add(h),p.push({...z0(h,g),available:!1})}return{models:p}}function J0(e,o){if(typeof o!=="string"||!Cn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as WG,statSync as zG}from"fs";import{basename as VG,resolve as JG}from"path";class ag{runtime;sessions;emit;arm;constructor(e,o,a,u){this.runtime=e;this.sessions=o;this.emit=a;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new m("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=JG(e.directory.trim());if(!WG(o)||!zG(o).isDirectory())throw new t(`${o} is not a directory on the server`);let a=this.runtime.store.projectByDirectory(o);if(a){if(a.closedAt!==null)return this.updateProject(a.id,{closed:!1});return a}let u=Date.now(),p={id:oe("p"),name:e.name?.trim()||VG(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((p)=>p.id)),a=new Set(e);if(!(a.size===e.length&&a.size===o.size&&e.every((p)=>o.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),a=[...this.sessions.values()].filter((p)=>p.projectID===e);if(a.some((p)=>p.status==="busy"))throw new Z("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let p of a)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as gK,readFileSync as yK}from"fs";import{homedir as xK}from"os";import{join as Au}from"path";var rv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),QG={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"]},XG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),mg={'"':['"'],"\u201C":["\u201D",'"']},ug=(e)=>e!==void 0&&/\s/.test(e),nv=(e)=>[...new Set(e)],em=(e)=>[...e].length;var YG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function ZG(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])*YG[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 x=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(a);if(!x)return null;let I=Number(x[1]),E=Number(x[3]);if(E<1||E>12)return null;if(x[4]===void 0){if(x[5]!==void 0)return null;return{start:new Date(I,E-1,1).getTime(),end:new Date(I,E,1).getTime()}}let k=Number(x[4]),A=Number(x[5]??0),P=Number(x[6]??0),C=Number(x[7]??0);if(A>23||P>59||C>59)return null;let M=new Date(I,E-1,k,A,P,C);if(M.getMonth()!==E-1||M.getDate()!==k)return null;if(x[5]!==void 0)return{start:M.getTime()};return{start:M.getTime(),end:new Date(I,E-1,k+1).getTime()}}var eK=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),pg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),lg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function cg(e,o,a,u,p,f){let h=a.trim(),g=(I,E)=>e.diagnostics.push({code:I,message:E,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 x=p?[h]:h.split(",").map((I)=>I.trim()).filter(Boolean);switch(o){case"in":case"project":for(let I of x){let E=I.toLowerCase();if(o==="in"&&E==="this")e.currentSession=!0;else if(o==="in"&&E==="title")e.fields.push("title");else e.projectID.push(I)}return;case"session":for(let I of x)if(I.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(I);return;case"from":case"role":for(let I of x){let E=QG[I.toLowerCase()];if(E)e.fields.push(...E);else g("bad_filter_value",`${o}:${I} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...x);return;case"model":e.model.push(...x);return;case"is":for(let I of x){let E=I.toLowerCase();if(E==="error")e.isError=!u;else if(E==="archived")e.archived=!u;else if(E==="compacted")e.compacted=!u;else g("bad_filter_value",`is:${I} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let I=ZG(h,f);if(!I)return g("bad_filter_value",`${o}:${h} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=pg(e.after,I.start);else if(o==="before")e.before=lg(e.before,I.start);else if(e.after=pg(e.after,I.start),I.end!==void 0)e.before=lg(e.before,I.end)}}}function tK(e,o){let a={},u=(C,M)=>{let J=nv([...C??[],...M]);return J.length?J:void 0},p=u(e?.projectID,o.projectID),f=u(e?.sessionID,o.sessionID),h=u(e?.fields,o.fields),g=u(e?.tools,o.tools),x=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(x)a.model=x;let I=o.isError??e?.isError,E=o.archived??e?.archived,k=o.compacted??e?.compacted;if(I!==void 0)a.isError=I;if(E!==void 0)a.archived=E;if(k!==void 0)a.compacted=k;let A=pg(e?.after,o.after),P=lg(e?.before,o.before);if(A!==void 0)a.after=A;if(P!==void 0)a.before=P;if(A!==void 0&&P!==void 0&&A>=P)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return a}function Q0(e,o){let a=mg[e[o]]??['"'],u="",p=o+1;while(p<e.length){let f=e[p],h=e[p+1];if(f==="\\"&&h!==void 0&&(h==="\\"||h==='"'||h==="\u201C"||h==="\u201D")){u+=h,p+=2;continue}if(a.includes(f))return{text:u,next:p+1,closed:!0};u+=f,p++}return{text:u,next:p,closed:!1}}function X0(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let a=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(a.length!==e.length-1)return;let u=a.toLowerCase();return rv.has(u)?u:void 0}function Y0(e,o,a){let u=e==="word"&&!a&&em(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 rK(e,o){let a=[],u=e.length,p=0;while(p<u){if(ug(e[p])){p++;continue}let f=!1;if(e[p]==="-"){if(p+1>=u||ug(e[p+1])){p++;continue}f=!0,p++}if(mg[e[p]]){let P=Q0(e,p);if(p=P.next,!P.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let C=P.text.trim();if(C)a.push({kind:"term",negated:f,term:Y0("phrase",C,!1)});continue}let h=[],g;while(p<u&&!ug(e[p])){let P=e[p],C=e[p+1];if(P==="\\"&&C!==void 0&&XG.has(C)){h.push({c:C,esc:!0}),p+=2;continue}let M=mg[P]?X0(h):void 0;if(M){let J=Q0(e,p);if(p=J.next,!J.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});g={key:M,value:J.text,quoted:!0};break}h.push({c:P,esc:!1}),p++}if(g){a.push({kind:"filter",negated:f,...g});continue}let x=h.findIndex((P,C)=>C>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),I=x>0?X0(h.slice(0,x+1)):void 0;if(I){a.push({kind:"filter",negated:f,key:I,value:h.slice(x+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 E=h[h.length-1],k=h.length>1&&E!==void 0&&!E.esc&&E.c==="*",A=(k?h.slice(0,-1):h).map((P)=>P.c).join("");if(A)a.push({kind:"term",negated:f,term:Y0("word",A,k)})}return a}var nK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function Z0(e){let o=[];return{rest:e.replace(nK,(u,p,f,h,g)=>{let x=h.toLowerCase();if(!rv.has(x))return u;let I=g.startsWith('"')&&g.length>=2;return o.push({key:x,value:I?g.slice(1,-1).replace(/\\(["\\])/g,"$1"):g,negated:f==="-",quoted:I}),p}).trim(),filters:o}}var ev={n:`
|
|
395
|
-
`,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function oK(e){let o=[...e],a=0,u=(E)=>{let k=o.slice(a,a+E).join("");if(k.length!==E||!/^[0-9a-fA-F]+$/.test(k))return;return a+=E,String.fromCodePoint(Number.parseInt(k,16))},p=()=>{let E=o[a++];if(E===void 0)return{kind:"lit",ch:"\\"};if(E in ev)return{kind:"lit",ch:ev[E]};if("dDwWsS".includes(E))return{kind:"any"};if(E==="b"||E==="B")return{kind:"zero"};if(E>="1"&&E<="9"){while(o[a]!==void 0&&/\d/.test(o[a]))a++;return{kind:"any"}}if(E==="k"||E==="p"||E==="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(E==="c")return a++,{kind:"any"};if(E==="x"){let k=u(2);return k===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:k}}if(E==="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:E}},f=()=>{if(o[a]==="^")a++;while(a<o.length&&o[a]!=="]")a+=o[a]==="\\"?2:1;return a++,{kind:"any"}},h=()=>{let E="capture";if(o[a]==="?"){let A=o[a+1],P=o[a+2];if(A===":")E="plain",a+=2;else if(A==="="||A==="!")E="look",a+=2;else if(A==="<"&&(P==="="||P==="!"))E="look",a+=3;else if(A==="<"){let C=o.indexOf(">",a);a=C<0?o.length:C+1}else{E="opaque";while(a<o.length&&o[a]!==":"&&o[a]!==")")a++;if(o[a]===":")a++}}let k=I();if(o[a]===")")a++;if(E==="look")return{kind:"zero"};return{kind:"group",alts:k,opaque:E==="opaque"}},g=()=>{let E=o[a],k=1,A=!0;if(E==="*"||E==="?")k=0,a++;else if(E==="+")a++;else if(E==="{"){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}},x=()=>{let E=[];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};E.push({atom:A,...g()})}return E};function I(){let E=[x()];while(o[a]==="|")a++,E.push(x());return E}return I()}function tv(e){let o=[],a="",u=()=>{if(a)o.push([a]);a=""},p=(f)=>{for(let h of f){let g=h.atom;if(g.kind==="lit")if(h.min>=1){if(a+=g.ch,h.quantified)u()}else u();else if(g.kind==="group"&&!g.opaque&&h.min>=1)if(g.alts.length===1&&!h.quantified)p(g.alts[0]);else u(),o.push(...ov(g.alts));else u()}};return p(e),u(),o}function ov(e){if(e.length===1)return tv(e[0]);let o=[];for(let a of e){let u=tv(a).filter((p)=>p.length===1).map((p)=>p[0]);if(!u.length)return[];o.push(u.reduce((p,f)=>em(f)>em(p)?f:p))}return[nv(o)]}var sK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function iK(e){return!/^\s*$/.test(e)&&(em(e)>=2||sK.test(e))}function aK(e){let o;try{o=ov(oK(e))}catch{return[]}let a=o.filter((x)=>x.every(iK)),u=a.filter((x)=>x.length===1).map((x)=>x[0]),p=a.filter((x)=>{if(x.length!==1)return!0;let I=x[0];return!u.some((E)=>E!==I&&E.includes(I))}),f=new Set,h=p.filter((x)=>{let I=JSON.stringify(x);if(f.has(I))return!1;return f.add(I),!0}),g=(x)=>Math.min(...x.map(em));return h.sort((x,I)=>g(I)-g(x))}function uK(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 cK(e,o){let a=`m${o?"":"i"}`;try{return new RegExp(e,`${a}u`),{flags:`${a}u`}}catch{}try{return new RegExp(e,a),{flags:a}}catch(u){let p=u instanceof Error?u.message:String(u),f="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))f="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))f="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))f="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))f="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${f}`}}}function Ul(e,o={}){let a=o.now??Date.now(),u=e.q??"",p=eK(),f=p.diagnostics,h,g=[];if(e.mode==="regex"){let M=Z0(u);for(let J of M.filters)cg(p,J.key,J.value,J.negated,J.quoted,a);h=M.rest}else{let M=Z0(u),J=/^\/([\s\S]+)\/$/.exec(M.rest);if(J){for(let O of M.filters)cg(p,O.key,O.value,O.negated,O.quoted,a);h=J[1]}else{g=[{include:[],exclude:[]}];for(let O of rK(u,f)){let B=g[g.length-1];if(O.kind==="or")g.push({include:[],exclude:[]});else if(O.kind==="filter")cg(p,O.key,O.value,O.negated,O.quoted,a);else(O.negated?B.exclude:B.include).push(O.term)}g=g.filter((O)=>O.include.length||O.exclude.length)}}let x=g.flatMap((M)=>[...M.include,...M.exclude]),I=h!==void 0?uK(h):x.some((M)=>/\p{Lu}/u.test(M.text)),E=e.caseSensitive??I,k=e.caseSensitive===void 0&&I,A,P;if(h){let M=cK(h,E);if("message"in M)P={code:"bad_regex",message:M.message};else{let J=aK(h);A={source:h,flags:M.flags,literals:J,deepScan:J.length===0}}}let C=tK(e.filters,p);return{mode:h!==void 0?"regex":"text",branches:g,...A?{regex:A}:{},filters:C,currentSession:p.currentSession,caseSensitive:E,smartCase:k,wholeWord:e.wholeWord??!1,fuzzy:g.some((M)=>M.include.some((J)=>J.fuzzy)),hasPositive:A!==void 0||g.some((M)=>M.include.length>0),hasFilters:Object.keys(C).length>0||p.currentSession,...P?{error:P}:{},diagnostics:f}}var fg={title:8,user:5,assistant:3,error:3,tool_input:2,notice:2,extension:1,thinking:0.5,tool_output:0.5,attachment:0.5},sv=new WeakMap;function iv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,a=sv.get(e);if(a?.version===o)return a.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return sv.set(e,{version:o,terms:u}),u}var dg=32,mK=1024,tm=(e)=>`"${e.replaceAll('"','""')}"`;function pK(e,o){let a=Array.from({length:o.length+1},(u,p)=>p);for(let u=0;u<e.length;u++){let p=[u+1];for(let f=0;f<o.length;f++)p.push(Math.min((p[f]??0)+1,(a[f+1]??0)+1,(a[f]??0)+Number(e[u]!==o[f])));a=p}return a[o.length]??e.length}function hg(e,o){let a=Dt(o.trim());if(!a||a.length>64)return[];let u=iv(e),p=u.filter((g)=>g.t.startsWith(a)).slice(0,8).map((g)=>g.t);if(p.length>=8||a.length<4)return p;let f=a.length>=8?2:1,h=[];for(let g of u){if(Math.abs(g.t.length-a.length)>f)continue;if(pK(a,g.t)<=f)h.push(g.t);if(h.length>=8)break}return[...new Set([...p,...h])].slice(0,8)}function av(e,o){let a=!1,u=[],p=[],f=o.filters,h=(J,O)=>{if(!O?.length)return;p.push(`${J} IN (${O.map(()=>"?").join(",")})`),u.push(...O)};if(h("s.project_id",f.projectID),f.sessionID?.length){p.push(`(${f.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let J of f.sessionID)u.push(J,J)}if(f.archived!==void 0)p.push(`s.archived_at IS ${f.archived?"NOT ":""}NULL`);let g=p.length?p.join(" AND "):"1",x=[...u];if(h("r.kind",f.fields?.map((J)=>$e[J])),h("r.tool",f.tools),f.model?.length){p.push(`(${f.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let J of f.model)u.push(J,J)}if(f.isError!==void 0)p.push("r.err = ?"),u.push(Number(f.isError));if(f.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
|
|
396
|
-
SELECT max(json_extract(body,'$.through')) FROM store.entries
|
|
397
|
-
WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
|
|
398
|
-
),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 I=e.query("SELECT v FROM meta WHERE k='layout'").get(),E=I&&JSON.parse(I.v).msg==="trigram",k=!o.hasPositive||Boolean(o.regex?.deepScan),A=(J)=>{let O=(X)=>{let te=Dt(X);if(!J&&E){if([...te].length<3){let Y=[...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&&Y.length>dg)Y.length=dg,a=!0;if(!Y.length)return tm("__basalt_no_short_match__");return`(${Y.map((me)=>tm(me.term)).join(" OR ")})`}return tm(te)}let j=/^[\p{Script=Latin}\p{N}]+$/u.test(X)?[te]:bs(X),re=j.filter((Y)=>!/^[a-z0-9]{1,2}$/.test(Y)),ye=re.length?re:j;if(!ye.length){k=!0;return}let Te=ye.map((Y,me)=>{let he=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(Y),we=ye.length>2&&me>0&&me<ye.length-1;if(he||we){let ke=e.query("SELECT n FROM term WHERE t=?").get(Y)?.n??0;return{expression:tm(Y),frequency:ke}}let Ee=[Y],ft=0;for(let ke of iv(e)){if(!ke.t.includes(Y))continue;if(ft+=ke.n,ke.t!==Y)Ee.push(ke.t);if(Ee.length>=dg){a=!0;break}}return{expression:`(${Ee.map(tm).join(" OR ")})`,frequency:ft}});return Te.sort((Y,me)=>Y.frequency-me.frequency),`(${Te.slice(0,(Te[0]?.frequency??1/0)<=mK?1:2).map((Y)=>Y.expression).join(" AND ")})`},B=o.regex?o.regex.literals:o.branches.map((X)=>X.include.map((te)=>te.text));if(o.regex){let X=B.map((te)=>te.map(O));if(X.some((te)=>te.some((j)=>!j)))return;return X.map((te)=>`(${te.join(" OR ")})`).join(" AND ")||void 0}let L=B.map((X)=>{let te=X.filter((j)=>!/^[a-z0-9]{1,2}$/i.test(j));return(te.length?te:X).map(O)});if(L.some((X)=>!X.length||X.some((te)=>!te)))return;return L.map((X)=>`(${X.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:x,partial:a,candidateLimit:o.branches.some((J)=>J.include.length>0&&J.include.every((O)=>[...O.text].length<2))?512:void 0}}function uv(e){let o=1/0,a=-1/0;for(let u of e)o=Math.min(o,u.relevance),a=Math.max(a,u.relevance);return e.map((u)=>({...u,relevance:o===a?-1:-(0.5+0.5*(a-u.relevance)/(a-o))}))}function Bl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(fg).map(([a,u])=>`WHEN ${$e[a]} THEN ${u}`).join(" ")} ELSE 1 END) *
|
|
399
|
-
(0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function cv(e,o,a,u){let p=Math.max(0,u-a)/86400000;return Math.max(0.000000001,-e)*fg[o]*(0.3+0.7/(1+p/30))}function gg(e,o){return e.sort((a,u)=>(o==="best"?u.score-a.score:0)||(o==="recent"?u.time-a.time:0)||(a.sessionID<u.sessionID?-1:Number(a.sessionID>u.sessionID))||u.seq-a.seq||a.field.localeCompare(u.field))}var xg=512;function mv(e,o,a){let u=performance.now(),p=o.partial;Ig(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[f,h]of[["fts",o.msg],["fts_out",o.out]]){if(!h)continue;let g=o.candidateLimit??2000,x=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
|
|
400
|
-
ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(h,o.candidateLimit?g+1:g);if(o.candidateLimit&&x.length>g)x.length=g,p=!0;else if(!o.candidateLimit&&x.length===g){let E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
|
|
401
|
-
AND rowid NOT IN (SELECT value FROM json_each(?))`).all(h,JSON.stringify(x.map((k)=>k.doc)));for(let k of E)x.push(k)}let I=uv(x);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
|
|
402
|
-
FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(I))}return a?.("match",performance.now()-u),p}function pv(e,o,a,u,p){let f=performance.now();if(o.candidateLimit){let g=e.query(`
|
|
403
|
-
SELECT r.session_id,r.seq,${Bl(u)} AS score
|
|
404
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
405
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
406
|
-
WHERE ${o.where} LIMIT ${o.candidateLimit+1}
|
|
407
|
-
`).all(...o.bindings);if(g.length>o.candidateLimit)g.length=o.candidateLimit,o.partial=!0;let x=new Map;for(let I of g){let E=a?I.seq:0,k=JSON.stringify([I.session_id,E]),A=x.get(k);if(!A||I.score>A.score)x.set(k,{...I,seq:E})}return p?.("filter",performance.now()-f),[...x.values()].sort((I,E)=>E.score-I.score||(I.session_id<E.session_id?-1:Number(I.session_id>E.session_id))||E.seq-I.seq)}let h=e.query(`
|
|
408
|
-
SELECT r.session_id,${a?"r.seq":"0"} AS seq,max(${Bl(u)}) AS score
|
|
409
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
410
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
411
|
-
WHERE ${o.where}
|
|
412
|
-
GROUP BY r.session_id${a?",r.seq":""}
|
|
413
|
-
ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
|
|
414
|
-
`).all(...o.bindings);return p?.("filter",performance.now()-f),h}var lv=new WeakMap,lK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
|
|
415
|
-
SELECT id,forked_from_id,forked_from_seq FROM store.sessions
|
|
416
|
-
WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
|
|
417
|
-
UNION
|
|
418
|
-
SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
|
|
419
|
-
FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
|
|
420
|
-
WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
|
|
421
|
-
)`;function Ig(e,o){if(!o.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${lK} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let a=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();lv.set(e,new Map(a.map((u)=>[u.ancestor,u.through])))}function yg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
|
|
422
|
-
SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
|
|
423
|
-
JOIN store.sessions ps ON ps.id=pr.session_id
|
|
424
|
-
WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
|
|
425
|
-
AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
|
|
426
|
-
AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
|
|
427
|
-
SELECT 1 FROM store.entries original JOIN store.entries copied
|
|
428
|
-
ON copied.session_id=r.session_id AND copied.seq=r.seq
|
|
429
|
-
WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
|
|
430
|
-
))
|
|
431
|
-
))`}function dv(e,o,a,u,p){let f=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let h=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,g=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
|
|
432
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${h>4000?"INDEXED BY ref_time":""}
|
|
433
|
-
${g} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${yg(o)}
|
|
434
|
-
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 x=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(x===u){let I=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(I)e.query(`
|
|
435
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${g}
|
|
436
|
-
WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
|
|
437
|
-
AND ${o.where} AND ${yg(o)} AND NOT EXISTS (
|
|
438
|
-
SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
|
|
439
|
-
)`).run(I.session_id,I.seq,...o.bindings,...o.forks?o.bindings:[]),x=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-f),x}function fv(e,o,a,u,p,f,h){let g=performance.now(),x=o.group==="none",I=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",E=e.query(`
|
|
440
|
-
SELECT r.session_id,${x?"r.seq":"0"} AS seq,
|
|
441
|
-
max(${Bl(p)}) AS relevance,max(r.time) AS time
|
|
442
|
-
FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
|
|
443
|
-
WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
|
|
444
|
-
GROUP BY r.session_id${x?",r.seq":""}
|
|
445
|
-
ORDER BY ${I},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(f),u,a);return h?.("group",performance.now()-g),E}function hv(e,o,a,u,p,f){let h=performance.now(),g=p?o:{...o,forks:!1},x=e.query(`
|
|
446
|
-
SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
|
|
447
|
-
${g.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
448
|
-
WHERE r.session_id=? ${u?"AND r.seq=?":""}
|
|
449
|
-
AND ${o.where} AND ${yg(g)}
|
|
450
|
-
${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),x}function Eg(e,o,a,u){if(!o.forks)return[];let p=lv.get(e)?.get(a.session_id);if(p===void 0||a.seq>p)return[];return e.query(`
|
|
451
|
-
SELECT DISTINCT r.session_id,s.title,e.body
|
|
452
|
-
FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
|
|
453
|
-
CROSS JOIN ref r ON r.session_id=l.child
|
|
454
|
-
JOIN store.sessions s ON s.id=r.session_id
|
|
455
|
-
LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
|
|
456
|
-
WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(a.session_id,a.doc,a.seq,a.part,...o.bindings).filter((f)=>{if(a.seq===0)return f.title===u;if(!f.body)return!1;let h=JSON.parse(f.body);return it(h,!0).some((g)=>g.part===a.part&&g.kind===So[a.kind]&&g.text===u)}).map((f)=>f.session_id)}function dK(e,o){let a=o?e:Dt(e);if(a.length===e.length)return{normalized:a,starts:void 0,ends:void 0};let u="",p=[],f=[],h=0;for(let g of e){let x=o?g:Dt(g);u+=x;for(let I=0;I<x.length;I++)p.push(h),f.push(h+g.length);h+=g.length}return{normalized:u,starts:p,ends:f}}function Gl(e,o){if(o.regex){let x=new RegExp(o.regex.source,`${o.regex.flags}g`),I=[];for(let E of e.matchAll(x)){if(o.wholeWord&&!gv(e,E.index,E.index+E[0].length))continue;I.push([E.index,E.index+E[0].length])}return I.length?I:void 0}let{normalized:a,starts:u,ends:p}=dK(e,o.caseSensitive),f=(x)=>{let I=o.caseSensitive?x.text:Dt(x.text),E=[],k=a.indexOf(I);while(k>=0&&I){let A=u?u[k]:k,P=p?p[k+I.length-1]:k+I.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(x.text));if(A!==void 0&&P!==void 0&&(!x.prefix||C)&&(!o.wholeWord||gv(e,A,P)))E.push([A,P]);k=a.indexOf(I,k+Math.max(1,I.length))}return E};if(!o.branches.length)return[];let h=[],g=!1;for(let x of o.branches){if(x.exclude.some((E)=>f(E).length))continue;let I=x.include.map(f);if(I.some((E)=>!E.length))continue;g=!0,h.push(...I.flat())}return g?h:void 0}function gv(e,o,a){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(a===e.length||!u.test(e.slice(a,a+1)))}function Kl(e,o){let a=e.split(`
|
|
457
|
-
`),u=new Set,p=0,f=a.map((h,g)=>{let x=p;if(o.some(([I,E])=>I<=x+h.length&&E>=x))for(let I=Math.max(0,g-1);I<=Math.min(a.length-1,g+1);I++)u.add(I);return p+=h.length+1,x});if(!u.size)u.add(0);return[...u].sort((h,g)=>h-g).slice(0,5).map((h)=>{let g=a[h]??"",x=f[h]??0,I=o.filter(([P,C])=>C>x&&P<x+g.length),E=Math.max(0,(I[0]?.[0]??x)-x-100),k=g.slice(E,E+300),A=I.map(([P,C])=>[Math.max(0,P-x-E),Math.min(k.length,C-x-E)]);return{text:k,line:h+1,ranges:A.filter(([P,C])=>P<C)}})}var yv=3;function fK(e){return Boolean(e&&typeof e==="object"&&"score"in e&&typeof e.score==="number"&&Number.isFinite(e.score)&&"sessionID"in e&&typeof e.sessionID==="string"&&e.sessionID.length<=1024&&"seq"in e&&typeof e.seq==="number"&&Number.isSafeInteger(e.seq)&&e.seq>=0)}function xv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function hK(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&&!fK(h))throw Error("invalid best cursor");let g=(x)=>Array.isArray(x)&&x.every((I)=>typeof I==="string"&&I.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&g(p)&&g(f))return{offset:a.offset,key:o,now:a.now,window:u,seen:p,emitted:f,after:h}}}catch{}throw Error("invalid search cursor")}function gn(e,o){let a=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return hK(e.cursor,a)}async function kr(e,o,a){let u="search"in e?e.search:e,p=performance.now(),f=(ke)=>{if(!a.signal?.aborted)a.onEvent(ke)};if(a.signal?.aborted)return;let h=gn(o,a.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let g=Ul(o,{now:h.now});if(g.error){f({type:"error",...g.error});return}if(g.currentSession){if(!a.sessionID){f({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}g.filters.sessionID=[a.sessionID]}if(!o.deep&&g.regex?.deepScan){f({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),a.signal?.aborted)return;let x=performance.now(),I=u.withIndex((ke)=>av(ke,g));if(!I){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()-x);let E=I.partial,k=h.after,A=new Map,P=new Map,C=[],M=!1,J=new Map,O=new WeakMap,B=new Map,L=new Map,{offset:X,window:te}=h,j=[...h.seen],re=[...h.emitted],ye=!1,Te=Math.max(1,Math.min(200,o.limit??30)),ze=Math.min(I.candidateLimit??2000,o.group==="none"?xg:Math.min(2000,Math.max(xg,Te*32))),Y=(ke,Le)=>{let zt=A.get(Le);if(zt)return zt;let gt=ke.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Le);if(gt)A.set(Le,gt);return gt??void 0},me=(ke,Le,zt)=>{if(a.allowedSessionIDs&&!a.allowedSessionIDs.has(Le.session_id))return;if(a.excludeEntry?.sessionID===Le.session_id&&a.excludeEntry.seq===Le.seq)return;let gt=Y(ke,Le.session_id);if(!gt)return;let Ut=So[Le.kind];if(!Ut)return;let xr=gt.title;if(Le.seq!==0){let at=`${Le.session_id}:${Le.seq}`,ur=L.get(at);if(!ur){let un=zt?void 0:ke.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Le.session_id,Le.seq);if(!zt&&!un)return;let sr=zt??JSON.parse(un?.body??"null");ur=it(sr,!0),L.set(at,ur)}let pr=ur.find((un)=>un.part===Le.part&&un.kind===Ut);if(!pr)return;xr=pr.text}let fr=Gl(xr,g);if(!fr)return;let rr=P.get(gt.id);if(rr===void 0)rr=ke.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(gt.id)?.through??0,P.set(gt.id,rr);let st=Le.seq>0&&Le.seq<=rr;if(g.filters.compacted!==void 0&&st!==g.filters.compacted)return;let Ct={sessionID:gt.id,seq:Le.seq,time:Le.time,field:Ut,tool:Le.tool??void 0,isError:Boolean(Le.err),model:Le.model??void 0,snippet:[],score:cv(Le.relevance,Ut,Le.time,h.now),flags:{archived:gt.archived_at!==null,compacted:st,partial:xr.length>ms+hs}};return J.set(Ct,{text:xr,ranges:fr}),C.push(Ct),M=!0,B.set(Ct,{doc:Le.doc,part:Le.part}),Ct},he=(ke)=>{let Le=performance.now(),zt=[...ke].sort((st,Ct)=>st.time-Ct.time||st.sessionID.localeCompare(Ct.sessionID)),gt=[],Ut=new Map;for(let st of zt){let Ct=B.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((Bo)=>Y(Bo,ur?.forked_from_id??""));let un=`${ur?.id??st.sessionID}:${st.seq}:${Ct?.part}:${Ct?.doc}`,sr=Ut.get(un);if(sr){if(sr.sessionID!==st.sessionID)sr.forks=[...new Set([...sr.forks??[],st.sessionID])]}else Ut.set(un,st),gt.push(st)}let xr=[],fr=new Map,rr=new Map;for(let st of gt){let Ct=`${st.sessionID}:${st.seq}`,at=rr.get(Ct);if(!at){rr.set(Ct,st),O.set(st,[st]);continue}let ur=[...O.get(at)??[at],st],pr=st.score>at.score?st:at;if(pr.forks=[...new Set([...at.forks??[],...st.forks??[]])],!pr.forks.length)pr.forks=void 0;pr.flags={archived:at.flags.archived||st.flags.archived,compacted:at.flags.compacted||st.flags.compacted,partial:at.flags.partial||st.flags.partial},rr.set(Ct,pr),O.set(pr,ur)}for(let st of gg([...rr.values()],o.sort??"best")){let Ct=A.get(st.sessionID);if(!Ct)continue;let at=o.group==="none"?void 0:fr.get(Ct.id);if(!at)at={session:{id:Ct.id,title:Ct.title,projectID:Ct.project_id,updated:Ct.updated},hits:[],more:0,...E&&o.group!=="none"?{moreIsLowerBound:!0}:{}},xr.push(at),fr.set(Ct.id,at);if(at.hits.length<yv||o.group==="none")at.hits.push(st);else at.more++}return a.onTiming?.("group",performance.now()-Le),xr},we=(ke)=>{for(let Le of ke)for(let zt of Le.hits){if(a.allowedSessionIDs&&zt.forks)zt.forks=zt.forks.filter((xr)=>a.allowedSessionIDs?.has(xr));let gt=performance.now(),Ut=new Map;for(let xr of O.get(zt)??[zt]){let fr=J.get(xr);if(!fr)continue;for(let rr of Kl(fr.text,fr.ranges)){let st=`${rr.line}:${rr.text}`,Ct=Ut.get(st);if(!Ct)Ut.set(st,rr);else Ct.ranges=[...new Map([...Ct.ranges,...rr.ranges].map((at)=>[at.join(":"),at])).values()]}}zt.snippet=[...Ut.values()],a.onTiming?.("snippet",performance.now()-gt)}},Ee=o.deep||I.scan,ft=(ke,Le)=>{let zt=Y(ke,Le.session_id);if(!zt)return[];let gt=hv(ke,I,Le,o.group==="none",zt.forked_from_id!==null,a.onTiming);if(I.candidateLimit&>.length>I.candidateLimit)gt.length=I.candidateLimit,E=!0;let Ut=C.length,xr=performance.now();for(let fr of gt){if(a.signal?.aborted)break;let rr=me(ke,fr);if(!rr)continue;let st=Eg(ke,I,fr,J.get(rr)?.text??"");if(st.length)rr.forks=st}return a.onTiming?.("body",performance.now()-xr),C.slice(Ut)};if(Ee){E=!1;let ke=[],Le=new Set,zt=u.withIndex((at)=>{Ig(at,I);for(let sr of at.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())A.set(sr.id,sr);let ur=new Set(at.query(`SELECT s.id FROM store.sessions s WHERE ${I.sessionWhere}`).all(...I.sessionBindings).map((sr)=>sr.id)),pr=(sr)=>{if(Le.has(sr.id))return;Le.add(sr.id);let Bo=sr.forked_from_id?A.get(sr.forked_from_id):void 0;if(Bo)pr(Bo);if(ur.has(sr.id))ke.push(sr)};for(let sr of A.values())pr(sr);return(at.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
|
|
458
|
-
SELECT s.id FROM store.sessions s WHERE ${I.sessionWhere}
|
|
459
|
-
)`).get(...I.sessionBindings)?.n??0)+ur.size})??0,gt=0,Ut=0,xr=0;if(g.regex?.deepScan)f({type:"groups",groups:[]});let fr=new Set,rr=new Set,st=new Map,Ct=()=>{let at=he(C),ur=[];for(let pr of at){let un=pr.session.id,sr=o.group==="none"?void 0:st.get(un);if(o.group!=="none"&&rr.has(un)&&!sr)continue;if(!sr){if(rr.add(un),Ut<h.offset){Ut++;continue}if(xr>=Te){ye=!0;break}xr++,X++}if(o.group!=="none"){let Bo=(sr?.count??0)+pr.hits.length+pr.more;pr.hits=pr.hits.slice(0,yv-(sr?.shown??0));let Pu=(sr?.shown??0)+pr.hits.length;pr.more=Bo-Pu,st.set(un,{shown:Pu,count:Bo})}ur.push(pr)}if(ur.length)we(ur),f({type:"groups",groups:ur});C.length=0,J.clear(),B.clear(),L.clear()};for(let at of ke){if(a.signal?.aborted||ye)break;let ur=-1,pr;for(;;){if(a.signal?.aborted||ye)break;let un=u.withIndex((sr)=>{let Bo=sr.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(at.id,Math.max(0,ur));if(ur<0)Bo.unshift({seq:0,time:at.updated,body:null});for(let ta of Bo){if(a.signal?.aborted)break;let $u=ta.body?JSON.parse(ta.body):void 0;if($u?.type==="assistant")pr=$u.model;let bv=$u?it($u,!0):[{part:0,kind:"title",text:at.title}];for(let ts of bv){if(a.signal?.aborted)break;let Ys={session_id:at.id,seq:ta.seq,part:ts.part,doc:Number(BigInt(Bun.hash(ts.text))&0x1fffffffffffffn),kind:$e[ts.kind],tool:ts.tool??null,err:Number(ts.err??!1),model:ts.model??(ts.tool?pr:void 0)??null,time:ta.time,relevance:-1};if(!sr.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
|
|
460
|
-
JOIN store.sessions s ON s.id=r.session_id WHERE ${I.where}`).get(Ys.session_id,Ys.seq,Ys.kind,Ys.tool,Ys.err,Ys.model,Ys.time,...I.bindings))continue;let wi=at,wg=new Set;while(wi.forked_from_id&&wi.forked_from_seq!==null&&ta.seq<=wi.forked_from_seq&&!wg.has(wi.id)){wg.add(wi.id);let Cu=A.get(wi.forked_from_id);if(!Cu)break;wi=Cu}let Tg=`${wi.id}:${ta.seq}:${ts.part}:${Bun.hash(ts.text)}`;if(fr.has(Tg))continue;let Rg=me(sr,Ys,$u);if(Rg){if(fr.add(Tg),I.forks){let Cu=sr.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(at.id,ta.seq,ts.part);if(Cu){let kg=Eg(sr,I,{...Ys,doc:Cu.doc},ts.text);if(kg.length)Rg.forks=kg}}}}}let Pu=Bo.at(-1);if(Pu)ur=Pu.seq;return Bo.length});if(un===void 0){f({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(gt+=un,f({type:"progress",scanned:gt,total:zt}),a.signal?.aborted)return;if(Ct(),!un||ye)break;await Bun.sleep(0)}}}else u.withIndex((ke)=>{if(E=mv(ke,I,a.onTiming)||E,g.regex?g.regex.literals.every((gt)=>gt.some((Ut)=>[...Ut].length<3)):g.branches.some((gt)=>gt.include.length>0&>.include.every((Ut)=>[...Ut.text].length<3)))ke.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let gt=pv(ke,I,o.group==="none",h.now,a.onTiming);if(E||=I.partial,I.candidateLimit&>.length>I.candidateLimit)gt.length=I.candidateLimit,E=!0;let Ut=[];for(let fr of gt){if(a.signal?.aborted)return;let rr=Ut[Te]?.key.score;if(rr!==void 0&&fr.score+0.000000000001<rr)break;let st=C.length,Ct=ft(ke,fr);C.splice(st);let at=gg([...Ct],"best")[0];if(!at)continue;let ur={score:at.score,sessionID:at.sessionID,seq:o.group==="none"?at.seq:0};if(h.after&&xv(ur,h.after)<=0)continue;if(Ut.push({key:ur,hits:Ct}),Ut.sort((pr,un)=>xv(pr.key,un.key)),Ut.length>Te+1)Ut.length=Te+1}ye=Ut.length>Te;let xr=Ut.slice(0,Te);for(let fr of xr)C.push(...fr.hits);k=xr.at(-1)?.key;return}let zt=0;for(;;){if(a.signal?.aborted)return;let gt=dv(ke,I,te,ze,a.onTiming),Ut=I.candidateLimit!==void 0&&te+gt>=I.candidateLimit;E||=Ut;let xr=fv(ke,o,X,Te-zt+1,h.now,j,a.onTiming);ye=xr.length>Te-zt;let fr=xr.slice(0,Te-zt);if(!fr.length){if(gt<ze||Ut){ye=!1;break}te+=gt,X=0,j=[...new Set([...j,...re])],re=[];continue}for(let rr of fr)if(X++,ft(ke,rr).length){if(zt++,o.group!=="none")re.push(rr.session_id)}if(zt>=Te){ye||=!Ut&>>=ze;break}if(!ye){if(gt<ze||Ut)break;te+=gt,X=0,j=[...new Set([...j,...re])],re=[]}}});if(a.signal?.aborted)return;if(!Ee){let ke=he(C);we(ke),f({type:"groups",groups:ke})}if(!M){let ke=g.branches.flatMap((Le)=>Le.include).find((Le)=>Le.fuzzy)?.text;if(ke)f({type:"suggest",terms:u.withIndex((Le)=>hg(Le,ke))??[]})}f({type:"done",cursor:ye?Buffer.from(JSON.stringify(!Ee&&o.sort!=="recent"?{...h,offset:0,window:0,seen:[],emitted:[],after:k}:{...h,offset:X,window:te,seen:j,emitted:re})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:E,index:u.status()})}function no(e,o){return e.withIndex((a)=>hg(a,o))??[]}function Iv(e,o,a){let u=T({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(y([s({maxLength:2000}),Un()])),scope:n(y([i("session"),i("project"),i("all"),i(""),Un()])),fields:n(y([H(vr({type:"string",enum:[...wn]})),Un()])),tool:n(y([s(),Un()])),isError:n(y([D(),Un()])),after:n(y([s(),ne(),Un()])),before:n(y([s(),ne(),Un()])),limit:n(y([S(),Un()])),session:n(y([s(),Un()])),seq:n(y([S(),Un()])),around:n(y([S(),Un()]))}),async execute(p,f,h){let g={query:f.query?.trim(),scope:f.scope||void 0,fields:f.fields?.length?f.fields:void 0,tool:f.tool?.trim(),isError:f.isError??void 0,after:f.after??void 0,before:f.before??void 0,limit:f.limit||void 0,session:f.session?.trim(),seq:f.seq??void 0,around:f.around??void 0},x=g.query?.trim(),I=!x&&Boolean(g.session?.trim())&&Number.isSafeInteger(g.seq)&&(g.seq??0)>=1;if(I&&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 E=e.sessions().find((Y)=>Y.id===a);if(!E)throw Error("History session is unavailable");let k=(Y)=>{if(Y===void 0||Y===0||typeof Y==="string"&&!Y.trim())return;if(typeof Y==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(Y))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let me=typeof Y==="number"?Y:Date.parse(Y);if(!Number.isFinite(me)||Math.abs(me)>8640000000000000){if(typeof Y==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return me},A=I?void 0:k(g.after),P=I?void 0:k(g.before);if(A!==void 0&&P!==void 0&&A>=P)throw Error("after must precede before");let C=[];if(I&&g.session&&g.seq!==void 0){if(!e.sessions().find((Ee)=>Ee.id===g.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let me=g.around??3,he=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-me),g.seq+me);if(!he.some((Ee)=>Ee.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:he.map((Ee)=>{let ft={...JSON.parse(Ee.body),seq:Ee.seq,time:Ee.time};return`[seq=${Ee.seq}]
|
|
461
|
-
${it(ft,!0).map((ke)=>`${ke.kind}: ${ke.kind==="error"?ke.text.replace(/^(?:error:\s*)+/i,""):ke.text}`).join(`
|
|
462
|
-
`).slice(0,4000)}`}).join(`
|
|
463
|
-
|
|
464
|
-
`)||"No history content"}],details:{groups:C,count:he.length}}}if(!x)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let M=Number.isFinite(g.limit)?Math.max(1,Math.min(30,Math.trunc(g.limit??10))):10,J=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(a)?.seq,O=new Set(e.sessions().filter((Y)=>{if(g.scope==="session")return Y.id===a;if((g.scope??"project")==="project"&&E.projectID)return Y.projectID===E.projectID;return!0}).map((Y)=>Y.id)),B={q:x,filters:{tools:g.tool?.trim()?[g.tool.trim()]:void 0,isError:g.isError,after:A,before:P},group:"none",limit:M},L=Ul(B);if(L.error)throw Error(L.error.message);if(g.fields?.length){if(L.filters.fields=g.fields.filter((Y)=>(Y in $e)),L.filters.fields.length!==g.fields.length)throw Error("Unknown search field")}if((g.scope??"project")==="session")L.filters.sessionID=[a];else if((g.scope??"project")==="project"&&E.projectID)L.filters.projectID=[E.projectID];let X=o.status().state!=="ready",te=!1;if(!X){let Y=L.filters.fields??Object.keys($e).filter((we)=>(we in $e)),me=Y.filter((we)=>we!=="title"),he=me.length?[me]:[];if(Y.includes("title"))he.push(["title"]);for(let we of he){if(C.length>=M&&te)break;if(await kr(o,{...B,limit:Math.max(1,M-C.length),filters:{...L.filters,fields:we}},{signal:h,excludeEntry:J===void 0?void 0:{sessionID:a,seq:J},sessionID:a,allowedSessionIDs:O,onEvent(Ee){if(Ee.type==="groups")C.push(...Ee.groups);if(Ee.type==="done")te||=Boolean(Ee.cursor)||Ee.partial;if(Ee.type==="error")if(Ee.code==="unavailable")X=!0;else throw Error(Ee.message)}}),X)break}}let j=[],re=0;if(X){C.length=0;let Y=performance.now()+2000;e:for(let me of e.sessions()){if(!O.has(me.id))continue;if(L.filters.sessionID&&!L.filters.sessionID.includes(me.id))continue;if(L.filters.projectID&&(!me.projectID||!L.filters.projectID.includes(me.projectID)))continue;let he=Number.MAX_SAFE_INTEGER,we=!0;for(;;){let Ee=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(me.id,he);if(we)Ee.push({body:"null",seq:0,time:me.updated}),we=!1;if(!Ee.length)break;for(let ft of Ee){if(ft.seq>0)he=ft.seq;if(h?.aborted)throw Error("History search cancelled");if(re>=1e4||performance.now()>Y){te=!0;break e}if(re++,me.id===a&&ft.seq===J)continue;if(L.filters.after!==void 0&&ft.time<L.filters.after||L.filters.before!==void 0&&ft.time>=L.filters.before)continue;let ke=ft.seq===0?[{part:0,kind:"title",text:me.title,tool:void 0,err:!1}]:it(JSON.parse(ft.body),!0);for(let Le of ke){if(L.filters.fields&&!L.filters.fields.includes(Le.kind))continue;if(L.filters.tools&&(!Le.tool||!L.filters.tools.includes(Le.tool)))continue;if(L.filters.isError!==void 0&&Boolean(Le.err)!==L.filters.isError)continue;let zt=Gl(Le.text,L);if(!zt)continue;if(C.length>=M&&Le.kind!=="title"){te=!0;break e}(Le.kind==="title"?j:C).push({session:{id:me.id,title:me.title,projectID:me.projectID,updated:me.updated},more:0,hits:[{sessionID:me.id,seq:ft.seq,time:ft.time,field:Le.kind,tool:Le.tool,isError:Boolean(Le.err),snippet:Kl(Le.text,zt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(h?.aborted)throw Error("History search cancelled");if(j.length>Math.max(0,M-C.length))te=!0;if(C.push(...j.slice(0,M)),C.sort((Y,me)=>Number(Y.hits[0]?.field==="title")-Number(me.hits[0]?.field==="title")),C.length>M)te=!0;C.length=Math.min(C.length,M);let ye=new Map;for(let Y of C)for(let me of Y.hits){let he=ye.get(Y.session.id)??[];he.push(`[${Y.session.title.replace(/[\r\n]/g," ")} \xB7 ${me.sessionID} \xB7 ${me.seq} \xB7 ${new Date(me.time).toISOString()} \xB7 ${me.field}${me.tool?`/${me.tool}`:""}]
|
|
465
|
-
${me.snippet.slice(0,3).map((we)=>{let Ee=we.text;for(let[ft,ke]of[...we.ranges].sort((Le,zt)=>zt[0]-Le[0]))Ee=`${Ee.slice(0,ft)}\u3010${Ee.slice(ft,ke)}\u3011${Ee.slice(ke)}`;return Ee}).join(`
|
|
466
|
-
`)}`),ye.set(Y.session.id,he)}let Te="";if(X){if(Te="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")Te="\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((Y,me)=>Y+me.hits.length,0);return{content:[{type:"text",text:[Te,X&&te?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${re} \u6761`:"",[...ye.values()].map((Y)=>Y.join(`
|
|
467
|
-
|
|
468
|
-
`)).join(`
|
|
469
|
-
|
|
470
|
-
`),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(`
|
|
471
|
-
`)}],details:{groups:C,count:ze}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var bg="basalt.git-snapshot";async function Ev(e,o,a){let u=o.projectID?e.store.project(o.projectID):void 0,p=u?.directory??process.cwd(),h=o.info().kind==="sub",g=()=>h||o.entries(0,["compaction"],!1).length>0,x=e.options.tools??Qt({directory:u?.directory,records:()=>o.records,history:(k)=>e.resolveHistory(o.id,k),onTodos:(k)=>o.setTodos(k),shell:()=>e.serverShell(),hasCompacted:g});if(e.options.tools===void 0)x.push(Iv(e.store,e.search,o.id));let I;if(u&&e.options.systemPrompt===void 0){let k=o.entries(0,["compaction"],!1).length,A=e.store.db,P=A.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(bg,o.id),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"))I=C.summary;else if(I=await g0(u.directory,a),!e.isClosed&&!a?.aborted)A.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(bg,o.id,JSON.stringify({compactions:k,summary:I})),A.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(bg)}let E=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:h0({project:u,globalInstructions:EK(e),git:I,shell:e.serverShell()});return{systemPrompt:E.map((k)=>k.detail).join(""),systemParts:E,tools:[...x,...e.tools.snapshot()],cwd:p}}var IK=[Au(".basalt","AGENTS.md"),Au(".agents","AGENTS.md"),Au(".opencode","AGENTS.md"),Au(".claude","CLAUDE.md"),Au(".codex","AGENTS.md")];function EK(e){let o=e.options.homeDir??xK();for(let a of IK){let u=Au(o,a);try{if(gK(u))return yK(u,"utf8")}catch{return}}return}class Zo{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new ag(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Dl(Sg(e.dataDir,"basalt.db")),this.plugins=new jh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new jl(this.plugins,()=>this.builtinToolNames()),this.search=new Uh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let a=this.open(o,"restore");this.sessions.set(o.id,a),this.restored.add(a)}}static async create(e){let o=new Zo(e);try{return await o.initialize(),o}catch(a){throw await o.close(),a}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Sg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Sg(e.directory,".basalt","plugins"))],this.options.plugins?.builtins===!1?[]:this.options.builtinPlugins??[]).then(async()=>{for(let e of this.restored)this.plugins.notify("session.open",e);if(this.initialized=!0,await this.plugins.idle(),!this.closed)for(let e of this.restored)e.recover();this.restored.clear()}),this.initialization}get ready(){return this.initialize()}builtinToolNames(){if(this.options.tools)return this.options.tools.map((e)=>e.name);return["read","write","edit","grep","glob","bash","todo","history_grep","history_list"]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}models(){return V0(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Fl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>W0(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((a)=>e||a.info().parentID===null).map((a)=>a.info()).filter((a)=>{let u=o.archive??"active";return u==="all"||a.archivedAt!==null===(u==="archived")}).sort((a,u)=>u.updated-a.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let a=this.get(e);if(!a)throw new t("History session is unavailable");return a.resolveHistory(o)}openStoredSession(e,o="restore"){let a=this.open(e,o);return this.sessions.set(e.id,a),this.emit({type:"session",session:a.info()}),a}create(e={}){let o=e.model??this.defaultModel;if(!Cn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let a=Date.now(),u={id:oe("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:a,updated:a,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let p=this.open(u);return this.sessions.set(u.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,o,a){o={...o,archivedAt:null},this.store.copySession(e,o,a);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new m("no such session");let a=o.info(),u=a.projectID?this.store.project(a.projectID):void 0;return P0(a,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let a=[o.model,e.model,this.defaultModel].find((h)=>h!==void 0&&Cn(this.options.models,h)!==void 0),u=a?Cn(this.options.models,a):void 0;if(!a||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:oe("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:a,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?v0(e.records,u):e.records);let f=this.open(p);return this.sessions.set(p.id,f),this.emit({type:"session",session:f.info()}),f}truncateHistory(e,o){let a=this.sessions.get(e.id);if(!a)throw new m("no such session");if(a.assertWritable(),a.status==="busy")throw new Z;if(!Cn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);a.close();for(let h of this.sessions.values()){if(h.info().parentID!==e.id)continue;if(h.status==="busy")h.abort()}this.store.truncateSession(e,o);let u=[],p=this.store.lastEntry(e.id,"run");if(p?.type==="run"&&p.state==="start"){let h=this.store.records(e.id,p.seq).filter((g)=>g.raw);for(let g of Ge(h)){if(g.result)continue;let{body:x,raw:I}=ll(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,x,I))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let f=this.open(e,"replay");this.sessions.set(e.id,f),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let h of u)this.emit({type:"entry",sessionID:e.id,entry:h});return f}setArchived(e,o){let a=this.sessions.get(e);if(!a)throw new m("no such session");let u=a.info().parentID;if(!o&&u&&this.sessions.get(u)?.isArchived)throw new t("\u8BF7\u5148\u6062\u590D\u6240\u5C5E\u7236\u4F1A\u8BDD");let p=this.sessionTree(a);if(p.some((f)=>f.status==="busy"))throw new Z;if(a.isArchived===o)return a.info();this.store.setArchived(p.map((f)=>f.id),o?Date.now():null);for(let f of p)f.refreshArchive();for(let f of p)f.archiveChanged();return a.info()}sessionTree(e){let o=[e];for(let a=0;a<o.length;a++){let u=o[a];if(!u)continue;for(let p of this.sessions.values())if(p.info().parentID===u.id)o.push(p)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new m("no such session");if(o.status==="busy")throw new Z;let a=this.sessionTree(o).slice(1),u=()=>{for(let p of a)p.close(),this.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!a.length)return u();o.close();for(let p of a)p.close(),p.abort();return Promise.allSettled(a.map((p)=>p.idle())).then((p)=>{u();let f=p.find((h)=>h.status==="rejected");if(f)throw f.reason})}open(e,o="create"){let a=e.id,u=new vl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p,f)=>Ev(this,p,f)},{entry:(p)=>{this.emit({type:"entry",sessionID:a,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:a,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:a})},draft:(p)=>this.emit({type:"draft",sessionID:a,parts:p}),changed:()=>{let p=this.sessions.get(a);if(p)this.emit({type:"session",session:p.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new ea(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!oi.includes(e))throw new t(`Invalid shell type; must be ${oi.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return J0(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(a){console.error("runtime listener failed",a)}}}export{Ke,ct,$i,N,Ko,Jn,Qo,qe,H,n,l,Q,vr,D,S,i,ne,s,y,Qe,Oe,Jo,ve,T,Mt,tt,R,Ge,F,G,Lt,rt,Xo,wt,_r,Xn,dn,Ot,Yn,Ce,de,mn,hn,Ar,Zn,eo,fn,Wi,jt,As,Pe,c,le,nt,Er,Tr,Pr,to,Nt,Yo,Vt,Kt,Qt,ot,Z,ro,Jt,Xt,oe,gn,kr,no,Zo};
|