@bkm016/basalt 0.1.12 → 0.1.13
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-7jezts2n.js → chunk-06s9pr82.js} +2 -2
- package/{chunk-jpnf71q7.js → chunk-095adzn5.js} +2 -2
- package/chunk-0a7ft50x.js +18 -0
- package/{chunk-vjne04dp.js → chunk-0nedq669.js} +4 -4
- package/chunk-0x9netvr.js +5 -0
- package/{chunk-9as0p561.js → chunk-15ve3nmv.js} +11 -11
- package/chunk-1dbfmejf.js +2 -0
- package/{chunk-hbnmymaq.js → chunk-1q6e3mj7.js} +2 -2
- package/{chunk-85v69h91.js → chunk-22az84sh.js} +2 -2
- package/{chunk-w0rr66z7.js → chunk-2q56egb8.js} +1 -1
- package/{chunk-fhxy6y34.js → chunk-2tf7qfbx.js} +2 -2
- package/{chunk-nw1xpt3s.js → chunk-2zbj8ny6.js} +2 -2
- package/chunk-302n9g7p.js +2 -0
- package/{chunk-bk4rpnm8.js → chunk-37ndxehw.js} +2 -2
- package/chunk-41das1ty.js +2 -0
- package/{chunk-6mges89p.js → chunk-44a7f5ta.js} +5 -5
- package/{chunk-jn5pqy5v.js → chunk-46vy2m29.js} +1 -1
- package/{chunk-1zj3zvw5.js → chunk-4k9t9jvx.js} +4 -4
- package/{chunk-eq4wqxzt.js → chunk-4rnmxtpx.js} +2 -2
- package/{chunk-1xfv4bd7.js → chunk-4w9zqv0k.js} +1 -1
- package/chunk-6d9r9p91.js +20 -0
- package/chunk-6f4ht2hw.js +2 -0
- package/{chunk-jj4hqbrx.js → chunk-6sea12mw.js} +3 -3
- package/chunk-74wwdx3y.js +3 -0
- package/{chunk-w6f2r052.js → chunk-77c2cqp2.js} +1 -1
- package/chunk-7chv3knf.js +2 -0
- package/chunk-86yr2c0r.js +3 -0
- package/{chunk-6sz5q3df.js → chunk-8cgz8xv7.js} +2 -2
- package/{chunk-tvm4zmgj.js → chunk-959z9efn.js} +2 -2
- package/{chunk-eyrtbbdd.js → chunk-9e8vhzy7.js} +1 -1
- package/chunk-b516bp7n.js +3 -0
- package/chunk-bja7p3em.js +25 -0
- package/chunk-bng72094.js +2 -0
- package/{chunk-ksk49hv0.js → chunk-bp61xdsc.js} +1 -1
- package/chunk-bq54argx.js +2 -0
- package/chunk-ct77cdg7.js +2 -0
- package/{chunk-02d3x4mj.js → chunk-dk6fgprw.js} +3 -3
- package/chunk-drett6hb.js +2 -0
- package/{chunk-4gtgqcct.js → chunk-edbq461k.js} +3 -3
- package/{chunk-p2pmdbt2.js → chunk-f0h2bv11.js} +12 -12
- package/{chunk-8mezk0cb.js → chunk-g2etemv5.js} +2 -2
- package/{chunk-n0ybj4h9.js → chunk-g5p9mj1r.js} +2 -2
- package/{chunk-fy82qxa1.js → chunk-gpnqmtbk.js} +1 -1
- package/{chunk-kpe7pnhy.js → chunk-h9zxqeqr.js} +4 -4
- package/{chunk-qfcr5g35.js → chunk-jjtt9aq8.js} +3 -3
- package/{chunk-5wnmbc1b.js → chunk-kbpbrr11.js} +2 -2
- package/chunk-m71pj3g1.js +2 -0
- package/chunk-mdkfm1ak.js +7 -0
- package/chunk-mf04h0yy.js +7 -0
- package/chunk-n22vd4at.js +2 -0
- package/{chunk-v7wcchy2.js → chunk-nbjnwd54.js} +1 -1
- package/{chunk-1h34mzh7.js → chunk-pryvvs96.js} +22 -22
- package/{chunk-2kxnw7vs.js → chunk-r1jn77q6.js} +2 -2
- package/{chunk-ypqjfv3a.js → chunk-rn3jwyh1.js} +2 -2
- package/chunk-sgrrxsnz.js +482 -0
- package/chunk-sgz87ht5.js +2 -0
- package/{chunk-stj493dn.js → chunk-snz19yc2.js} +2 -2
- package/{chunk-qs8zzg50.js → chunk-szj85dqe.js} +2 -2
- package/{chunk-nrsd810j.js → chunk-tfhp09nj.js} +2 -2
- package/{chunk-hc300148.js → chunk-tfhze1vq.js} +2 -2
- package/{chunk-01nve4qy.js → chunk-tjg0gcks.js} +1 -1
- package/{chunk-cbgpymt4.js → chunk-tnj2kqb8.js} +1 -1
- package/{chunk-3pf1d62g.js → chunk-vqm94hz2.js} +2 -2
- package/{chunk-82v8jh1h.js → chunk-xvm0y99b.js} +2 -2
- package/{chunk-rwks9zaw.js → chunk-y23dpz5e.js} +2 -2
- package/{chunk-ejjem0tc.js → chunk-y4pvhes1.js} +6 -6
- package/{chunk-bwawt15q.js → chunk-ydzag81d.js} +2 -2
- package/chunk-ymg7mtcx.js +3 -0
- package/chunk-yy1f9jxc.js +4044 -0
- package/{chunk-ntks40jd.js → chunk-z0c8ek0j.js} +5 -5
- package/chunk-zk91579b.js +3 -0
- package/{chunk-0fc9apfn.js → chunk-zx75vnw8.js} +18 -18
- package/compiled.js +85 -12
- package/package.json +1 -1
- package/ui-test-worker.js +53 -53
- package/web/{chunk-aeymdtm1.js → chunk-0jbf73pr.js} +3 -3
- package/web/{chunk-7vgh17es.js → chunk-0rhx7qb8.js} +1 -1
- package/web/{chunk-7adsmqv6.js → chunk-0rvwj2wh.js} +2 -2
- package/web/chunk-12qf1r6m.js +1 -0
- package/web/{chunk-dndd757x.js → chunk-14vmr99v.js} +3 -3
- package/web/{chunk-4f6a8dsk.js → chunk-16jc5m0f.js} +1 -1
- package/web/{chunk-bra33pt0.js → chunk-1m6fx2h7.js} +2 -2
- package/web/{chunk-hva7xyne.js → chunk-1xm9x7d6.js} +1 -1
- package/web/{chunk-8539865x.js → chunk-20jxvmbw.js} +1 -1
- package/web/chunk-2n5xbnrt.js +1 -0
- package/web/{chunk-bygwbpvq.js → chunk-2sef2wft.js} +2 -2
- package/web/{chunk-w9gnqkez.js → chunk-2x7vmhm0.js} +2 -2
- package/web/{chunk-19zd0tye.js → chunk-2y1avvqj.js} +8 -8
- package/web/chunk-36s08nye.js +1 -0
- package/web/chunk-3ctmehg4.js +1 -0
- package/web/{chunk-ncfzmf2g.js → chunk-3jjksgze.js} +1 -1
- package/web/{chunk-aebrw6cv.js → chunk-3p9w8sg5.js} +2 -2
- package/web/{chunk-sdr5wa4z.js → chunk-3wpxymxa.js} +3 -3
- package/web/{chunk-v34mr9ky.js → chunk-4py9sndw.js} +3 -3
- package/web/chunk-4swea9sn.js +1 -0
- package/web/chunk-4zz5a483.js +1 -0
- package/web/{chunk-3rkkp6ed.js → chunk-5cwxhhae.js} +5 -5
- package/web/{chunk-d57fm7k0.js → chunk-5ym5ffd5.js} +2 -2
- package/web/{chunk-gten0rpx.js → chunk-6e87m0nm.js} +2 -2
- package/web/{chunk-b99k8q22.js → chunk-6rsr2cyw.js} +8 -8
- package/web/chunk-6y55gk1n.js +1 -0
- package/web/chunk-7aep7k4v.js +1 -0
- package/web/{chunk-yf8ykk4v.js → chunk-8j4tzff5.js} +3 -3
- package/web/{chunk-ny436sqg.js → chunk-8tgavnwx.js} +1 -1
- package/web/{chunk-xvfeq8v2.js → chunk-97t3ngqf.js} +12 -12
- package/web/{chunk-gkmaryr4.js → chunk-980zhtht.js} +1 -1
- package/web/chunk-9k7fkx80.js +1 -0
- package/web/{chunk-hxbfkdjd.js → chunk-9wz8jne3.js} +1 -1
- package/web/chunk-a00vg115.js +1 -0
- package/web/chunk-a4gbxnm3.js +1 -0
- package/web/{chunk-6f2sz84q.js → chunk-a6g3nqp0.js} +1 -1
- package/web/{chunk-n9v14vyd.js → chunk-a9er7a7c.js} +22 -22
- package/web/chunk-atppv8fk.js +1 -0
- package/web/{chunk-xbyrgyy0.js → chunk-awkdw9rw.js} +2 -2
- package/web/{chunk-hqxc9m07.js → chunk-b4gcpsbg.js} +10 -10
- package/web/{chunk-qdd3bx8q.js → chunk-b9jry5a3.js} +1 -1
- package/web/{chunk-jyf7a7yp.js → chunk-ba9qy65y.js} +1 -1
- package/web/chunk-bq6mep6p.js +2 -0
- package/web/chunk-bwy3e58v.js +1 -0
- package/web/{chunk-aa46mrgh.js → chunk-c57f714b.js} +2 -2
- package/web/{chunk-b5zf1hs3.js → chunk-c6m4vfn5.js} +101 -101
- package/web/{chunk-5np514v5.js → chunk-cr04125j.js} +4 -4
- package/web/{chunk-ym7kv2hs.js → chunk-cr05dttm.js} +1 -1
- package/web/{chunk-2cyzaqjy.js → chunk-ct7z7bea.js} +3 -3
- package/web/{chunk-y2rzeb4v.js → chunk-ct90yf8z.js} +2 -2
- package/web/{chunk-yjs6jmdb.js → chunk-ddg8rz82.js} +3 -3
- package/web/{chunk-8cnjd0f2.js → chunk-dmha2y9c.js} +18 -18
- package/web/{chunk-jeafmjsm.js → chunk-e57h40qa.js} +6 -6
- package/web/chunk-eeesa5q1.js +1 -0
- package/web/{chunk-4wwd3pfz.js → chunk-eqndhs21.js} +2 -2
- package/web/{chunk-td83xf12.js → chunk-eqxy6535.js} +2 -2
- package/web/{chunk-wvrs986a.js → chunk-et1rsgmp.js} +3 -3
- package/web/chunk-f7jpakwh.js +1 -0
- package/web/{chunk-v1hfbjz9.js → chunk-fnvgdvrg.js} +4 -4
- package/web/chunk-fp62avjh.js +1 -0
- package/web/{chunk-6jb2zyp6.js → chunk-frnh4zqf.js} +2 -2
- package/web/chunk-g0be12na.js +1 -0
- package/web/{chunk-60mym60n.js → chunk-g7hqafb8.js} +1 -1
- package/web/{chunk-wqzbxzk3.js → chunk-ga07tv37.js} +1 -1
- package/web/chunk-gr163fex.js +1 -0
- package/web/chunk-gxtz10wf.js +1 -0
- package/web/{chunk-pjpre6de.js → chunk-h1k2kqbs.js} +6 -6
- package/web/{chunk-7tkgbbf9.js → chunk-h6k1x096.js} +2 -2
- package/web/{chunk-885kpj14.js → chunk-jccz14ye.js} +2 -2
- package/web/{chunk-d73zkc4q.js → chunk-jh33m2mq.js} +2 -2
- package/web/{chunk-g488hxx0.js → chunk-jh3k7xex.js} +3 -3
- package/web/{chunk-3qxxrwsp.js → chunk-jpem3qvs.js} +10 -10
- package/web/chunk-k9qnvx86.js +2 -0
- package/web/chunk-kcnj0gan.js +1 -0
- package/web/{chunk-2jfesv7m.js → chunk-ke8dffnk.js} +2 -2
- package/web/chunk-kpp5xqsb.js +1 -0
- package/web/chunk-m33yted6.js +1 -0
- package/web/chunk-me5jqqn6.js +1 -0
- package/web/{chunk-7v85yvb2.js → chunk-mkxeenph.js} +1 -1
- package/web/{chunk-mxkbmgcv.js → chunk-mnf4ngj9.js} +1 -1
- package/web/{chunk-30aeb767.js → chunk-mykrm8ba.js} +2 -2
- package/web/chunk-mzqqwbmr.js +1 -0
- package/web/chunk-npyrdsf8.css +1 -0
- package/web/chunk-p6e2vr51.js +34 -0
- package/web/{chunk-3n9ypydh.js → chunk-p7pa02k9.js} +2 -2
- package/web/chunk-q34as3v6.js +1 -0
- package/web/{chunk-7ksg3ccg.js → chunk-q4vy3dkk.js} +2 -2
- package/web/chunk-q6c8p73w.js +1 -0
- package/web/{chunk-h754ntg7.js → chunk-qb8mbptk.js} +1 -1
- package/web/{chunk-g4zm0crw.js → chunk-qbmtah1x.js} +1 -1
- package/web/chunk-qn93we3a.js +1 -0
- package/web/{chunk-c3fty2c2.js → chunk-qq06x2ce.js} +7 -7
- package/web/{chunk-fj753yzt.js → chunk-qq6m2my8.js} +2 -2
- package/web/chunk-r1f1egve.js +1 -0
- package/web/{chunk-80z8s8zb.js → chunk-s935z8er.js} +1 -1
- package/web/{chunk-3psgr0q8.js → chunk-sq75q603.js} +20 -20
- package/web/{chunk-qp3tjhaq.js → chunk-ss96cz1f.js} +1 -1
- package/web/{chunk-hn8m1vsg.js → chunk-t82sngk9.js} +7 -7
- package/web/chunk-tt9410zw.js +8 -0
- package/web/{chunk-act3rr85.js → chunk-v4cqc9f9.js} +1 -1
- package/web/chunk-ve8gy05p.js +1142 -0
- package/web/chunk-vg1ebkce.js +1 -0
- package/web/{chunk-k4dnjf8n.js → chunk-vk7ch6fh.js} +3 -3
- package/web/chunk-vnt34mkb.js +1 -0
- package/web/{chunk-kerfb21g.js → chunk-w28dn4dw.js} +1 -1
- package/web/{chunk-rdr6wt22.js → chunk-w4tfad6c.js} +4 -4
- package/web/{chunk-81s15c2e.js → chunk-wpxtkxjt.js} +2 -2
- package/web/{chunk-h24ybwp6.js → chunk-xcyqd7cn.js} +1 -1
- package/web/chunk-xe121vg7.js +1 -0
- package/web/chunk-xh4xn1az.js +1 -0
- package/web/{chunk-e94pd9rr.js → chunk-xk1vkcj4.js} +9 -9
- package/web/chunk-xrk5ewsn.js +1 -0
- package/web/{chunk-5g8md2wg.js → chunk-xvm66b7v.js} +4 -4
- package/web/{chunk-q1zxvjhs.js → chunk-xxmaqj1m.js} +2 -2
- package/web/chunk-xzwxcxb4.js +1 -0
- package/web/{chunk-xpecre7w.js → chunk-y9waq403.js} +4 -4
- package/web/chunk-ydhnkws0.js +1 -0
- package/web/{chunk-ar6jnhm5.js → chunk-yn4t5s9r.js} +1 -1
- package/web/chunk-ys2tns0p.js +1 -0
- package/web/chunk-zb61mf0a.js +1 -0
- package/web/{chunk-r6kk4vp1.js → chunk-ze6azq7z.js} +4 -4
- package/web/chunk-zh7193nq.js +2 -0
- package/web/chunk-zqcg6frm.js +1 -0
- package/web/{chunk-enwfd8d5.js → chunk-zxrbbbtp.js} +2 -2
- package/web/index.html +1 -1
- package/worker.js +1 -1
- package/chunk-2fyjph3f.js +0 -2
- package/chunk-37zystxb.js +0 -25
- package/chunk-3k627vf2.js +0 -3
- package/chunk-7er5pz7s.js +0 -479
- package/chunk-7g5smgjj.js +0 -2
- package/chunk-7m3jagqn.js +0 -2
- package/chunk-9c4gdg1q.js +0 -3
- package/chunk-b2bxqeb4.js +0 -2
- package/chunk-bpw6q7g0.js +0 -3
- package/chunk-cdw03j4t.js +0 -20
- package/chunk-ch1r3ted.js +0 -2
- package/chunk-cmwdjes8.js +0 -18
- package/chunk-db7ws33a.js +0 -7
- package/chunk-e1x629v0.js +0 -5
- package/chunk-j64dc767.js +0 -3
- package/chunk-m4bg1apa.js +0 -7
- package/chunk-nhm9z3d8.js +0 -2
- package/chunk-pnspvnyd.js +0 -2
- package/chunk-qnkrrwmg.js +0 -2
- package/chunk-r4gm8ngh.js +0 -2
- package/chunk-rks90mh1.js +0 -2
- package/chunk-t7te60m7.js +0 -2
- package/chunk-tv52xajf.js +0 -2
- package/chunk-wqqjzsjt.js +0 -3983
- package/chunk-xef4642x.js +0 -3
- package/web/chunk-04drx71p.js +0 -1
- package/web/chunk-0mdf1qja.js +0 -1
- package/web/chunk-0rdgt4jb.css +0 -1
- package/web/chunk-1m0kp0g3.js +0 -8
- package/web/chunk-3j2tcphs.js +0 -1
- package/web/chunk-3k9h7a73.js +0 -1142
- package/web/chunk-3m1bb2fw.js +0 -1
- package/web/chunk-55nvm2mj.js +0 -1
- package/web/chunk-5dkqfnh7.js +0 -2
- package/web/chunk-7ky5nrrr.js +0 -1
- package/web/chunk-8sdjgv3k.js +0 -1
- package/web/chunk-9bxtzwtc.js +0 -1
- package/web/chunk-9jy8nc4r.js +0 -1
- package/web/chunk-bcjgzwef.js +0 -1
- package/web/chunk-cxpnj495.js +0 -2
- package/web/chunk-d1btrqmw.js +0 -1
- package/web/chunk-d94t9z70.js +0 -1
- package/web/chunk-e68jw0bg.js +0 -1
- package/web/chunk-fr4fft89.js +0 -1
- package/web/chunk-gckmcef6.js +0 -1
- package/web/chunk-gnb09wmx.js +0 -1
- package/web/chunk-hrgqc1vr.js +0 -1
- package/web/chunk-j9c8fa82.js +0 -1
- package/web/chunk-jz5mmp64.js +0 -1
- package/web/chunk-kxeaj44h.js +0 -1
- package/web/chunk-m0136xav.js +0 -1
- package/web/chunk-m1rdyvb5.js +0 -1
- package/web/chunk-m6vyvgm5.js +0 -1
- package/web/chunk-my0ec787.js +0 -1
- package/web/chunk-nkpdd9hw.js +0 -1
- package/web/chunk-pbp1p5ex.js +0 -1
- package/web/chunk-ph75hddv.js +0 -1
- package/web/chunk-phdfyqaa.js +0 -1
- package/web/chunk-phxa5krt.js +0 -1
- package/web/chunk-r4zbw4zj.js +0 -2
- package/web/chunk-ry4ycah9.js +0 -1
- package/web/chunk-sqm16fat.js +0 -1
- package/web/chunk-tj1fn8v2.js +0 -1
- package/web/chunk-v0wtk059.js +0 -34
- package/web/chunk-v1qt3gq4.js +0 -1
- package/web/chunk-v854w9yn.js +0 -1
- package/web/chunk-ve56gxq0.js +0 -1
- package/web/chunk-w573ym17.js +0 -1
- package/web/chunk-x0mjydtp.js +0 -1
- package/web/chunk-zhybh04p.js +0 -1
package/chunk-7er5pz7s.js
DELETED
|
@@ -1,479 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$o,Qr,W}from"./chunk-4gtgqcct.js";import{Si,He,Et,wi,Yn,vi,_i,Ai,Tt,Pi,Ne,eo,Ke}from"./chunk-6mges89p.js";import{Gn,Ci,Kr}from"./chunk-n0ybj4h9.js";import{Ie,te,Ho,zn,M,jn,ht,Me,dr,U,Le,Vn,ft,me,$t,oe,Xr,qo,Oe,re,nt,Kn,Go,be,Ii,yi,Se,Qn,d,Mi,Q,Jr,G,Li}from"./chunk-ejjem0tc.js";import{Xn,L,Jn,Ve,bi,Ht,ke}from"./chunk-qs8zzg50.js";import{r,Xe}from"./chunk-bwawt15q.js";var zg=r(function(dH,Wg){var Dv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],ed=/[\n\r\u2028\u2029]/,qv=/[\s#!"$&'():;<=>@\\^`|~]/g;Wg.exports=function(o){var i=!1;return o.map(function(u){if(i&&typeof u==="string"&&ed.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(ed.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(qv,"\\$&")}if("op"in u&&typeof u.op==="string"){if(Dv.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(ed.test(u.comment))throw TypeError("`comment` must not contain line terminators");return i=!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 ty=r(function(fH,ey){var Yg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Vg=new RegExp("^"+Yg+"$"),Jg="|&;()<> \\t",Fv="'([^']*?)'",Zg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Qg="\\$'"+Zg+"'",Yc=new RegExp("\\$'"+Zg+"(?:(')|\\\\?$)","g"),jv="abeEfnrtv",Uv=`\x07\b\x1B\x1B\f
|
|
3
|
-
\r \v`,Bv=/^#$/,td="'",Xg='"',bu="$",Ui="",Gv=4294967296;for(Xc=0;Xc<4;Xc++)Ui+=(Gv*Math.random()).toString(16);var Xc,Kv=new RegExp("^"+Ui);function Hv(e,o){var i=o.lastIndex,u=[],p;while(p=o.exec(e))if(u[u.length]=p,o.lastIndex===p.index)o.lastIndex+=1;return o.lastIndex=i,u}function Wv(e,o,i){var u=typeof e==="function"?e(i):e[i];if(typeof u>"u"&&i!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+Ui+JSON.stringify(u)+Ui;return o+u}var zv=/\\([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 Vv(e,o){var i=o.charAt(0);if(i==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="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(i>="0"&&i<="7")return String.fromCharCode(parseInt(o,8)&255);var g=jv.indexOf(o);return g<0?o:Uv.charAt(g)}function Jv(e){return e.replace(zv,Vv).split("\x00")[0]}function Qv(e,o){return Yc.lastIndex=o,!!Yc.exec(e)[1]}function Xv(e,o,i){if(!i)i={};var u=i.escape||"\\",p=i.splitUnquoted===!0?`
|
|
4
|
-
`:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",g="(\\"+u+`['"$\\`+u+Jg+"]|\\$\\$|\\$(?!"+Qg.slice(2)+`)|[^\\s'"$`+Jg+"])+",y='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',b=new RegExp(["("+Yg+")","("+Qg+"|"+g+"|"+y+"|"+Fv+")+"].join("|"),"g"),E=Hv(e,b);if(E.length===0)return[];if(!o)o={};var S=!1;return E.map(function(w){var R=w[0];if(!R||S)return;if(Vg.test(R))return{op:R};var k=!1,A=!1,C="",q=[],X=!1,j=null,V=!1,J;function ee(){J+=1;var de,qe,xt=R.charAt(J);if(xt==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var Je=1;de=J;while(Je>0&&de<R.length){if(R.charAt(de)==="{"&&R.charAt(de-1)==="$")Je+=1;else if(R.charAt(de)==="}")Je-=1;de+=1}if(Je!==0)throw Error("Bad substitution: "+R.slice(J));de-=1,qe=R.slice(J,de),J=de}else if(/[*@#?$!-]/.test(xt))qe=xt;else{var Yt=R.slice(J);if(de=Yt.match(/[^\w\d_]/),!de)qe=Yt,J=R.length;else qe=Yt.slice(0,de.index),J+=de.index-1}return Wv(o,"",qe)}function pe(){if(j===null)return;if(j===0){if(C!=="")q[q.length]=C,C=""}else{q[q.length]=C,C="";for(var de=1;de<j;de+=1)q[q.length]=""}j=null}for(J=0;J<R.length;J++){var H=R.charAt(J);if(p&&H!==bu)pe();if(V=V||!k&&(H==="*"||H==="?"),A)C+=H,A=!1;else if(k)if(H===k)k=!1;else if(k==td)C+=H;else if(H===u)if(J+=1,H=R.charAt(J),H===Xg||H===u||H===bu)C+=H;else C+=u+H;else if(H===bu)C+=ee();else C+=H;else if(H===Xg||H===td)k=H,X=!0;else if(Vg.test(H))return{op:R};else if(Bv.test(H)){S=!0;var le={comment:e.slice(w.index+J+1)};if(C.length)return[C,le];return[le]}else if(H===u)A=!0;else if(H===bu&&R.charAt(J+1)===td&&Qv(R,J))pe(),X=!0,C+=Jv(R.slice(J+2,Yc.lastIndex-1)),J=Yc.lastIndex-1;else if(H===bu){var he=ee();if(!p)C+=he;else for(var $e=0;$e<he.length;$e+=1){var Ee=he.charAt($e);if(p.indexOf(Ee)<0)pe(),C+=Ee;else if(j===null)j=Ee===" "||Ee==="\t"||Ee===`
|
|
5
|
-
`?0:1;else if(Ee!==" "&&Ee!=="\t"&&Ee!==`
|
|
6
|
-
`)j+=1}}else C+=H}if(V)return{op:"glob",pattern:C};if(p){if(j!==null&&j>0){q[q.length]=C,C="";for(var ae=1;ae<j;ae+=1)q[q.length]=""}if(C!==""||X&&q.length===0)q[q.length]=C;return q}return C}).reduce(function(w,R){if(typeof R>"u")return w;return[].concat(R).forEach(function(k){w[w.length]=k}),w},[])}ey.exports=function(o,i,u){var p=Xv(o,i,u);if(typeof i!=="function")return p;return p.reduce(function(g,y){if(typeof y==="object")return g[g.length]=y,g;var b=y.split(RegExp("("+Ui+".*?"+Ui+")","g"));if(b.length===1)return g[g.length]=b[0],g;return b.filter(Boolean).forEach(function(E){g[g.length]=Kv.test(E)?JSON.parse(E.split(Ui)[1]):E}),g},[])}});var Wo={};Xe(Wo,{ArchivedError:()=>dt,BadRequestError:()=>t,BusyError:()=>se,DEFAULT_TIMEOUT:()=>c$,FoldingPolicy:()=>Uc,MAX_ATTACHMENTS:()=>ut,MAX_TIMEOUT:()=>m$,MAX_TOOL_OUTPUT:()=>Pe,NotFoundError:()=>f,PluginCheckError:()=>pt,ProcessRegistry:()=>Wt,Type:()=>io,aliased:()=>_e,budget:()=>jc,calls:()=>To,clip:()=>ie,clipSaved:()=>rt,dataDir:()=>et,definePlugin:()=>P,estimateMessage:()=>F,estimateTokens:()=>D,estimateTools:()=>Di,extensionTranscript:()=>wl,findWindowsBash:()=>tr,foldPoint:()=>qc,foldedThrough:()=>xa,formatLines:()=>Bc,gateShellCommand:()=>je,groupRuns:()=>Ks,historyTodos:()=>ir,newID:()=>ne,normalizeRunRecords:()=>qh,processRegistry:()=>sr,project:()=>Re,projectUserText:()=>qi,releaseProcesses:()=>lr,requestBody:()=>I,resolveShellCommand:()=>Ea,retainProcesses:()=>ar,routeParam:()=>v,runShell:()=>rr,sealPoint:()=>iu,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>xl,text:()=>c,timerClock:()=>Ce,tool:()=>x,toolSession:()=>z,transcript:()=>cu,usable:()=>ue,userTranscript:()=>Sl,validAttachment:()=>Ft,workState:()=>bl});var Uo={};Xe(Uo,{AssistantMessageEventStream:()=>L,AssistantMessageFrameEncoder:()=>RR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>CR,EventStream:()=>Xn,InMemoryCredentialStore:()=>zn,InMemoryModelsStore:()=>jn,ModelsError:()=>M,StringEnum:()=>Hq,Type:()=>io,appendAssistantMessageDiagnostic:()=>ke,calculateCost:()=>Q,clampThinkingLevel:()=>G,cleanupSessionResources:()=>Ci,collapseSystemMessages:()=>Oe,contentText:()=>dr,createAssistantMessageDiagnostic:()=>Ht,createAssistantMessageEventStream:()=>Jn,createFauxCore:()=>TR,createInitialSystemMessage:()=>Vn,createModels:()=>Qn,createProvider:()=>d,declarationsEqual:()=>Kn,defaultProviderAuthContext:()=>Ho,envApiKeyAuth:()=>h,extractDiagnosticError:()=>bi,fauxAssistantMessage:()=>No,fauxProvider:()=>Do,fauxText:()=>On,fauxThinking:()=>Oo,fauxToolCall:()=>Tq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>Xr,getCurrentSystemPrompt:()=>qo,getCurrentTools:()=>oe,getDeclaredTools:()=>be,getInitialSystemMessage:()=>me,getModelType:()=>ht,getOverflowPatterns:()=>jq,getSupportedThinkingLevels:()=>Jr,getSystemMessageText:()=>U,getToolStateChanges:()=>Go,hasApi:()=>Mi,hasNonAdditiveToolChanges:()=>yi,hasToolRedefinitions:()=>Ii,isContextOverflow:()=>ca,isModelType:()=>Me,isRecoverableLength:()=>Fq,isRetryableAssistantError:()=>$R,lazyApi:()=>te,lazyOAuth:()=>ce,lazyStream:()=>Ie,modelsAreEqual:()=>Li,normalizeContext:()=>ft,parseJsonWithRepair:()=>Qr,parseStreamingJson:()=>W,reduceAssistantMessageFrames:()=>Nq,registerSessionResourceCleanup:()=>Gn,renderSystemMessageUpdate:()=>Le,repairJson:()=>$o,resolveTranscript:()=>re,resolveTranscriptTools:()=>Se,retryAssistantCall:()=>Kq,retryDelayMs:()=>PR,toToolDeclaration:()=>nt,uuidv7:()=>Kr,validateToolArguments:()=>nu,validateToolCall:()=>$U,withoutInitialSystemMessage:()=>$t});var K={};Xe(K,{Counted:()=>pd,Entries:()=>ln,EntriesRegExp:()=>ld,Every:()=>an,EveryAll:()=>An,GraphemeCount:()=>AM,HasPropertyKey:()=>fe,IsArray:()=>Ge,IsBigInt:()=>Nr,IsBoolean:()=>pn,IsClassInstance:()=>xy,IsConstructor:()=>cd,IsDeepEqual:()=>Ta,IsEqual:()=>O,IsFunction:()=>ms,IsGreaterEqualThan:()=>Sa,IsGreaterThan:()=>Ki,IsInteger:()=>rm,IsLessEqualThan:()=>ps,IsLessThan:()=>Su,IsMaxLength:()=>Iy,IsMinLength:()=>by,IsMultipleOf:()=>yy,IsNull:()=>ho,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>Vo,IsString:()=>gt,IsSymbol:()=>md,IsUndefined:()=>Ut,IsUnsafePropertyKey:()=>wu,IsValueLike:()=>Hi,Keys:()=>we,ShiftLeft:()=>It,Some:()=>wa,SomeAll:()=>Ey,Symbols:()=>Sy,Values:()=>dd});var Yi={};Xe(Yi,{Hash:()=>bd,HashCode:()=>rx});var _t={};Xe(_t,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Te,ExtendsUnion:()=>Bd,IsExtendsFalse:()=>Hd,IsExtendsTrue:()=>Kd,IsExtendsTrueLike:()=>so,IsExtendsUnion:()=>Gd,Match:()=>br});var io={};Xe(io,{Any:()=>Ca,Array:()=>B,BigInt:()=>Pu,Boolean:()=>N,Call:()=>hw,Capitalize:()=>Sw,Codec:()=>lm,Conditional:()=>$w,Constructor:()=>ds,ConstructorParameters:()=>Mw,Cyclic:()=>gs,Decode:()=>ix,DecodeBuilder:()=>pm,Dependent:()=>Xi,Encode:()=>ax,EncodeBuilder:()=>mm,Enum:()=>Wy,Evaluate:()=>Rn,Exclude:()=>_w,Extends:()=>Tn,ExtendsResult:()=>_t,Extract:()=>Nw,Function:()=>fs,Generic:()=>Ys,Identifier:()=>$u,Immutable:()=>ux,Index:()=>jw,Infer:()=>Cu,InstanceType:()=>pT,Instantiate:()=>Co,Integer:()=>_,Interface:()=>QS,Intersect:()=>Pn,IsAny:()=>vr,IsArray:()=>wt,IsBigInt:()=>mo,IsBoolean:()=>Wn,IsCall:()=>ja,IsCodec:()=>Hn,IsConstructor:()=>en,IsCyclic:()=>Qt,IsDependent:()=>Dr,IsEnum:()=>on,IsEnumValue:()=>Hy,IsFunction:()=>tn,IsGeneric:()=>Aa,IsIdentifier:()=>lx,IsImmutable:()=>Zi,IsInfer:()=>nn,IsInteger:()=>fn,IsIntersect:()=>ze,IsKind:()=>Ae,IsLiteral:()=>yt,IsNever:()=>co,IsNull:()=>xs,IsNumber:()=>kr,IsObject:()=>Qe,IsOptional:()=>cn,IsParameter:()=>gx,IsReadonly:()=>ta,IsRecord:()=>Gt,IsRef:()=>qt,IsRefine:()=>dm,IsRest:()=>oi,IsSchema:()=>Pr,IsString:()=>sn,IsSymbol:()=>Is,IsTemplateLiteral:()=>ur,IsThis:()=>Am,IsTuple:()=>mt,IsUndefined:()=>Zo,IsUnion:()=>xe,IsUnknown:()=>rn,IsUnsafe:()=>cm,IsVoid:()=>po,KeyOf:()=>dT,Literal:()=>s,Lowercase:()=>ww,Mapped:()=>ET,Module:()=>cR,Never:()=>zt,NonNullable:()=>RT,Null:()=>$n,Number:()=>Y,Object:()=>l,Omit:()=>AT,Optional:()=>n,Parameter:()=>ra,Parameters:()=>$T,Partial:()=>MT,Pick:()=>FT,Readonly:()=>cx,ReadonlyObject:()=>Ef,ReadonlyType:()=>BT,Record:()=>bs,RecordKey:()=>ni,RecordPattern:()=>hn,RecordValue:()=>fr,Ref:()=>un,Refine:()=>mx,Required:()=>nR,Rest:()=>oa,ReturnType:()=>sR,Script:()=>dR,String:()=>a,Symbol:()=>va,TemplateLiteral:()=>yS,This:()=>km,Tuple:()=>Ur,Uncapitalize:()=>Tw,Undefined:()=>_a,Union:()=>m,Unknown:()=>Rr,Unsafe:()=>qr,Uppercase:()=>Rw,Void:()=>Cm,With:()=>lp});var eu={};Xe(eu,{Clear:()=>Wk,Entries:()=>YF,Get:()=>t1,Has:()=>e1,IsDate:()=>Xa,IsDateTime:()=>Ep,IsDuration:()=>Sp,IsEmail:()=>wp,IsHostname:()=>vp,IsIPv4:()=>_p,IsIPv6:()=>Lp,IsIdnEmail:()=>Mp,IsIdnHostname:()=>Op,IsIri:()=>Dp,IsIriReference:()=>Np,IsJsonPointer:()=>Fp,IsJsonPointerUriFragment:()=>qp,IsRegex:()=>jp,IsRelativeJsonPointer:()=>Up,IsTime:()=>Ya,IsUri:()=>Kp,IsUriReference:()=>Bp,IsUriTemplate:()=>Gp,IsUrl:()=>Hp,IsUuid:()=>Wp,Reset:()=>Vk,Set:()=>ZF,Test:()=>zk});var Iu="shell-guard",qg=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class f extends Error{constructor(e){super(e);this.name="NotFoundError"}}function Fg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function jg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function Ov(e,o){if(e===o)return 0;let i=Array.from({length:o.length+1},(u,p)=>p);for(let u=1;u<=e.length;u++){let p=i[0]??0;i[0]=u;for(let g=1;g<=o.length;g++){let y=i[g]??0;i[g]=Math.min((i[g]??0)+1,(i[g-1]??0)+1,p+(e[u-1]===o[g-1]?0:1)),p=y}}return i[o.length]??0}function Ug(e,o){let i=Fg(e);if(!i)return[];let u=jg(e),p=[];for(let g of o){let y=g.id.indexOf("/"),b=y>=0?g.id.slice(y+1):"",S=[g.id,g.name,b].filter(Boolean).map((R)=>({compact:Fg(R),tokens:jg(R)})).filter((R)=>R.compact.length>0),w=Number.POSITIVE_INFINITY;for(let R of S)if(R.compact===i)w=Math.min(w,0);else if(R.compact.includes(i)||i.includes(R.compact)){let k=Math.abs(R.compact.length-i.length);w=Math.min(w,1+k/Math.max(R.compact.length,i.length))}else{let k=0;for(let A of u)if(R.tokens.has(A))k++;if(k>0){let A=k/Math.max(u.size,R.tokens.size);w=Math.min(w,10+(1-A)*10)}}if(!Number.isFinite(w)&&i.length>=4){let R=Math.max(2,Math.floor(i.length*0.34));for(let k of S){if(Math.abs(k.compact.length-i.length)>R)continue;let A=Ov(i,k.compact);if(A<=R)w=Math.min(w,100+A)}}if(Number.isFinite(w))p.push({model:g,score:w})}return p.sort((g,y)=>g.score-y.score||g.model.id.localeCompare(y.model.id))}function _v(e,o,i=5){return Ug(e,o).slice(0,Math.max(1,i)).map((u)=>u.model)}function Fr(e,o){let i=Ug(e,o);if(i.length===0)return;let u=i.filter((g)=>g.score===0);if(u.length===1&&u[0])return u[0].model;if(u.length>1)return;let p=i.filter((g)=>g.score<10);if(p.length===1&&p[0])return p[0].model;return}function Wr(e,o){let i=[...o].sort((y,b)=>y.id.localeCompare(b.id)),u=(y)=>y.name===y.id?y.id:`${y.id} (${y.name})`,p=_v(e,i).map(u),g=i.map(u);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${g.length}): ${g.length>0?g.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
|
|
7
|
-
`)}var li=["openai-completions","openai-responses","anthropic-messages"];function $r(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let o=e.trim().toLowerCase();if(!o)return;let i=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let u=Number.parseFloat(i[1]??"");if(!Number.isFinite(u)||u<=0)return;let p=i[2];if(p==="k")return Math.round(u*1000);if(p==="m")return Math.round(u*1e6);return Math.round(u)}function Ql(e){if(e>=1e6&&e%1e5===0)return`${e/1e6}m`;if(e>=1000&&e%1000===0)return`${e/1000}k`;return String(e)}function Lv(e){let o=e.trim();if(!o)return;let i,u,p=o,g=p.match(/\s*\[(.*?)\]\s*$/);if(g&&g.index!==void 0){p=p.slice(0,g.index).trim();let w=g[1]?.split(",").map((k)=>k.trim()).filter(Boolean)??[],R=0;for(let k of w){let A=k.indexOf("=");if(A>=0){let C=k.slice(0,A).trim().toLowerCase(),q=$r(k.slice(A+1).trim());if(C==="context"||C==="ctx"||C==="window"||C==="contextwindow")i=q;else if(C==="max"||C==="output"||C==="maxtokens")u=q}else{let C=$r(k);if(R===0)i=C;else if(R===1)u=C;R++}}}else{let w=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(w?.[1]&&w[2])p=w[1].trim(),i=$r(w[2])}let y=p.indexOf("="),b,E;if(y<0)b=p.trim(),E=b;else b=p.slice(0,y).trim(),E=p.slice(y+1).trim()||b;if(!b)return;let S={id:b,name:E};if(i!==void 0)S.contextWindow=i;if(u!==void 0)S.maxTokens=u;return S}function er(e){return e.split(/\r?\n/).map(Lv).filter((o)=>o!==void 0)}function Io(e){return e.map((o)=>{let i=o.name===o.id?o.id:`${o.id}=${o.name}`,u=[];if(o.contextWindow!==void 0)u.push(Ql(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)u.push(Ql(o.maxTokens));else u.push(`max=${Ql(o.maxTokens)}`);return u.length>0?`${i} [${u.join(", ")}]`:i}).join(`
|
|
8
|
-
`)}var Bg=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var Ln=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],ci=["text","regex"],ui=["best","recent"],pi=["session","none"];var Bt=4,di="https://basalt.work",mi=["https://basalt.work","https://www.basalt.work"],Hr=7420;var Xl=["auto","bash","powershell","cmd"];var Mo=["active","archived","all"],hi="session.group";var Gg=["pending","in_progress","completed"],Yl="basalt-session",Qc=["image","text","path"];var Kg=["defer","always"],Hg=["global","tool","source"];function Be(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let i=o;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:o};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:o}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:o};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:o}}}function fi(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var ut=10,Nv=15000000;function Ft(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"&&Qc.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=Nv}function Zl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}var Yv=zg(),rd=ty();import{AsyncLocalStorage as Zv}from"async_hooks";var z=new Zv;var eM=3,ry=160,tM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),rM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),sy=/^[A-Za-z_][A-Za-z0-9_]*=/,nM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),oM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),sM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,iM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),aM=new Set(["command","builtin","nohup","time","exec"]),uM=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir","-S","--split-string"]],["nice",["-n","--adjustment"]]]);function Zc(e){return{out:e.out,depth:e.depth+1}}function ny(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function nd(e,o,i,u){let p=e.length,g=0,y=o;while(y<p){let b=e.charAt(y);if(b==="\\"){y+=2;continue}if(b==="'"||b==='"'||b==="`"){let E=y+1;while(E<p){let S=e.charAt(E);if(S==="\\"){E+=2;continue}if(S===b)break;E++}y=E+1;continue}if(b===i)g++;else if(b===u){if(g--,g===0)return y+1}y++}return p}function cM(e){let o={text:"",subs:[],heredocs:[]},i=[],u=[],p=e.length,g=0,y=0,b=null,E=(S)=>{if(e.charAt(S)==="`"){let A=S+1;while(A<p){let C=e.charAt(A);if(C==="\\"){A+=2;continue}if(C==="`")break;A++}return o.subs.push(e.slice(S+1,A)),A<p?A+1:p}if(e.charAt(S+1)==="("){let A=nd(e,S+1,"(",")");if(e.charAt(S+2)==="(")return i.push(e.slice(S,A)),A;return o.subs.push(e.slice(S+2,A-1)),A}let R=nd(e,S+1,"{","}"),k=e.slice(S+2,R-1);for(let A=0;A<k.length;A++){let C=k.charAt(A);if(C==="\\"){A++;continue}if(C==="`"){let q=k.indexOf("`",A+1);o.subs.push(q<0?k.slice(A+1):k.slice(A+1,q)),A=q<0?k.length:q;continue}if(C==="$"&&k.charAt(A+1)==="("){let q=nd(k,A+1,"(",")");o.subs.push(k.slice(A+2,q-1)),A=q-1}}return R};while(g<p){let S=e.charAt(g);if(b==="'"){if(S==="'")b=null;i.push(S),g++;continue}if(b==='"'){if(S==="\\"){if(!'$`"\\\n'.includes(e.charAt(g+1)))i.push("\\");i.push(S,e.charAt(g+1)),g+=2;continue}if(S==='"'){b=null,i.push(S),g++;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}i.push(S),g++;continue}if(S==="'"||S==='"'){b=S,i.push(S),g++;continue}if(S==="\\"){i.push(S,e.charAt(g+1)),g+=2;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}if(S==="#"){let w=i.at(-1);if(w===void 0||`
|
|
9
|
-
;&|()`.includes(w)){while(g<p&&e.charAt(g)!==`
|
|
10
|
-
`)g++;continue}i.push(S),g++;continue}if(S==="<"&&e.charAt(g+1)==="<"&&e.charAt(g+2)!=="<"){let w=g+2;if(e.charAt(w)==="-")w++;i.push(e.slice(g,w));let R=w;while(R<p&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let k="";while(R<p){let A=e.charAt(R);if(A==="'"||A==='"'){let C=e.indexOf(A,R+1);if(C<0)break;k+=e.slice(R+1,C),R=C+1;continue}if(A==="\\"){k+=e.charAt(R+1),R+=2;continue}if(` \r
|
|
11
|
-
;&|()<>`.includes(A))break;k+=A,R++}if(k)u.push(k);g=w;continue}if(S===`
|
|
12
|
-
`){if(u.length>0){let w=sM.test(i.slice(y).join(""));g++;for(let R of u.splice(0)){let k=g,A=p;while(g<p){let C=e.indexOf(`
|
|
13
|
-
`,g),q=C<0?p:C;if(e.slice(g,q).trim()===R){A=g,g=C<0?p:C+1;break}g=C<0?p:C+1}if(w&&A>k)o.heredocs.push(e.slice(k,A))}}else g++;i.push(";",`
|
|
14
|
-
`),y=i.length;continue}i.push(S),g++}return o.text=i.join(""),o}function Eu(e,o){if(o.depth>eM)return;let i=cM(e),u;try{u=rd(i.text)}catch{return}let p=[];for(let g of u){if(typeof g==="string"){p.push({kind:"word",text:g});continue}if("pattern"in g){p.push({kind:"word",text:g.pattern});continue}if("op"in g)p.push({kind:"op",text:g.op})}mM(p,o);for(let g of i.subs)Eu(g,Zc(o));for(let g of i.heredocs)Eu(g,Zc(o))}function mM(e,o){let i=[],u=()=>{if(i.length>0)pM(i,o);i=[]};for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;if(g.kind==="op"){if(nM.has(g.text)){u();continue}if(oM.has(g.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(g.text)}u()}function pM(e,o){let i=0;for(;;){let y=e[i];if(y===void 0)return;if(rM.has(y)||sy.test(y)){i++;continue}let b=dM(ny(y),e,i);if(b===i)break;i=b}let u=e[i];if(u===void 0)return;let p=ny(u),g=e.slice(i+1);if(p==="git"){hM(u,g,o);return}if(tM.has(p)){lM(g,o);return}if(p==="powershell"||p==="pwsh")oy(g,/^-(command|c)$/i,o);if(p==="cmd")oy(g,/^\/[ck]$/i,o)}function oy(e,o,i){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let p=e.slice(u+1).join(" ");if(p.trim())Eu(p,Zc(i));return}}function lM(e,o){for(let i=0;i<e.length;i++){let u=e[i]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){i++;continue}if(u.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(u);if(p){let g=p[1]||e[i+1];if(g)Eu(g,Zc(o));return}if(u.startsWith("-")||u==="")continue;return}}function dM(e,o,i){if(aM.has(e)){let g=i+1;while(o[g]?.startsWith("-"))g++;return g}let u=uM.get(e);if(!u)return i;let p=i+1;for(;;){let g=o[p];if(g===void 0)return p;if(u.includes(g)){p+=2;continue}if(sy.test(g)||g.startsWith("-")){p++;continue}return p}}function zo(e,o){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(o))}function ro(e,o){return e.some((i)=>i===`--${o}`||i.startsWith(`--${o}=`))}var fM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(zo(e,"f")||zo(e,"i")||ro(e,"force")||ro(e,"interactive"))&&!(zo(e,"n")||ro(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>zo(e,"f")||ro(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>zo(e,"f")||ro(e,"force")||zo(e,"C")||ro(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>zo(e,"f")||ro(e,"force")||ro(e,"force-with-lease")||ro(e,"force-if-includes")||ro(e,"delete")||ro(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)=>ro(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>zo(e,"D")||zo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>ro(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>zo(e,"f")||ro(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(zo(e,"f")||ro(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function hM(e,o,i){let u=0;for(;;){let E=o[u];if(E===void 0)break;if(iM.has(E)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(E)||/^-[Cc].+/.test(E)||E.startsWith("-")){u++;continue}break}let p=o[u]?.toLowerCase();if(!p)return;let g=fM[p];if(!g)return;let y=g(o.slice(u+1));if(!y)return;let b=[e,...o.slice(u)].join(" ");i.out.push({rule:p,fragment:b.length>ry?`${b.slice(0,ry)}\u2026`:b,reason:y})}function sd(e){let o={out:[],depth:0};return Eu(e,o),o.out}function iy(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),i=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${i}`}var od=new Map;function gM(e,o,i,u,p){let g=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((y)=>{let b=(S)=>{if(!od.delete(g))return;p?.removeEventListener("abort",E),y(S)},E=()=>{ay(e,g),b("aborted")};if(od.set(g,{session:e,finish:b}),e.appendExtension({namespace:Iu,kind:"requested",schemaVersion:1,payload:{id:g,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:S,reason:w})=>({fragment:S,reason:w})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)E();else p?.addEventListener("abort",E,{once:!0})})}function ay(e,o){try{e.appendExtension({namespace:Iu,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Lo(e,o,i){let u=od.get(o);if(!u||u.session!==e){if(!yM(e,o))return"unknown";return ay(e,o),"expired"}return e.appendExtension({namespace:Iu,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(i?"approved":"denied"),"answered"}function yM(e,o){let i=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==Iu)continue;let p=u.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==o)continue;if(u.kind==="requested")i=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return i}function id(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${iy(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 je(e,o){let i=sd(e);if(!i.at(0))return;let p=iy(i),g=z.getStore();if(g?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${id(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let y=await gM(g,e,p,i,o);if(y==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${y==="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`}import{existsSync as xM,mkdirSync as IM,writeFileSync as bM}from"fs";import{homedir as EM}from"os";import{join as Bi}from"path";function et(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=EM();if(process.platform==="win32")return Bi(e.LOCALAPPDATA??Bi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Bi(o,"Library","Application Support","basalt");return Bi(e.XDG_DATA_HOME??Bi(o,".local","share"),"basalt")}function SM(e){return Bi(e,".basalt","tmp")}function ad(e){let o=SM(e);IM(o,{recursive:!0});let i=Bi(o,".gitignore");if(!xM(i))bM(i,`*
|
|
15
|
-
!.gitignore
|
|
16
|
-
`);return o}function em(e){try{let o=ad(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var cs={assign:0,create:0,clone:0,discard:0,update:0};function Gi(e,o,i){return e>=o&&e<=i}function my(e){return e===8205}function wM(e){return Gi(e,55296,56319)}function uy(e){return Gi(e,127462,127487)}function py(e){return Gi(e,65024,65039)}function ly(e){return Gi(e,768,879)||Gi(e,6832,6911)||Gi(e,7616,7679)||Gi(e,65056,65071)}function tm(e){return e>65535?2:1}function cy(e,o){while(o<e.length){let i=e.codePointAt(o);if(ly(i)||py(i))o+=tm(i);else break}return o}function ud(e,o){let i=e.codePointAt(o),u=o+tm(i);u=cy(e,u);while(u<e.length-1&&my(e.codePointAt(u))){let p=e.codePointAt(u+1);u+=1+tm(p),u=cy(e,u)}if(uy(i)&&u<e.length&&uy(e.codePointAt(u)))u+=tm(e.codePointAt(u));return u}function dy(e){return e>=768&&(wM(e)||ly(e)||py(e)||my(e))}function fy(e){let o=0,i=0;while(i<e.length)i=ud(e,i),o++;return o}function TM(e,o){let i=0,u=0;while(u<e.length)if(u=ud(e,u),++i>=o)return!0;return!1}function RM(e,o){let i=0,u=0;while(u<e.length)if(u=ud(e,u),++i>o)return!1;return!0}function hy(e,o){if(o===0)return!0;if(e.length<o)return!1;let i=0;while(!0){if(dy(e.charCodeAt(i)))return TM(e,o);if(++i>=o)return!0}}function gy(e,o){if(e.length<=o)return!0;let i=0;while(!0){if(dy(e.charCodeAt(i)))return RM(e,o);if(++i>o)return!1}}function Ge(e){return Array.isArray(e)}function Nr(e){return O(typeof e,"bigint")}function pn(e){return O(typeof e,"boolean")}function cd(e){if(Ut(e)||!ms(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 ms(e){return O(typeof e,"function")}function rm(e){return Number.isInteger(e)}function ho(e){return O(e,null)}function Ot(e){return Number.isFinite(e)}function Vo(e){return at(e)&&!Ge(e)}function at(e){return O(typeof e,"object")&&!ho(e)}function gt(e){return O(typeof e,"string")}function md(e){return O(typeof e,"symbol")}function Ut(e){return O(e,void 0)}function O(e,o){return e===o}function Ki(e,o){return e>o}function Su(e,o){return e<o}function ps(e,o){return e<=o}function Sa(e,o){return e>=o}function yy(e,o){if(Nr(e)||Nr(o))return BigInt(e)%BigInt(o)===0n;let i=0.0000000001;if(!Ot(e))return!0;if(rm(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))<i}function xy(e){if(!at(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(ho(o))return!1;return O(typeof o.constructor,"function")&&!(O(o.constructor,globalThis.Object)||O(o.constructor.name,"Object"))}function Hi(e){return Nr(e)||pn(e)||ho(e)||Ot(e)||gt(e)||Ut(e)}function AM(e){return fy(e)}function Iy(e,o){return gy(e,o)}function by(e,o){return hy(e,o)}function an(e,o,i){return e.every((u,p)=>p<o||i(u,p))}function An(e,o,i){let u=!0;return e.forEach((p,g)=>{if(g>=o&&!i(p,g))u=!1}),u}function wa(e,o){return e.some((i,u)=>o(i,u))}function Ey(e,o){let i=!1;return e.forEach((u,p)=>{if(o(u,p))i=!0}),i}function pd(e,o){return e.reduce((i,u,p)=>o(u,p)?++i:i,0)}function It(e,o,i){return O(e.length,0)?i():o(e[0],e.slice(1))}function wu(e){return O(e,"__proto__")||O(e,"constructor")||O(e,"prototype")}function fe(e,o){return wu(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function ld(e){return we(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function ln(e){return Object.entries(e)}function we(e){return Object.getOwnPropertyNames(e)}function Sy(e){return Object.getOwnPropertySymbols(e)}function dd(e){return Object.values(e)}function CM(e,o){if(!at(o))return!1;let i=we(e);return O(i.length,we(o).length)&&i.every((u)=>Ta(e[u],o[u]))}function PM(e,o){return Ge(o)&&O(e.length,o.length)&&e.every((i,u)=>Ta(e[u],o[u]))}function Ta(e,o){return Ge(e)?PM(e,o):at(e)?CM(e,o):O(e,o)}var $M=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function vM(e){return $M.test(e)}function Sn(e,o){return`(${e} && ${o})`}function xr(e,o){return`(${e} || ${o})`}function Un(e){return`!(${e})`}function nm(e){return`Array.isArray(${e})`}function wy(e){return`typeof ${e} === "bigint"`}function MM(e){return`typeof ${e} === "boolean"`}function OM(e){return`Number.isInteger(${e})`}function _M(e){return`${e} === null`}function Ty(e){return`Number.isFinite(${e})`}function Ry(e){return Sn(ky(e),Un(nm(e)))}function ky(e){return`typeof ${e} === "object" && ${e} !== null`}function Ay(e){return`typeof ${e} === "string"`}function LM(e){return`typeof ${e} === "symbol"`}function fd(e){return`${e} === undefined`}function NM(e){return`typeof ${e} === "function"`}function DM(e){return`Guard.IsConstructor(${e})`}function uo(e,o){return`${e} === ${o}`}function Cy(e,o){return`${e} > ${o}`}function hd(e,o){return`${e} < ${o}`}function Wi(e,o){return`${e} <= ${o}`}function Tu(e,o){return`${e} >= ${o}`}function qM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function FM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function ls(e,o,i,u){return O(o,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${u}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${o}) || (${u}))`}function jM(e,o,i){return`${e}.some((${o[0]}, ${o[1]}) => ${i})`}function UM(e,o,i){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${i}) result = true }); return result })(${e})`}function om(e,o,i){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${i}) ? ++result : result, 0)`}function Py(e){return`Object.entries(${e})`}function zi(e){return`Object.getOwnPropertyNames(${e})`}function Vi(e,o){return O(o,'"__proto__"')||O(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function $y(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function BM(e){return`[${e.join(", ")}]`}function Js(e,o){return`((${e.join(", ")}) => ${o})`}function Ir(e,o){return`${e}(${o.join(", ")})`}function gd(e,o){return`new ${e}(${o.join(", ")})`}function bt(e,o){return`${e}${vM(o)?`.${o}`:`[${De(o)}]`}`}function De(e){if(!Hi(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function GM(e,o,i){return`(${e} ? ${o} : ${i})`}function sm(e){return`{ ${e.join("; ")}; }`}function vs(e,o){return`const ${e} = ${o}`}function vy(e,o){return`if(${e}) { ${o} }`}function im(e){return`return ${e}`}function Cn(e){return O(e.length,0)?"true":e.reduce((o,i)=>Sn(o,i))}function yd(e){return O(e.length,0)?"false":e.reduce((o,i)=>xr(o,i))}function KM(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function HM(e){return e instanceof Boolean}function WM(e){return e instanceof Number}function zM(e){return e instanceof String}function My(e){return globalThis.ArrayBuffer.isView(e)}function Oy(e){return e instanceof globalThis.RegExp}function VM(e){return e instanceof globalThis.Date}function JM(e){return e instanceof globalThis.Set}function QM(e){return e instanceof globalThis.Map}var YM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Jo(){return YM}function Qs(e){return Jo().immutableTypes?Object.freeze(e):e}function dn(e,o){return cs.assign+=1,Qs({...e,...o})}function ZM(e){return e}function eO(e){return fe(e,"~kind")||fe(e,"~unsafe")}function tO(e){let o={};for(let i of we(e)){if(wu(i))continue;let u=Object.getOwnPropertyDescriptor(e,i);if(u.value=Ji(u.value),O(u.enumerable,!0))o[i]=u.value;else Object.defineProperty(o,i,u)}return o}function rO(e){let o={};for(let i of we(e)){if(wu(i))continue;o[i]=Ji(e[i])}for(let i of Sy(e))o[i]=Ji(e[i]);return o}function nO(e){return xy(e)?ZM(e):eO(e)?tO(e):rO(e)}function oO(e){return e.map((o)=>Ji(o))}function sO(e){return e.slice()}function iO(e){return new RegExp(e.source,e.flags)}function aO(e){return new Map(Ji([...e.entries()]))}function uO(e){return new Set(Ji([...e.values()]))}function Ji(e){return My(e)?sO(e):Oy(e)?iO(e):QM(e)?aO(e):JM(e)?uO(e):Ge(e)?oO(e):at(e)?nO(e):e}function Ra(e){return cs.clone+=1,Ji(e)}function cO(e,o){for(let i of Object.keys(o))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:o[i]});return e}function _y(e,o){return{...e,...o}}function Pt(e,o,i={}){cs.create+=1;let u=_y(o,i),p=Jo().enumerableKind?_y(u,e):cO(u,e);return Qs(p)}function Qo(e,o){cs.discard+=1;let i={};for(let u of we(e)){if(o.includes(u))continue;let p=Object.getOwnPropertyDescriptor(e,u);p.value=Ra(p.value),Object.defineProperty(i,u,p)}return Qs(i)}function St(e,o,i){cs.update+=1;let u=Jo(),p=Ra(e);for(let g of Object.keys(o))Object.defineProperty(p,g,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[g]});for(let g of Object.keys(i))Object.defineProperty(p,g,{configurable:!0,enumerable:!0,writable:!0,value:i[g]});return Qs(p)}function Ae(e,o){return at(e)&&fe(e,"~kind")&&O(e["~kind"],o)}function Pr(e){return at(e)}function ve(e,o,i){return Pt({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:i},{})}function Xs(e){return Ae(e,"Deferred")}function mO(e){return St(e,{"~readonly":!0},{})}function ku(e,o){return St(mO(e),{},o)}function Ly(e,o,i,u){let p=ge(e,o,i);return ku(p,u)}function pO(e){return St(e,{"~optional":!0},{})}function Au(e,o){return St(pO(e),{},o)}function Ny(e,o,i,u){let p=ge(e,o,i);return Au(p,u)}function B(e,o){return Pt({"~kind":"Array"},{type:"array",items:e},o)}function wt(e){return Ae(e,"Array")}function ka(e){return Qo(e,["~kind","type","items"])}function ds(e,o,i={}){return Pt({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},i)}function en(e){return Ae(e,"Constructor")}function Dy(e){return Qo(e,["~kind","type","parameters","instanceType"])}function fs(e,o,i={}){return Pt({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},i)}function tn(e){return Ae(e,"Function")}function qy(e){return Qo(e,["~kind","type","parameters","returnType"])}function un(e,o){return Pt({["~kind"]:"Ref"},{$ref:e},o)}function qt(e){return Ae(e,"Ref")}function Ys(e,o){return Pt({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Aa(e){return Ae(e,"Generic")}function Ca(e){return Pt({["~kind"]:"Any"},{},e)}function vr(e){return Ae(e,"Any")}var Fy="(?!)";function zt(e){return Pt({"~kind":"Never"},{not:{}},e)}function co(e){return Ae(e,"Never")}function hs(e,o={}){return ve("AddOptional",[e],o)}function Qi(e,o={}){return Au(e,o)}function n(e){return Qi(e)}function cn(e){return Pr(e)&&fe(e,"~optional")}function jy(e){return we(e).filter((o)=>!cn(e[o]))}function am(e){return we(e)}function um(e){return dd(e)}function l(e,o={}){let i=jy(e),u=i.length>0?{required:i}:{};return Pt({"~kind":"Object"},{type:"object",...u,properties:e},o)}function Qe(e){return Ae(e,"Object")}function Uy(e){return Qo(e,["~kind","type","properties","required"])}function Rr(e){return Pt({["~kind"]:"Unknown"},{},e)}function rn(e){return Ae(e,"Unknown")}function gs(e,o,i){let u=we(e).reduce((p,g)=>({...p,[g]:St(e[g],{},{$id:g})}),{});return Pt({["~kind"]:"Cyclic"},{$defs:u,$ref:o},i)}function Qt(e){return Ae(e,"Cyclic")}function qr(e){return St(e,{["~unsafe"]:null},{})}function cm(e){return Vo(e)&&fe(e,"~unsafe")&&ho(e["~unsafe"])}function wn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Cu(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p,p],1:(u)=>[u,Rr(),Rr()]});return Pt({["~kind"]:"Infer"},{type:"infer",name:o,extends:i},{})}function nn(e){return Ae(e,"Infer")}function Xi(e,o,i,u={}){return Pt({"~kind":"Dependent"},{if:e,then:o,else:i},u)}function Dr(e){return Ae(e,"Dependent")}function By(e){return Qo(e,["~kind","if","then","else"])}function Gy(e){return Vo(e)}function Ky(e){return we(e).filter((i)=>isNaN(i)).reduce((i,u)=>[...i,e[u]],[])}function Hy(e){return gt(e)||Ot(e)}function Wy(e,o){let i=Gy(e)?Ky(e):e;return Pt({"~kind":"Enum"},{enum:i},o)}function on(e){return Ae(e,"Enum")}function Pn(e,o={}){return Pt({"~kind":"Intersect"},{allOf:e},o)}function ze(e){return Ae(e,"Intersect")}function zy(e){return Qo(e,["~kind","allOf"])}var xd=void 0;function lO(){try{return Jy("null")(),!0}catch{return!1}}function Vy(){if(Ut(xd))xd=lO();return xd&&Jo().useAcceleration}function Jy(...e){return new globalThis.Function(...e)}function jr(){throw Error("Unreachable")}function dO(e){let o=new Set,i=e;while(i&&i!==Object.prototype){for(let u of Reflect.ownKeys(i))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);i=Object.getPrototypeOf(i)}return[...o]}function fO(e){return typeof e==="number"}var Bn;(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"})(Bn||(Bn={}));var Pa=BigInt("14695981039346656037"),[hO,gO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],yO=Array.from({length:256}).map((e,o)=>BigInt(o)),Zy=new Float64Array(1),ex=new DataView(Zy.buffer),tx=new Uint8Array(Zy.buffer);function In(e){Pa=Pa^yO[e],Pa=Pa*hO%gO}function xO(e){In(Bn.Array);for(let o of e)Zs(o)}function IO(e){In(Bn.BigInt),ex.setBigInt64(0,e);for(let o of tx)In(o)}function Xy(e){In(Bn.Boolean),In(e?1:0)}function bO(e){In(Bn.Constructor),Zs(e.toString())}function EO(e){In(Bn.Date),Zs(e.getTime())}function SO(e){In(Bn.Function),Zs(e.toString())}function wO(e){In(Bn.Null)}function Yy(e){In(Bn.Number),ex.setFloat64(0,e,!0);for(let o of tx)In(o)}function TO(e){In(Bn.Object);for(let o of dO(e).sort())Zs(o),Zs(e[o])}function RO(e){In(Bn.RegExp),Id(e.toString())}var kO=new TextEncoder;function Id(e){In(Bn.String);for(let o of kO.encode(e))In(o)}function AO(e){In(Bn.Symbol),Zs(e.toString())}function CO(e){In(Bn.TypeArray);let o=new Uint8Array(e.buffer);for(let i=0;i<o.length;i++)In(o[i])}function PO(e){return In(Bn.Undefined)}function Zs(e){return My(e)?CO(e):VM(e)?EO(e):Oy(e)?RO(e):HM(e)?Xy(e.valueOf()):zM(e)?Id(e.valueOf()):WM(e)?Yy(e.valueOf()):fO(e)?Yy(e):Ge(e)?xO(e):pn(e)?Xy(e):Nr(e)?IO(e):cd(e)?bO(e):ho(e)?wO(e):at(e)?TO(e):gt(e)?Id(e):md(e)?AO(e):Ut(e)?PO(e):ms(e)?SO(e):jr()}function rx(e){return Pa=BigInt("14695981039346656037"),Zs(e),Pa}function bd(e){return rx(e).toString(16).padStart(16,"0")}function nx(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 $O=nx;function ox(){return $O}class mm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,i=Hn(o)?(g)=>this.decode(o["~codec"].decode(g)):this.decode,u=Hn(o)?(g)=>o["~codec"].encode(e(g)):e,p={decode:i,encode:u};return St(this.type,{"~codec":p},{})}}class pm{constructor(e){this.type=e}Decode(e){return new mm(this.type,e)}}function lm(e){return new pm(e)}function ix(e,o){return lm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function ax(e,o){return lm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Hn(e){return Pr(e)&&fe(e,"~codec")&&at(e["~codec"])&&fe(e["~codec"],"encode")&&fe(e["~codec"],"decode")}function ux(e){return $a(e)}function Zi(e){return Pr(e)&&fe(e,"~immutable")}function ys(e,o={}){return ve("AddReadonly",[e],o)}function ea(e,o={}){return ku(e,o)}function cx(e){return ea(e)}function ta(e){return Pr(e)&&fe(e,"~readonly")}function MO(e,o){let i=dm(e)?[...e["~refine"],o]:[o];return St(e,{"~refine":i},{})}function mx(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,()=>"Refine Error"]});return MO(o,{check:i,error:u})}function OO(e){return Vo(e)&&fe(e,"check")&&fe(e,"error")&&ms(e.check)&&ms(e.error)}function dm(e){return Pr(e)&&fe(e,"~refine")&&Ge(e["~refine"])&&an(e["~refine"],0,(o)=>OO(o))}var px="-?(?:0|[1-9][0-9]*)n";function Pu(e){return Pt({"~kind":"BigInt"},{type:"bigint"},e)}function mo(e){return Ae(e,"BigInt")}function N(e){return Pt({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return Ae(e,"Boolean")}function $u(e){return Pt({"~kind":"Identifier"},{name:e})}function lx(e){return Ae(e,"Identifier")}var fm="-?(?:0|[1-9][0-9]*)";function _(e){return Pt({"~kind":"Integer"},{type:"integer"},e)}function fn(e){return Ae(e,"Integer")}class dx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function _O(e){return Nr(e)?"bigint":pn(e)?"boolean":Ot(e)?"number":gt(e)?"string":(()=>{throw new dx(e)})()}function s(e,o){return Pt({"~kind":"Literal"},{type:_O(e),const:e},o)}function hm(e){return Nr(e)||pn(e)||Ot(e)||gt(e)}function fx(e){return yt(e)&&Nr(e.const)}function hx(e){return yt(e)&&pn(e.const)}function gm(e){return yt(e)&&Ot(e.const)}function ym(e){return yt(e)&>(e.const)}function yt(e){return Ae(e,"Literal")}function $n(e){return Pt({"~kind":"Null"},{type:"null"},e)}function xs(e){return Ae(e,"Null")}var xm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Y(e){return Pt({"~kind":"Number"},{type:"number"},e)}function kr(e){return Ae(e,"Number")}function va(e){return Pt({"~kind":"Symbol"},{type:"symbol"},e)}function Is(e){return Ae(e,"Symbol")}function ra(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,g],1:(p)=>[p,Rr(),Rr()]});return Pt({"~kind":"Parameter"},{name:o,extends:i,equals:u},{})}function gx(e){return Ae(e,"Parameter")}var Im=".*";function a(e){return Pt({"~kind":"String"},{type:"string"},e)}function sn(e){return Ae(e,"String")}function m(e,o={}){return Pt({"~kind":"Union"},{anyOf:e},o)}function xe(e){return Ae(e,"Union")}function yx(e){return Qo(e,["~kind","anyOf"])}function vu(e){let o=xx(e);return O(o.length,2)?o[0]:[]}function LO(e){return!0}function Ix(e){return It(e,(o,i)=>NO(o)?Ix(i):!1,()=>!0)}function bx(e){return O(e.length,0)?!1:Ix(e)}function NO(e){return xe(e)?bx(e.anyOf):yt(e)?LO(e.const):!1}function bm(e){return bx(e)}function Em(e){return Pt({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function Ex(e,o,i=[]){return It(e,(u,p)=>Ex(p,o,[...i,`${u}${o}`]),()=>i)}function DO(e,o){return O(e.length,0)?[`${o}`]:Ex(e,o)}function Sx(e,o,i=[]){return It(o,(u,p)=>Sx(e,p,[...i,...wx(e,u)]),()=>i)}function wx(e,o){return xe(o)?Sx(e,o.anyOf):yt(o)?DO(e,o.const):jr()}function Tx(e,o){return It(o,(i,u)=>Tx(wx(e,i),u),()=>e)}function qO(e){return e.map((o)=>s(o))}function FO(e){let o=Tx([],e),i=qO(o);return m(i)}function jO(e){return O(e.length,0)?jr():O(e.length,1)&&yt(e[0])?e[0]:FO(e)}function Ed(e){let o=vu(e);return O(o.length,0)?a():bm(o)?jO(o):Em(e)}function Mu(e){let o=Ed(e);return ur(o)?a():o}function no(e,o){let u={[e]:o};return Pt({["~kind"]:"Record"},{type:"object",patternProperties:u})}function Rx(e){return no(Xo,e)}function kx(e){return l({true:e,false:e})}function Ur(e,o={}){let[i,u,p]=[e,e.length,!1];return Pt({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:u},o)}function mt(e){return Ae(e,"Tuple")}function Ax(e){return Qo(e,["~kind","type","items","minItems","additionalItems"])}function UO(e){return Qo(e,["~readonly"])}function Sd(e,o){return St(UO(e),{},o)}function Cx(e,o,i,u){let p=ge(e,o,i);return Sd(p,u)}function Px(e,o={}){return ve("RemoveReadonly",[e],o)}function $x(e,o={}){return Sd(e,o)}function BO(e){return Qo(e,["~optional"])}function wd(e,o){return St(BO(e),{},o)}function vx(e,o,i,u){let p=ge(e,o,i);return wd(p,u)}function Mx(e,o={}){return ve("RemoveOptional",[e],o)}function Sm(e,o={}){return wd(e,o)}function Td(e){return e.reduceRight((i,u,p)=>({[p]:u,...i}),{})}function Ox(e){let o=Td(e.items);return l(o)}function Rd(e){return Qe(e)||mt(e)}function GO(e,o){return ta(e)?ta(o)?!0:!1:!1}function KO(e,o){return cn(e)?cn(o)?!0:!1:!1}function HO(e,o){let i=GO(e,o),u=KO(e,o),p=Ar([e,o]),g=$x(Sm(p));return i&&u?ea(Qi(g)):i&&!u?ea(g):!i&&u?Qi(g):g}function WO(e,o,i){return i in e?i in o?HO(e[i],o[i]):e[i]:(i in o)?o[i]:zt()}function zO(e,o){return[...new Set([...we(e),...we(o)])].reduce((p,g)=>({...p,[g]:WO(e,o,g)}),{})}function _x(e){return Qe(e)?e.properties:mt(e)?Td(e.items):{}}function Lx(e,o){let i=_x(e),u=_x(o),p=zO(i,u);return l(p)}function VO(e,o){let i=Ma(e,o);return O(i,_u)?e:O(i,Lu)?o:O(i,Ou)?o:zt()}function JO(e,o){let i=Rd(e),u=Rd(o);return i&&u?Lx(e,o):i&&!u?e:!i&&u?o:VO(e,o)}function Nx(e,o){return co(e)?e:vr(e)?e:rn(e)?o:co(o)?o:vr(o)?o:rn(o)?e:JO(e,o)}function QO(e,o){return xe(e)||xe(o)}function XO(e,o){let i=Ao(e),u=Ao(o);return QO(i,u)?Ar([i,u]):Nx(i,u)}function Dx(e,o,i=[]){return It(o,(u,p)=>Dx(e,p,[...i,XO(u,e)]),()=>O(i.length,0)?[e]:i)}function qx(e,o,i=[]){return It(e,(u,p)=>qx(p,o,[...i,...Nu([u],o)]),()=>i)}function Nu(e,o=[]){return It(e,(i,u)=>xe(i)?Nu(u,qx(i.anyOf,o)):Nu(u,Dx(i,o)),()=>o)}function YO(e,o){let i=Tn({},e,o);return so(i)?[]:[e]}function Fx(e,o,i=[]){return It(e,(u,p)=>Fx(p,o,[...i,...YO(u,o)]),()=>i)}function wm(e,o){let i=Ao(e),u=xe(i)?i.anyOf:[i],p=Fx(u,o);return oo(p)}function Yo(e,o,i){let u=Ar([e,o]),p=wm(i,e);return oo([u,p])}function Zn(e,o=[]){return It(e,(i,u)=>Zn(u,[...o,s(i)]),()=>oo(o))}function Ar(e){let o=Nu(e),i=kd(o);return oo(i)}function vn(e){let o=Mu(e);return Ao(o)}function oo(e){let o=kd(e);return ei(o)}function Ao(e){return Dr(e)?Yo(e.if,e.then,e.else):on(e)?Zn(e.enum):ze(e)?Ar(e.allOf):ur(e)?vn(e.pattern):xe(e)?oo(e.anyOf):e}function ei(e){return O(e.length,1)?e[0]:O(e.length,0)?zt():m(e)}function jx(e,o){let i=Zn(e);return ti(i,o)}function Ux(e,o){return no(ri,o)}function Bx(e,o){let i=Ar(e);return ti(i,o)}function Gx(e,o){return gt(e)||Ot(e)?l({[e]:o}):O(e,!1)?l({false:o}):O(e,!0)?l({true:o}):l({})}function Kx(e,o){return no(Oa,o)}function Hx(e,o){return fe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?no(e.pattern.toString(),o):no(Xo,o)}function Wx(e,o){let i=vu(e);return bm(i)?ti(vn(e),o):no(e,o)}function ZO(e){return xe(e)?na(e.anyOf):[e]}function na(e,o=[]){return It(e,(i,u)=>na(u,[...o,...ZO(i)]),()=>o)}function e_(e){return e.some((o)=>sn(o)||kr(o)||fn(o))}function t_(e,o){return O(e_(e),!0)?no(Xo,o):void 0}function r_(e,o){return e.reduce((i,u)=>yt(u)&&(gt(u.const)||Ot(u.const))?{...i,[u.const]:o}:i,{})}function n_(e,o){let i=r_(e,o);return l(i)}function zx(e,o){let i=na(e),u=t_(i,o);return Pr(u)?u:n_(i,o)}function ti(e,o){return vr(e)?Rx(o):Wn(e)?kx(o):on(e)?jx(e.enum,o):fn(e)?Ux(e,o):ze(e)?Bx(e.allOf,o):yt(e)?Gx(e.const,o):kr(e)?Kx(e,o):xe(e)?zx(e.anyOf,o):sn(e)?Hx(e,o):ur(e)?Wx(e.pattern,o):l({})}function Ad(e,o,i){return ct([e])?St(ti(e,o),{},i):Tm(e,o,i)}function Vx(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return Ad(g,y,p)}var ri=`^${fm}$`,Oa=`^${xm}$`,Xo=`^${Im}$`;function Tm(e,o,i={}){return ve("Record",[e,o],i)}function bs(e,o,i={}){return Ad(e,o,i)}function Jx(e,o){return no(e,o)}function Rm(e){return O(e,Xo)?a():O(e,ri)?_():O(e,Oa)?Y():Ed(e)}function hn(e){return we(e.patternProperties)[0]}function ni(e){let o=hn(e);return Rm(o)}function fr(e){return e.patternProperties[hn(e)]}function Gt(e){return Ae(e,"Record")}function oa(e){return Pt({"~kind":"Rest"},{type:"rest",items:e},{})}function oi(e){return Ae(e,"Rest")}function km(e){return Pt({["~kind"]:"This"},{$ref:"#"},e)}function Am(e){return Ae(e,"This")}function _a(e){return Pt({"~kind":"Undefined"},{type:"undefined"},e)}function Zo(e){return Ae(e,"Undefined")}function Cm(e){return Pt({"~kind":"Void"},{type:"void"},e)}function po(e){return Ae(e,"Void")}function s_(e,o){return O(e,"Array")?B(o[0]):O(e,"Capitalize")?$m(o[0]):O(e,"ConstructorParameters")?Lm(o[0]):O(e,"Evaluate")?lE(o[0]):O(e,"Exclude")?Nm(o[0],o[1]):O(e,"Extract")?Dm(o[0],o[1]):O(e,"Index")?ju(o[0],o[1]):O(e,"InstanceType")?qm(o[0]):O(e,"Lowercase")?vm(o[0]):O(e,"NonNullable")?Fm(o[0]):O(e,"Omit")?jm(o[0],o[1]):O(e,"Parameters")?Um(o[0]):O(e,"Partial")?Bm(o[0]):O(e,"Pick")?Gm(o[0],o[1]):O(e,"Readonly")?Km(o[0]):O(e,"KeyOf")?Uu(o[0]):O(e,"Record")?Tm(o[0],o[1]):O(e,"Required")?Hm(o[0]):O(e,"ReturnType")?Wm(o[0]):O(e,"Uncapitalize")?Mm(o[0]):O(e,"Uppercase")?Om(o[0]):Fu(un(e),o)}function sa(){throw Error("Unreachable")}function eI(e,o=[]){return It(e,(i,u)=>eI(u,[...o,i[1]]),()=>o)}function Ms(e){return O(e.length,3)?[e[0],...eI(e[1])]:[]}function tI(e){return ra(e[0],e[2],e[4])}function rI(e){return ra(e[0],e[2],e[2])}function nI(e){return ra(e[0],Rr(),e[2])}function oI(e){return ra(e,Rr(),Rr())}function sI(e){return e}function iI(e){return Ms(e)}function aI(e){return e[1]}function uI(e){return Ms(e)}function cI(e){return e[1]}function mI(e){return s_(e[0],e[1])}function pI(e){return null}function lI(e){return a()}function dI(e){return Y()}function fI(e){return N()}function hI(e){return _a()}function gI(e){return $n()}function yI(e){return _()}function xI(e){return Pu()}function II(e){return Rr()}function bI(e){return Ca()}function EI(e){return l({})}function SI(e){return zt()}function wI(e){return va()}function TI(e){return Cm()}function RI(e){return km()}function kI(e){return s(BigInt(e))}function AI(e){return s(O(e,"true"))}function CI(e){return s(parseFloat(e))}function PI(e){return s(e)}function $I(e){return e[1]}function vI(e){return s(e)}function MI(e){return O(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function OI(e){return e[1]}function _I(e){return Pm(e)}function LI(e){return O(e.length,6)?Xi(e[1],e[3],e[5]):Xi(e[1],e[3],Rr())}function NI(e){return e.length>0}function DI(e){return e.reduce((o,i)=>O(i.length,3)?[...o,[i[1]]]:[...o,[]],[])}function qI(e){return O(e.length,6)?[e[1],e[3],e[5]]:[]}function FI(e){return Ge(e)&&O(e.length,3)?e[1]:e}function jI(e){return O(e.length,2)?e[1]:[]}function Qx(e,o){return o.reduce((i,u)=>{let p=u;return O(p.length,1)?ju(i,p[0]):O(p.length,0)?B(i):sa()},e)}function Xx(e,o){return O(o.length,3)?_m(e,o[0],o[1],o[2]):e}function i_(e,o){return Ge(o)&&O(o.length,0)?e:zm(e,o)}function UI(e){let[o,i,u,p,g]=e;return i_(o?Xx(Uu(Qx(i,u)),p):Xx(Qx(i,u),p),g)}function Cd(e,o){return O(o.length,3)?(()=>{let[i,u,p]=o,g=Cd(u,p);if(O(i,"&"))return ze(g)?Pn([e,...g.allOf]):Pn([e,g]);if(O(i,"|"))return xe(g)?m([e,...g.anyOf]):m([e,g]);sa()})():e}function BI(e){return e}function GI(e){let[o,i]=e;return Cd(o,i)}function KI(e){return e}function HI(e){let[o,i]=e;return Cd(o,i)}function WI(e){return pE(e[1])}function zI(e){return e[1]}function VI(e){return Ys(e[0],e[2])}function JI(e){return O(e.length,4)?Cu(e[1],e[3]):O(e.length,2)?Cu(e[1],Rr()):sa()}function QI(e){return e}function XI(e){return`${e}`}function YI(e){return e}function ZI(e){return e}function eb(e){return fn(e[3])?ri:kr(e[3])?Oa:Is(e[3])?Xo:sn(e[3])?Xo:sa()}function tb(e){return e}function rb(e){return e.length>0}function nb(e){return e.length>0}function ob(e){let[o,i,u,p,g]=e;return{[i]:o&&u?ys(hs(g)):o&&!u?ys(g):!o&&u?hs(g):g}}function sb(e){return e}function ib(e){return Ms(e)}function ab(e){return e.reduce((o,i)=>fe(i,ri)||fe(i,Oa)||fe(i,Xo)?[o[0],dn(o[1],i)]:[dn(o[0],i),o[1]],[{},{}])}function ub(e){return ab(e[1])}function cb(e){let[o,i]=e,u=O(we(i).length,0)?{}:{patternProperties:i};return l(o,u)}function mb(e){return O(e.length,5)?ys(hs(e[4])):O(e.length,3)?e[2]:O(e.length,4)?O(e[2],"readonly")?ys(e[3]):hs(e[3]):sa()}function pb(e){if(!Ge(e)||!O(e.length,3))return e;let[o,i,u]=e;return o&&u?ys(hs(i)):o&&!u?ys(i):!o&&u?hs(i):i}function lb(e){return O(e.length,2)?oa(e[1]):O(e.length,1)?e[0]:sa()}function db(e){return Ms(e)}function fb(e){return Ur(e[1])}function hb(e){return ys(hs(e[4]))}function gb(e){return ys(e[3])}function yb(e){return hs(e[3])}function xb(e){return e[2]}function Ib(e){return e}function bb(e){return O(e.length,2)?oa(e[1]):O(e.length,1)?e[0]:sa()}function Eb(e){return Ms(e)}function Sb(e){return fs(e[1],e[4])}function wb(e){return ds(e[2],e[5])}function Yx(e,o){return O(e,"remove")?Px(o):O(e,"add")?ys(o):o}function Tb(e){return O(e.length,2)&&O(e[0],"-")?"remove":O(e.length,2)&&O(e[0],"+")?"add":O(e.length,1)?"add":"none"}function Zx(e,o){return O(e,"remove")?Mx(o):O(e,"add")?hs(o):o}function Rb(e){return O(e.length,2)&&O(e[0],"-")?"remove":O(e.length,2)&&O(e[0],"+")?"add":O(e.length,1)?"add":"none"}function kb(e){return O(e.length,2)?[e[1]]:[]}function Ab(e){return Ge(e[6])&&O(e[6].length,1)?Du($u(e[3]),e[5],e[6][0],Yx(e[1],Zx(e[8],e[10]))):Du($u(e[3]),e[5],un(e[3]),Yx(e[1],Zx(e[8],e[10])))}function Cb(e){return un(e)}function Pb(e){return BigInt(e)}function $b(e){return parseFloat(e)}function vb(e){return O(e,"true")}function Mb(e){return e}function Ob(e){return null}function _b(e){return}function Lb(e){return{[e[0]]:e[2]}}function Nb(e){return Ms(e)}function a_(e){return e.reduce((o,i)=>dn(o,i),{})}function Db(e){return a_(e[1])}function qb(e){return Ms(e)}function Fb(e){return e[1]}function jb(e){return e}function Ub(e){return Pu()}function Bb(e){return a()}function Gb(e){return Y()}function Kb(e){return _()}function Hb(e){return zt()}function Wb(e){return s(e)}function zb(e){return e}function Vb(e){return m(e[1])}function Jb(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Qb(e){return[e[0],...e[1]]}function Xb(e){return e}function Yb(e){return e[1]}function Zb(e){return Ms(e)}function eE(e){return O(e.length,2)?e[1]:[]}function tE(e){let o=e[2],i=e[3],[u,p]=e[4],g=O(we(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Ys(o,qu(i,u,g))}}function rE(e){let o=e[2],[i,u]=e[3],p=O(we(u).length,0)?{}:{patternProperties:u};return{[e[1]]:qu(o,i,p)}}function nE(e){return{[e[1]]:Ys(e[2],e[4])}}function oE(e){return{[e[1]]:e[3]}}function sE(e){return null}function iE(e){return e}function aE(e){return Ms(e)}function uE(e){return e[1]}function cE(e){let[o,i]=[e[0],e[1]];return dE(dn(o,ab(i)[0]))}function mE(e){return e}function Bu(e){return O(e.length,2)}function Rt(e,o,i){return Bu(e)?o(e[0],e[1]):i()}function m_(e,o){return O(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Or(e,o){for(let i=0;i<e.length;i++){let u=m_(e[i],o);if(Bu(u))return u}return[]}function Pd(e,o){return Array.from({length:o-e+1},(i,u)=>String.fromCharCode(e+u))}var fE=[...Pd(97,122),...Pd(65,90)],$d="0",vd=Pd(49,57),La=[$d,...vd],hE=" ",Na=`
|
|
17
|
-
`;var si="_",Vm=".",gE="$",Jm="-";var yE="//",xE="/*",l_="*/";function IE(e){let o=e.indexOf(l_);return O(o,-1)?"":e.slice(o+2)}function bE(e){let o=e.indexOf(Na);return O(o,-1)?"":e.slice(o)}function d_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Qm(e){let o=d_(e);return o.startsWith(xE)?Qm(IE(o.slice(2))):o.startsWith(yE)?Qm(bE(o.slice(2))):o}function bn(e){let o=e.trimStart();return o.startsWith(xE)?bn(IE(o.slice(2))):o.startsWith(yE)?bn(bE(o.slice(2))):o}function Xm(e,o){return Rt(Or([e],o),(i,u)=>[i,u],()=>["",o])}function f_(e,o){return e.includes(o)}function Da(e,o,i,u=""){return Rt(Or(e,i),(p,g)=>f_(o,p)?Da(e,o,g,u):Da(e,o,g,`${u}${p}`),()=>[u,i])}function h_(e){return Or(vd,e)}var g_=[...La,si];function y_(e){return Da(g_,[si],e)}function x_(e){return Rt(Or([$d],e),(o,i)=>[o,i],()=>Rt(h_(e),(o,i)=>Rt(y_(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[]))}function Ym(e){return x_(bn(e))}function I_(e){return Xm(Jm,e)}function b_(e){return Rt(I_(e),(o,i)=>Rt(Ym(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function EE(e){return b_(bn(e))}function E_(e){return Rt(EE(e),(o,i)=>Rt(Or(["n"],i),(u,p)=>[`${o}`,p],()=>[]),()=>[])}function Md(e){return E_(e)}function Od(e,o){return Or([e],o)}function Z(e,o){return O(e,"")?["",o]:e.startsWith(Na)?Od(e,Qm(o)):e.startsWith(hE)?Od(e,o):Od(e,bn(o))}var SE=[...fE,si,gE];function S_(e){return Or(SE,e)}var w_=[...SE,...La];function wE(e,o=""){return Rt(Or(w_,e),(i,u)=>wE(u,`${o}${i}`),()=>[o,e])}function T_(e){return Rt(S_(e),(o,i)=>Rt(wE(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Br(e){return T_(bn(e))}var R_=[...La,si];function k_(e){return Bu(Or([Vm],e))}function TE(e){return Rt(Da(R_,[si],e),(o,i)=>O(o,"")?[]:[o,i],()=>[])}function A_(e){return Rt(Or([Vm],e),(o,i)=>Rt(TE(i),(u,p)=>[`0${o}${u}`,p],()=>[]),()=>[])}function C_(e){return Rt(Ym(e),(o,i)=>Rt(Or([Vm],i),(u,p)=>Rt(TE(p),(g,y)=>[`${o}${u}${g}`,y],()=>[`${o}`,p]),()=>[`${o}`,i]),()=>[])}function P_(e){return k_(e)?A_(e):C_(e)}function RE(e){return P_(bn(e))}function $_(e){return Xm(Jm,e)}function v_(e){return Rt($_(e),(o,i)=>Rt(RE(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Zm(e){return v_(bn(e))}function M_(e){return O(e,"")?[]:[e.slice(0,1),e.slice(1)]}function kE(e,o){return It(e,(i,u)=>o.startsWith(i)?!0:kE(u,o),()=>!1)}function ii(e,o,i=""){return Rt(M_(o),(u,p)=>kE(e,o)?[i,o]:ii(e,p,`${i}${u}`),()=>[])}function O_(e,o,i){return Rt(Or([e],i),(u,p)=>Rt(ii([o],p),(g,y)=>Rt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function __(e,o,i){return Rt(Or([e],i),(u,p)=>Rt(ii([Na,o],p),(g,y)=>Rt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function AE(e,o,i,u){return i?O_(e,o,bn(u)):__(e,o,bn(u))}function L_(e,o){return Or(e,o)}function N_(e,o){return AE(e,e,!1,o)}function D_(e,o){return Rt(L_(e,o),(i,u)=>N_(i,`${i}${u}`),()=>[])}function ep(e,o){return D_(e,bn(o))}function CE(e,o){return Rt(ii(e,o),(i,u)=>O(i,"")?[]:[i,u],()=>[])}var T=(e,o,i=()=>[])=>e.length===2?o(e):i(),F_=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([u,p])=>T(vt(p),([g,y])=>T(Z("=",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[tI(o),i]),j_=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[rI(o),i]),U_=(e)=>T(T(Br(e),([o,i])=>T(Z("=",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[nI(o),i]),B_=(e)=>T(Br(e),([o,i])=>[oI(o),i]),vE=(e)=>T(T(F_(e),([o,i])=>[o,i],()=>T(j_(e),([o,i])=>[o,i],()=>T(U_(e),([o,i])=>[o,i],()=>T(B_(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[sI(o),i]),ME=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vE(u),([p,g])=>[[i,p],g])),([i,u])=>ME(u,[...o,i]),()=>[o,e]),G_=(e)=>T(T(T(vE(e),([o,i])=>T(ME(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[iI(o),i]),Nd=(e)=>T(T(Z("<",e),([o,i])=>T(G_(i),([u,p])=>T(Z(">",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[aI(o),i]),OE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vt(u),([p,g])=>[[i,p],g])),([i,u])=>OE(u,[...o,i]),()=>[o,e]),K_=(e)=>T(T(T(vt(e),([o,i])=>T(OE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[uI(o),i]),H_=(e)=>T(T(Z("<",e),([o,i])=>T(K_(i),([u,p])=>T(Z(">",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[cI(o),i]),W_=(e)=>T(T(Br(e),([o,i])=>T(H_(i),([u,p])=>[[o,u],p])),([o,i])=>[mI(o),i]),_E=(e)=>T(T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[pI(o),i]),LE=(e)=>T(Z("string",e),([o,i])=>[lI(o),i]),NE=(e)=>T(Z("number",e),([o,i])=>[dI(o),i]),z_=(e)=>T(Z("boolean",e),([o,i])=>[fI(o),i]),V_=(e)=>T(Z("undefined",e),([o,i])=>[hI(o),i]),J_=(e)=>T(Z("null",e),([o,i])=>[gI(o),i]),DE=(e)=>T(Z("integer",e),([o,i])=>[yI(o),i]),Q_=(e)=>T(Z("bigint",e),([o,i])=>[xI(o),i]),X_=(e)=>T(Z("unknown",e),([o,i])=>[II(o),i]),Y_=(e)=>T(Z("any",e),([o,i])=>[bI(o),i]),Z_=(e)=>T(Z("object",e),([o,i])=>[EI(o),i]),eL=(e)=>T(Z("never",e),([o,i])=>[SI(o),i]),qE=(e)=>T(Z("symbol",e),([o,i])=>[wI(o),i]),tL=(e)=>T(Z("void",e),([o,i])=>[TI(o),i]),rL=(e)=>T(Z("this",e),([o,i])=>[RI(o),i]),nL=(e)=>T(T(Z("${",e),([o,i])=>T(vt(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[$I(o),i]),_d=(e)=>T(ii(["${","`"],e),([o,i])=>[vI(o),i]),FE=(e)=>T(T(T(_d(e),([o,i])=>T(nL(i),([u,p])=>T(FE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(T(_d(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(_d(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[MI(o),i]),Dd=(e)=>T(T(Z("`",e),([o,i])=>T(FE(i),([u,p])=>T(Z("`",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[OI(o),i]),oL=(e)=>T(Dd(e),([o,i])=>[_I(o),i]),sL=(e)=>T(T(T(Z("if",e),([o,i])=>T(vt(i),([u,p])=>T(Z("then",p),([g,y])=>T(vt(y),([b,E])=>T(Z("else",E),([S,w])=>T(vt(w),([R,k])=>[[o,u,g,b,S,R],k])))))),([o,i])=>[o,i],()=>T(T(Z("if",e),([o,i])=>T(vt(i),([u,p])=>T(Z("then",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>[])),([o,i])=>[LI(o),i]),iL=(e)=>T(Md(e),([o,i])=>[kI(o),i]),aL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[AI(o),i]),uL=(e)=>T(Zm(e),([o,i])=>[CI(o),i]),cL=(e)=>T(ep(["'",'"'],e),([o,i])=>[PI(o),i]),mL=(e)=>T(T(T(Z("keyof",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[NI(o),i]),jE=(e,o=[])=>T(T(T(Z("[",e),([i,u])=>T(vt(u),([p,g])=>T(Z("]",g),([y,b])=>[[i,p,y],b]))),([i,u])=>[i,u],()=>T(T(Z("[",e),([i,u])=>T(Z("]",u),([p,g])=>[[i,p],g])),([i,u])=>[i,u],()=>[])),([i,u])=>jE(u,[...o,i]),()=>[o,e]),pL=(e)=>T(jE(e),([o,i])=>[DI(o),i]),lL=(e)=>T(T(T(Z("extends",e),([o,i])=>T(vt(i),([u,p])=>T(Z("?",p),([g,y])=>T(vt(y),([b,E])=>T(Z(":",E),([S,w])=>T(vt(w),([R,k])=>[[o,u,g,b,S,R],k])))))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[qI(o),i]),dL=(e)=>T(T(T(Z("(",e),([o,i])=>T(vt(i),([u,p])=>T(Z(")",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(LE(e),([o,i])=>[o,i],()=>T(NE(e),([o,i])=>[o,i],()=>T(z_(e),([o,i])=>[o,i],()=>T(V_(e),([o,i])=>[o,i],()=>T(J_(e),([o,i])=>[o,i],()=>T(DE(e),([o,i])=>[o,i],()=>T(Q_(e),([o,i])=>[o,i],()=>T(X_(e),([o,i])=>[o,i],()=>T(Y_(e),([o,i])=>[o,i],()=>T(Z_(e),([o,i])=>[o,i],()=>T(eL(e),([o,i])=>[o,i],()=>T(qE(e),([o,i])=>[o,i],()=>T(tL(e),([o,i])=>[o,i],()=>T(rL(e),([o,i])=>[o,i],()=>T(iL(e),([o,i])=>[o,i],()=>T(aL(e),([o,i])=>[o,i],()=>T(uL(e),([o,i])=>[o,i],()=>T(cL(e),([o,i])=>[o,i],()=>T(oL(e),([o,i])=>[o,i],()=>T(sL(e),([o,i])=>[o,i],()=>T(TL(e),([o,i])=>[o,i],()=>T(AL(e),([o,i])=>[o,i],()=>T(OL(e),([o,i])=>[o,i],()=>T(ML(e),([o,i])=>[o,i],()=>T(DL(e),([o,i])=>[o,i],()=>T(W_(e),([o,i])=>[o,i],()=>T(qL(e),([o,i])=>[o,i],()=>[])))))))))))))))))))))))))))),([o,i])=>[FI(o),i]),fL=(e)=>T(T(T(Z("with",e),([o,i])=>T(nS(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[jI(o),i]),UE=(e)=>T(T(mL(e),([o,i])=>T(dL(i),([u,p])=>T(pL(p),([g,y])=>T(lL(y),([b,E])=>T(fL(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[UI(o),i]),BE=(e)=>T(T(T(Z("&",e),([o,i])=>T(UE(i),([u,p])=>T(BE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[BI(o),i]),GE=(e)=>T(T(UE(e),([o,i])=>T(BE(i),([u,p])=>[[o,u],p])),([o,i])=>[GI(o),i]),KE=(e)=>T(T(T(Z("|",e),([o,i])=>T(GE(i),([u,p])=>T(KE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[KI(o),i]),tp=(e)=>T(T(GE(e),([o,i])=>T(KE(i),([u,p])=>[[o,u],p])),([o,i])=>[HI(o),i]),hL=(e)=>T(T(Z("readonly",e),([o,i])=>T(tp(i),([u,p])=>[[o,u],p])),([o,i])=>[WI(o),i]),gL=(e)=>T(T(Z("|",e),([o,i])=>T(tp(i),([u,p])=>[[o,u],p])),([o,i])=>[zI(o),i]),yL=(e)=>T(T(Nd(e),([o,i])=>T(Z("=",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[VI(o),i]),xL=(e)=>T(T(T(Z("infer",e),([o,i])=>T(Br(i),([u,p])=>T(Z("extends",p),([g,y])=>T(tp(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Z("infer",e),([o,i])=>T(Br(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>[])),([o,i])=>[JI(o),i]),vt=(e)=>T(T(xL(e),([o,i])=>[o,i],()=>T(gL(e),([o,i])=>[o,i],()=>T(hL(e),([o,i])=>[o,i],()=>T(tp(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[QI(o),i]),IL=(e)=>T(Zm(e),([o,i])=>[XI(o),i]),bL=(e)=>T(Br(e),([o,i])=>[YI(o),i]),EL=(e)=>T(ep(["'",'"'],e),([o,i])=>[ZI(o),i]),SL=(e)=>T(T(Z("[",e),([o,i])=>T(Br(i),([u,p])=>T(Z(":",p),([g,y])=>T(T(DE(y),([b,E])=>[b,E],()=>T(NE(y),([b,E])=>[b,E],()=>T(LE(y),([b,E])=>[b,E],()=>T(qE(y),([b,E])=>[b,E],()=>[])))),([b,E])=>T(Z("]",E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[eb(o),i]),HE=(e)=>T(T(IL(e),([o,i])=>[o,i],()=>T(bL(e),([o,i])=>[o,i],()=>T(EL(e),([o,i])=>[o,i],()=>T(SL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[tb(o),i]),WE=(e)=>T(T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[rb(o),i]),zE=(e)=>T(T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[nb(o),i]),VE=(e)=>T(T(WE(e),([o,i])=>T(HE(i),([u,p])=>T(zE(p),([g,y])=>T(Z(":",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[ob(o),i]),rp=(e)=>T(T(T(Z(",",e),([o,i])=>T(Z(`
|
|
18
|
-
`,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>T(Z(`
|
|
19
|
-
`,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(",",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
|
|
20
|
-
`,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))))),([o,i])=>[sb(o),i]),JE=(e,o=[])=>T(T(rp(e),([i,u])=>T(VE(u),([p,g])=>[[i,p],g])),([i,u])=>JE(u,[...o,i]),()=>[o,e]),wL=(e)=>T(T(T(VE(e),([o,i])=>T(JE(i),([u,p])=>T(T(rp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[ib(o),i]),qd=(e)=>T(T(Z("{",e),([o,i])=>T(wL(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[ub(o),i]),TL=(e)=>T(qd(e),([o,i])=>[cb(o),i]),RL=(e)=>T(T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(Z("readonly",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>[])))),([o,i])=>[mb(o),i]),PE=(e)=>T(T(RL(e),([o,i])=>[o,i],()=>T(T(WE(e),([o,i])=>T(vt(i),([u,p])=>T(zE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>[])),([o,i])=>[pb(o),i]),QE=(e)=>T(T(T(Z("...",e),([o,i])=>T(PE(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(PE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[lb(o),i]),XE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(QE(u),([p,g])=>[[i,p],g])),([i,u])=>XE(u,[...o,i]),()=>[o,e]),kL=(e)=>T(T(T(QE(e),([o,i])=>T(XE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[db(o),i]),AL=(e)=>T(T(Z("[",e),([o,i])=>T(kL(i),([u,p])=>T(Z("]",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[fb(o),i]),CL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[hb(o),i]),PL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(Z("readonly",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[gb(o),i]),$L=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[yb(o),i]),vL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[xb(o),i]),$E=(e)=>T(T(CL(e),([o,i])=>[o,i],()=>T(PL(e),([o,i])=>[o,i],()=>T($L(e),([o,i])=>[o,i],()=>T(vL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[Ib(o),i]),YE=(e)=>T(T(T(Z("...",e),([o,i])=>T($E(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T($E(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[bb(o),i]),ZE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(YE(u),([p,g])=>[[i,p],g])),([i,u])=>ZE(u,[...o,i]),()=>[o,e]),eS=(e)=>T(T(T(YE(e),([o,i])=>T(ZE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Eb(o),i]),ML=(e)=>T(T(Z("(",e),([o,i])=>T(eS(i),([u,p])=>T(Z(")",p),([g,y])=>T(Z("=>",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Sb(o),i]),OL=(e)=>T(T(Z("new",e),([o,i])=>T(Z("(",i),([u,p])=>T(eS(p),([g,y])=>T(Z(")",y),([b,E])=>T(Z("=>",E),([S,w])=>T(vt(w),([R,k])=>[[o,u,g,b,S,R],k])))))),([o,i])=>[wb(o),i]),_L=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("readonly",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("readonly",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Tb(o),i]),LL=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("?",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("?",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Rb(o),i]),NL=(e)=>T(T(T(Z("as",e),([o,i])=>T(vt(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[kb(o),i]),DL=(e)=>T(T(Z("{",e),([o,i])=>T(_L(i),([u,p])=>T(Z("[",p),([g,y])=>T(Br(y),([b,E])=>T(Z("in",E),([S,w])=>T(vt(w),([R,k])=>T(NL(k),([A,C])=>T(Z("]",C),([q,X])=>T(LL(X),([j,V])=>T(Z(":",V),([J,ee])=>T(vt(ee),([pe,H])=>T(_E(H),([le,he])=>T(Z("}",he),([$e,Ee])=>[[o,u,g,b,S,R,A,q,j,J,pe,le,$e],Ee]))))))))))))),([o,i])=>[Ab(o),i]),qL=(e)=>T(Br(e),([o,i])=>[Cb(o),i]),FL=(e)=>T(Md(e),([o,i])=>[Pb(o),i]),jL=(e)=>T(Zm(e),([o,i])=>[$b(o),i]),UL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[vb(o),i]),BL=(e)=>T(ep(['"',"'"],e),([o,i])=>[Mb(o),i]),GL=(e)=>T(Z("null",e),([o,i])=>[Ob(o),i]),KL=(e)=>T(Z("undefined",e),([o,i])=>[_b(o),i]),tS=(e)=>T(T(HE(e),([o,i])=>T(Z(":",i),([u,p])=>T(Fd(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Lb(o),i]),rS=(e,o=[])=>T(T(rp(e),([i,u])=>T(tS(u),([p,g])=>[[i,p],g])),([i,u])=>rS(u,[...o,i]),()=>[o,e]),HL=(e)=>T(T(T(tS(e),([o,i])=>T(rS(i),([u,p])=>T(T(rp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Nb(o),i]),nS=(e)=>T(T(Z("{",e),([o,i])=>T(HL(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Db(o),i]),oS=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(Fd(u),([p,g])=>[[i,p],g])),([i,u])=>oS(u,[...o,i]),()=>[o,e]),WL=(e)=>T(T(T(Fd(e),([o,i])=>T(oS(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[qb(o),i]),zL=(e)=>T(T(Z("[",e),([o,i])=>T(WL(i),([u,p])=>T(Z("]",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Fb(o),i]),Fd=(e)=>T(T(FL(e),([o,i])=>[o,i],()=>T(jL(e),([o,i])=>[o,i],()=>T(UL(e),([o,i])=>[o,i],()=>T(BL(e),([o,i])=>[o,i],()=>T(GL(e),([o,i])=>[o,i],()=>T(KL(e),([o,i])=>[o,i],()=>T(nS(e),([o,i])=>[o,i],()=>T(zL(e),([o,i])=>[o,i],()=>[])))))))),([o,i])=>[jb(o),i]),VL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)n",e),([o,i])=>[Ub(o),i]),JL=(e)=>T(Z(".*",e),([o,i])=>[Bb(o),i]),QL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,i])=>[Gb(o),i]),XL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)",e),([o,i])=>[Kb(o),i]),YL=(e)=>T(Z("(?!)",e),([o,i])=>[Hb(o),i]),ZL=(e)=>T(CE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,i])=>[Wb(o),i]),eN=(e)=>T(T(VL(e),([o,i])=>[o,i],()=>T(JL(e),([o,i])=>[o,i],()=>T(QL(e),([o,i])=>[o,i],()=>T(XL(e),([o,i])=>[o,i],()=>T(YL(e),([o,i])=>[o,i],()=>T(tN(e),([o,i])=>[o,i],()=>T(ZL(e),([o,i])=>[o,i],()=>[]))))))),([o,i])=>[zb(o),i]),tN=(e)=>T(T(Z("(",e),([o,i])=>T(jd(i),([u,p])=>T(Z(")",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Vb(o),i]),sS=(e)=>T(T(T(Ld(e),([o,i])=>T(Z("|",i),([u,p])=>T(sS(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(T(Ld(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[]))),([o,i])=>[Jb(o),i]),Ld=(e)=>T(T(eN(e),([o,i])=>T(jd(i),([u,p])=>[[o,u],p])),([o,i])=>[Qb(o),i]),jd=(e)=>T(T(sS(e),([o,i])=>[o,i],()=>T(Ld(e),([o,i])=>[o,i],()=>[])),([o,i])=>[Xb(o),i]),xx=(e)=>T(T(Z("^",e),([o,i])=>T(jd(i),([u,p])=>T(Z("$",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Yb(o),i]),iS=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vt(u),([p,g])=>[[i,p],g])),([i,u])=>iS(u,[...o,i]),()=>[o,e]),rN=(e)=>T(T(T(vt(e),([o,i])=>T(iS(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Zb(o),i]),aS=(e)=>T(T(T(Z("extends",e),([o,i])=>T(rN(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[eE(o),i]),nN=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([u,p])=>T(Nd(p),([g,y])=>T(aS(y),([b,E])=>T(qd(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[tE(o),i]),oN=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([u,p])=>T(aS(p),([g,y])=>T(qd(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[rE(o),i]),sN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([u,p])=>T(Nd(p),([g,y])=>T(Z("=",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[nE(o),i]),iN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([u,p])=>T(Z("=",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[oE(o),i]),aN=(e)=>T(T(T(Z("export",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[sE(o),i]),uS=(e)=>T(T(T(Z(";",e),([o,i])=>T(Z(`
|
|
21
|
-
`,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
|
|
22
|
-
`,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[iE(o),i]),cS=(e,o=[])=>T(T(uS(e),([i,u])=>T(Ud(u),([p,g])=>[[i,p],g])),([i,u])=>cS(u,[...o,i]),()=>[o,e]),uN=(e)=>T(T(T(Ud(e),([o,i])=>T(cS(i),([u,p])=>T(T(uS(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[aE(o),i]),Ud=(e)=>T(T(aN(e),([o,i])=>T(T(nN(i),([u,p])=>[u,p],()=>T(oN(i),([u,p])=>[u,p],()=>T(sN(i),([u,p])=>[u,p],()=>T(iN(i),([u,p])=>[u,p],()=>[])))),([u,p])=>T(_E(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[uE(o),i]),cN=(e)=>T(T(Ud(e),([o,i])=>T(uN(i),([u,p])=>[[o,u],p])),([o,i])=>[cE(o),i]),mS=(e)=>T(T(cN(e),([o,i])=>[o,i],()=>T(yL(e),([o,i])=>[o,i],()=>T(vt(e),([o,i])=>[o,i],()=>[]))),([o,i])=>[mE(o),i]);function pS(e){let o=Dd(`\`${e}\``);return O(o.length,2)?o[0]:jr()}function pN(e){return e.join("|")}function lN(e){return e.slice(1,e.length-1)}function dN(e,o,i){return ai(o,`${i}${e}`)}function fN(e,o){return ai(e,`${o}${px}`)}function hN(e,o){return ai(e,`${o}${fm}`)}function gN(e,o){return ai(e,`${o}${xm}`)}function yN(e,o){return Gu(m([s("false"),s("true")]),e,o)}function xN(e,o){return ai(e,`${o}${Im}`)}function IN(e,o,i){return ai(o,`${i}${lN(e)}`)}function bN(e,o,i){let u=Ku(e,{});return Gu(u,o,i)}function EN(e,o,i){let u=Zn(e);return Gu(u,o,i)}function lS(e,o,i,u=[]){return It(e,(p,g)=>lS(g,o,i,[...u,Gu(p,[],"")]),()=>ai(o,`${i}(${pN(u)})`))}function Gu(e,o,i){return on(e)?EN(e.enum,o,i):fn(e)?hN(o,i):yt(e)?dN(e.const,o,i):mo(e)?fN(o,i):Wn(e)?yN(o,i):kr(e)?gN(o,i):sn(e)?xN(o,i):ur(e)?IN(e.pattern,o,i):fS(e)?bN(e.parameters[0],o,i):xe(e)?lS(e.anyOf,o,i):Fy}function ai(e,o){return It(e,(i,u)=>Gu(i,u,o),()=>o)}function SN(e){return`^${ai(e,"")}$`}function dS(e){let o=SN(e);return Em(o)}function Ku(e,o){return ct(e)?St(dS(e),{},o):Pm(e,o)}function hS(e,o,i,u){let p=yo(e,o,i);return Ku(p,u)}function Pm(e,o={}){return ve("TemplateLiteral",[e],o)}function fS(e){return Pr(e)&&fe(e,"action")&&O(e.action,"TemplateLiteral")}function gS(e){return Ku(e,{})}function wN(e){let o=pS(e);return gS(o)}function yS(e,o={}){let i=gt(e)?wN(e):gS(e);return St(i,{},o)}function ur(e){return Ae(e,"TemplateLiteral")}function Bd(e){return Pt({["~kind"]:"ExtendsUnion"},{inferred:e})}function Gd(e){return at(e)&&fe(e,"~kind")&&fe(e,"inferred")&&O(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function Te(e){return Pt({["~kind"]:"ExtendsTrue"},{inferred:e})}function Kd(e){return at(e)&&fe(e,"~kind")&&fe(e,"inferred")&&O(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ze(){return Pt({["~kind"]:"ExtendsFalse"},{})}function Hd(e){return at(e)&&fe(e,"~kind")&&O(e["~kind"],"ExtendsFalse")}function so(e){return Gd(e)||Kd(e)}function br(e,o,i){return so(e)?o(e.inferred):i()}function TN(e,o,i,u){return br(kt(e,i,u),(p)=>Te(dn(dn(e,p),{[o]:i})),()=>Ze())}function RN(e,o){return Te(e)}function kN(e,o,i,u,p){return br(kt(e,o,i),(g)=>br(kt(g,o,u),(y)=>Te(y),()=>Ze()),()=>br(kt(e,o,p),(g)=>Te(g),()=>Ze()))}function AN(e,o,i){let u=Zn(i);return kt(e,o,u)}function xS(e,o,i){return It(i,(u,p)=>br(kt(e,o,u),(g)=>xS(g,o,p),()=>Ze()),()=>Te(e))}function CN(e,o,i){let u=vn(i);return kt(e,o,u)}function IS(e,o,i){return It(i,(u,p)=>br(kt(e,o,u),(g)=>Te(g),()=>IS(e,o,p)),()=>Ze())}function Nt(e,o,i){return vr(i)?RN(e,o):Dr(i)?kN(e,o,i.if,i.then,i.else):on(i)?AN(e,o,i.enum):nn(i)?TN(e,i.name,o,i.extends):ze(i)?xS(e,o,i.allOf):ur(i)?CN(e,o,i.pattern):xe(i)?IS(e,o,i.anyOf):rn(i)?Te(e):Ze()}function bS(e,o,i){return nn(i)?Nt(e,o,i):vr(i)?Te(e):rn(i)?Te(e):Bd(e)}function PN(e,o){let i=Zi(e),u=Zi(o);return i&&u?!0:!i&&u?!0:i&&!u?!1:!0}function ES(e,o,i,u){return wt(u)?PN(o,u)?kt(e,i,u.items):Ze():Nt(e,o,u)}function SS(e,o,i){return mo(i)?Te(e):Nt(e,o,i)}function wS(e,o,i){return Wn(i)?Te(e):Nt(e,o,i)}function $N(e,o,i,u,p){let g=nn(u)?o:u,y=nn(u)?u:o,b=cn(o),E=cn(u);return!b&&E?Ze():br(kt(e,g,y),(S)=>Hu(S,i,p),()=>Ze())}function vN(e,o,i,u){return It(u,(p,g)=>$N(e,o,i,p,g),()=>cn(o)?Te(e):Ze())}function MN(e,o,i){return It(o,(u,p)=>vN(e,u,p,i),()=>Te(e))}function Hu(e,o,i){return MN(e,o,i)}function np(e,o,i){return po(i)?Te(e):kt(e,o,i)}function TS(e,o,i,u){return vr(u)?Te(e):rn(u)?Te(e):en(u)?br(Hu(e,o,u.parameters),(p)=>np(p,i,u.instanceType),()=>Ze()):Ze()}function RS(e,o,i,u,p){return br(kt(e,o,p),()=>kt(e,i,p),()=>kt(e,u,p))}function kS(e,o,i){let u=Zn(o);return kt(e,u,i)}function AS(e,o,i,u){return vr(u)?Te(e):rn(u)?Te(e):tn(u)?br(Hu(e,o,u.parameters),(p)=>np(p,i,u.returnType),()=>Ze()):Ze()}function CS(e,o,i){return fn(i)?Te(e):kr(i)?Te(e):Nt(e,o,i)}function PS(e,o,i){let u=Ar(o);return kt(e,u,i)}function op(e,o,i){return o===i?Te(e):Ze()}function ON(e,o,i){return yt(i)?op(e,o,i.const):mo(i)?Te(e):Nt(e,s(o),i)}function _N(e,o,i){return yt(i)?op(e,o,i.const):Wn(i)?Te(e):Nt(e,s(o),i)}function LN(e,o,i){return yt(i)?op(e,o,i.const):kr(i)?Te(e):Nt(e,s(o),i)}function NN(e,o,i){return yt(i)?op(e,o,i.const):sn(i)?Te(e):Nt(e,s(o),i)}function $S(e,o,i){return Nr(o.const)?ON(e,o.const,i):pn(o.const)?_N(e,o.const,i):Ot(o.const)?LN(e,o.const,i):gt(o.const)?NN(e,o.const,i):jr()}function vS(e,o,i){return nn(i)?Nt(e,o,i):Te(e)}function MS(e,o,i){return xs(i)?Te(e):Nt(e,o,i)}function OS(e,o,i){return kr(i)?Te(e):Nt(e,o,i)}function DN(e,o,i){return cn(o)?cn(i)?Te(e):Ze():Te(e)}function qN(e,o,i){return nn(i)&&co(i.extends)?Ze():br(kt(e,o,i),(u)=>DN(u,o,i),()=>Ze())}function FN(e,o){return e.reduce((i,u)=>(u in o)?so(o[u])?{...i,...o[u].inferred}:jr():jr(),{})}function jN(e,o,i){let u={};for(let y of we(i))u[y]=y in o?qN({},o[y],i[y]):cn(i[y])?nn(i[y])?Te(dn(e,{[i[y].name]:i[y].extends})):Te(e):Ze();let p=dd(u).every((y)=>so(y)),g=p?FN(we(u),u):{};return p?Te(g):Ze()}function UN(e,o,i){let u=jN(e,o,i);return so(u)?Te(dn(e,u.inferred)):Ze()}function BN(e,o,i){return UN(e,o,i)}function GN(e,o){return we(o).reduce((i,u)=>({...i,[u]:fe(e,u)?xe(i[u])?m([...i[u].anyOf,o[u]]):m([e[u],o[u]]):o[u]}),e)}function _S(e,o,i,u){return It(o,(p,g)=>br(kt({},e[p],i),(y)=>_S(e,g,i,GN(u,y)),()=>Ze()),()=>Te(u))}function KN(e,o,i,u){let p=we(o);return _S(o,p,u,e)}function LS(e,o,i){return Gt(i)?KN(e,o,hn(i),fr(i)):Qe(i)?BN(e,o,i.properties):Nt(e,l(o),i)}function HN(e,o){return O(we(o).length,0)?Te(e):Ze()}function WN(e,o,i,u,p){return kt(e,i,p)}function NS(e,o,i,u){return Gt(u)?WN(e,Rm(o),i,Rm(hn(u)),fr(u)):Qe(u)?HN(e,u.properties):vr(u)?Te(e):rn(u)?Te(e):Ze()}function DS(e,o,i){return sn(i)?Te(e):Nt(e,o,i)}function qS(e,o,i){return Is(i)?Te(e):Nt(e,o,i)}function FS(e,o,i){let u=vn(o);return kt(e,u,i)}function Wd(e,o){return Pt({"~kind":"Inferrable"},{name:e,type:o},{})}function Wu(e){return at(e)&&fe(e,"~kind")&&fe(e,"name")&&fe(e,"type")&&O(e["~kind"],"Inferrable")&>(e.name)&&at(e.type)}function zd(e){return oi(e)?nn(e.items)?wt(e.items.extends)?Wd(e.items.name,e.items.extends.items):rn(e.items.extends)?Wd(e.items.name,e.items.extends):void 0:jr():void 0}function sp(e){return nn(e)?Wd(e.name,e.extends):void 0}function Vd(e,o,i=[]){return It(e,(u,p)=>br(kt({},u,o),()=>Vd(p,o,[...i,u]),()=>{return}),()=>i)}function jS(e,o,i,u){let p=Vd(i,u);return Ge(p)?Te(dn(e,{[o]:Ur(p)})):Ze()}function ip(e,o,i,u){let p=Vd(i,u);return Ge(p)?Te(dn(e,{[o]:m(p)})):Ze()}function zN(e){return[...e].reverse()}function Jd(e,o){return o?zN(e):e}function VN(e){let o=e.length>0?e[0]:void 0,i=Pr(o)?zd(o):void 0;return Pr(i)}function JN(e,o,i,u,p,g){return br(kt(e,i,p),(y)=>US(y,o,u,g),()=>Ze())}function QN(e,o,i,u,p){let g=zd(u);return Wu(g)?jS(e,g.name,Jd(i,o),g.type):It(i,(y,b)=>JN(e,o,y,b,u,p),()=>Ze())}function XN(e,o,i,u){return It(u,(p,g)=>QN(e,o,i,p,g),()=>O(i.length,0)?Te(e):Ze())}function US(e,o,i,u){return XN(e,o,i,u)}function YN(e,o,i){let u=xi(e,hr([],[]),i),p=VN(u);return US(e,p,Jd(o,p),Jd(u,p))}function BS(e,o,i){let u=sp(i);return Wu(u)?ip(e,u.name,o,u.type):It(o,(p,g)=>br(kt(e,p,i),(y)=>BS(y,g,i),()=>Ze()),()=>Te(e))}function GS(e,o,i){let u=xi(e,hr([],[]),o);return mt(i)?YN(e,u,i.items):wt(i)?BS(e,u,i.items):Nt(e,Ur(u),i)}function KS(e,o,i){return po(i)?Te(e):Zo(i)?Te(e):Nt(e,o,i)}function HS(e,o,i){return It(i,(u,p)=>br(kt(e,o,u),(g)=>Te(g),()=>HS(e,o,p)),()=>Ze())}function Qd(e,o,i){return It(o,(u,p)=>br(HS(e,u,i),(g)=>Qd(g,p,i),()=>Ze()),()=>Te(e))}function WS(e,o,i){let u=sp(i);return Wu(u)?ip(e,u.name,o,u.type):xe(i)?Qd(e,o,i.anyOf):Qd(e,o,[i])}function zS(e,o,i){return nn(i)?Nt(e,o,i):vr(i)?Te(e):rn(i)?Te(e):Ze()}function VS(e,o,i){return po(i)?Te(e):Nt(e,o,i)}function kt(e,o,i){return vr(o)?bS(e,o,i):wt(o)?ES(e,o,o.items,i):mo(o)?SS(e,o,i):Wn(o)?wS(e,o,i):en(o)?TS(e,o.parameters,o.instanceType,i):Dr(o)?RS(e,o.if,o.then,o.else,i):on(o)?kS(e,o.enum,i):tn(o)?AS(e,o.parameters,o.returnType,i):fn(o)?CS(e,o,i):ze(o)?PS(e,o.allOf,i):yt(o)?$S(e,o,i):co(o)?vS(e,o,i):xs(o)?MS(e,o,i):kr(o)?OS(e,o,i):Qe(o)?LS(e,o.properties,i):Gt(o)?NS(e,hn(o),fr(o),i):sn(o)?DS(e,o,i):Is(o)?qS(e,o,i):ur(o)?FS(e,o.pattern,i):mt(o)?GS(e,o.items,i):Zo(o)?KS(e,o,i):xe(o)?WS(e,o.anyOf,i):rn(o)?zS(e,o,i):po(o)?VS(e,o,i):Ze()}function ZN(e,o){return Ar([...e,l(o)])}function Xd(e,o,i){return ct(e)?St(ZN(e,o),{},i):qu(e,o,i)}function JS(e,o,i,u,p){let g=yo(e,o,i),y=zu(e,o,u);return Xd(g,y,p)}function qu(e,o,i={}){return ve("Interface",[e,o],i)}function qa(e){return Pr(e)&&fe(e,"action")&&O(e.action,"Interface")}function QS(e,o,i={}){return Xd(e,o,i)}function eD(e,o,i){return e.includes(i)?!0:Vu([...e,i],o,o[i])}function XS(e,o,i){let u=um(i);return ia(e,o,u)}function ia(e,o,i){return It(i,(u,p)=>Vu(e,o,u)?!0:ia(e,o,p),()=>!1)}function Vu(e,o,i){return qt(i)?eD(e,o,i.$ref):wt(i)?Vu(e,o,i.items):en(i)?ia(e,o,[...i.parameters,i.instanceType]):tn(i)?ia(e,o,[...i.parameters,i.returnType]):qa(i)?XS(e,o,i.parameters[1]):ze(i)?ia(e,o,i.allOf):Qe(i)?XS(e,o,i.properties):xe(i)?ia(e,o,i.anyOf):mt(i)?ia(e,o,i.items):Gt(i)?Vu(e,o,fr(i)):!1}function YS(e,o,i){return Vu(e,o,i)}function tD(e,o){return o.reduce((i,u)=>YS([u],e,e[u])?[...i,u]:i,[])}function ZS(e){let o=am(e);return tD(e,o)}function rD(e,o,i){return i.includes(o)?i:(o in e)?Ju(e,e[o],[...i,o]):jr()}function ew(e,o,i){let u=um(o);return Fa(e,u,i)}function Fa(e,o,i){return o.reduce((u,p)=>Ju(e,p,u),i)}function Ju(e,o,i){return qt(o)?rD(e,o.$ref,i):wt(o)?Ju(e,o.items,i):en(o)?Fa(e,[...o.parameters,o.instanceType],i):tn(o)?Fa(e,[...o.parameters,o.returnType],i):qa(o)?ew(e,o.parameters[1],i):ze(o)?Fa(e,o.allOf,i):Qe(o)?ew(e,o.properties,i):xe(o)?Fa(e,o.anyOf,i):mt(o)?Fa(e,o.items,i):Gt(o)?Ju(e,fr(o),i):i}function tw(e,o,i){return Ju(e,i,[o])}function nD(e){return Ca()}function oD(e){return we(e).reduce((o,i)=>({...o,[i]:aa(e[i])}),{})}function Qu(e){return e.reduce((o,i)=>[...o,aa(i)],[])}function aa(e){return qt(e)?nD(e.$ref):wt(e)?B(aa(e.items),ka(e)):en(e)?ds(Qu(e.parameters),aa(e.instanceType)):tn(e)?fs(Qu(e.parameters),aa(e.returnType)):ze(e)?Pn(Qu(e.allOf)):Qe(e)?l(oD(e.properties)):Gt(e)?bs(ni(e),aa(fr(e))):xe(e)?m(Qu(e.anyOf)):mt(e)?Ur(Qu(e.items)):e}function sD(e,o){return o in e?aa(e[o]):Rr()}function rw(e){return sD(e.$defs,e.$ref)}function iD(e,o,i){let u=yo(e,hr([],[]),o),p=zu({},hr([],[]),i);return Ar([...u,l(p)])}function aD(e,o){return we(e).filter((u)=>o.includes(u)).reduce((u,p)=>{let g=e[p],y=qa(g)?iD(e,g.parameters[0],g.parameters[1]):g;return{...u,[p]:y}},{})}function nw(e,o,i){let u=tw(e,o,i),p=aD(e,u);return gs(p,o)}function ow(e,o){return o in e?qt(e[o])?ow(e,e[o].$ref):e[o]:zt()}function Es(e,o){return ow(e,o)}function sw(e){return Qt(e)?rw(e):cm(e)?Rr():e}function Tn(e,o,i){let u=sw(o),p=sw(i);return kt(e,u,p)}var Ou=0,Xu=1,_u=2,Lu=3;function Ma(e,o){let i=[Tn({},e,o),Tn({},o,e)];return so(i[0])&&so(i[1])?Ou:so(i[0])&&Hd(i[1])?_u:Hd(i[0])&&so(i[1])?Lu:Xu}function Yd(e,o,i=[],u=o){return It(o,(p,g)=>{let y=Ma(e,p);return O(y,_u)||O(y,Ou)?u:O(y,Xu)?Yd(e,g,[...i,p],u):Yd(e,g,i,u)},()=>[...i,e])}function uD(e,o,i){let u=Ao(e);return vr(u)?[u]:rn(u)?[u]:co(u)?ap(o,i):Qe(u)?ap(o,[...i,u]):ap(o,Yd(u,i))}function ap(e,o=[]){return It(e,(i,u)=>uD(i,u,o),()=>o)}function kd(e){let o=ap(e);return na(o)}function Zd(e,o){return St(Ao(e),{},o)}function iw(e,o,i,u){let p=ge(e,o,i);return Zd(p,u)}function Yu(e,o=[]){return Xs(e)&&O(e.action,"Conditional")?qt(e.parameters[0])?Yu(e.parameters[2],Yu(e.parameters[3],[...o,e.parameters[0].$ref])):Yu(e.parameters[2],Yu(e.parameters[3],o)):Xs(e)&&O(e.action,"Mapped")?Xs(e.parameters[1])&&O(e.parameters[1].action,"KeyOf")&&qt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function cD(e,o){return e.reduce((i,u)=>[...i,o.includes(u.name)],[])}function cw(e,o,i=[]){return It(e,(u,p)=>It(o,(g,y)=>cw(p,y,[...i,[g,u]]),()=>i),()=>i)}function mD(e){return ur(e)?vn(e.pattern):on(e)?Zn(e.enum):e}function pD(e){let o=mD(e);return xe(o)?[...o.anyOf]:[o]}function lD(e,o){return e.reduce((i,u)=>[...i,[...u,o]],[])}function aw(e,o){return o.reduce((i,u)=>[...i,...lD(e,u)],[])}function uw(e){return e.reduce((o,i)=>O(i[0],!0)?aw(o,pD(i[1])):aw(o,[i[1]]),[[]])}function mw(e,o,i){let u=Yu(i),p=cD(e,u),g=cw(o,p);return Xs(i)&&O(i.action,"Conditional")?uw(g):Xs(i)&&O(i.action,"Mapped")?uw(g):[o]}function dD(){return["(not-resolvable)",zt()]}function fD(){return["(not-generic)",zt()]}function hD(e,o,i){return[e,Ys(o,i)]}function gD(e,o,i){return o in e?pw(e,o,e[o],i):dD()}function pw(e,o,i,u){return Aa(i)?hD(o,i.parameters,i.expression):qt(i)?gD(e,i.$ref,u):fD()}function lw(e,o,i){return pw(e,"(anonymous)",o,i)}function yD(e,o,i){if(nn(o)||ja(o)||so(Tn({},o,i)))return;let u={parameter:e,expect:i,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function dw(e,o,i,u,p){let g=ge(e,o,p);return yD(i,g,u),dn(e,{[i]:g})}function xD(e,o,i,u,p){let g=ge(e,o,i.extends),y=ge(e,o,i.equals);return It(p,(b,E)=>ef(dw(e,o,i.name,g,b),o,u,E),()=>ef(dw(e,o,i.name,g,y),o,u,[]))}function ef(e,o,i,u){return It(i,(p,g)=>xD(e,o,p,g,u),()=>e)}function fw(e,o,i,u){return ef(e,o,i,u)}var tf=0,rf=0;function ID(){if(Su(rf,Jo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function bD(){ID(),rf++,tf++}function ED(){if(tf--,O(tf,0))rf=0}function SD(e){return Ki(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function wD(e,o){return O(SD(e),o)}function TD(e,o,i,u,p,g){bD();try{let y=fw(e,o,u,g),b=ge(y,hr([...o.callstack,i.$ref],o.visited),p);return ge(y,hr([],[]),b)}finally{ED()}}function RD(e,o,i,u,p,g){return g.reduce((y,b)=>{let E=TD(e,o,i,u,p,b);return[...y,E]},[])}function kD(e,o,i,u,p,g){let y=mw(u,g,p),b=RD(e,o,i,u,p,y);return O(b.length,1)?b[0]:oo(b)}function up(e,o,i,u){let p=yo(e,o,u),g=lw(e,i,u),y=g[0],b=g[1];return Aa(b)?wD(o,y)?Fu(un(y),p):kD(e,o,un(y),b.parameters,b.expression,p):Fu(i,p)}function Fu(e,o){return Pt({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function hw(e,o){return up({},hr([],[]),e,o)}function ja(e){return Ae(e,"Call")}function AD(e){return Qo(e,["~immutable"])}function gw(e,o){return St(AD(e),{},o)}function yw(e,o,i,u){let p=ge(e,o,i);return gw(p,u)}function xw(e,o){return e(o)}function Iw(e,o){return gt(o)?s(xw(e,o)):s(o)}function bw(e,o){let i=vn(o);return Os(e,i)}function Ew(e,o){let i=o.map((u)=>Os(e,u));return m(i)}function Os(e,o){return yt(o)?Iw(e,o.const):ur(o)?bw(e,o.pattern):xe(o)?Ew(e,o.anyOf):o}function $m(e,o={}){return ve("Capitalize",[e],o)}function Sw(e,o={}){return nf(e,o)}function vm(e,o={}){return ve("Lowercase",[e],o)}function ww(e,o={}){return of(e,o)}function Mm(e,o={}){return ve("Uncapitalize",[e],o)}function Tw(e,o={}){return sf(e,o)}function Om(e,o={}){return ve("Uppercase",[e],o)}function Rw(e,o={}){return af(e,o)}var CD=(e)=>e[0].toUpperCase()+e.slice(1),PD=(e)=>e.toLowerCase(),$D=(e)=>e[0].toLowerCase()+e.slice(1),vD=(e)=>e.toUpperCase();function nf(e,o){return ct([e])?St(Os(CD,e),{},o):$m(e,o)}function of(e,o){return ct([e])?St(Os(PD,e),{},o):vm(e,o)}function sf(e,o){return ct([e])?St(Os($D,e),{},o):Mm(e,o)}function af(e,o){return ct([e])?St(Os(vD,e),{},o):Om(e,o)}function kw(e,o,i,u){let p=ge(e,o,i);return nf(p,u)}function Aw(e,o,i,u){let p=ge(e,o,i);return of(p,u)}function Cw(e,o,i,u){let p=ge(e,o,i);return sf(p,u)}function Pw(e,o,i,u){let p=ge(e,o,i);return af(p,u)}function _m(e,o,i,u,p={}){return ve("Conditional",[e,o,i,u],p)}function $w(e,o,i,u,p={}){return uf({},hr([],[]),e,o,i,u,p)}function MD(e,o,i,u,p,g){let y=Tn(e,i,u);return Gd(y)?m([ge(y.inferred,o,p),ge(e,o,g)]):Kd(y)?ge(y.inferred,o,p):ge(e,o,g)}function uf(e,o,i,u,p,g,y){return ct([i,u])?St(MD(e,o,i,u,p,g),{},y):_m(i,u,p,g,y)}function vw(e,o,i,u,p,g,y){let b=ge(e,o,i),E=ge(e,o,u);return uf(e,o,b,E,p,g,y)}function Lm(e,o={}){return ve("ConstructorParameters",[e],o)}function Mw(e,o={}){return cf(e,o)}function OD(e){let o=en(e)?e.parameters:[],i=xi({},hr([],[]),o);return Ur(i)}function cf(e,o){return ct([e])?St(OD(e),{},o):Lm(e,o)}function Ow(e,o,i,u){let p=ge(e,o,i);return cf(p,u)}function Nm(e,o,i={}){return ve("Exclude",[e,o],i)}function _w(e,o,i={}){return Zu(e,o,i)}function Zu(e,o,i){return ct([e,o])?St(wm(e,o),{},i):Nm(e,o,i)}function Lw(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return Zu(g,y,p)}function Dm(e,o,i={}){return ve("Extract",[e,o],i)}function Nw(e,o,i={}){return mf(e,o,i)}function _D(e,o){let i=Tn({},e,o);return so(i)?[e]:[]}function Dw(e,o,i=[]){return It(e,(u,p)=>Dw(p,o,[...i,..._D(u,o)]),()=>i)}function qw(e,o){let i=Ao(e),u=xe(i)?i.anyOf:[i],p=Dw(u,o);return oo(p)}function mf(e,o,i){return ct([e,o])?St(qw(e,o),{},i):Dm(e,o,i)}function Fw(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return mf(g,y,p)}function LD(e){return e.reduce((o,i)=>hm(i)?[...o,s(i)]:o,[])}function Ua(e){let o=LD(e);return m(o)}function ju(e,o,i={}){return ve("Index",[e,o],i)}function jw(e,o,i={}){let u=Ge(o)?Ua(o):o;return pf(e,u,i)}function Uw(e,o){let i=Es(e,o);return xo(i)}function Bw(e,o,i){let u=Yo(e,o,i);return xo(u)}function ND(e,o){let i=we(e).filter((w)=>!fe(o,w)),u=we(o).filter((w)=>!fe(e,w)),p=we(e).filter((w)=>fe(o,w)),g=i.reduce((w,R)=>({...w,[R]:e[R]}),{}),y=u.reduce((w,R)=>({...w,[R]:o[R]}),{}),b=p.reduce((w,R)=>({...w,[R]:Ar([e[R],o[R]])}),{}),E=dn(g,y);return dn(E,b)}function Gw(e){return e.reduce((o,i)=>ND(o,xo(i)),{})}function Kw(e){return e}function Hw(e){let o=Ox(Ur(e));return xo(o)}function DD(e,o){return we(e).filter((p)=>(p in o)).reduce((p,g)=>({...p,[g]:oo([e[g],o[g]])}),{})}function Ww(e,o){return It(e,(i,u)=>Ww(u,DD(o,xo(i))),()=>o)}function zw(e){return It(e,(o,i)=>Ww(i,xo(o)),()=>jr())}function xo(e){return Qt(e)?Uw(e.$defs,e.$ref):Dr(e)?Bw(e.if,e.then,e.else):ze(e)?Gw(e.allOf):xe(e)?zw(e.anyOf):mt(e)?Hw(e.items):Qe(e)?Kw(e.properties):{}}function Ba(e){let o=xo(e);return l(o)}var qD=new RegExp("^(?:0|[1-9][0-9]*)$");function Ga(e){let o=`${e}`;return qD.test(o)?parseInt(o):e}function FD(e){return s(Ga(e))}function Vw(e){return e.map((o)=>Jw(o))}function Jw(e){return ze(e)?Pn(Vw(e.allOf)):xe(e)?m(Vw(e.anyOf)):yt(e)?FD(e.const):e}function Qw(e,o){let i=Jw(o),u=Tn({},i,Y());return so(u)?e:yt(o)&&O(o.const,"length")?Y():zt()}function Xw(e,o){let i=Es(e,o);return lo(i)}function Yw(e,o,i){let u=Yo(e,o,i);return lo(u)}function Zw(e){let o=Zn(e);return lo(o)}function eT(e){let o=Ar(e);return lo(o)}function tT(e){return[`${e}`]}function rT(e){let o=vn(e);return lo(o)}function nT(e){return e.reduce((o,i)=>[...o,...lo(i)],[])}function lo(e){return Qt(e)?Xw(e.$defs,e.$ref):Dr(e)?Yw(e.if,e.then,e.else):on(e)?Zw(e.enum):ze(e)?eT(e.allOf):yt(e)?tT(e.const):ur(e)?rT(e.pattern):xe(e)?nT(e.anyOf):[]}function Ka(e){return lo(e)}function ec(e,o){return o.map((i)=>tc(e,i))}function tc(e,o){return wt(o)?B(tc(e,o.items)):en(o)?ds(ec(e,o.parameters),tc(e,o.instanceType)):tn(o)?fs(ec(e,o.parameters),tc(e,o.returnType)):mt(o)?Ur(ec(e,o.items)):xe(o)?m(ec(e,o.anyOf)):ze(o)?Pn(ec(e,o.allOf)):Am(o)?l(e):o}function oT(e,o){return tc(e,o)}function jD(e,o){let i=o in e?e[o]:zt();return oT(e,i)}function sT(e,o){return o.reduce((i,u)=>[...i,jD(e,u)],[])}function UD(e,o){let i=Ka(o),u=sT(e,i);return oo(u)}var BD=new RegExp(ri);function GD(e){return e.filter((i)=>BD.test(i))}function KD(e){let o=am(e),i=GD(o),u=sT(e,i);return oo(u)}function iT(e,o){return kr(o)?KD(e):UD(e,o)}function HD(e){return s(Ga(e))}function aT(e){return e.map((o)=>lf(o))}function lf(e){return ze(e)?Pn(aT(e.allOf)):xe(e)?m(aT(e.anyOf)):yt(e)?HD(e.const):e}function WD(e,o){return e.reduceRight((i,u,p)=>{let g=Tn({},s(p),o);return so(g)?[u,...i]:i},[])}function zD(e,o){let i=lf(o),u=WD(e,i);return ei(u)}function VD(e){return ei(e)}function uT(e,o){return yt(o)&&O(o.const,"length")?s(e.length):kr(o)||fn(o)?VD(e):zD(e,o)}function cT(e,o){return wt(e)?Qw(e.items,o):Qe(e)?iT(e.properties,o):mt(e)?uT(e.items,o):zt()}function JD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function pf(e,o,i){return ct([e,o])?St(cT(JD(e),o),{},i):ju(e,o,i)}function mT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return pf(g,y,p)}function qm(e,o={}){return ve("InstanceType",[e],o)}function pT(e,o={}){return df(e,o)}function QD(e){return en(e)?e.instanceType:zt()}function df(e,o){return ct([e])?St(QD(e),{},o):qm(e,o)}function lT(e,o,i,u={}){let p=ge(e,o,i);return df(p,u)}function Uu(e,o={}){return ve("KeyOf",[e],o)}function dT(e,o={}){return ff(e,o)}function fT(){return m([Y(),a(),va()])}function hT(e){return Y()}function XD(e){return e.reduce((i,u)=>hm(u)?[...i,s(Ga(u))]:jr(),[])}function gT(e){let o=we(e),i=XD(o);return ei(i)}function yT(e){return ni(e)}function xT(e){let o=e.map((i,u)=>s(u));return ei(o)}function IT(e){return vr(e)?fT():wt(e)?hT(e.items):Qe(e)?gT(e.properties):Gt(e)?yT(e):mt(e)?xT(e.items):zt()}function YD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function ff(e,o){return ct([e])?St(IT(YD(e)),{},o):Uu(e,o)}function bT(e,o,i,u){let p=ge(e,o,i);return ff(p,u)}function Du(e,o,i,u,p={}){return ve("Mapped",[e,o,i,u],p)}function ET(e,o,i,u,p={}){return hf({},hr([],[]),e,o,i,u,p)}function ZD(e){let o=vn(e);return cp(o)}function eq(e){return e.reduce((o,i)=>[...o,...cp(i)],[])}function tq(e){let o=Zn(e);return cp(o)}function rq(e){return Ot(e)?[s(`${e}`)]:[s(e)]}function cp(e){return on(e)?tq(e.enum):yt(e)?rq(e.const):ur(e)?ZD(e.pattern):xe(e)?eq(e.anyOf):[e]}function ST(e){return cp(e)}function nq(e){return ur(e)?vn(e.pattern):e}function oq(e,o,i,u,p,g){let y=dn(e,{[i.name]:u}),b=ge(y,o,p),E=nq(b),S=ge(y,o,g);return gm(E)||ym(E)?{[E.const]:S}:{}}function sq(e,o,i,u,p,g){return u.reduce((y,b)=>[...y,oq(e,o,i,b,p,g)],[])}function iq(e){return e.reduce((o,i)=>[...o,l(i)],[])}function wT(e,o,i,u,p,g){let y=ST(u),b=sq(e,o,i,y,p,g),E=iq(b);return Ar(E)}function hf(e,o,i,u,p,g,y){return ct([u])?St(wT(e,o,i,u,p,g),{},y):Du(i,u,p,g,y)}function TT(e,o,i,u,p,g,y){let b=ge(e,o,u);return hf(e,o,i,b,p,g,y)}function aq(e,o,i){let u=dn(e,o);return we(o).filter((g)=>i.includes(g)).reduce((g,y)=>({...g,[y]:nw(u,y,o[y])}),{})}function uq(e,o,i){let u=dn(e,o);return we(o).filter((g)=>!i.includes(g)).reduce((g,y)=>({...g,[y]:ge(u,hr([],[]),o[y])}),{})}function cq(e,o,i){let u=ZS(o),p=aq(e,o,u),g=uq(e,o,u),y={...p,...g};return St(y,{},i)}function mp(e,o,i,u){return cq(e,i,u)}function Fm(e,o={}){return ve("NonNullable",[e],o)}function RT(e,o={}){return gf(e,o)}function mq(e){let o=m([$n(),_a()]);return Zu(e,o,{})}function gf(e,o){return ct([e])?St(mq(e),{},o):Fm(e,o)}function kT(e,o,i,u){let p=ge(e,o,i);return gf(p,u)}function jm(e,o,i={}){return ve("Omit",[e,o],i)}function AT(e,o,i={}){let u=Ge(o)?Ua(o):o;return yf(e,u,i)}function pp(e){let o=Ba(e);return Qe(o)?o.properties:jr()}function pq(e,o){return we(e).reduce((u,p)=>o.includes(p)?u:{...u,[p]:e[p]},{})}function CT(e,o){let i=pp(e),u=Ka(o),p=pq(i,u);return l(p)}function yf(e,o,i){return ct([e,o])?St(CT(e,o),{},i):jm(e,o,i)}function PT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return yf(g,y,p)}function Um(e,o={}){return ve("Parameters",[e],o)}function $T(e,o={}){return xf(e,o)}function lq(e){let o=tn(e)?e.parameters:[],i=xi({},hr([],[]),o);return Ur(i)}function xf(e,o){return ct([e])?St(lq(e),{},o):Um(e,o)}function vT(e,o,i,u){let p=ge(e,o,i);return xf(p,u)}function Bm(e,o={}){return ve("Partial",[e],o)}function MT(e,o={}){return If(e,o)}function OT(e,o){let i=Es(e,o),u=Ss(i);return gs(dn(e,{[o]:u}),o)}function _T(e,o,i){let u=Yo(e,o,i);return Ss(u)}function LT(e){let o=Ar(e);return Ss(o)}function NT(e){let o=e.map((i)=>Ss(i));return m(o)}function DT(e){let o=we(e).reduce((u,p)=>({...u,[p]:Qi(e[p])}),{});return l(o)}function Ss(e){return Qt(e)?OT(e.$defs,e.$ref):Dr(e)?_T(e.if,e.then,e.else):ze(e)?LT(e.allOf):xe(e)?NT(e.anyOf):Qe(e)?DT(e.properties):l({})}function If(e,o){return ct([e])?St(Ss(e),{},o):Bm(e,o)}function qT(e,o,i,u){let p=ge(e,o,i);return If(p,u)}function Gm(e,o,i={}){return ve("Pick",[e,o],i)}function FT(e,o,i={}){let u=Ge(o)?Ua(o):o;return bf(e,u,i)}function dq(e,o){return we(e).reduce((u,p)=>o.includes(p)?dn(u,{[p]:e[p]}):u,{})}function jT(e,o){let i=pp(e),u=Ka(o),p=dq(i,u);return l(p)}function bf(e,o,i){return ct([e,o])?St(jT(e,o),{},i):Gm(e,o,i)}function UT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return bf(g,y,p)}function Km(e,o={}){return ve("ReadonlyObject",[e],o)}function Ef(e,o={}){return Sf(e,o)}var BT=Ef;function GT(e){return $a(B(e))}function KT(e,o){let i=Es(e,o),u=ws(i);return gs(dn(e,{[o]:u}),o)}function HT(e,o,i){let u=Yo(e,o,i);return ws(u)}function WT(e){let o=Ar(e);return ws(o)}function zT(e){let o=we(e).reduce((u,p)=>({...u,[p]:ea(e[p])}),{});return l(o)}function VT(e){return $a(Ur(e))}function JT(e){let o=e.map((i)=>ws(i));return m(o)}function ws(e){return wt(e)?GT(e.items):Qt(e)?KT(e.$defs,e.$ref):Dr(e)?HT(e.if,e.then,e.else):ze(e)?WT(e.allOf):Qe(e)?zT(e.properties):mt(e)?VT(e.items):xe(e)?JT(e.anyOf):e}function Sf(e,o){return ct([e])?St(ws(e),{},o):Km(e)}function QT(e,o,i,u){let p=ge(e,o,i);return Sf(p,u)}function XT(e,o,i,u){return o.visited.includes(u)?i:(u in e)?ge(e,hr(o.callstack,[...o.visited,u]),e[u]):i}function YT(e,o){let i=Es(e,o),u=Ts(i);return gs(dn(e,{[o]:u}),o)}function ZT(e,o,i){let u=Yo(e,o,i);return Ts(u)}function eR(e){let o=Ar(e);return Ts(o)}function tR(e){let o=e.map((i)=>Ts(i));return m(o)}function rR(e){let o=we(e).reduce((u,p)=>({...u,[p]:Sm(e[p])}),{});return l(o)}function Ts(e){return Qt(e)?YT(e.$defs,e.$ref):Dr(e)?ZT(e.if,e.then,e.else):ze(e)?eR(e.allOf):xe(e)?tR(e.anyOf):Qe(e)?rR(e.properties):l({})}function Hm(e,o={}){return ve("Required",[e],o)}function nR(e,o={}){return wf(e,o)}function wf(e,o){return ct([e])?St(Ts(e),{},o):Hm(e,o)}function oR(e,o,i,u){let p=ge(e,o,i);return wf(p,u)}function Wm(e,o={}){return ve("ReturnType",[e],o)}function sR(e,o={}){return Tf(e,o)}function fq(e){return tn(e)?e.returnType:zt()}function Tf(e,o){return ct([e])?St(fq(e),{},o):Wm(e,o)}function iR(e,o,i,u={}){let p=ge(e,o,i);return Tf(p,u)}function zm(e,o){return ve("With",[e,o],{})}function lp(e,o){return Rf(e,o)}function Rf(e,o){return ct([e])?St(e,{},o):zm(e,o)}function aR(e,o,i,u){let p=ge(e,o,i);return Rf(p,u)}function hq(e){return oi(e)?mt(e.items)?kf(e.items.items):nn(e.items)?[e]:qt(e.items)?[e]:[zt()]:[e]}function kf(e){return e.reduce((i,u)=>[...i,...hq(u)],[])}function hr(e,o){return{callstack:e,visited:o}}function ct(e){return It(e,(o,i)=>qt(o)?!1:ct(i),()=>!0)}function zu(e,o,i){return we(i).reduce((u,p)=>({...u,[p]:ge(e,o,i[p])}),{})}function xi(e,o,i){let u=yo(e,o,i);return kf(u)}function yo(e,o,i){return i.map((u)=>ge(e,o,u))}function gq(e,o){let i=cn(e)?Au(o,{}):o,u=ta(e)?ku(i,{}):i;return Zi(e)?rc(u,{}):u}function yq(e,o,i,u,p){return O(i,"AddImmutable")?uR(e,o,u[0],p):O(i,"RemoveImmutable")?yw(e,o,u[0],p):O(i,"AddReadonly")?Ly(e,o,u[0],p):O(i,"RemoveReadonly")?Cx(e,o,u[0],p):O(i,"AddOptional")?Ny(e,o,u[0],p):O(i,"RemoveOptional")?vx(e,o,u[0],p):O(i,"Capitalize")?kw(e,o,u[0],p):O(i,"Conditional")?vw(e,o,u[0],u[1],u[2],u[3],p):O(i,"ConstructorParameters")?Ow(e,o,u[0],p):O(i,"Evaluate")?iw(e,o,u[0],p):O(i,"Exclude")?Lw(e,o,u[0],u[1],p):O(i,"Extract")?Fw(e,o,u[0],u[1],p):O(i,"Index")?mT(e,o,u[0],u[1],p):O(i,"InstanceType")?lT(e,o,u[0],p):O(i,"Interface")?JS(e,o,u[0],u[1],p):O(i,"KeyOf")?bT(e,o,u[0],p):O(i,"Lowercase")?Aw(e,o,u[0],p):O(i,"Mapped")?TT(e,o,u[0],u[1],u[2],u[3],p):O(i,"Module")?mp(e,o,u[0],p):O(i,"NonNullable")?kT(e,o,u[0],p):O(i,"Pick")?UT(e,o,u[0],u[1],p):O(i,"Parameters")?vT(e,o,u[0],p):O(i,"Partial")?qT(e,o,u[0],p):O(i,"Omit")?PT(e,o,u[0],u[1],p):O(i,"ReadonlyObject")?QT(e,o,u[0],p):O(i,"Record")?Vx(e,o,u[0],u[1],p):O(i,"Required")?oR(e,o,u[0],p):O(i,"ReturnType")?iR(e,o,u[0],p):O(i,"TemplateLiteral")?hS(e,o,u[0],p):O(i,"Uncapitalize")?Cw(e,o,u[0],p):O(i,"Uppercase")?Pw(e,o,u[0],p):O(i,"With")?aR(e,o,u[0],u[1]):ve(i,u,p)}function xq(e,o,i){let u=qt(i)?XT(e,o,i,i.$ref):wt(i)?B(ge(e,o,i.items),ka(i)):ja(i)?up(e,o,i.target,i.arguments):en(i)?ds(yo(e,o,i.parameters),ge(e,o,i.instanceType),Dy(i)):tn(i)?fs(yo(e,o,i.parameters),ge(e,o,i.returnType),qy(i)):Dr(i)?Xi(ge(e,o,i.if),ge(e,o,i.then),ge(e,o,i.else),By(i)):ze(i)?Pn(yo(e,o,i.allOf),zy(i)):Qe(i)?l(zu(e,o,i.properties),Uy(i)):Gt(i)?Jx(hn(i),ge(e,o,fr(i))):oi(i)?oa(ge(e,o,i.items)):mt(i)?Ur(xi(e,o,i.items),Ax(i)):xe(i)?m(yo(e,o,i.anyOf),yx(i)):i;return gq(i,u)}function ge(e,o,i){return Xs(i)?yq(e,o,i.action,i.parameters,i.options):xq(e,o,i)}function Co(e,o){return ge(e,hr([],[]),o)}function Iq(e){return St(e,{"~immutable":!0},{})}function rc(e,o){return St(Iq(e),{},o)}function uR(e,o,i,u){let p=ge(e,o,i);return rc(p,u)}function pE(e,o={}){return ve("AddImmutable",[e],o)}function $a(e,o={}){return rc(e,o)}function lE(e,o={}){return ve("Evaluate",[e],o)}function Rn(e,o={}){return Zd(e,o)}function dE(e,o={}){return ve("Module",[e],o)}function cR(e,o={}){return mp({},hr([],[]),e,o)}function bq(e,o){let i=Ma(e,o);return O(i,Lu)?1:O(i,Xu)?1:0}function mR(e,o,i=[]){return It(o,(u,p)=>O(bq(e,u),1)?mR(e,p,[...i,u]):[...i,e,...o],()=>[...i,e])}function pR(e,o=[]){return It(e,(i,u)=>pR(u,mR(i,o)),()=>o)}function lR(e){return pR(e)}function dR(...e){let[o,i,u]=wn(e,{2:(y,b)=>gt(y)?[{},y,b]:[y,b,{}],3:(y,b,E)=>[y,b,E],1:(y)=>[{},y,{}]}),p=mS(i),g=Ge(p)&&O(p.length,2)?ge(o,hr([],[]),p[0]):zt();return St(g,{},u)}function h(e,o){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let u=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:u}},resolve:async({ctx:i,credential:u,signal:p})=>{if(p.throwIfAborted(),u?.key)return{auth:{apiKey:u.key},env:u.env,source:"stored credential"};for(let g of o){let y=await i.env(g);if(p.throwIfAborted(),y)return{auth:{apiKey:y},source:g}}return}}}function ce(e){let o,i=()=>(o??=e.load(),o);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(u,p)=>(await i()).login(u,p),refresh:async(u,p)=>(await i()).refresh(u,p),toAuth:async(u)=>(await i()).toAuth(u)}}var yR="faux",xR="faux",IR="faux-1",Eq="Faux Model",Sq="http://localhost:0",wq=3,fR=5,hp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function On(e){return{type:"text",text:e}}function Oo(e){return{type:"thinking",thinking:e}}function Tq(e,o,i={}){return{type:"toolCall",id:i.id??Pf("tool"),name:e,arguments:o}}function Rq(e){if(typeof e==="string")return[On(e)];return Array.isArray(e)?e:[e]}function No(e,o={}){return{role:"assistant",content:Rq(e),api:yR,provider:xR,model:IR,usage:hp,stopReason:o.stopReason??"stop",...o.deferred===void 0?{}:{deferred:o.deferred},...o.errorMessage===void 0?{}:{errorMessage:o.errorMessage},...o.responseId===void 0?{}:{responseId:o.responseId},timestamp:o.timestamp??Date.now()}}function bR(e){return Math.ceil(e.length/4)}function Pf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function ER(e){if(typeof e==="string")return e;return e.map((o)=>{if(o.type==="text")return o.text;return`[image:${o.mimeType}:${o.data.length}]`}).join(`
|
|
23
|
-
`)}function SR(e){return e.map((o)=>{if(o.type==="text")return o.text;if(o.type==="thinking")return o.thinking;return`${o.name}:${JSON.stringify(o.arguments)}`}).join(`
|
|
24
|
-
`)}function kq(e){return[e.toolName,...e.content.map((o)=>ER([o]))].join(`
|
|
25
|
-
`)}function Aq(e){if(e.role==="system")return[U(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
|
|
26
|
-
`);if(e.role==="user")return ER(e.content);if(e.role==="assistant")return SR(e.content);return kq(e)}function wR(e,o=e.length){let i=o>0?(o-1)*2:0;for(let u=0;u<o;u++)i+=e[u].length;return i}function Cq(e,o){let i=0;while(i<e.length&&i<o.length&&e[i]===o[i])i++;let u=(p)=>i===p.length?"":(i>0?`
|
|
27
|
-
|
|
28
|
-
`:"")+p.slice(i).join(`
|
|
29
|
-
|
|
30
|
-
`);return wR(e,i)+Pq(u(e),u(o))}function Pq(e,o){let i=Math.min(e.length,o.length),u=0;while(u<i&&e[u]===o[u])u++;return u}function hR(e,o,i,u){let p=o.messages.map((k)=>`${k.role}:${Aq(k)}`),g=wR(p),y=Math.ceil(g/4),b=bR(SR(e.content)),E=y,S=0,w=0,R=i?.sessionId;if(R&&i?.cacheRetention!=="none"){let k=u.get(R);if(k){let A=Cq(k,p);S=Math.ceil(A/4),w=Math.ceil((g-A)/4),E=Math.max(0,y-S)}else w=y;u.set(R,p)}return{...e,usage:{input:E,output:b,cacheRead:S,cacheWrite:w,totalTokens:E+b+S+w,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function Af(e,o,i){let u=[],p=0;while(p<e.length){let g=o+Math.floor(Math.random()*(i-o+1)),y=Math.max(1,g*4);u.push(e.slice(p,p+y)),p+=y}return u.length>0?u:[""]}function $q(e,o,i,u){let p=structuredClone(e);return{...p,api:o,provider:i,model:u,timestamp:p.timestamp??Date.now(),usage:p.usage??hp}}function gR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:hp,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function dp(e,o,i,u){return{role:"assistant",content:[],api:o,provider:i,model:u,usage:hp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function nc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Cf(e,o){if(!o||o<=0)return new Promise((u)=>queueMicrotask(u));let i=bR(e)/o*1000;return new Promise((u)=>setTimeout(u,i))}async function fp(e,o,i,u,p,g){let y={...o,content:[],stopReason:"pending"};if(g?.aborted){let b=nc(y);e.push({type:"error",reason:"aborted",error:b}),e.end(b);return}e.push({type:"start",partial:{...y}});for(let b=0;b<o.content.length;b++){if(g?.aborted){let S=nc(y);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}let E=o.content[b];if(E.type==="thinking"){y.content=[...y.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:b,partial:{...y}});for(let S of Af(E.thinking,i,u)){if(await Cf(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].thinking+=S,e.push({type:"thinking_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"thinking_end",contentIndex:b,content:E.thinking,partial:{...y}});continue}if(E.type==="text"){y.content=[...y.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:b,partial:{...y}});for(let S of Af(E.text,i,u)){if(await Cf(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].text+=S,e.push({type:"text_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"text_end",contentIndex:b,content:E.text,partial:{...y}});continue}y.content=[...y.content,{type:"toolCall",id:E.id,name:E.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:b,partial:{...y}});for(let S of Af(JSON.stringify(E.arguments),i,u)){if(await Cf(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}e.push({type:"toolcall_delta",contentIndex:b,delta:S,partial:{...y}})}y.content[b].arguments=E.arguments,e.push({type:"toolcall_end",contentIndex:b,toolCall:E,partial:{...y}})}if(o.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(o.stopReason==="error"||o.stopReason==="aborted"){e.push({type:"error",reason:o.stopReason,error:o}),e.end(o);return}e.push({type:"done",reason:o.stopReason,message:o}),e.end(o)}function TR(e){let o=e.api??Pf(yR),i=e.provider??xR,u=Math.max(1,Math.min(e.tokenSize?.min??wq,e.tokenSize?.max??fR)),p=Math.max(u,e.tokenSize?.max??fR),g=[],y=e.tokensPerSecond,b={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},E=new Map,S=new Map,R=((e.models?.length)?e.models:[{id:IR,name:Eq,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((V)=>({id:V.id,name:V.name??V.id,api:o,provider:i,baseUrl:Sq,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),k=async(V,J,ee,pe)=>{let H=typeof V==="function"?await V(J,ee,b,pe):V;return hR($q(H,o,i,pe.id),J,ee,E)},A=(V,J,ee)=>{let pe=Jn(),H=g.shift();return b.callCount++,queueMicrotask(async()=>{try{if(await ee?.onResponse?.({status:200,headers:{}},V),!H){let he=dp(Error("No more faux responses queued"),o,i,V.id);he=hR(he,J,ee,E),pe.push({type:"error",reason:"error",error:he}),pe.end(he);return}if(ee?.deferred){let he={provider:V.provider,modelId:V.id,api:V.api,id:Pf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};S.set(he.id,{handle:he,step:H,context:J,options:ee,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await fp(pe,gR(V,he),u,p,y,ee.signal);return}let le=await k(H,J,ee,V);await fp(pe,le,u,p,y,ee?.signal)}catch(le){let he=dp(le,o,i,V.id);pe.push({type:"error",reason:"error",error:he}),pe.end(he)}}),pe},C=(V,J,ee)=>A(V,J,ee),q=(V,J,ee)=>{let pe=Jn();return b.deferredFetchCount++,queueMicrotask(async()=>{try{await ee?.onResponse?.({status:200,headers:{}},V);let H=S.get(J.id);if(!H||H.handle.provider!==J.provider||H.handle.modelId!==J.modelId||H.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(H.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(H.pendingFetches>0){H.pendingFetches--,await fp(pe,gR(V,H.handle),u,p,y,ee?.signal);return}if(!H.final){let{deferred:le,signal:he,onResponse:$e,...Ee}=H.options??{};try{H.final=await k(H.step,H.context,Ee,H.model)}catch(ae){H.final=dp(ae,o,i,H.model.id)}}await fp(pe,H.final,u,p,y,ee?.signal)}catch(H){let le=dp(H,o,i,V.id);pe.push({type:"error",reason:"error",error:le}),pe.end(le)}}),pe},X=async(V,J,ee)=>{b.cancelledDeferred.push(structuredClone(J));let pe=S.get(J.id);if(pe)pe.cancelled=!0;await ee?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return R[0];return R.find((J)=>J.id===V)}return{api:o,provider:i,models:R,stream:A,streamSimple:C,fetchDeferred:q,cancelDeferred:X,getModel:j,state:b,setResponses(V){g=[...V]},appendResponses(V){g.push(...V)},getPendingResponseCount(){return g.length}}}function Do(e={}){let o=TR(e);return{provider:d({id:o.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:o.models,api:{stream:o.stream,streamSimple:o.streamSimple,fetchDeferred:o.fetchDeferred,cancelDeferred:o.cancelDeferred}}),api:o.api,models:o.models,getModel:o.getModel,state:o.state,setResponses:o.setResponses,appendResponses:o.appendResponses,getPendingResponseCount:o.getPendingResponseCount}}function vq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function Mq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Oq(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 _q(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 oc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Ha(e){oc(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 vf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var Lq=vf(W(""));function Mf(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)=>Mf(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 i=o;return Object.entries(e).every(([u,p])=>Object.hasOwn(i,u)&&Mf(p,i[u]))}class RR{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:_q(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=Ha(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:vq(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Ha(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=Ha(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:Mq(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Ha(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=Ha(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let i=vf(o.arguments),u=i===Lq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Oq(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 i=W(o.catchupJson);if(vf(i)!==o.snapshotArguments){let p=W(o.snapshotArguments);if(!Mf(p,i))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=Ha(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(oc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){oc(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(i.kind!==o)throw Error(`Assistant message block ${e} is ${i.kind}, not ${o}`);return i}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,i){let u=this.block(e,i);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let p=u.deltaChars;u.deltaChars+=o.length;let g=Math.max(0,u.coveredChars-p);if(g>=o.length)return;let y=g===0?o:o.slice(g);return i==="text"?{type:"text_delta",contentIndex:e,delta:y}:{type:"thinking_delta",contentIndex:e,delta:y}}}function $f(e,o,i,u,p){if(oc(i),i!==e.content.length){let g=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${g}`)}e.content.push(structuredClone(u)),o.set(i,p)}function ua(e,o,i,u,p){oc(i);let g=o.get(i),y=e.content[i];if(!g||!y)throw Error(`${p} frame has no started block at index ${i}`);if(g.kind!==u||y.type!==u)throw Error(`${p} frame expected ${u} block at index ${i}, found ${y.type}`);if(g.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:y,state:g}}function Nq(e){let o,i,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(i!==void 0)throw Error(`${i} frame appears before the start frame`);o=structuredClone(p.partial);continue}if(!o){i??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);$f(o,u,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:g}=ua(o,u,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");g.text+=p.delta;break}case"text_end":{let{block:g,state:y}=ua(o,u,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");if(g.text=p.content,delete g.textSignature,p.textSignature!==void 0)g.textSignature=p.textSignature;y.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);$f(o,u,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:g}=ua(o,u,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");g.thinking+=p.delta;break}case"thinking_end":{let{block:g,state:y}=ua(o,u,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");if(g.thinking=p.content,delete g.thinkingSignature,delete g.redacted,p.thinkingSignature!==void 0)g.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)g.redacted=p.redacted;y.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);$f(o,u,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:g,state:y}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");y.json=p.json,g.arguments=W(p.json);break}case"toolcall_delta":{let{block:g,state:y}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call frame state");y.json+=p.delta;break}case"toolcall_end":{let{block:g,state:y}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(g.id=p.id,g.name=p.name,g.arguments=structuredClone(p.arguments),delete g.thoughtSignature,delete g.namespace,p.thoughtSignature!==void 0)g.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)g.namespace=p.namespace;y.ended=!0;break}}}if(!o)return;for(let[p,g]of u){if(g.kind!=="toolCall"||g.ended||g.json.length===0)continue;let y=o.content[p];if(y?.type!=="toolCall")throw Error("Unreachable tool-call frame state");y.arguments=W(g.json)}return o}var kR=[/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],Dq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,qq=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ca(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!qq.some((u)=>u.test(e.errorMessage))){if(kR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&Dq.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 Fq(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function jq(){return[...kR]}function AR(e){return new RegExp(e.join("|"),"i")}var Uq=AR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),Bq=AR(["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"]),CR=60000;function PR(e,o){let i=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??CR)}class gp extends Error{constructor(){super("Aborted")}}function Gq(e,o){return new Promise((i,u)=>{if(o?.aborted){u(new gp);return}let p=setTimeout(i,e);o?.addEventListener("abort",()=>{clearTimeout(p),u(new gp)},{once:!0})})}async function Kq(e,o,i,u){let p=o?.enabled?o.maxRetries:0,g=0,y;for(;;){let b=await e();if(b.stopReason==="aborted"){if(y)await u?.onRetryFinished?.(!1,y.attempt);return b}if(b.stopReason!=="error"){if(y)await u?.onRetryFinished?.(!0,y.attempt);return b}if(g>=p||!$R(b)){if(y)await u?.onRetryFinished?.(!1,y.attempt,b.errorMessage);return b}g++,y={attempt:g,errorMessage:b.errorMessage||"Unknown error"};let E=PR(o,g);await u?.onRetryScheduled?.(g,p,E,y.errorMessage);try{await Gq(E,i)}catch(S){if(await u?.onRetryFinished?.(!1,g,y.errorMessage),S instanceof gp){let{errorMessage:w,...R}=b;return{...R,stopReason:"aborted"}}throw S}await u?.onRetryAttemptStart?.()}}function $R(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(Uq.test(o))return!1;return Bq.test(o)}function Hq(e,o){return qr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function sc(e){return fe(e,"~refine")&&Ge(e["~refine"])&&an(e["~refine"],0,(o)=>at(o)&&fe(o,"check")&&fe(o,"error")&&ms(o.check)&&ms(o.error))}function gn(e){return at(e)&&!Ge(e)}function _s(e){return pn(e)}function Ye(e){return gn(e)||_s(e)}function Wa(e){return fe(e,"additionalItems")&&Ye(e.additionalItems)}function Po(e){return fe(e,"additionalProperties")&&Ye(e.additionalProperties)}function ic(e){return fe(e,"allOf")&&Ge(e.allOf)&&e.allOf.every((o)=>Ye(o))}function ac(e){return fe(e,"$anchor")&>(e.$anchor)}function uc(e){return fe(e,"anyOf")&&Ge(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function yp(e){return fe(e,"const")}function Rs(e){return fe(e,"contains")&&Ye(e.contains)}function bo(e){return fe(e,"default")}function cc(e){return fe(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||Ge(o)&&o.every((i)=>gt(i)))}function mc(e){return fe(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Ge(o)&&o.every((i)=>gt(i)))}function za(e){return fe(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function Ls(e){return fe(e,"$dynamicAnchor")&>(e.$dynamicAnchor)}function pc(e){return fe(e,"$dynamicRef")&>(e.$dynamicRef)}function lc(e){return fe(e,"else")&&Ye(e.else)}function xp(e){return fe(e,"enum")&&Ge(e.enum)}function dc(e){return fe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||Nr(e.exclusiveMaximum))}function es(e){return fe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||Nr(e.exclusiveMinimum))}function ma(e){return fe(e,"format")&>(e.format)}function Eo(e){return fe(e,"$id")&>(e.$id)}function fc(e){return fe(e,"if")&&Ye(e.if)}function Ns(e){return fe(e,"items")&&(Ye(e.items)||Ge(e.items)&&e.items.every((o)=>Ye(o)))}function hc(e){return Ns(e)&&Ge(e.items)}function gc(e){return fe(e,"maximum")&&(Ot(e.maximum)||Nr(e.maximum))}function yc(e){return fe(e,"maxContains")&&Ot(e.maxContains)}function Va(e){return fe(e,"maxItems")&&Ot(e.maxItems)}function xc(e){return fe(e,"maxLength")&&Ot(e.maxLength)}function Ic(e){return fe(e,"maxProperties")&&Ot(e.maxProperties)}function ts(e){return fe(e,"minimum")&&(Ot(e.minimum)||Nr(e.minimum))}function Ds(e){return fe(e,"minContains")&&Ot(e.minContains)}function Ei(e){return fe(e,"minItems")&&Ot(e.minItems)}function pa(e){return fe(e,"minLength")&&Ot(e.minLength)}function la(e){return fe(e,"minProperties")&&Ot(e.minProperties)}function bc(e){return fe(e,"multipleOf")&&(Ot(e.multipleOf)||Nr(e.multipleOf))}function Ec(e){return fe(e,"not")&&Ye(e.not)}function Sc(e){return fe(e,"oneOf")&&Ge(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function da(e){return fe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function qs(e){return fe(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function rs(e){return fe(e,"prefixItems")&&Ge(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function Fs(e){return fe(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function Ja(e){return fe(e,"propertyNames")&&(at(e.propertyNames)||Ye(e.propertyNames))}function Wq(e){return fe(e,"$recursiveAnchor")&&pn(e.$recursiveAnchor)}function wc(e){return Wq(e)&&O(e.$recursiveAnchor,!0)}function Tc(e){return fe(e,"$recursiveRef")&>(e.$recursiveRef)}function Rc(e){return fe(e,"$ref")&>(e.$ref)}function ns(e){return fe(e,"required")&&Ge(e.required)&&e.required.every((o)=>gt(o))}function kc(e){return fe(e,"then")&&Ye(e.then)}function Ac(e){return fe(e,"type")&&(gt(e.type)||Ge(e.type)&&e.type.every((o)=>gt(o)))}function Ti(e){return fe(e,"uniqueItems")&&pn(e.uniqueItems)}function Ri(e){return fe(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function ki(e){return fe(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function zq(e){return Ri(e)||ki(e)||wa(we(e),(o)=>Ip(e[o]))}function Vq(e){return wa(e,(o)=>Ip(o))}function Ip(e){return Ge(e)?Vq(e):at(e)?zq(e):!1}function vR(e,o){return Ip(o)||wa(we(e),(i)=>Ip(e[i]))}class Of{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ir(bt("context","Push"),[])}Pop(){return Ir(bt("context","Pop"),[])}AddIndex(e){return Ir(bt("context","AddIndex"),[e])}AddKey(e){return Ir(bt("context","AddKey"),[e])}Merge(e){return Ir(bt("context","Merge"),[e])}}class _n{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((i)=>this.GetIndices().add(i)),o.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class qn extends _n{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Jo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var bp={identifier:"External",variables:[]};function vo(e){let o=`External[${bp.variables.length}]`;return bp.variables.push(e),o}function MR(){bp.variables=[]}function OR(){return{...bp}}function _R(e,o,i,u){let p=vo(i["~refine"].map((g)=>g));return ls(p,De(0),["refinement","_"],Ir(bt("refinement","check"),[u]))}function LR(e,o,i,u){return an(i["~refine"],0,(p,g)=>p.check(u))}function NR(e,o,i,u,p,g){return An(p["~refine"],0,(y,b)=>y.check(g)||o.AddError({keyword:"~refine",schemaPath:i,instancePath:u,params:{index:b,message:y.error(g)}}))}var Jq=0;function Vt(){return`var_${Jq++}`}function _f(e){return Ns(e)&&Ge(e.items)}function Qq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=hd(g,De(i.items.length)),E=o.AddIndex(g);return ls(u,De(0),[p,g],xr(b,Sn(y,E)))}function Xq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=hd(g,De(i.items.length));return ls(u,De(0),[p,g],xr(b,y))}function DR(e,o,i,u){if(!_f(i))return De(!0);return o.UseUnevaluated()?Qq(e,o,i,u):Xq(e,o,i,u)}function qR(e,o,i,u){if(!_f(i))return!0;return an(u,0,(g,y)=>Su(y,i.items.length)||So(e,o,i.additionalItems,g)&&o.AddIndex(y))}function FR(e,o,i,u,p,g){if(!_f(p))return!0;return an(g,0,(b,E)=>{let S=`${i}/additionalItems`,w=`${u}/${E}`;return Su(E,p.items.length)||wo(e,o,S,w,p.additionalItems,b)&&o.AddIndex(E)})}function os(e){return new RegExp(e,"u")}function Yq(e,o){return!e.UseUnevaluated()&&(O(o,!0)||at(o)&&O(we(o).length,0))}function Zq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Lf(e){let o=[];if(qs(e))o.push(...we(e.patternProperties));if(Fs(e))o.push(...we(e.properties).map(Zq));return O(o.length,0)?"(?!)":`(${o.join("|")})`}function eF(e,o,i){return ns(o)&&Fs(o)&&!qs(o)&&O(o.additionalProperties,!1)&&O(we(o.properties).length,o.required.length)}function tF(e,o,i){return uo(bt(Ir(bt("Object","getOwnPropertyNames"),[i]),"length"),De(o.required.length))}function rF(e,o,i,u){let[p,g]=[Vt(),Vt()],y=vo(os(Lf(i))),b=to(e,o,i.additionalProperties,`${u}[${p}]`),E=Ir(bt(y,"test"),[p]),S=o.AddKey(p),w=o.UseUnevaluated()?xr(E,Sn(b,S)):xr(E,b);return ls(zi(u),De(0),[p,g],w)}function jR(e,o,i,u){if(Yq(o,i.additionalProperties))return De(!0);return eF(o,i,u)?tF(o,i,u):rF(e,o,i,u)}function UR(e,o,i,u){let p=os(Lf(i));return an(we(u),0,(y,b)=>p.test(y)||So(e,o,i.additionalProperties,u[y])&&o.AddKey(y))}function BR(e,o,i,u,p,g){let y=os(Lf(p)),b=[];return An(we(g),0,(S,w)=>{let R=`${i}/additionalProperties`,k=`${u}/${S}`,A=y.test(S)||wo(e,o,R,k,p.additionalProperties,g[S])&&o.AddKey(S);if(!A)b.push(S);return A})||o.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:u,params:{additionalProperties:b}})}function $i(e,o,i,u,p){let g=vs("results","[]"),y=i.map((w,R)=>vs(`context_${R}`,gd("CheckContext",[]))),b=i.map((w,R)=>vs(`condition_${R}`,Ir(Js(["context"],Lt(e,o,w,u)),[`context_${R}`]))),E=i.map((w,R)=>vy(`condition_${R}`,Ir(bt("results","push"),[`context_${R}`]))),S=im(Sn(p,o.Merge("results")));return Ir(Js([],sm([g,...y,...b,...E,S])),[])}function nF(e,o,i,u){return $i(e,o,i.allOf,u,uo(bt("results","length"),De(i.allOf.length)))}function oF(e,o,i,u){return Cn(i.allOf.map((p)=>Lt(e,o,p,u)))}function GR(e,o,i,u){return o.UseUnevaluated()?nF(e,o,i,u):oF(e,o,i,u)}function KR(e,o,i,u){let p=i.allOf.reduce((g,y)=>{let b=new _n;return At(e,b,y,u)?[...g,b]:g},[]);return O(p.length,i.allOf.length)&&o.Merge(p)}function HR(e,o,i,u,p,g){let y=[],b=p.allOf.reduce((S,w,R)=>{let k=`${i}/allOf/${R}`,A=new qn,C=mr(e,A,k,u,w,g);if(!C)y.push(A);return C?[...S,A]:S},[]),E=O(b.length,p.allOf.length)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E}function sF(e,o,i,u){return $i(e,o,i.anyOf,u,Cy(bt("results","length"),De(0)))}function iF(e,o,i,u){return yd(i.anyOf.map((p)=>Lt(e,o,p,u)))}function WR(e,o,i,u){return o.UseUnevaluated()?sF(e,o,i,u):iF(e,o,i,u)}function zR(e,o,i,u){let p=i.anyOf.reduce((g,y)=>{let b=new _n;return At(e,b,y,u)?[...g,b]:g},[]);return Ki(p.length,0)&&o.Merge(p)}function VR(e,o,i,u,p,g){let y=[],b=p.anyOf.reduce((S,w,R)=>{let k=new qn,A=`${i}/anyOf/${R}`,C=mr(e,k,A,u,w,g);if(!C)y.push(k);return C?[...S,k]:S},[]),E=Ki(b.length,0)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E||o.AddError({keyword:"anyOf",schemaPath:i,instancePath:u,params:{}})}function JR(e,o,i,u){return i?De(!0):De(!1)}function Nf(e,o,i,u){return i}function QR(e,o,i,u,p,g){return Nf(e,o,p,g)||o.AddError({keyword:"boolean",schemaPath:i,instancePath:u,params:{}})}function XR(e,o,i,u){return Hi(i.const)?uo(u,De(i.const)):$y(u,vo(i.const))}function Df(e,o,i,u){return Hi(i.const)?O(u,i.const):Ta(u,i.const)}function YR(e,o,i,u,p,g){return Df(e,o,p,g)||o.AddError({keyword:"const",schemaPath:i,instancePath:u,params:{allowedValue:p.const}})}function ZR(e){return!(Ds(e)&&O(e.minContains,0))}function aF(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Un(uo(bt(u,"length"),De(0))),b=UM(u,[p,g],Sn(Lt(e,o,i.contains,p),o.AddIndex(g)));return Sn(y,b)}function uF(e,o,i,u){let[p]=[Vt()],g=Un(uo(bt(u,"length"),De(0))),y=jM(u,[p,"_"],Lt(e,o,i.contains,p));return Sn(g,y)}function ek(e,o,i,u){if(!ZR(i))return De(!0);return o.UseUnevaluated()?aF(e,o,i,u):uF(e,o,i,u)}function qf(e,o,i,u){if(!ZR(i))return!0;return!O(u.length,0)&&Ey(u,(p,g)=>At(e,o,i.contains,p)&&o.AddIndex(g))}function tk(e,o,i,u,p,g){return qf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:1}})}function rk(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Cn(ln(i.dependencies).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Lt(e,o,b,u),w=(R)=>Cn(R.map((k)=>Vi(u,De(k))));return xr(E,Ge(b)?w(b):S)}));return xr(p,g)}function nk(e,o,i,u){let p=O(we(u).length,0),g=an(ln(i.dependencies),0,([y,b])=>!fe(u,y)||(Ge(b)?b.every((E)=>fe(u,E)):At(e,o,b,u)));return p||g}function ok(e,o,i,u,p,g){let y=O(we(g).length,0),b=An(ln(p.dependencies),0,([E,S])=>{let w=`${i}/dependencies/${E}`;return!fe(g,E)||(Ge(S)?S.every((R)=>fe(g,R)||o.AddError({keyword:"dependencies",schemaPath:i,instancePath:u,params:{property:E,dependencies:S}})):mr(e,o,w,u,S,g))});return y||b}function sk(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Cn(ln(i.dependentRequired).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Cn(b.map((w)=>Vi(u,De(w))));return xr(E,S)}));return xr(p,g)}function ik(e,o,i,u){let p=O(we(u).length,0),g=an(ln(i.dependentRequired),0,([y,b])=>!fe(u,y)||b.every((E)=>fe(u,E)));return p||g}function ak(e,o,i,u,p,g){let y=O(we(g).length,0),b=An(ln(p.dependentRequired),0,([E,S])=>!fe(g,E)||An(S,0,(w)=>fe(g,w)||o.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:u,params:{property:E,dependencies:S}})));return y||b}function uk(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Cn(ln(i.dependentSchemas).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Lt(e,o,b,u);return xr(E,S)}));return xr(p,g)}function ck(e,o,i,u){let p=O(we(u).length,0),g=an(ln(i.dependentSchemas),0,([y,b])=>!fe(u,y)||At(e,o,b,u));return p||g}function mk(e,o,i,u,p,g){let y=O(we(g).length,0),b=An(ln(p.dependentSchemas),0,([E,S])=>{let w=`${i}/dependentSchemas/${E}`;return!fe(g,E)||mr(e,o,w,u,S,g)});return y||b}function pk(e,o,i,u){let p=e.DynamicRef(i)??!1;return js(e,o,p,u)}function lk(e,o,i,u){let p=e.DynamicRef(i)??!1;return Ye(p)&&At(e,o,p,u)}function dk(e,o,i,u,p,g){let y=e.DynamicRef(p)??!1;return Ye(y)&&mr(e,o,"#",u,y,g)}function fk(e,o,i,u){return yd(i.enum.map((p)=>{if(Hi(p))return uo(u,De(p));let g=vo(p);return $y(u,g)}))}function jf(e,o,i,u){return wa(i.enum,(p)=>Hi(p)?O(u,p):Ta(u,p))}function hk(e,o,i,u,p,g){return jf(e,o,p,g)||o.AddError({keyword:"enum",schemaPath:i,instancePath:u,params:{allowedValues:p.enum}})}function gk(e,o,i,u){return hd(u,De(i.exclusiveMaximum))}function Uf(e,o,i,u){return Su(u,i.exclusiveMaximum)}function yk(e,o,i,u,p,g){return Uf(e,o,p,g)||o.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:u,params:{comparison:"<",limit:p.exclusiveMaximum}})}function xk(e,o,i,u){return Cy(u,De(i.exclusiveMinimum))}function Bf(e,o,i,u){return Ki(u,i.exclusiveMinimum)}function Ik(e,o,i,u,p,g){return Bf(e,o,p,g)||o.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:u,params:{comparison:">",limit:p.exclusiveMinimum}})}var cF=[0,31,28,31,30,31,30,31,31,30,31,30,31],mF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function pF(e){return e%4===0&&(e%100!==0||e%400===0)}function Xa(e){let o=mF.exec(e);if(!o)return!1;let i=+o[1],u=+o[2],p=+o[3];return u>=1&&u<=12&&p>=1&&p<=(u===2&&pF(i)?29:cF[u])}var lF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Ya(e,o=!0){let i=lF.exec(e);if(!i)return!1;if(o&&!i[4]&&!i[5])return!1;let u=+i[1],p=+i[2],g=+i[3];if(u>23||p>59||g>60)return!1;if(i[5]){let w=+i[6],R=+i[7];if(w>23||R>59)return!1}if(g<60)return!0;let y=i[5]==="-"?-1:1,b=+(i[6]||0),E=+(i[7]||0);return((u*60+p-y*(b*60+E))%1440+1440)%1440===1439}function Ep(e){let o=e.split(/T/i);return o.length===2&&Xa(o[0])&&Ya(o[1])}var dF=/^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 Sp(e){return dF.test(e)}var fF=/^(?:[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 wp(e){return fF.test(e)}var bk=/^(?!-).*(?<!-)$/,Ek=/^(?!..--)/,Sk=/^[a-zA-Z0-9-]*$/;var Za=/[^\p{ASCII}]/u;var hF=/[0-9]/,wk=/[\u{0660}-\u{0669}]/u,gF=/[\u{06f0}-\u{06f9}]/u,yF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,xF=/[\u{002d}\u{002b}]/u,Gf=/\p{Mn}/u,IF=/\p{Mc}/u;var Tk=/[\p{Mn}\p{Mc}\p{Me}]/u,Kf=/\p{L}/u,bF=/\p{Nd}/u,Rk=/\p{Script=Greek}/u,Tp=/\p{Script=Hebrew}/u,kk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Ak=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Hf=/[\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,Ck=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,EF=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,SF=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Pk=new RegExp([hF,gF].map((e)=>e.source).join("|"),"u"),$k=new RegExp([Kf,xF,yF,bF,Gf,IF,EF,SF].map((e)=>e.source).join("|"),"u");function vk(e){return bk.test(e)&&Ek.test(e)&&Sk.test(e)}var ss=36,Pc=1,$c=26,TF=38,RF=700,Ok=72,_k=128;function Wf(){throw null}function Rp(e){return e.toLowerCase().startsWith("xn--")}function Lk(e,o,i){e=i?Math.floor(e/RF):e>>1,e+=Math.floor(e/o);let u=0;while(e>(ss-Pc)*$c>>1)e=Math.floor(e/(ss-Pc)),u+=ss;return u+Math.floor((ss-Pc+1)*e/(e+TF))}function kp(e){let o=[],i=_k,u=0,p=Ok,g=e.lastIndexOf("-");if(g>0)for(let b=0;b<g;b++){let E=e.charCodeAt(b);if(E>=128)Wf();o.push(E)}let y=g<0?0:g+1;while(y<e.length){let b=u,E=1,S=ss;while(!0){if(y>=e.length)Wf();let R=e.charCodeAt(y++),k;if(R>=97&&R<=122)k=R-97;else if(R>=48&&R<=57)k=R-48+26;else Wf();u+=k*E;let A=S<=p?Pc:S>=p+$c?$c:S-p;if(k<A)break;E*=ss-A,S+=ss}let w=o.length+1;p=Lk(u-b,w,b===0),i+=Math.floor(u/w),u%=w,o.splice(u,0,i),u++}return String.fromCodePoint(...o)}function Mk(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var kF=new RegExp(Za.source,"gu");function Nk(e){let o=e.replace(kF,""),i=o.length,u=i>0?[o,"-"]:[],p=Array.from(e,(S)=>S.codePointAt(0)),g=_k,y=0,b=Ok,E=i;while(E<p.length){let S=1/0;for(let w of p)if(w>=g&&w<S)S=w;y+=(S-g)*(E+1),g=S;for(let w of p){if(w<g)y++;if(w===g){let R=y;for(let k=ss;;k+=ss){let A=k<=b?Pc:k>=b+$c?$c:k-b;if(R<A)break;let C=A+(R-A)%(ss-A);u.push(Mk(C)),R=Math.floor((R-A)/(ss-A))}u.push(Mk(R)),b=Lk(y,E+1,E===i),y=0,E++}}y++,g++}return u.join("")}var AF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Dk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,CF=/^(?:R|AL|AN)$/;function qk(e){if(Rp(e))try{return Ap(kp(e.slice(4).toLowerCase()))}catch{return!1}return Ap(e)}function Fk(e){let o=String.fromCodePoint(e);return Pk.test(o)?"EN":wk.test(o)?"AN":Gf.test(o)?"NSM":Tp.test(o)?"R":Ak.test(o)?"AL":Kf.test(o)?"L":"ON"}function Ap(e){for(let o of e)if(CF.test(Fk(o.codePointAt(0))))return!0;return!1}function Cp(e){let o=!1,i=Dk,u=!1,p=!1,g=!0;for(let y of e){let b=Fk(y.codePointAt(0));if(g){if(b!=="L"&&b!=="R"&&b!=="AL")return!1;o=b==="R"||b==="AL",i=o?AF:Dk,g=!1}if(!i.test(b))return!1;if(b==="EN")u=!0;else if(b==="AN")p=!0}if(o&&u&&p)return!1;return!0}function PF(e){return Za.test(e)&&Nk(e).length+4>63}function $F(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Pp(e){if(PF(e))return!1;if(Ap(e)&&!Cp(e))return!1;let o=[...e],i=o.map((g)=>g.codePointAt(0)),u=i.length;if($F(o))return!1;if(Tk.test(o[0]))return!1;let p=!1;for(let g=0;g<u;g++){let y=i[g],b=o[g];if(Ck.test(b))return!1;if(!$k.test(b))return!1;if(kk.test(b))p=!0;let E=i[g-1],S=i[g+1];switch(y){case 183:if(E!==108||S!==108)return!1;break;case 885:if(!S||!Rk.test(o[g+1]))return!1;break;case 1523:case 1524:if(!E||!Tp.test(o[g-1]))return!1;break;case 8204:if(!E||E<128&&!Hf.test(o[g-1]))return!1;break;case 8205:if(!E||!Hf.test(o[g-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function $p(e){if(!Rp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let i=kp(o);if(!Za.test(i))return!1;return Pp(i)}catch{return!1}}function vF(e){return e.length>0&&e.length<=63}function MF(e){return vF(e)&&($p(e)||vk(e))}function Gk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>MF(o))}function OF(e){return e.length>0&&e.length<=63}function _F(e){return OF(e)&&($p(e)||Pp(e))}function LF(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 Kk(e){if(e.length===0||e.includes(" "))return!1;let o=LF(e);if(o.length>253)return!1;let i=o.split("."),u=i.some((p)=>qk(p));return i.every((p)=>_F(p)&&(!u||Cp(p)))}function vp(e){return Gk(e)}var NF=/^(?:[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 Mp(e){return NF.test(e.normalize("NFC"))}function Op(e){return Kk(e)}var DF=/^(?:(?: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 _p(e){return DF.test(e)}var qF=/^(?:(?:(?:[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 Lp(e){return qF.test(e)}var FF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,jF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Np(e){return!FF.test(e)&&!jF.test(e)&&URL.canParse(e,"http://example.com")}var UF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,BF=/[\x00-\x20<>\^`{|}\\]/,GF=/%(?![0-9a-fA-F]{2})/;function KF(e){return e.length<2048?e.replace(UF,"[::1]"):e}function Dp(e){if(BF.test(e))return!1;if(GF.test(e))return!1;return URL.canParse(KF(e))}var HF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function qp(e){return HF.test(e)}var WF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Fp(e){return WF.test(e)}function jp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var zF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Up(e){return zF.test(e)}var VF=/^(?:[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 Bp(e){return VF.test(e)}var JF=/^(?:(?:[^\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 Gp(e){return JF.test(e)}var QF=/^[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 Kp(e){return QF.test(e)}function Hp(e){return URL.canParse(e)}var XF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Wp(e){return XF.test(e)}var Er=new Map;function Wk(){Er.clear()}function YF(){return[...Er.entries()]}function ZF(e,o){Er.set(e,o)}function e1(e){return Er.has(e)}function t1(e){return Er.get(e)}function zk(e,o){return Er.get(e)?.(o)??!0}function Vk(){Wk(),Er.set("date-time",Ep),Er.set("date",Xa),Er.set("duration",Sp),Er.set("email",wp),Er.set("hostname",vp),Er.set("idn-email",Mp),Er.set("idn-hostname",Op),Er.set("ipv4",_p),Er.set("ipv6",Lp),Er.set("iri-reference",Np),Er.set("iri",Dp),Er.set("json-pointer-uri-fragment",qp),Er.set("json-pointer",Fp),Er.set("regex",jp),Er.set("relative-json-pointer",Up),Er.set("time",Ya),Er.set("uri-reference",Bp),Er.set("uri-template",Gp),Er.set("uri",Kp),Er.set("url",Hp),Er.set("uuid",Wp)}Vk();function Jk(e,o,i,u){return Ir(bt("Format","Test"),[De(i.format),u])}function Vf(e,o,i,u){return zk(i.format,u)}function Qk(e,o,i,u,p,g){return Vf(e,o,p,g)||o.AddError({keyword:"format",schemaPath:i,instancePath:u,params:{format:p.format}})}function Xk(e,o,i,u){let p=kc(i)?i.then:!0,g=lc(i)?i.else:!0;return GM(Lt(e,o,i.if,u),Lt(e,o,p,u),Lt(e,o,g,u))}function Yk(e,o,i,u){let p=kc(i)?i.then:!0,g=lc(i)?i.else:!0;return At(e,o,i.if,u)?At(e,o,p,u):At(e,o,g,u)}function Zk(e,o,i,u,p,g){let y=kc(p)?p.then:!0,b=lc(p)?p.else:!0,E=new qn,S=mr(e,E,`${i}/if`,u,p.if,g)?mr(e,E,`${i}/then`,u,y,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"then"}}):mr(e,o,`${i}/else`,u,b,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"else"}});if(S)o.Merge([E]);return S}function r1(e,o,i,u){return Cn(i.items.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`),E=o.AddIndex(De(g));return xr(y,Sn(b,E))}))}function n1(e,o,i,u){return Cn(i.items.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`);return xr(y,b)}))}function o1(e,o,i,u){return o.UseUnevaluated()?r1(e,o,i,u):n1(e,o,i,u)}function s1(e,o,i,u){return an(i.items,0,(p,g)=>ps(u.length,g)||So(e,o,p,u[g])&&o.AddIndex(g))}function i1(e,o,i,u,p,g){return An(p.items,0,(y,b)=>{let E=`${i}/items/${b}`,S=`${u}/${b}`;return ps(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function a1(e,o,i,u){let p=rs(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element"),y=o.AddIndex("index");return ls(u,De(p),["element","index"],Sn(g,y))}function u1(e,o,i,u){let p=rs(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element");return ls(u,De(p),["element","index"],g)}function c1(e,o,i,u){return o.UseUnevaluated()?a1(e,o,i,u):u1(e,o,i,u)}function m1(e,o,i,u){let p=rs(i)?i.prefixItems.length:0;return an(u,p,(g,y)=>So(e,o,i.items,g)&&o.AddIndex(y))}function p1(e,o,i,u,p,g){let y=rs(p)?p.prefixItems.length:0;return An(g,y,(b,E)=>{let S=`${i}/items`,w=`${u}/${E}`;return wo(e,o,S,w,p.items,b)&&o.AddIndex(E)})}function eA(e,o,i,u){return hc(i)?o1(e,o,i,u):c1(e,o,i,u)}function tA(e,o,i,u){return hc(i)?s1(e,o,i,u):m1(e,o,i,u)}function rA(e,o,i,u,p,g){return hc(p)?i1(e,o,i,u,p,g):p1(e,o,i,u,p,g)}function nA(e){return Rs(e)}function oA(e,o,i,u){if(!nA(i))return De(!0);let[p]=[Vt()],g=om(u,[p,"_"],Lt(e,o,i.contains,p));return Wi(g,De(i.maxContains))}function Jf(e,o,i,u){if(!nA(i))return!0;let p=pd(u,(g)=>At(e,o,i.contains,g));return ps(p,i.maxContains)}function sA(e,o,i,u,p,g){let y=Ds(p)?p.minContains:1;return Jf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:y,maxContains:p.maxContains}})}function iA(e,o,i,u){return Wi(u,De(i.maximum))}function Qf(e,o,i,u){return ps(u,i.maximum)}function aA(e,o,i,u,p,g){return Qf(e,o,p,g)||o.AddError({keyword:"maximum",schemaPath:i,instancePath:u,params:{comparison:"<=",limit:p.maximum}})}function uA(e,o,i,u){return Wi(bt(u,"length"),De(i.maxItems))}function Xf(e,o,i,u){return ps(u.length,i.maxItems)}function cA(e,o,i,u,p,g){return Xf(e,o,p,g)||o.AddError({keyword:"maxItems",schemaPath:i,instancePath:u,params:{limit:p.maxItems}})}function mA(e,o,i,u){return FM(u,De(i.maxLength))}function Yf(e,o,i,u){return Iy(u,i.maxLength)}function pA(e,o,i,u,p,g){return Yf(e,o,p,g)||o.AddError({keyword:"maxLength",schemaPath:i,instancePath:u,params:{limit:p.maxLength}})}function lA(e,o,i,u){return Wi(bt(zi(u),"length"),De(i.maxProperties))}function Zf(e,o,i,u){return ps(we(u).length,i.maxProperties)}function dA(e,o,i,u,p,g){return Zf(e,o,p,g)||o.AddError({keyword:"maxProperties",schemaPath:i,instancePath:u,params:{limit:p.maxProperties}})}function fA(e){return Rs(e)}function l1(e,o,i,u){let[p,g]=[Vt(),Vt()],y=om(u,[p,g],Sn(Lt(e,o,i.contains,p),o.AddIndex(g)));return Tu(y,De(i.minContains))}function d1(e,o,i,u){let[p]=[Vt()],g=om(u,[p,"_"],Lt(e,o,i.contains,p));return Tu(g,De(i.minContains))}function hA(e,o,i,u){if(!fA(i))return De(!0);return o.UseUnevaluated()?l1(e,o,i,u):d1(e,o,i,u)}function eh(e,o,i,u){if(!fA(i))return!0;let p=pd(u,(g,y)=>At(e,o,i.contains,g)&&o.AddIndex(y));return Sa(p,i.minContains)}function gA(e,o,i,u,p,g){return eh(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:p.minContains}})}function yA(e,o,i,u){return Tu(u,De(i.minimum))}function th(e,o,i,u){return Sa(u,i.minimum)}function xA(e,o,i,u,p,g){return th(e,o,p,g)||o.AddError({keyword:"minimum",schemaPath:i,instancePath:u,params:{comparison:">=",limit:p.minimum}})}function IA(e,o,i,u){return Tu(bt(u,"length"),De(i.minItems))}function rh(e,o,i,u){return Sa(u.length,i.minItems)}function bA(e,o,i,u,p,g){return rh(e,o,p,g)||o.AddError({keyword:"minItems",schemaPath:i,instancePath:u,params:{limit:p.minItems}})}function EA(e,o,i,u){return qM(u,De(i.minLength))}function nh(e,o,i,u){return by(u,i.minLength)}function SA(e,o,i,u,p,g){return nh(e,o,p,g)||o.AddError({keyword:"minLength",schemaPath:i,instancePath:u,params:{limit:p.minLength}})}function wA(e,o,i,u){return Tu(bt(zi(u),"length"),De(i.minProperties))}function oh(e,o,i,u){return Sa(we(u).length,i.minProperties)}function TA(e,o,i,u,p,g){return oh(e,o,p,g)||o.AddError({keyword:"minProperties",schemaPath:i,instancePath:u,params:{limit:p.minProperties}})}function RA(e,o,i,u){return KM(u,De(i.multipleOf))}function sh(e,o,i,u){return yy(u,i.multipleOf)}function kA(e,o,i,u,p,g){return sh(e,o,p,g)||o.AddError({keyword:"multipleOf",schemaPath:i,instancePath:u,params:{multipleOf:p.multipleOf}})}function f1(e,o,i,u){return $i(e,o,[i.not],u,Un(uo(bt("results","length"),De(1))))}function h1(e,o,i,u){return Un(Lt(e,o,i.not,u))}function AA(e,o,i,u){return o.UseUnevaluated()?f1(e,o,i,u):h1(e,o,i,u)}function ih(e,o,i,u){let p=new _n;return!At(e,p,i.not,u)&&o.Merge([p])}function CA(e,o,i,u,p,g){return ih(e,o,p,g)||o.AddError({keyword:"not",schemaPath:i,instancePath:u,params:{}})}function g1(e,o,i,u){return $i(e,o,i.oneOf,u,uo(bt("results","length"),De(1)))}function y1(e,o,i,u){let[p]=[Vt()],g=BM(i.oneOf.map((b)=>Lt(e,o,b,u))),y=om(g,[p,"_"],uo(p,De(!0)));return uo(y,De(1))}function PA(e,o,i,u){return o.UseUnevaluated()?g1(e,o,i,u):y1(e,o,i,u)}function $A(e,o,i,u){let p=i.oneOf.reduce((g,y)=>{let b=new _n;return At(e,b,y,u)?[...g,b]:g},[]);return O(p.length,1)&&o.Merge(p)}function vA(e,o,i,u,p,g){let y=[],b=[],E=p.oneOf.reduce((w,R,k)=>{let A=new qn,C=`${i}/oneOf/${k}`,q=mr(e,A,C,u,R,g);if(q)b.push(k);if(!q)y.push(A);return q?[...w,A]:w},[]),S=O(E.length,1)&&o.Merge(E);if(!S&&O(b.length,0))y.forEach((w)=>w.GetErrors().forEach((R)=>o.AddError(R)));return S||o.AddError({keyword:"oneOf",schemaPath:i,instancePath:u,params:{passingSchemas:b}})}function MA(e,o,i,u){let p=vo(gt(i.pattern)?os(i.pattern):i.pattern);return Ir(bt(p,"test"),[u])}function ah(e,o,i,u){return(gt(i.pattern)?os(i.pattern):i.pattern).test(u)}function OA(e,o,i,u,p,g){return ah(e,o,p,g)||o.AddError({keyword:"pattern",schemaPath:i,instancePath:u,params:{pattern:p.pattern}})}function _A(e,o,i,u){return Cn(ln(i.patternProperties).map(([p,g])=>{let[y,b]=[Vt(),Vt()],E=vo(os(p)),S=Un(Ir(bt(E,"test"),[y])),w=to(e,o,g,b),R=o.AddKey(y),k=o.UseUnevaluated()?xr(S,Sn(w,R)):xr(S,w);return ls(Py(u),De(0),[`[${y}, ${b}]`,"_"],k)}))}function LA(e,o,i,u){return an(ln(i.patternProperties),0,([p,g])=>{let y=os(p);return an(ln(u),0,([b,E])=>!y.test(b)||So(e,o,g,E)&&o.AddKey(b))})}function NA(e,o,i,u,p,g){return An(ln(p.patternProperties),0,([y,b])=>{let E=`${i}/patternProperties/${y}`,S=os(y);return An(ln(g),0,([w,R])=>{let k=`${u}/${w}`;return!S.test(w)||wo(e,o,E,k,b,R)&&o.AddKey(w)})})}function DA(e,o,i,u){return Cn(i.prefixItems.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`),E=o.AddIndex(De(g)),S=o.UseUnevaluated()?Sn(b,E):b;return xr(y,S)}))}function qA(e,o,i,u){return O(u.length,0)||an(i.prefixItems,0,(p,g)=>ps(u.length,g)||So(e,o,p,u[g])&&o.AddIndex(g))}function FA(e,o,i,u,p,g){return O(g.length,0)||An(p.prefixItems,0,(y,b)=>{let E=`${i}/prefixItems/${b}`,S=`${u}/${b}`;return ps(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function zp(e,o){return e.includes(o)||Jo().exactOptionalPropertyTypes}function jA(e,o){return fd(bt(e,o))}function uh(e,o){return Ut(e[o])}function UA(e,o,i,u){let p=ns(i)?i.required:[],g=ln(i.properties).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=to(e,o,b,bt(u,y)),w=o.AddKey(De(y)),R=o.UseUnevaluated()?Sn(S,w):S,k=p.includes(y)?R:xr(E,R);return zp(p,y)?k:xr(jA(u,y),k)});return Cn(g)}function BA(e,o,i,u){let p=ns(i)?i.required:[];return an(ln(i.properties),0,([y,b])=>{let E=!fe(u,y)||So(e,o,b,u[y])&&o.AddKey(y);return zp(p,y)?E:uh(u,y)||E})}function GA(e,o,i,u,p,g){let y=ns(p)?p.required:[];return An(ln(p.properties),0,([E,S])=>{let w=`${i}/properties/${E}`,R=`${u}/${E}`,k=()=>!fe(g,E)||wo(e,o,w,R,S,g[E])&&o.AddKey(E);return zp(y,E)?k():uh(g,E)||k()})}function KA(e,o,i,u){let[p,g]=[Vt(),Vt()];return ls(zi(u),De(0),[p,g],Lt(e,o,i.propertyNames,p))}function HA(e,o,i,u){return an(we(u),0,(p,g)=>At(e,o,i.propertyNames,p))}function WA(e,o,i,u,p,g){let y=[];return An(we(g),0,(E,S)=>{let w=`${u}/${E}`,R=`${i}/propertyNames`,k=mr(e,o,R,w,p.propertyNames,E);if(!k)y.push(E);return k})||o.AddError({keyword:"propertyNames",schemaPath:i,instancePath:u,params:{propertyNames:y}})}function zA(e,o,i,u){let p=e.RecursiveRef(i)??!1;return js(e,o,p,u)}function VA(e,o,i,u){let p=e.RecursiveRef(i)??!1;return Ye(p)&&At(e,o,p,u)}function JA(e,o,i,u,p,g){let y=e.RecursiveRef(p)??!1;return Ye(y)&&mr(e,o,"#",u,y,g)}function x1(e,o,i,u){let p=Js(["context","value"],js(e,o,i,"value")),g=Js(["context","value"],sm([vs("nextContext",gd("CheckContext",[])),vs("result",Ir(p,["nextContext","value"])),vy("result",o.Merge("[nextContext]")),im("result")]));return Ir(g,["context",u])}function I1(e,o,i,u){return js(e,o,i,u)}function QA(e,o,i,u){let p=e.Ref(i)??!1;return o.UseUnevaluated()?x1(e,o,p,u):I1(e,o,p,u)}function XA(e,o,i,u){let p=e.Ref(i)??!1,g=new _n,y=Ye(p)&&At(e,g,p,u);if(y)o.Merge([g]);return y}function YA(e,o,i,u,p,g){let y=e.Ref(p)??!1,b=new qn,E=Ye(y)&&mr(e,b,"#",u,y,g);if(E)o.Merge([b]);if(!E)b.GetErrors().forEach((S)=>o.AddError(S));return E}function ZA(e,o,i,u){return Cn(i.required.map((p)=>Vi(u,De(p))))}function e0(e,o,i,u){return an(i.required,0,(p)=>fe(u,p))}function t0(e,o,i,u,p,g){let y=[];return An(p.required,0,(E)=>{let S=fe(g,E);if(!S)y.push(E);return S})||o.AddError({keyword:"required",schemaPath:i,instancePath:u,params:{requiredProperties:y}})}function r0(e,o,i,u){return O(i,"object")?Ry(u):O(i,"array")?nm(u):O(i,"boolean")?MM(u):O(i,"integer")?OM(u):O(i,"number")?Ty(u):O(i,"null")?_M(u):O(i,"string")?Ay(u):O(i,"bigint")?wy(u):O(i,"constructor")?DM(u):O(i,"function")?NM(u):O(i,"symbol")?LM(u):O(i,"undefined")?fd(u):O(i,"void")?fd(u):De(!0)}function ch(e,o,i,u,p){return O(i,"object")?Vo(p):O(i,"array")?Ge(p):O(i,"boolean")?pn(p):O(i,"integer")?rm(p):O(i,"number")?Ot(p):O(i,"null")?ho(p):O(i,"string")?gt(p):O(i,"bigint")?Nr(p):O(i,"constructor")?cd(p):O(i,"function")?ms(p):O(i,"symbol")?md(p):O(i,"undefined")?Ut(p):O(i,"void")?Ut(p):!0}function b1(e,o,i,u){return yd(i.map((p)=>r0(e,o,p,u)))}function n0(e,o,i,u,p){return wa(i,(g)=>ch(e,o,g,u,p))}function o0(e,o,i,u){return Ge(i.type)?b1(e,o,i.type,u):r0(e,o,i.type,u)}function s0(e,o,i,u){return Ge(i.type)?n0(e,o,i.type,i,u):ch(e,o,i.type,i,u)}function i0(e,o,i,u,p,g){return(Ge(p.type)?n0(e,o,p.type,p,g):ch(e,o,p.type,p,g))||o.AddError({keyword:"type",schemaPath:i,instancePath:u,params:{type:p.type}})}function a0(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetIndices"),[]),b=Ir(bt("indices","has"),[p]),E=Lt(e,o,i.unevaluatedItems,g),S=Ir(bt("context","AddIndex"),[p]),w=ls(u,De(0),[g,p],Sn(xr(b,E),S));return Ir(Js(["context"],sm([vs("indices",y),im(w)])),["context"])}function u0(e,o,i,u){let p=o.GetIndices();return an(u,0,(g,y)=>(p.has(y)||At(e,o,i.unevaluatedItems,g))&&o.AddIndex(y))}function c0(e,o,i,u,p,g){let y=o.GetIndices(),b=[];return An(g,0,(S,w)=>{let R=new qn,k=(y.has(w)||mr(e,R,i,u,p.unevaluatedItems,S))&&o.AddIndex(w);if(!k)b.push(w);return k})||o.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:u,params:{unevaluatedItems:b}})}function m0(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetKeys"),[]),b=Ir(bt("keys","has"),[p]),E=Ir(bt("context","AddKey"),[p]),S=Lt(e,o,i.unevaluatedProperties,g),w=ls(Py(u),De(0),[`[${p}, ${g}]`,"_"],xr(b,Sn(S,E)));return Ir(Js(["context"],sm([vs("keys",y),im(w)])),["context"])}function p0(e,o,i,u){let p=o.GetKeys();return an(ln(u),0,([g,y])=>p.has(g)||At(e,o,i.unevaluatedProperties,y)&&o.AddKey(g))}function l0(e,o,i,u,p,g){let y=o.GetKeys(),b=[];return An(ln(g),0,([S,w])=>{let R=new qn,k=y.has(S)||mr(e,R,i,u,p.unevaluatedProperties,w)&&o.AddKey(S);if(!k)b.push(S);return k})||o.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:u,params:{unevaluatedProperties:b}})}function mh(e){return!O(e.uniqueItems,!1)}function d0(e,o,i,u){if(!mh(i))return De(!0);let p=bt(gd("Set",[Ir(bt(u,"map"),[bt("Hashing","Hash")])]),"size"),g=bt(u,"length");return uo(p,g)}function f0(e,o,i,u){if(!mh(i))return!0;let p=new Set(u.map(bd)).size,g=u.length;return O(p,g)}function h0(e,o,i,u,p,g){if(!mh(p))return!0;let y=new Set,b=g.reduce((S,w,R)=>{let k=bd(w);if(y.has(k))return[...S,R];return y.add(k),S},[]);return O(b.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:u,params:{duplicateItems:b}})}function vc(e,o){return Ac(e)&&(Ge(e.type)&&Ki(e.type.length,0)&&an(e.type,0,(i)=>O(i,o))||O(e.type,o))}function E1(e){return vc(e,"object")}function S1(e){return gn(e)&&(Po(e)||cc(e)||mc(e)||za(e)||Fs(e)||qs(e)||Ja(e)||la(e)||Ic(e)||ns(e)||ki(e))}function w1(e){return vc(e,"array")}function T1(e){return gn(e)&&(Wa(e)||Ns(e)||Rs(e)||yc(e)||Va(e)||Ds(e)||Ei(e)||rs(e)||Ri(e)||Ti(e))}function R1(e){return vc(e,"string")}function k1(e){return gn(e)&&(pa(e)||xc(e)||ma(e)||da(e))}function A1(e){return vc(e,"number")||vc(e,"bigint")}function C1(e){return gn(e)&&(ts(e)||gc(e)||dc(e)||es(e)||bc(e))}function to(e,o,i,u){return o.UseUnevaluated()?Sn(Sn(o.Push(),Lt(e,o,i,u)),o.Pop()):Lt(e,o,i,u)}function Lt(e,o,i,u){e.Push(i);let p=[];if(_s(i))return JR(e,o,i,u);if(Ac(i))p.push(o0(e,o,i,u));if(S1(i)){let y=[];if(ns(i))y.push(ZA(e,o,i,u));if(Po(i))y.push(jR(e,o,i,u));if(cc(i))y.push(rk(e,o,i,u));if(mc(i))y.push(sk(e,o,i,u));if(za(i))y.push(uk(e,o,i,u));if(qs(i))y.push(_A(e,o,i,u));if(Fs(i))y.push(UA(e,o,i,u));if(Ja(i))y.push(KA(e,o,i,u));if(la(i))y.push(wA(e,o,i,u));if(Ic(i))y.push(lA(e,o,i,u));let b=Cn(y),E=xr(Un(Ry(u)),b);p.push(E1(i)?b:E)}if(T1(i)){let y=[];if(Wa(i))y.push(DR(e,o,i,u));if(Rs(i))y.push(ek(e,o,i,u));if(Ns(i))y.push(eA(e,o,i,u));if(yc(i))y.push(oA(e,o,i,u));if(Va(i))y.push(uA(e,o,i,u));if(Ds(i))y.push(hA(e,o,i,u));if(Ei(i))y.push(IA(e,o,i,u));if(rs(i))y.push(DA(e,o,i,u));if(Ti(i))y.push(d0(e,o,i,u));let b=Cn(y),E=xr(Un(nm(u)),b);p.push(w1(i)?b:E)}if(k1(i)){let y=[];if(xc(i))y.push(mA(e,o,i,u));if(pa(i))y.push(EA(e,o,i,u));if(ma(i))y.push(Jk(e,o,i,u));if(da(i))y.push(MA(e,o,i,u));let b=Cn(y),E=xr(Un(Ay(u)),b);p.push(R1(i)?b:E)}if(C1(i)){let y=[];if(dc(i))y.push(gk(e,o,i,u));if(es(i))y.push(xk(e,o,i,u));if(gc(i))y.push(iA(e,o,i,u));if(ts(i))y.push(yA(e,o,i,u));if(bc(i))y.push(RA(e,o,i,u));let b=Cn(y),E=xr(Un(xr(Ty(u),wy(u))),b);p.push(A1(i)?b:E)}if(Rc(i))p.push(QA(e,o,i,u));if(Tc(i))p.push(zA(e,o,i,u));if(pc(i))p.push(pk(e,o,i,u));if(yp(i))p.push(XR(e,o,i,u));if(xp(i))p.push(fk(e,o,i,u));if(fc(i))p.push(Xk(e,o,i,u));if(Ec(i))p.push(AA(e,o,i,u));if(ic(i))p.push(GR(e,o,i,u));if(uc(i))p.push(WR(e,o,i,u));if(Sc(i))p.push(PA(e,o,i,u));if(Ri(i))p.push(xr(Un(nm(u)),a0(e,o,i,u)));if(ki(i))p.push(xr(Un(ky(u)),m0(e,o,i,u)));if(sc(i))p.push(_R(e,o,i,u));let g=Cn(p);return e.Pop(i),g}function So(e,o,i,u){return o.Push()&&At(e,o,i,u)&&o.Pop()}function At(e,o,i,u){e.Push(i);let p=_s(i)?Nf(e,o,i,u):(!Ac(i)||s0(e,o,i,u))&&(!(at(u)&&!Ge(u))||(!ns(i)||e0(e,o,i,u))&&(!Po(i)||UR(e,o,i,u))&&(!cc(i)||nk(e,o,i,u))&&(!mc(i)||ik(e,o,i,u))&&(!za(i)||ck(e,o,i,u))&&(!qs(i)||LA(e,o,i,u))&&(!Fs(i)||BA(e,o,i,u))&&(!Ja(i)||HA(e,o,i,u))&&(!la(i)||oh(e,o,i,u))&&(!Ic(i)||Zf(e,o,i,u)))&&(!Ge(u)||(!Wa(i)||qR(e,o,i,u))&&(!Rs(i)||qf(e,o,i,u))&&(!Ns(i)||tA(e,o,i,u))&&(!yc(i)||Jf(e,o,i,u))&&(!Va(i)||Xf(e,o,i,u))&&(!Ds(i)||eh(e,o,i,u))&&(!Ei(i)||rh(e,o,i,u))&&(!rs(i)||qA(e,o,i,u))&&(!Ti(i)||f0(e,o,i,u)))&&(!gt(u)||(!xc(i)||Yf(e,o,i,u))&&(!pa(i)||nh(e,o,i,u))&&(!ma(i)||Vf(e,o,i,u))&&(!da(i)||ah(e,o,i,u)))&&(!(Ot(u)||Nr(u))||(!dc(i)||Uf(e,o,i,u))&&(!es(i)||Bf(e,o,i,u))&&(!gc(i)||Qf(e,o,i,u))&&(!ts(i)||th(e,o,i,u))&&(!bc(i)||sh(e,o,i,u)))&&(!Rc(i)||XA(e,o,i,u))&&(!Tc(i)||VA(e,o,i,u))&&(!pc(i)||lk(e,o,i,u))&&(!yp(i)||Df(e,o,i,u))&&(!xp(i)||jf(e,o,i,u))&&(!fc(i)||Yk(e,o,i,u))&&(!Ec(i)||ih(e,o,i,u))&&(!ic(i)||KR(e,o,i,u))&&(!uc(i)||zR(e,o,i,u))&&(!Sc(i)||$A(e,o,i,u))&&(!Ri(i)||(!Ge(u)||u0(e,o,i,u)))&&(!ki(i)||(!at(u)||p0(e,o,i,u)))&&(!sc(i)||LR(e,o,i,u));return e.Pop(i),p}function wo(e,o,i,u,p,g){return o.Push()&&mr(e,o,i,u,p,g)&&o.Pop()}function mr(e,o,i,u,p,g){if(o.AtCapacity())return!1;e.Push(p);let y=_s(p)?QR(e,o,i,u,p,g):!!(+(!Ac(p)||i0(e,o,i,u,p,g))&+(!(at(g)&&!Ge(g))||!!(+(!ns(p)||t0(e,o,i,u,p,g))&+(!Po(p)||BR(e,o,i,u,p,g))&+(!cc(p)||ok(e,o,i,u,p,g))&+(!mc(p)||ak(e,o,i,u,p,g))&+(!za(p)||mk(e,o,i,u,p,g))&+(!qs(p)||NA(e,o,i,u,p,g))&+(!Fs(p)||GA(e,o,i,u,p,g))&+(!Ja(p)||WA(e,o,i,u,p,g))&+(!la(p)||TA(e,o,i,u,p,g))&+(!Ic(p)||dA(e,o,i,u,p,g))))&+(!Ge(g)||!!(+(!Wa(p)||FR(e,o,i,u,p,g))&+(!Rs(p)||tk(e,o,i,u,p,g))&+(!Ns(p)||rA(e,o,i,u,p,g))&+(!yc(p)||sA(e,o,i,u,p,g))&+(!Va(p)||cA(e,o,i,u,p,g))&+(!Ds(p)||gA(e,o,i,u,p,g))&+(!Ei(p)||bA(e,o,i,u,p,g))&+(!rs(p)||FA(e,o,i,u,p,g))&+(!Ti(p)||h0(e,o,i,u,p,g))))&+(!gt(g)||!!(+(!xc(p)||pA(e,o,i,u,p,g))&+(!pa(p)||SA(e,o,i,u,p,g))&+(!ma(p)||Qk(e,o,i,u,p,g))&+(!da(p)||OA(e,o,i,u,p,g))))&+(!(Ot(g)||Nr(g))||!!(+(!dc(p)||yk(e,o,i,u,p,g))&+(!es(p)||Ik(e,o,i,u,p,g))&+(!gc(p)||aA(e,o,i,u,p,g))&+(!ts(p)||xA(e,o,i,u,p,g))&+(!bc(p)||kA(e,o,i,u,p,g))))&+(!Rc(p)||YA(e,o,i,u,p,g))&+(!Tc(p)||JA(e,o,i,u,p,g))&+(!pc(p)||dk(e,o,i,u,p,g))&+(!yp(p)||YR(e,o,i,u,p,g))&+(!xp(p)||hk(e,o,i,u,p,g))&+(!fc(p)||Zk(e,o,i,u,p,g))&+(!Ec(p)||CA(e,o,i,u,p,g))&+(!ic(p)||HR(e,o,i,u,p,g))&+(!uc(p)||VR(e,o,i,u,p,g))&+(!Sc(p)||vA(e,o,i,u,p,g))&+(!Ri(p)||(!Ge(g)||c0(e,o,i,u,p,g)))&+(!ki(p)||(!at(g)||l0(e,o,i,u,p,g))))&&(!sc(p)||NR(e,o,i,u,p,g));return e.Pop(p),y}var g0=[0],Vp=new Map,Mc=new Map;function P1(){return`${g0[0]++}`}function $1(e,o){if(!Vp.has(e))Vp.set(e,new Map);let i=Vp.get(e);if(i.has(o))return i.get(o);let u=P1();return i.set(o,u),u}function v1(e,o,i,u){return e.UseUnevaluated()?Ir(`check_${i}`,["context",u]):Ir(`check_${i}`,[u])}function M1(e,o,i,u){let p=Lt(e,o,i,"value");return o.UseUnevaluated()?vs(`check_${u}`,Js(["context","value"],p)):vs(`check_${u}`,Js(["value"],p))}function y0(){g0[0]=0,Vp.clear(),Mc.clear()}function x0(){return[...Mc.values()]}function js(e,o,i,u){let p=$1(i,e.LexicalBaseURL()),g=v1(o,i,p,u);if(Mc.has(p))return g;return Mc.set(p,""),Mc.set(p,M1(e,o,i,p)),g}function O1(e,o){return at(o)&&!wu(e)?o[e]:void 0}function _1(e,o){return e.reduce((i,u)=>O1(u,i),o)}function L1(e){if(O(e.length,0))return[];let o=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function N1(e,o){let i=L1(o);return _1(i,e)}var Qp="https://json-schema.org";function b0(e,o){if(at(e)&&Ls(e)&&O(e.$dynamicAnchor,o))return e;if(at(e))for(let i of we(e)){let u=b0(e[i],o);if(u)return u}return}function ph(e,o,i){if(O(e,i))return o.href;let u=gn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(Ge(e))for(let p of e){let g=ph(p,u,i);if(!Ut(g))return g}else if(at(e))for(let p of we(e)){let g=ph(e[p],u,i);if(!Ut(g))return g}return}function D1(e,o,i){if(O(e.$id,i.hash))return e;let u=new URL(i.href,o.href);if(O(o.pathname,u.pathname))return i.hash.startsWith("#")?E0(e,i):e;return}function q1(e,o,i){let u=new URL(`#${e.$anchor}`,o.href),p=new URL(i.href,o.href);return O(u.href,p.href)?e:void 0}function F1(e,o,i){let u=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(i.href,o.href);return O(u.href,p.href)?e:void 0}function E0(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let i=decodeURIComponent(o.hash.slice(1));if(!i.startsWith("/"))return;return N1(e,i)}function j1(e,o,i){if(Eo(e)){let u=D1(e,o,i);if(!Ut(u))return u}if(ac(e)){let u=q1(e,o,i);if(!Ut(u))return u}if(Ls(e)){let u=F1(e,o,i);if(!Ut(u))return u}return E0(e,i)}function U1(e,o,i){return e.reduce((u,p)=>{let g=Xp(p,o,i);return!Ut(g)?g:u},void 0)}function B1(e){return O(e,"const")||O(e,"enum")}function G1(e,o,i){return we(e).reduce((u,p)=>{if(B1(p))return u;let g=Xp(e[p],o,i);return!Ut(g)?g:u},void 0)}function Xp(e,o,i){let u=gn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(gn(e)){let p=j1(e,u,i);if(!Ut(p))return p}if(Ge(e))return U1(e,u,i);if(at(e))return G1(e,u,i);return}function K1(e,o,i){return ph(e,new URL(o||".",Qp),i)}function H1(e,o,i,u){let p=Yp(e,o,i,u,!1);return gn(p)&&Eo(p)?p:void 0}function I0(e){return e.href.split("#")[0]}function W1(e,o){return fe(e,o)?e[o]:void 0}function z1(e,o,i){return Xp(e,o,i)}function V1(e,o,i){let u=I0(i);if(O(u,I0(o)))return;if(!fe(e,u))return;let p=e[u],g=gn(p)&&Eo(p)?new URL(p.$id,u):new URL(u);return O(i.hash,"")?p:Xp(p,g,i)}function J1(e,o,i,u,p){if(!u.$ref.startsWith("#"))return;if(fe(e,"$schema"))return;let g=K1(o,i,p);if(Ut(g)||O(g,i))return;return{target:p,base:g,root:o}}function Q1(e,o,i){let u=e[o];if(!gn(u))return;return{target:i,base:o,root:u}}function X1(e,o,i,u,p){let g=p?Q1(e.context,u,i):void 0;if(!Ut(g))return g;return J1(e.root,e.lexicalSchema,e.referenceBase,o,i)}function Y1(e,o,i,u,p,g){if(Eo(p))return;let y=H1(e,o,i,u);if(!y||g.includes(y))return;return{target:p,resource:y}}function Yp(e,o,i,u,p=!0){let g=new URL(i||".",Qp),y=p&&Eo(o)?new URL(o.$id,g):g,b=new URL(u,y.href);return W1(e,u)??z1(o,y,b)??V1(e,y,b)}function Z1(e,o,i,u,p,g){let y=new URL(i||".",Qp),b=p.$dynamicRef.startsWith("#")?u:o,E=Yp(e,b,i,p.$dynamicRef,!1);if(Ut(E)){let R=new URL(p.$dynamicRef,y).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let k=decodeURIComponent(R.slice(1));return g.find((C)=>O(C.$dynamicAnchor,k))??b0(o,k)}return}if(!gn(E)||!Ls(E))return E;if(new URL(p.$dynamicRef,y).hash.startsWith("#/"))return E;return g.find((R)=>O(R.$dynamicAnchor,E.$dynamicAnchor))??E}function ej(e,o){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:i,p=Yp(e.context,u,e.referenceBase,o.$ref,!1);if(!p||!gn(p))return{schema:p};let g=new URL(o.$ref,e.referenceBase).href.split("#")[0],y=!O(g,e.resourceBase),b=X1(e,o,p,g,y),E=y?Y1(e.context,e.root,e.referenceBase,g,p,e.ids):void 0;return{schema:p,retrievedResource:b,resolvedResource:E}}function tj(e,o){let i=wc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Yp(e.context,i,e.lexicalBase,o.$recursiveRef,!1)}function rj(e,o){return Z1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var _r=function(e,o,i,u){if(i==="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 i==="m"?u:i==="a"?u.call(e):u?u.value:o.get(e)},Sr,el,A0,hh,Zp,S0,w0,T0,R0,dh,fh,gh,yh,k0,C0;class Oi{constructor(e,o){Sr.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 _r(this,Sr,"m",hh).call(this,this.ids)}Push(e){if(!gn(e))return;if(Eo(e))_r(this,Sr,"m",gh).call(this,e);if(ac(e))this.anchors.push(e);if(wc(e))this.recursiveAnchors.push(e);if(Ls(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(!gn(e))return;if(Eo(e))_r(this,Sr,"m",yh).call(this,e);if(ac(e))this.anchors.pop();if(wc(e))this.recursiveAnchors.pop();if(Ls(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();_r(this,Sr,"m",C0).call(this,e)}Ref(e){let o=ej(_r(this,Sr,"m",el).call(this),e);return _r(this,Sr,"m",A0).call(this,o),o.schema}RecursiveRef(e){let o=tj(_r(this,Sr,"m",el).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=rj(_r(this,Sr,"m",el).call(this),e);if(o)this.pendingResource=!0;return o}}Sr=new WeakSet,el=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:_r(this,Sr,"m",w0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:_r(this,Sr,"m",S0).call(this),resourceBase:_r(this,Sr,"m",Zp).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},A0=function(o){if(!Ut(o.schema))this.pendingResource=!0;if(!Ut(o.resolvedResource))_r(this,Sr,"m",k0).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!Ut(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},hh=function(o){let i=this.retrievedFrames[this.retrievedFrames.length-1],u=i?new URL(i.base):new URL(Qp);return(i?o.slice(i.idDepth):o).reduce((g,y)=>new URL(y.$id,g),u).href},Zp=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return _r(this,Sr,"m",hh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((i,u)=>new URL(u.$id,i),new URL(o.base)).href},S0=function(){if(this.retrievedFrames.length>0)return _r(this,Sr,"m",Zp).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 _r(this,Sr,"m",Zp).call(this)},w0=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},T0=function(o){o.forEach((i)=>_r(this,Sr,"m",dh).call(this,i,!1))},R0=function(o){o.forEach((i)=>_r(this,Sr,"m",fh).call(this,i,!1))},dh=function e(o,i=!0){if(_s(o))return;if(Ge(o))return _r(this,Sr,"m",T0).call(this,o);if(!gn(o))return;let u=o;if(!i&&Eo(u))return;if(!i&&Ls(u))this.dynamicAnchors.push(u);for(let p of we(u))_r(this,Sr,"m",e).call(this,u[p],!1)},fh=function e(o,i=!0){if(_s(o))return;if(Ge(o))return _r(this,Sr,"m",R0).call(this,o);if(!gn(o))return;let u=o;if(!i&&Eo(u))return;if(!i&&Ls(u))this.dynamicAnchors.pop();for(let p of we(u))_r(this,Sr,"m",e).call(this,u[p],!1)},gh=function(o){this.ids.push(o);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(o);_r(this,Sr,"m",dh).call(this,o,!0)},yh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&O(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();_r(this,Sr,"m",fh).call(this,o,!0)},k0=function(o,i){_r(this,Sr,"m",gh).call(this,i),this.resolvedResources.set(o,i)},C0=function(o){if(!this.resolvedResources.has(o))return;let i=this.resolvedResources.get(o);_r(this,Sr,"m",yh).call(this,i),this.resolvedResources.delete(o)};function nj(e){let o=e.Functions().join(`;
|
|
31
|
-
`),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${i.join("; ")} }`}function oj(e,o){return Jy("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(_n,K,eu,Yi,e.External().variables)}function sj(e){let o=new Oi(e.Context(),e.Schema()),i=new _n;return(u)=>At(o,i,e.Schema(),u)}function ij(e,o){return Vy()?oj(e,o):sj(e)}class P0{constructor(e,o,i){this.isAccelerated=e,this.code=o,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class $0{constructor(e,o,i,u,p,g){this.context=e,this.schema=o,this.external=i,this.functions=u,this.entry=p,this.useUnevaluated=g}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=nj(this),o=ij(this,e);return new P0(Vy(),e,o)}}function tl(...e){let[o,i]=wn(e,{2:(E,S)=>[E,S],1:(E)=>[{},E]});MR(),y0();let u=new Oi(o,i),p=new Of(vR(o,i)),g=js(u,p,i,"value"),y=x0(),b=OR();return new $0(o,i,b,y,g,p.UseUnevaluated())}function rl(...e){let[o,i,u]=wn(e,{3:(w,R,k)=>[w,R,k],2:(w,R)=>[{},w,R]}),p=new Oi(o,i),g=new qn,y=mr(p,g,"#","",i,u),b=g.GetErrors(),E=ox(),S=b.map((w)=>({...w,message:E(w)}));return[y,S]}function Ih(...e){let[o,i,u]=wn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),p=new Oi(o,i),g=new _n;return At(p,g,i,u)}function Xt(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Ih(o,i,u)}function ks(...e){let[o,i,u]=wn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),[p,g]=rl(o,i,u);return g}class fa extends Error{constructor(e,o,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:o},writable:!1,configurable:!1,enumerable:!1})}}function v0(e,o,i){if(!Ge(i))return i;return i.map((u)=>yn(e,o.items,u))}function M0(e,o,i){return yn({...e,...o.$defs},un(o.$ref),i)}function cj(e,o){let i=fe(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Co(e,o),p=Rn(u);return Qe(p)?lp(p,i):p}function O0(e,o,i){let u=cj(e,o);return yn(e,u,i)}function nl(e){return fe(e,"additionalProperties")?e.additionalProperties:void 0}function _0(e,o,i){if(!at(i)||Ge(i))return i;let u=nl(o);for(let p of we(i)){if(fe(o.properties,p)){i[p]=yn(e,o.properties[p],i[p]);continue}if(pn(u)&&O(u,!0)||Pr(u)&&Xt(e,u,i[p])){i[p]=yn(e,u,i[p]);continue}delete i[p]}return i}function L0(e,o,i){if(!at(i))return i;let u=nl(o),[p,g]=[new RegExp(hn(o)),fr(o)];for(let y of we(i)){if(p.test(y)){i[y]=yn(e,g,i[y]);continue}if(pn(u)&&O(u,!0)||Pr(u)&&Xt(e,u,i[y])){i[y]=yn(e,u,i[y]);continue}delete i[y]}return i}function N0(e,o,i){return fe(e,o.$ref)?yn(e,e[o.$ref],i):i}function D0(e,o,i){if(!Ge(i))return i;let u=Math.min(i.length,o.items.length);for(let p=0;p<u;p++)i[p]=yn(e,o.items[p],i[p]);return Ki(i.length,u)?i.slice(0,u):i}function Vr(e){return Ra(e)}function q0(e,o,i){for(let u of o.anyOf){let p=yn(e,u,Vr(i));if(Xt(e,u,p))return p}return i}function yn(e,o,i){return wt(o)?v0(e,o,i):Qt(o)?M0(e,o,i):ze(o)?O0(e,o,i):Qe(o)?_0(e,o,i):Gt(o)?L0(e,o,i):qt(o)?N0(e,o,i):mt(o)?D0(e,o,i):xe(o)?q0(e,o,i):i}function mj(e,o){for(let i of we(e)){if(fe(o,i))continue;o[i]=e[i]}return o}function pj(e){let o={};for(let i of we(e))o[i]=Oc(e[i]);return o}function lj(e){return bh(lR(e))}function bh(e){return e.map((o)=>Oc(o))}function Oc(e){let o=wt(e)?B(Oc(e.items),ka(e)):ze(e)?Pn(bh(e.allOf)):xe(e)?m(lj(e.anyOf)):Qe(e)?l(pj(e.properties)):Gt(e)?bs(ni(e),Oc(fr(e))):mt(e)?Ur(bh(e.items)):e;return mj(e,o)}function tu(e){return Oc(e)}function _o(...e){let[o,i,u]=wn(e,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]}),p=Jo().unionPrioritySort?tu(i):i;return yn(o,p,u)}function fo(e){return at(e)&&fe(e,"value")}function We(e){return{value:e}}function wr(){return}function dj(e){return Ge(e)?We(e):We([e])}function fj(e){return O(e,!0)?We(BigInt(1)):We(BigInt(0))}var hj=/^-?(0|[1-9]\d*)n$/,gj=/^-?(0|[1-9]\d*)\.\d+$/,yj=/^-?(0|[1-9]\d*)$/;function xj(e){return hj.test(e)}function Ij(e){return gj.test(e)}function bj(e){return yj.test(e)}function Ej(e){let o=e.toLowerCase();return xj(e)?We(BigInt(e.slice(0,e.length-1))):Ij(e)?We(BigInt(e.split(".")[0])):bj(e)?We(BigInt(e)):O(o,"false")?We(BigInt(0)):O(o,"true")?We(BigInt(1)):wr()}function ol(e){return Nr(e)?We(e):pn(e)?fj(e):Ot(e)?We(BigInt(Math.trunc(e))):ho(e)?We(BigInt(0)):gt(e)?Ej(e):Ut(e)?We(BigInt(0)):wr()}function Sj(e){return O(e,BigInt(0))?We(!1):O(e,BigInt(1))?We(!0):wr()}function wj(e){return O(e,0)?We(!1):O(e,1)?We(!0):wr()}function Tj(e){return O(e.toLowerCase(),"false")?We(!1):O(e.toLowerCase(),"true")?We(!0):O(e,"0")?We(!1):O(e,"1")?We(!0):wr()}function F0(e){return Nr(e)?Sj(e):pn(e)?We(e):Ot(e)?wj(e):ho(e)?We(!1):gt(e)?Tj(e):Ut(e)?We(!1):wr()}function Rj(e){return O(e,BigInt(0))?We(null):wr()}function kj(e){return O(e,!1)?We(null):wr()}function Aj(e){return O(e,0)?We(null):wr()}function Cj(e){let o=e.toLowerCase();return O(o,"undefined")||O(o,"null")||O(e,"")||O(e,"0")?We(null):wr()}function Pj(e){return Nr(e)?Rj(e):pn(e)?kj(e):Ot(e)?Aj(e):ho(e)?We(null):gt(e)?Cj(e):Ut(e)?We(null):wr()}var j0=BigInt(Number.MAX_SAFE_INTEGER),U0=BigInt(Number.MIN_SAFE_INTEGER);function $j(e){return e<=j0&&e>=U0?We(Number(e)):wr()}function vj(e){return We(e?1:0)}function Mj(e){let o=+e;if(Ot(o))return We(o);let i=e.toLowerCase();if(O(i,"false"))return We(0);if(O(i,"true"))return We(1);let u=ol(e);if(fo(u))return u.value<=j0&&u.value>=U0?We(Number(u.value)):wr();return wr()}function Eh(e){return Nr(e)?$j(e):pn(e)?vj(e):Ot(e)?We(e):ho(e)?We(0):gt(e)?Mj(e):Ut(e)?We(0):wr()}function B0(e){return Nr(e)?We(e.toString()):pn(e)?We(e.toString()):Ot(e)?We(e.toString()):ho(e)?We("null"):gt(e)?We(e):Ut(e)?We(""):wr()}function Oj(e){return O(e,BigInt(0))?We(void 0):wr()}function _j(e){return O(e,!1)?We(void 0):wr()}function Lj(e){return O(e,0)?We(void 0):wr()}function Nj(e){let o=e.toLowerCase();return O(o,"undefined")||O(o,"null")||O(e,"")||O(e,"0")?We(void 0):wr()}function G0(e){return Nr(e)?Oj(e):pn(e)?_j(e):Ot(e)?Lj(e):ho(e)?We(void 0):gt(e)?Nj(e):Ut(e)?We(e):wr()}function K0(e,o,i){return dj(i).value.map((p)=>Yr(e,o.items,p))}function H0(e,o,i){let u=ol(i);return fo(u)?u.value:i}function W0(e,o,i){let u=F0(i);return fo(u)?u.value:i}function z0(e,o,i){return Yr({...e,...o.$defs},un(o.$ref),i)}function V0(e,o,i){return Yr(e,Rn(o),i)}function J0(e,o,i){let u=Eh(i);return fo(u)?Math.trunc(u.value):i}function Q0(e,o,i){let u=Co(e,o),p=Rn(u);return Yr(e,p,i)}function Dj(e,o,i){let u=ol(i);return fo(u)&&O(o.const,u.value)?u.value:i}function qj(e,o,i){let u=F0(i);return fo(u)&&O(o.const,u.value)?u.value:i}function Fj(e,o,i){let u=Eh(i);return fo(u)&&O(o.const,u.value)?u.value:i}function jj(e,o,i){let u=B0(i);return fo(u)&&O(o.const,u.value)?u.value:i}function X0(e,o,i){if(O(o.const,i))return i;return fx(o)?Dj(e,o,i):hx(o)?qj(e,o,i):gm(o)?Fj(e,o,i):ym(o)?jj(e,o,i):jr()}function Y0(e,o,i){let u=Pj(i);return fo(u)?u.value:i}function Z0(e,o,i){let u=Eh(i);return fo(u)?u.value:i}function sl(e,o,i,u){let p=we(u);for(let[g,y]of o)for(let b of p)if(!g.test(b))u[b]=Yr(e,i,u[b]);return u}function _c(e,o,i){return cn(e)&&Ut(i[o])}function Uj(e,o,i){let u=ld(o.properties),p=we(i);for(let[g,y]of u)for(let b of p){if(!g.test(b)||_c(y,b,i))continue;i[b]=Yr(e,y,i[b])}return fe(o,"additionalProperties")&&at(o.additionalProperties)?sl(e,u,o.additionalProperties,i):i}function eC(e,o,i){return Vo(i)?Uj(e,o,i):i}function Bj(e,o,i){let u=ld(o.patternProperties),p=we(i);for(let[g,y]of u)for(let b of p)if(g.test(b))i[b]=Yr(e,y,i[b]);return fe(o,"additionalProperties")&&at(o.additionalProperties)?sl(e,u,o.additionalProperties,i):i}function tC(e,o,i){return Vo(i)?Bj(e,o,i):i}function rC(e,o,i){return fe(e,o.$ref)?Yr(e,e[o.$ref],i):i}function nC(e,o,i){let u=B0(i);return fo(u)?u.value:i}function oC(e,o,i){return Yr(e,Rn(o),i)}function sC(e,o,i){if(!Ge(i))return i;for(let u=0;u<Math.min(o.items.length,i.length);u++)i[u]=Yr(e,o.items[u],i[u]);return i}function iC(e,o,i){let u=G0(i);return fo(u)?u.value:i}function aC(e,o,i){if(o.anyOf.some((y)=>Xt(e,y,i)))return i;let g=o.anyOf.map((y)=>Yr(e,y,Vr(i))).find((y)=>Xt(e,o,y));return Ut(g)?i:g}function uC(e,o,i){let u=G0(i);return fo(u)?void 0:i}function Yr(e,o,i){return wt(o)?K0(e,o,i):mo(o)?H0(e,o,i):Wn(o)?W0(e,o,i):Qt(o)?z0(e,o,i):on(o)?V0(e,o,i):fn(o)?J0(e,o,i):ze(o)?Q0(e,o,i):yt(o)?X0(e,o,i):xs(o)?Y0(e,o,i):kr(o)?Z0(e,o,i):Qe(o)?eC(e,o,i):Gt(o)?tC(e,o,i):qt(o)?rC(e,o,i):sn(o)?nC(e,o,i):ur(o)?oC(e,o,i):mt(o)?sC(e,o,i):Zo(o)?iC(e,o,i):xe(o)?aC(e,o,i):po(o)?uC(e,o,i):i}function as(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Yr(o,i,u)}function cC(e,o,i){if(!Ge(i))return i;for(let u=0;u<i.length;u++)i[u]=xn(e,o.items,i[u]);return i}function mC(e,o,i){return xn({...e,...o.$defs},un(o.$ref),i)}function pC(e,o){if(!Ut(o))return o;return ms(e.default)?e.default():Vr(e.default)}function lC(e,o,i){let u=Co(e,o),p=Rn(u);return xn(e,p,i)}function dC(e,o,i){if(!at(i))return i;let u=we(o.properties);for(let p of u){let g=xn(e,o.properties[p],i[p]);if(Ut(g)&&(cn(o.properties[p])||!fe(o.properties[p],"default")))continue;i[p]=g}if(!Po(o)||pn(o.additionalProperties))return i;for(let p of we(i)){if(u.includes(p))continue;i[p]=xn(e,o.additionalProperties,i[p])}return i}function fC(e,o,i){if(!at(i))return i;let[u,p]=[new RegExp(hn(o)),fr(o)];for(let g of we(i)){if(!(u.test(g)&&bo(p)))continue;i[g]=xn(e,p,i[g])}if(!Po(o))return i;for(let g of we(i)){if(u.test(g))continue;i[g]=xn(e,o.additionalProperties,i[g])}return i}function hC(e,o,i){return fe(e,o.$ref)?xn(e,e[o.$ref],i):i}function gC(e,o,i){if(!Ge(i))return i;let[u,p]=[o.items,Math.max(o.items.length,i.length)];for(let g=0;g<p;g++)if(g<u.length)i[g]=xn(e,u[g],i[g]);return i}function yC(e,o,i){for(let u of o.anyOf){let p=xn(e,u,Vr(i));if(Xt(e,u,p))return p}return i}function xn(e,o,i){let u=bo(o)?pC(o,i):i;return wt(o)?cC(e,o,u):Qt(o)?mC(e,o,u):ze(o)?lC(e,o,u):Qe(o)?dC(e,o,u):Gt(o)?fC(e,o,u):qt(o)?hC(e,o,u):mt(o)?gC(e,o,u):xe(o)?yC(e,o,u):u}function Us(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return xn(o,i,u)}function ru(e){return(...o)=>{let[i,u,p]=wn(o,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]});return e.reduce((g,y)=>y(i,u,g),p)}}function Gj(e,o,i){return o["~codec"].decode(i)}function Kj(e,o,i){return o["~codec"].encode(i)}function Tr(e,o,i,u){if(!Hn(i))return u;return O(e,"Decode")?Gj(o,i,u):Kj(o,i,u)}function Hj(e,o,i,u){if(!Ge(u))return u;for(let p=0;p<u.length;p++)u[p]=Cr(e,o,i.items,u[p]);return Tr(e,o,i,u)}function Wj(e,o,i,u){let p=Tr(e,o,i,u);if(!Ge(p))return p;for(let g=0;g<p.length;g++)p[g]=Cr(e,o,i.items,p[g]);return p}function xC(e,o,i,u){return O(e,"Decode")?Hj(e,o,i,u):Wj(e,o,i,u)}function IC(e,o,i,u){return u=Cr(e,{...o,...i.$defs},un(i.$ref),u),Tr(e,o,i,u)}function bC(e){return e.reduce((o,i)=>({...o,...i}),{})}function EC(e,o){for(let i of o)if(!Ta(e,i))return i;return e}function zj(e,o,i,u){if(O(i.allOf.length,0))return Tr(e,o,i,u);let p=i.allOf.map((b)=>Cr(e,o,b,_o(b,Vr(u)))),y=p.every((b)=>at(b))?bC(p):EC(u,p);return Tr(e,o,i,y)}function Vj(e,o,i,u){if(O(i.allOf.length,0))return Tr(e,o,i,u);let p=Tr(e,o,i,u),g=i.allOf.map((b)=>Cr(e,o,b,_o(b,Vr(p))));if(g.every((b)=>at(b)))return bC(g);return EC(p,g)}function SC(e,o,i,u){return O(e,"Decode")?zj(e,o,i,u):Vj(e,o,i,u)}function Jj(e,o,i,u){if(!Vo(u))return u;for(let p of we(i.properties)){if(!fe(u,p)||_c(i.properties[p],p,u))continue;u[p]=Cr(e,o,i.properties[p],u[p])}return Tr(e,o,i,u)}function Qj(e,o,i,u){let p=Tr(e,o,i,u);if(!Vo(p))return p;for(let g of we(i.properties)){if(!fe(p,g)||_c(i.properties[g],g,p))continue;p[g]=Cr(e,o,i.properties[g],p[g])}return p}function wC(e,o,i,u){return O(e,"Decode")?Jj(e,o,i,u):Qj(e,o,i,u)}function Xj(e,o,i,u){if(!Vo(u))return u;let p=new RegExp(hn(i));for(let g of we(u)){if(!p.test(g))continue;u[g]=Cr(e,o,fr(i),u[g])}return Tr(e,o,i,u)}function Yj(e,o,i,u){let p=Tr(e,o,i,u);if(!Vo(p))return p;let g=new RegExp(hn(i));for(let y of we(p)){if(!g.test(y))continue;p[y]=Cr(e,o,fr(i),p[y])}return p}function TC(e,o,i,u){return O(e,"Decode")?Xj(e,o,i,u):Yj(e,o,i,u)}function RC(e,o,i,u){return fe(o,i.$ref)?Cr(e,o,o[i.$ref],u):u}function kC(e,o,i,u){return O(e,"Decode")?Tr(e,o,i,RC(e,o,i,u)):RC(e,o,i,Tr(e,o,i,u))}function Zj(e,o,i,u){if(!Ge(u))return u;for(let p=0;p<Math.min(i.items.length,u.length);p++)u[p]=Cr(e,o,i.items[p],u[p]);return Tr(e,o,i,u)}function eU(e,o,i,u){let p=Tr(e,o,i,u);if(!Ge(p))return u;for(let g=0;g<Math.min(i.items.length,p.length);g++)p[g]=Cr(e,o,i.items[g],p[g]);return p}function AC(e,o,i,u){return O(e,"Decode")?Zj(e,o,i,u):eU(e,o,i,u)}function tU(e,o,i,u){for(let p of i.anyOf){if(!Xt(o,p,u))continue;let g=Cr(e,o,p,u);return Tr(e,o,i,g)}return u}function rU(e,o,i,u){let p=Tr(e,o,i,u);for(let g of i.anyOf){let y=Cr(e,o,g,Vr(p));if(!Xt(o,g,y))continue;return y}return p}function CC(e,o,i,u){return O(e,"Decode")?tU(e,o,i,u):rU(e,o,i,u)}function Cr(e,o,i,u){return wt(i)?xC(e,o,i,u):Qt(i)?IC(e,o,i,u):ze(i)?SC(e,o,i,u):Qe(i)?wC(e,o,i,u):Gt(i)?TC(e,o,i,u):qt(i)?kC(e,o,i,u):mt(i)?AC(e,o,i,u):xe(i)?CC(e,o,i,u):Tr(e,o,i,u)}class PC extends fa{constructor(e,o){super("Decode",e,o)}}function nU(e,o,i){if(!Xt(e,o,i))throw new PC(i,ks(e,o,i));return i}function oU(e,o,i){let u=Jo().unionPrioritySort?tu(o):o;return Cr("Decode",e,u,i)}var sU=ru([(e,o,i)=>Vr(i),(e,o,i)=>Us(e,o,i),(e,o,i)=>as(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>nU(e,o,i),(e,o,i)=>oU(e,o,i)]);function Sh(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return sU(o,i,u)}class $C extends fa{constructor(e,o){super("Encode",e,o)}}function iU(e,o,i){if(!Xt(e,o,i))throw new $C(i,ks(e,o,i));return i}function aU(e,o,i){let u=Jo().unionPrioritySort?tu(o):o;return Cr("Encode",e,u,i)}var uU=ru([(e,o,i)=>Vr(i),(e,o,i)=>aU(e,o,i),(e,o,i)=>Us(e,o,i),(e,o,i)=>as(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>iU(e,o,i)]);function wh(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return uU(o,i,u)}function cU(e,o){return Hn(o)||Ni(e,o.items)}function mU(e,o){return Hn(o)||vC({...e,...o.$defs},un(o.$ref))}function pU(e,o){return Hn(o)||o.allOf.some((i)=>Ni(e,i))}function lU(e,o){return Hn(o)||we(o.properties).some((i)=>Ni(e,o.properties[i]))}function dU(e,o){return Hn(o)||Ni(e,fr(o))}function vC(e,o){if(Th.has(o.$ref))return!1;return Th.add(o.$ref),Hn(o)||fe(e,o.$ref)&&Ni(e,e[o.$ref])}function fU(e,o){return Hn(o)||o.items.some((i)=>Ni(e,i))}function hU(e,o){return Hn(o)||o.anyOf.some((i)=>Ni(e,i))}function Ni(e,o){return wt(o)?cU(e,o):Qt(o)?mU(e,o):ze(o)?pU(e,o):Qe(o)?lU(e,o):Gt(o)?dU(e,o):qt(o)?vC(e,o):mt(o)?fU(e,o):xe(o)?hU(e,o):Hn(o)}var Th=new Set;function Rh(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Th.clear(),Ni(o,i)}class us extends Error{constructor(e,o){super(o);this.type=e}}function MC(e,o){return ms(o.default)?o.default(o):at(o.default)?Vr(o.default):o.default}function OC(e,o){if(Ti(o)&&!bo(o))throw new us(o,"Arrays with uniqueItems constraints must specify a default annotation");let i=Ei(o)?o.minItems:0;return Array.from({length:i},()=>Zr(e,o.items))}function _C(e,o){return es(o)?BigInt(o.exclusiveMinimum)+BigInt(1):ts(o)?BigInt(o.minimum):BigInt(0)}function LC(e,o){return!1}function NC(e,o){let i=Zr(e,o.instanceType);return class{constructor(){Object.assign(this,i)}}}function DC(e,o){return Zr({...e,...o.$defs},un(o.$ref))}function qC(e,o){return Zr(e,Rn(o))}function FC(e,o){let i=Zr(e,o.returnType);return()=>i}function jC(e,o){return es(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:ts(o)?o.minimum:0}function UC(e,o){let i=Co(e,o),u=Rn(i);return Zr(e,u)}function BC(e,o){return o.const}function GC(e,o){throw new us(o,"Cannot create TNever types")}function KC(e,o){return null}function HC(e,o){return es(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:ts(o)?o.minimum:0}function WC(e,o){return(Ut(o.required)?[]:o.required).reduce((u,p)=>({...u,[p]:Zr(e,o.properties[p])}),{})}function zC(e,o){if(la(o)&&!bo(o))throw new us(o,"Record with the minProperties constraint must have a default annotation");return{}}function VC(e,o){return fe(e,o.$ref)?Zr(e,e[o.$ref]):(()=>{throw new us(o,"Unable to deref Ref")})()}function JC(e,o){if((da(o)||ma(o))&&!bo(o))throw Error("Strings with format or pattern constraints must specify default");let u=pa(o)?o.minLength:0;return"".padEnd(u)}function QC(e,o){return Symbol()}function XC(e,o){let i=Mu(o.pattern);if(sn(i))throw new us(o,"Unable to create TemplateLiteral due to infinite type expansion");return Zr(e,i)}function YC(e,o){return Array.from({length:o.minItems},(i,u)=>Zr(e,o.items[u]))}function ZC(e,o){return}function eP(e,o){if(O(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Zr(e,o.anyOf[0])}function tP(e,o){return}function Zr(e,o){return bo(o)?MC(e,o):wt(o)?OC(e,o):mo(o)?_C(e,o):Wn(o)?LC(e,o):en(o)?NC(e,o):Qt(o)?DC(e,o):on(o)?qC(e,o):tn(o)?FC(e,o):fn(o)?jC(e,o):ze(o)?UC(e,o):yt(o)?BC(e,o):co(o)?GC(e,o):xs(o)?KC(e,o):kr(o)?HC(e,o):Qe(o)?WC(e,o):Gt(o)?zC(e,o):qt(o)?VC(e,o):sn(o)?JC(e,o):Is(o)?QC(e,o):ur(o)?XC(e,o):mt(o)?YC(e,o):Zo(o)?ZC(e,o):xe(o)?eP(e,o):po(o)?tP(e,o):void 0}function As(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Zr(o,i)}class il extends fa{constructor(e,o){super("Parse",e,o)}}function gU(e,o,i){if(!Xt(e,o,i))throw new il(i,ks(e,o,i));return i}var rP=ru([(e,o,i)=>Vr(i),(e,o,i)=>Us(e,o,i),(e,o,i)=>as(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>gU(e,o,i)]);var xU=l({type:s("insert"),path:a(),value:Rr()}),IU=Object({type:s("update"),path:a(),value:Rr()}),bU=l({type:s("delete"),path:a()}),DOe=m([xU,IU,bU]);class al{constructor(e,o){this.hasCodec=Rh(e,o),this.buildResult=tl(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(Jo().correctiveParse)return rP(this.Context(),this.Type(),e);throw new il(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return ks(this.Context(),this.Type(),e)}Clean(e){return _o(this.Context(),this.Type(),e)}Convert(e){return as(this.Context(),this.Type(),e)}Create(){return As(this.Context(),this.Type())}Default(e){return Us(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Sh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?wh(this.Context(),this.Type(),e):this.Parse(e)}}function Ah(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return new al(o,i)}var oP=new WeakMap,wU=Symbol.for("TypeBox.Kind");function TU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function RU(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 Ch(e){try{return iP(e)}catch{return}}function kU(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isFinite(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isInteger(i))return i}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 AU(e,o){let i=o.properties,u=new Set(i?Object.keys(i):[]);if(i)for(let[p,g]of Object.entries(i)){if(!(p in e))continue;e[p]=ga(e[p],g)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[p,g]of Object.entries(e)){if(u.has(p))continue;e[p]=ga(g,o.additionalProperties)}}function CU(e,o){if(Array.isArray(o.items)){for(let i=0;i<e.length;i++){let u=o.items[i];if(!u)continue;e[i]=ga(e[i],u)}return}if(o.items&&typeof o.items==="object")for(let i=0;i<e.length;i++)e[i]=ga(e[i],o.items)}function sP(e,o){for(let i of o)if(Ch(i)?.Check(e))return e;for(let i of o){let u=structuredClone(e),p=ga(u,i);if(Ch(i)?.Check(p))return p}return e}function ga(e,o){let i=e;if(Array.isArray(o.allOf))for(let g of o.allOf)i=ga(i,g);if(Array.isArray(o.anyOf))i=sP(i,o.anyOf);if(Array.isArray(o.oneOf))i=sP(i,o.oneOf);let u=TU(o),p=u.length>1&&u.some((g)=>RU(i,g));if(u.length>0&&!p)for(let g of u){let y=kU(i,g);if(y!==i){i=y;break}}if(u.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))AU(i,o);if(u.includes("array")&&Array.isArray(i))CU(i,o);return i}function ul(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let p=0;p<e.length;p++){let g=o.items[p];if(g)ul(e[p],g)}else if(o.items)for(let p of e)ul(p,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let i=e,u=new Set(o.required??[]);for(let[p,g]of Object.entries(o.properties)){if(!(p in i))continue;if(i[p]===null&&!u.has(p)&&typeof g.$ref!=="string"&&Ch(g)?.Check(null)===!1)delete i[p];else ul(i[p],g)}}function iP(e){let o=e,i=oP.get(o);if(i)return i;let u=Ah(e);return oP.set(o,u),u}function PU(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 $U(e,o){let i=e.find((u)=>u.name===o.name);if(!i)throw Error(`Tool "${o.name}" not found`);return nu(i,o)}function nu(e,o){let i=structuredClone(o.arguments);ul(i,e.parameters),as(e.parameters,i);let u=iP(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(wU)){let y=ga(i,e.parameters);if(y!==i)if(typeof i==="object"&&i!==null&&typeof y==="object"&&y!==null){for(let b of Object.keys(i))delete i[b];Object.assign(i,y)}else return u.Check(y)?y:i}if(u.Check(i))return i;let p=u.Errors(i).map((y)=>` - ${PU(y)}: ${y.message}`).join(`
|
|
32
|
-
`)||"Unknown validation error",g=`Validation failed for tool "${o.name}":
|
|
33
|
-
${p}
|
|
34
|
-
|
|
35
|
-
Received arguments:
|
|
36
|
-
${JSON.stringify(o.arguments,null,2)}`;throw Error(g)}var aP;function Lc(){if(!aP)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return aP}async function uP(e,o,i,u,p,g){let y=pP(o,e),b=[...y],E={...o,messages:[...o.messages,...y]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let S of y)await u({type:"message_start",message:S}),await u({type:"message_end",message:S});return await mP(E,b,i,p,u,g??Lc()),b}async function cP(e,o,i,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 g=[],y={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await mP(y,g,o,u,i,p??Lc()),g}async function mP(e,o,i,u,p,g){let y=e,b=i,E,S=!1,w=await b.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||w.length>0){let A=[];if(E){let J=await b.prepareNextTurn?.(E);if(J)y=J.context??y,A=J.messages??[],b={...b,model:J.model??b.model,reasoning:J.thinkingLevel===void 0?b.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(w.length===0)w=await b.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let J of pP(y,[...A,...w]))await p({type:"message_start",message:J}),await p({type:"message_end",message:J}),y.messages.push(J),o.push(J);w=[];let C=await b.prepareRequest?.({context:y,model:b.model,thinkingLevel:b.reasoning??"off"},u);if(C)y=C.context??y,b={...b,model:C.model??b.model,reasoning:C.thinkingLevel===void 0?b.reasoning:C.thinkingLevel==="off"?void 0:C.thinkingLevel};let q=await MU(y,b,u,p,g);if(o.push(q),q.stopReason==="error"||q.stopReason==="aborted"){E={message:q,toolResults:[],context:y,newMessages:o},await b.finishTurn?.(E,u),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:o});return}let X=q.content.filter((J)=>J.type==="toolCall"),j=[];if(R=!1,X.length>0){let J=q.stopReason==="length"?await OU(X,p):await _U(y,q,b,u,p);j.push(...J.messages),R=!J.terminate;for(let ee of j)y.messages.push(ee),o.push(ee)}E={message:q,toolResults:j,context:y,newMessages:o};let V=await b.finishTurn?.(E,u);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:o});return}if(S=V?.action==="continue",w=await b.getSteeringMessages?.()||[],R||w.length>0)S=!1}let k=await b.getFollowUpMessages?.()||[];if(k.length>0){S=!1,w=k;continue}if(S){S=!1;continue}break}await p({type:"agent_end",messages:o})}function pP(e,o){let i=-1;for(let w=o.length-1;w>=0;w--)if(o[w].role==="system"){i=w;break}let u=o[i],p=u?o.map((w,R)=>R===i?Ph(u,vU):w):o,g=Go(oe([...e.messages,...p]),(e.tools??[]).map(nt)),y=g.toolsAdded.length===0&&g.toolsRemoved.length===0;if(u){if(y&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return p.map((w,R)=>R===i?Ph(u,g):w)}if(y)return o;let b=Ph({role:"system",content:"",timestamp:Date.now()},g),E=o.findIndex((w)=>w.role!=="system"),S=E===-1?o.length:E;return[...o.slice(0,S),b,...o.slice(S)]}var vU={toolsAdded:[],toolsRemoved:[]};function Ph(e,{toolsAdded:o,toolsRemoved:i}){let{toolsAdded:u,toolsRemoved:p,...g}=e;return{...g,...o.length>0?{toolsAdded:o}:{},...i.length>0?{toolsRemoved:i}:{}}}async function MU(e,o,i,u,p){let g=e.messages;if(o.transformContext)g=await o.transformContext(g,i);let y=await o.convertToLlm(g),b=ft({messages:y}),E=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,S=await p(o.model,b,{...o,apiKey:E,signal:i}),w=async()=>Object.assign(await S.result(),{thinkingLevel:o.reasoning??"off"}),R=null,k=!1;for await(let C of S)switch(C.type){case"start":R=C.partial,e.messages.push(R),k=!0,await u({type:"message_start",message:{...R}});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(R)R=C.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:C,message:{...R}});break;case"done":case"error":{let q=await w();if(k)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!k)await u({type:"message_start",message:{...q}});return await u({type:"message_end",message:q}),q}}let A=await w();if(k)e.messages[e.messages.length-1]=A;else e.messages.push(A),await u({type:"message_start",message:{...A}});return await u({type:"message_end",message:A}),A}async function OU(e,o){let i=[];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:Gs(`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 Nc(p,o);let g=$h(p);await vh(g,o),i.push(g)}return{messages:i,terminate:!1}}async function _U(e,o,i,u,p){let g=o.content.filter((b)=>b.type==="toolCall"),y=g.some((b)=>e.tools?.find((E)=>E.name===b.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||y)return LU(e,o,g,i,u,p);return NU(e,o,g,i,u,p)}async function LU(e,o,i,u,p,g){let y=[],b=[];for(let E of i){await g({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await dP(e,o,E,u,p),w;if(S.kind==="immediate")w={toolCall:E,result:S.result,isError:S.isError};else{let k=await hP(S,p,fP(E,g));w=await gP(e,o,S,k,u,p)}await Nc(w,g);let R=$h(w);if(await vh(R,g),y.push(w),b.push(R),p?.aborted)break}return{messages:b,terminate:lP(y)}}async function NU(e,o,i,u,p,g){let y=[];for(let S of i){await g({type:"tool_execution_start",toolCallId:S.id,toolName:S.name,args:S.arguments});let w=await dP(e,o,S,u,p);if(w.kind==="immediate"){let R={toolCall:S,result:w.result,isError:w.isError};if(await Nc(R,g),y.push(R),p?.aborted)break;continue}if(y.push(async()=>{if(p?.aborted){let A={toolCall:S,result:Gs("Operation aborted"),isError:!0};return await Nc(A,g),A}let R=await hP(w,p,fP(S,g)),k=await gP(e,o,w,R,u,p);return await Nc(k,g),k}),p?.aborted)break}let b=await Promise.all(y.map((S)=>typeof S==="function"?S():Promise.resolve(S))),E=[];for(let S of b){let w=$h(S);await vh(w,g),E.push(w)}return{messages:E,terminate:lP(b)}}function lP(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function DU(e,o){if(!e.prepareArguments)return o;let i=e.prepareArguments(o.arguments);if(i===o.arguments)return o;return{...o,arguments:i}}async function dP(e,o,i,u,p,g=e.tools??[]){let y=g.find((b)=>b.name===i.name);if(!y)return{kind:"immediate",result:Gs(`Tool ${i.name} not found`),isError:!0};try{let b=DU(y,i),E=nu(y,b);if(u.beforeToolCall){let S=await u.beforeToolCall({assistantMessage:o,toolCall:i,args:E,context:e},p);if(p?.aborted)return{kind:"immediate",result:Gs("Operation aborted"),isError:!0};if(S?.block){let w=Gs(S.reason||"Tool execution was blocked");if(S.terminate===!0)w.terminate=!0;return{kind:"immediate",result:w,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Gs("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:y,args:E}}catch(b){return{kind:"immediate",result:Gs(b instanceof Error?b.message:String(b)),isError:!0}}}function fP(e,o){return(i)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function hP(e,o,i){let u=[],p=!0,g=performance.now(),y=()=>Math.round(performance.now()-g);try{let b=await e.tool.execute(e.toolCall.id,e.args,o,(S)=>{if(!p)return;u.push(Promise.resolve(i(S)))}),E=y();return p=!1,await Promise.all(u),{result:b,isError:b.isError===!0,durationMs:E}}catch(b){let E=y();return p=!1,await Promise.all(u),{result:Gs(b instanceof Error?b.message:String(b)),isError:!0,durationMs:E}}finally{p=!1}}async function gP(e,o,i,u,p,g){let{result:y,isError:b}=u;if(p.afterToolCall)try{let E=await p.afterToolCall({assistantMessage:o,toolCall:i.toolCall,args:i.args,result:y,isError:b,context:e},g);if(E){let S=E.structuredContent??(E.content?void 0:y.structuredContent);if(y={...y,content:E.content??y.content,details:E.details??y.details,usage:E.usage??y.usage,terminate:E.terminate??y.terminate},S===void 0)delete y.structuredContent;else y.structuredContent=S;b=E.isError??b}}catch(E){y=Gs(E instanceof Error?E.message:String(E)),b=!0}return{toolCall:i.toolCall,result:y,isError:b,durationMs:u.durationMs}}function Gs(e){return{content:[{type:"text",text:e}],details:{}}}async function Nc(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 $h(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 vh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function qU(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}},jU={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 UU(e){let o=e?.tools?.slice()??[],i=e?.messages?.slice()??[],u=Vn(e?.systemPrompt,o.map(nt));if(i[0]?.role!=="system"&&u)i.unshift(u);return{get systemPrompt(){return qo(i)},model:e?.model??jU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(p){o=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Mh{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 Oh{_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=UU(o.initialState),this.convertToLlm=o.convertToLlm??qU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Lc(),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 Mh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Mh(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=Xr(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 i=this.normalizePromptInput(e,o);await this.runPromptMessages(i)}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 i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);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 i=[{type:"text",text:e}];if(o&&o.length>0)i.push(...o);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(i)=>{await uP(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await cP(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(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,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,i=()=>{},u=new Promise((p)=>{i=p});this.activeRun={promise:u,resolve:i,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 i={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:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}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 i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;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 i of this.listeners)await i(e,o)}}function _e(e,...o){return Object.assign(e,{aliases:o})}function ya(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function BU(e){let o=[],i="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(i)o.push(i);i="";continue}if(u>="A"&&u<="Z"&&i&&!/[A-Z]$/.test(i))o.push(i),i="";i+=u}if(i)o.push(i);return o}function yP(e,o){if(e.some((C)=>C.name===o))return o;let i=e.map((C)=>C.name),u=(C)=>i.filter((q)=>ya(q)===C),p=u(ya(o));if(p.length===1&&p[0])return p[0];if(p.length>1)return o;let g=o.split(/[.:/]/).pop()??o,y=g===o?[]:u(ya(g));if(y.length===1&&y[0])return y[0];let b=new Map;for(let C of e)for(let q of C.aliases??[]){let X=ya(q);b.set(X,(b.get(X)??new Set).add(C.name))}let E=(C)=>[...new Set([...u(C),...b.get(C)??[]])],S=E(ya(g));if(S.length===1&&S[0])return S[0];if(S.length>1)return o;let w=BU(g),R=new Set;w.forEach((C,q)=>{R.add(ya(C));let X=w[q+1];if(X)R.add(ya(C+X))});let k=new Set;for(let C of R)for(let q of E(C))k.add(q);let A=[...k];return A.length===1&&A[0]?A[0]:o}function x(e){return e}function En(e,o){let i=o.indexOf("/");if(i<=0)return;return e.getModel(o.slice(0,i),o.slice(i+1))}function tt(e){return`${e.provider}/${e.id}`}function GU(e,o,i){let u=async(g,y)=>{try{if(o){let E=g instanceof Request?g:void 0;o({at:Date.now(),method:y?.method??E?.method??"GET",url:typeof g==="string"?g:g instanceof URL?g.toString():g.url,headers:xP(y?.headers??E?.headers),body:KU(y?.body!==void 0?y.body:E?.body??void 0)})}}catch{}let b=await e(g,y);if(i)try{let E=Date.now(),{status:S,statusText:w}=b,R=xP(b.headers);if(!b.body)return i({at:E,status:S,statusText:w,headers:R,body:""}),b;let k="",A=new TextDecoder,C=new TransformStream({transform(j,V){V.enqueue(j),k+=A.decode(j,{stream:!0}),i({at:E,status:S,statusText:w,headers:R,body:k})},flush(){k+=A.decode(),i({at:E,status:S,statusText:w,headers:R,body:k})}}),q=b.body.pipeThrough(C),X=new Response(q,b);try{Object.defineProperty(X,"url",{value:b.url})}catch{}return X}catch{}return b},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:p})}function xP(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,p)=>{o[p]=u}),o;let i=Array.isArray(e)?e:Object.entries(e);for(let u of i)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function KU(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 HU(e,o){return yP(e,o)}function WU(e,o,i){let u=Date.now(),p=new WeakSet,g=(E)=>{if(!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;let S=Date.now(),w=Math.max(10,S-u);E.generationMs=w},y=async(E)=>{if(!i||!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;if(g(E),p.has(E))return;p.add(E),Object.assign(E,await i(E))},b=(E)=>{let S=E?.content;if(!Array.isArray(S))return;for(let w of S)if(w&&w.type==="toolCall"&&typeof w.name==="string")w.name=HU(o(),w.name)};return{async*[Symbol.asyncIterator](){for await(let E of e){let{partial:S,message:w}=E;b(S),await y(w),b(w),yield E}},result:async()=>{let E=await e.result();return g(E),await y(E),b(E),E}}}function Dc(e,o){let i=(o??[]).filter((b)=>b.kind==="path").map((b)=>`<file path=${JSON.stringify(b.data)} />`),u=(o??[]).filter((b)=>b.kind==="text").map((b)=>`<file name=${JSON.stringify(b.name)}>
|
|
37
|
-
${b.data}
|
|
38
|
-
</file>`),p=(o??[]).filter((b)=>b.kind==="image").map((b)=>({type:"image",data:b.data,mimeType:b.mimeType})),g=(o??[]).filter((b)=>b.kind==="image"&&b.id).map((b)=>`<image id=${JSON.stringify(b.id)} name=${JSON.stringify(b.name)} />`);return{merged:[...i,...u,...g,...e.trim()?[e]:[]].join(`
|
|
39
|
-
|
|
40
|
-
`),images:p}}function _h(e,o){let{merged:i,images:u}=Dc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:i},...u]:i,timestamp:Date.now()}}function IP(e){let o=new Set;for(let b of e.tools){let E=b.name.toLowerCase();if(o.has(E))throw Error(`Tool names collide ignoring case: ${b.name}`);o.add(E)}let i=new Oh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(b,E,S)=>{let{captureRequest:w,captureResponse:R}=e,k=w||R?{...S,fetch:GU(S?.fetch??globalThis.fetch,w?(C)=>w({...C,model:tt(b)}):void 0,R?(C)=>R({...C,model:tt(b)}):void 0)}:S,A=b.api==="openai-completions"||b.api==="openai-responses"?{...b,compat:{...b.compat,supportsDeveloperRole:!1}}:b;return WU(e.models.streamSimple(A,E,k),()=>i.state.tools,e.hooks.response)},convertToLlm:(b)=>b,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:b,model:E})=>{let S=b.messages.findIndex((A)=>A.role!=="system"),w=b.messages.slice(0,S===-1?b.messages.length:S),R=e.hooks.prepare,k=e.hooks.tools?.()??b.tools;if(k){i.state.tools=k;let A=w[0];if(A?.role==="system")w[0]={...A,toolsAdded:k.map(nt),toolsRemoved:void 0}}return{context:{...b,tools:k,messages:await R(w,k,E)}}}:void 0}),u=new Map,p=new Map,g=new WeakSet,y;return i.subscribe((b)=>{if(b.type==="message_update"&&b.message.role==="assistant"){p.clear(),e.hooks.draft(bP(b.message));return}if(b.type==="tool_execution_update"){let S=u.get(b.toolCallId)??Be(b.toolName,b.args),w=Array.isArray(b.partialResult?.content)?b.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";p.set(b.toolCallId,{type:"tool_call",id:b.toolCallId,name:S.name,input:S.input,...S.source?{source:S.source}:{},output:w}),e.hooks.draft([...p.values()]);return}if(b.type==="tool_execution_end"){if(p.delete(b.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(b.type!=="message_end")return;if(g.has(b.message)){e.steerConsumed?.(b.message);return}let E=b.message.role==="user"&&y?{type:"user",text:y.text,...y.attachments?.length?{attachments:y.attachments}:{}}:zU(b.message);if(b.message.role==="user")y=void 0;if(E?.type==="assistant"){for(let S of E.parts)if(S.type==="tool_call")u.set(S.id,S)}if(E?.type==="tool_result"){let S=u.get(E.callID);if(S?.source)Object.assign(E,{name:S.name,source:S.source})}if(E)e.hooks.message(E,b.message);if(b.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(b,E)=>{y={text:b,attachments:E};let{merged:S,images:w}=Dc(b,E);return i.prompt(S,w.length>0?w:void 0)},retry:async()=>{let b=i.state.messages;if(b.at(-1)?.role==="assistant")i.state.messages=b.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(b)=>{g.add(b),i.steer(b)},unsteer:(b)=>{let S=i.steeringQueue?.messages;if(!S)return!1;let w=S.indexOf(b);if(w<0){let k=JSON.stringify(b);w=S.findIndex((A)=>JSON.stringify(A)===k)}if(w<0)return!1;let[R]=S.splice(w,1);if(R)g.delete(R);return!0},abort:()=>i.abort()}}function Lh(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 cl(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:i,source:u}=Be(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:i,...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 bP(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,...Be(o.name,o.arguments)}})}function zU(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:bP(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((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class pt extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function P(e){return e}import{createHash as EP}from"crypto";import{existsSync as VU}from"fs";import{readFile as SP,realpath as ml}from"fs/promises";import{dirname as JU,isAbsolute as wP,relative as TP,resolve as RP,sep as kP}from"path";var AP=[...Bg];class pl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class ll{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 i=JU(RP(e)),u=RP(i,o??"web.tsx");if(!o&&!VU(u))return;let p=TP(await ml(i),await ml(u));if(wP(p)||p===".."||p.startsWith(`..${kP}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let i=this.pending.get(e);if(i)return i;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 i=this.cache.get(e);if(i){let S=!0;for(let[w,R]of i.inputs){let k=await SP(w).catch(()=>{return});if(!k||EP("sha256").update(k).digest("hex")!==R){S=!1;break}}if(S)return i.source;this.cache.delete(e)}let u=await ml(o),p=new Map,g=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:AP,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(S){S.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(w)=>{if(!AP.includes(w.path))throw Error(`Unsupported shared web import: ${w.path}`);return{path:w.path,external:!0}}),S.onLoad({filter:/.*/},async(w)=>{let R=TP(u,await ml(w.path));if(wP(R)||R===".."||R.startsWith(`..${kP}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await SP(w.path);p.set(w.path,EP("sha256").update(k).digest("hex"));return})}}]}).catch((S)=>{let R=(S instanceof AggregateError?S.errors:[S]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:S})});if(!g.success)throw new pl(g.logs.filter((S)=>S.level==="error").map((S)=>({file:S.position?.file??null,line:S.position?.line??null,message:S.message})));let y=g.outputs.find((S)=>S.kind==="entry-point"&&S.path.endsWith(".js")),b=g.outputs.find((S)=>S.path.endsWith(".css"));if(!y||g.outputs.some((S)=>S!==y&&S!==b))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let E=await y.text();return this.cache.set(e,{source:E,css:await b?.text(),inputs:p}),E}}function jo(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Cs(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function dl(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
|
|
41
|
-
|
|
42
|
-
`)}function ou(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function su(e){return e.role==="assistant"&&e.content.length>0}function To(e){let o=[],i=new Map,u=0;for(let p of e){let g=p.raw;if(g.role==="assistant"){if(su(g))u++;for(let y of g.content){if(y.type!=="toolCall")continue;let b={call:y,step:u,message:g};o.push(b),i.set(y.id,b)}}else if(g.role==="toolResult"){let y=i.get(g.toolCallId);if(y)y.result=g}}return o}var fl=new Set(["edit","write"]),CP=new Set(["grep","glob"]);function ao(e,o){let i=Be(e.name,e.arguments).input?.[o];return typeof i==="string"?i:void 0}function PP(e){return[...new Set(To(e).flatMap((o)=>fl.has(Be(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&ao(o.call,"path")?[ao(o.call,"path")]:[]))]}function Nh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function hl(e){let o=[{source:"ASSISTANT_TOOL",text:`${Be(e.call.name,e.call.arguments).name}(${jo(Be(e.call.name,e.call.arguments).input)}) [${Nh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:ou(e.result)});return o}function D(e){let o=0,i=0,u=0;for(let p of e){let g=p.codePointAt(0);if(g<=127)o++;else if(g>=19968&&g<=40959||g>=12288&&g<=12351||g>=65280&&g<=65519||g>=131072&&g<=173791)i++;else u++}return Math.max(0,Math.ceil(o/4+i+u/2))}var Dh=8192;function F(e){let o=e,i=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 i++;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}${jo(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")u+=p.text;else i++;else u=jo(e);return D(u)+16+i*Dh}function Di(e=[]){return e.reduce((o,i)=>o+D(i.name+i.description+jo(i.parameters))+16,0)}function Fn(e,o){let i=e.replace(/\s+/g," ").trim();if(D(i)<=o)return i;let u=Math.min(i.length,o*4);while(u>0&&D(i.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${i.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Ro(e,o,i=Number.POSITIVE_INFINITY){if(D(e)<=o&&e.length<=i)return e;let u=`
|
|
43
|
-
[... omitted; use history tools for the full text ...]
|
|
44
|
-
`,p=Math.floor((o-D(u))/2);if(p<=0)return"";let g=(y)=>{let b=0,E=Math.max(0,Math.min(e.length,p*4,Math.floor((i-u.length)/2)));while(b<E){let S=Math.ceil((b+E)/2),w=y?e.slice(-S):e.slice(0,S);if(D(w)<=p)b=S;else E=S-1}if(!b)return"";return y?e.slice(-b).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,b).replace(/[\uD800-\uDBFF]$/,"")};return`${g(!1)}${u}${g(!0)}`}function gl(e,o){if(D(e.join(`
|
|
45
|
-
`))<=o)return e;let i=(w)=>`- [... ${w} steps omitted; use history tools for the full text ...]`,u=o-D(i(e.length)),p=[],g=[],y=0,b=0,E=e.length-1;while(b<=E){let w=p.length<=g.length,R=w?e[b]:e[E],k=D(`${R}
|
|
46
|
-
`);if(y+k>u)break;if(y+=k,w)p.push(e[b++]);else g.unshift(e[E--])}let S=E-b+1;return[...p,...S>0?[i(S)]:[],...g]}function Ks(e){let o=[],i;for(let u of e){let p=u.entry;if(p.type==="run"&&p.state==="start"){i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=QU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!u.raw)continue;if(!i&&p.type==="user"&&p.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);i.records.push(u)}for(let u of o)u.records=qh(u.records);return o}function qh(e){if(e.length<=1)return[...e];let o=[],i=[],u=new Set;for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;let y=g.raw?.role;if(y==="assistant"){let E=g.raw.content?.filter((S)=>S.type==="toolCall")??[];if(E.length>0)for(let S of E)u.add(S.id);if(o.push(g),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="toolResult"){let b=g.raw;if(b.toolCallId)u.delete(b.toolCallId);if(o.push(g),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="user"){if(o.length===0){o.push(g);continue}let b=e.slice(p+1).some((E)=>E.raw?.role==="assistant");if(u.size>0||b){i.push(g);continue}o.push(g);continue}o.push(g)}if(i.length>0)o.push(...i);return o}function QU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&ca(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ca(i)?"interrupted":"failed";default:return"interrupted"}}function xa(e){for(let o=e.length-1;o>=0;o--){let i=e[o]?.entry;if(i?.type==="compaction")return i.through}return 0}function yl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((i)=>i.entry.seq<=o)}function Fh(e,o){return e.find((i)=>i.start<o&&!yl(i,o)&&i.records.some((u)=>u.entry.seq<=o))}function iu(e){let o=xa(e),u=Ks(e).findLast((p)=>p.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function xl(e){let o=xa(e);return Fh(Ks(e),o)?.end}function qc(e,o){let i=xa(e),u=Ks(e).at(-1);if(!u||u.end!==void 0)return;let p=u.records.filter((w)=>w.entry.seq>i),g=[],y=new Set;for(let w of p){let R=w.raw,k=F(w.raw);if(R.role==="assistant"){for(let A of R.content)if(A.type==="toolCall")y.add(A.id)}else if(R.role==="toolResult")y.delete(R.toolCallId);if(su(R)||!g.length||R.role==="user"&&g.at(-1)?.assistant)g.push({end:w.entry.seq,tokens:k,assistant:su(R),pending:y.size});else{let A=g.at(-1);A.end=w.entry.seq,A.tokens+=k,A.pending=y.size}}let b=g.findLastIndex((w)=>w.assistant),E=0,S;for(let w=g.length-1;w>=0;w--){let R=g[w];if(w<b&&R.assistant&&R.pending===0&&(E<=o||S===void 0))S=R.end;if(E+=R.tokens,E>o&&S!==void 0)break}if(E<=o)return;return S}var $P=2000;function qi(e,o){let i=D(o);if(i<=$P)return o;let u=new TextEncoder().encode(o).length,p=o.split(`
|
|
47
|
-
`).length,g=[`<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 ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
|
|
48
|
-
`),y="</user-text-reference>",b=$P-D(`${g}
|
|
49
|
-
|
|
50
|
-
${y}`);if(b<=0)return o;let E=`${g}
|
|
51
|
-
${Ro(o,b,o.length-g.length-y.length-3)}
|
|
52
|
-
${y}`;return E.length<o.length&&D(E)<i?E:o}function vP(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=qi(e.entry.seq,o.content);return p===o.content?o:{...o,content:p}}let i=!1,u=o.content.map((p)=>{if(p.type!=="text")return p;let g=qi(e.entry.seq,p.text);if(g!==p.text)i=!0;return g===p.text?p:{...p,text:g}});return i?{...o,content:u}:o}function jh(e,o=!1){let i=e.records.filter((A)=>A.entry.type==="user"&&!A.entry.notices&&A.raw.role==="user"),u=i.flatMap((A)=>{let C=A.raw.content;return typeof C==="string"?[]:C.filter((q)=>q.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,g=e.status==="open"?"interrupted":e.status,y="";if(i.length){let A=o?Ro(i.map((C)=>Cs(C.raw)).join(`
|
|
53
|
-
|
|
54
|
-
`),600):i.map((C,q)=>`<user-message sequence="${q+1}">
|
|
55
|
-
${qi(C.entry.seq,Cs(C.raw))}
|
|
56
|
-
</user-message>`).join(`
|
|
57
|
-
|
|
58
|
-
`);y=[`<chunk-input id="${e.id}" status="${g}"${o?' excerpt="true"':""}>`,A,...o?[p]:[],"</chunk-input>"].join(`
|
|
59
|
-
`)}let E=e.records.filter((A)=>A.raw.role==="assistant").at(-1)?.raw,S=E?dl(E):"",w=[];if(g!=="completed"){let A=To(e.records),C=new Map(A.map((J)=>[J.call,J])),q=A.slice(-3),X=new Set(q.map((J)=>J.message)),j=[],V=[];for(let J of e.records){let ee=J.raw;if(ee.role!=="assistant")continue;let pe=X.has(ee);for(let H of ee.content)if(H.type==="text"&&ee!==E&&H.text.trim())if(pe)V.push(`ASSISTANT: ${Fn(H.text,50)}`);else j.push(`- ASSISTANT: ${Fn(H.text,50)}`);else if(H.type==="toolCall"){let le=C.get(H);if(!le)continue;if(pe){if(q.includes(le))for(let he of hl(le))V.push(`${he.source}: ${Ro(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${H.name}(${Fn(jo(H.arguments),40)}) [${Nh(le)}]`)}}w.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,...j.length?[`Earlier steps, oldest first:
|
|
60
|
-
${gl(j,o?300:800).join(`
|
|
61
|
-
`)}`]:[],...V)}let R=PP(e.records),k=[`<chunk-summary id="${e.id}" status="${g}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,S?o?Ro(S,600):S:"No final assistant response was recorded.",...w,...R.length?[`Recorded file changes:
|
|
62
|
-
${Ro(R.join(`
|
|
63
|
-
`),250)}`]:[],...o&&g==="completed"?[p]:[],"</chunk-summary>"].join(`
|
|
64
|
-
`);return{input:y,images:u,summary:k,tokens:XU(y,k,u.length)}}function XU(e,o,i){return(e?D(e)+16:0)+D(o)+16+i*Dh}var YU=["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."],ZU="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.",eB=1500,tB=80,rB=240;function MP(e,o,i){let u=[],p=0,g=Math.min(o.target,o.hard);for(let b=e.length-1;b>=0;b--){let E=e[b],S=jh(E),w=p+S.tokens>g?jh(E,!0):void 0,R=w&&w.tokens<S.tokens?w:S;if(!(!i&&b===e.length-1&&E.status!=="completed")&&p+R.tokens>o.hard)break;p+=R.tokens,u.push({run:E,content:R})}u.reverse();let y=e.slice(0,e.length-u.length);return{visible:u,archived:y,tokens:p}}function OP(e){let{runs:o,visible:i,archived:u,partial:p}=e,g=u.flatMap((E)=>{let S=E.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>Cs(R.raw));if(!S.length)return[];let w=E===o[0]?rB:tB;return[`- ${E.id} [${E.status}]: ${Fn(S.join(" / "),w)}`]}),y=new Map(o.map((E,S)=>[E,S+1])),b=[...i.map((E)=>y.get(E)??0),...p?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...YU,...p?[ZU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((E)=>E.id).join(", "):"none"}`,`visible sequences: ${b.length?`${b[0]}..${b.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...g.length?["archived requests, oldest first:",Ro(g.join(`
|
|
65
|
-
`),eB)]:[],"</conversation-checkpoint>"].join(`
|
|
66
|
-
`)}function _P(e,o){let i=e.split(`
|
|
67
|
-
`),u=o.split(`
|
|
68
|
-
`),p=new Set(i),g=new Set(u),y=[...i.filter((E)=>E.trim()&&!g.has(E)).map((E)=>`- ${Fn(E,40)}`),...u.filter((E)=>E.trim()&&!p.has(E)).map((E)=>`+ ${Fn(E,40)}`)],b=i.find((E)=>E.trim()&&g.has(E));return[...y.slice(0,6),...y.length>6?[`\u2026 ${y.length-6} more changed lines`]:[],...b&&y.every((E)=>E.startsWith("+"))?[`@ ${Fn(b,40)}`]:[]]}function Il(e,o){if(!o)return e;let i=o.endsWith("/")?o:`${o}/`;return e.startsWith(i)?e.slice(i.length):e}function nB(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((i)=>{let u=i&&typeof i==="object"?i.path:void 0;return typeof u==="string"?[u]:[]})}function oB(e,o){let i=ao(e,"path");if(fl.has(e.name)&&i)return`file:${Il(i,o)}`;let u=ao(e,"command");if(u)return`command:${u}`;return`${e.name}:${jo(e.arguments)}`}function sB(e,o){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let g of To(e)){let y=u.get(g.step)??[];y.push(g),u.set(g.step,y)}let p=new Map;for(let g of e){let y=g.raw;if(!su(y))continue;let b=++i.steps,E=dl(y);if(E)i.narration.push({step:b,text:Fn(E,60)});for(let{call:S,result:w}of u.get(b)??[]){if(!w)continue;let R=Be(S.name,S.arguments),k={...S,name:R.name,arguments:R.input},A=oB(k,o),C=ou(w);if(w.isError){let ee=ao(k,"command"),pe=ee?`${k.name} \`${Fn(ee,40)}\``:`${k.name} ${A.startsWith("file:")?A.slice(5):Fn(jo(k.arguments),40)}`,H={step:b,key:A,what:pe,detail:Ro(C.trim().split(`
|
|
69
|
-
`).slice(0,8).join(`
|
|
70
|
-
`),200)};i.errors.push(H);let le=p.get(A)??[];le.push(H),p.set(A,le);continue}for(let ee of p.get(A)??[])ee.resolved=b;p.delete(A);let q=ao(k,"path");if(fl.has(k.name)&&q){let ee=Il(q,o),pe=i.files.get(ee)??{count:0,first:b,last:b,diffs:[]};if(pe.count++,pe.last=b,pe.diffs.push({step:b,lines:k.name==="edit"?ao(k,"old_string")!==void 0?_P(ao(k,"old_string")??"",ao(k,"new_string")??""):[]:_P("",ao(k,"content")??"")}),pe.diffs.length>3)pe.diffs.shift();i.files.set(ee,pe);continue}let X=k.name==="read"?[...q?[q]:[],...nB(k)]:[];if(X.length){for(let ee of X){let pe=Il(ee,o),H=i.reads.get(pe)??[];H.push(b),i.reads.set(pe,H)}continue}if(CP.has(k.name)){let ee=q?` in ${Il(q,o)}`:"",pe=k.name==="grep"&&ao(k,"glob")?` (${ao(k,"glob")})`:"",H=`${k.name} ${ao(k,"pattern")??""}${ee}${pe}`.replace(/\s+/g," "),le=i.searches.get(H)??{steps:[],head:""};le.steps.push(b),le.head=Fn(C.trim().split(`
|
|
71
|
-
`)[0]??"",25),i.searches.set(H,le);continue}let j=ao(k,"command");if(j){let ee=C.trim().split(`
|
|
72
|
-
`);i.commands.push({step:b,command:Fn(j,40),exit:"0",lines:ee.length,tail:ee.slice(-3).map((pe)=>Fn(pe,40))});continue}let V=`${k.name} ${Fn(jo(k.arguments),40)}`,J=i.other.get(V)??[];J.push(b),i.other.set(V,J)}}return i}function LP(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Fc(e,o,i){let u=(S,w)=>w===void 0||!S.length?S:gl(S,w),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).`],g=[...e.files];p.push("",`## Modified files (${g.length})`),g.forEach(([S,w],R)=>{if(p.push(`- ${S}: ${w.count} change${w.count>1?"s":""} (step ${w.first}${w.last!==w.first?`-${w.last}`:""})`),R<g.length-i.diffFiles)return;for(let k of w.diffs)p.push(` step ${k.step}:`,...k.lines.map((A)=>` ${A}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((S)=>S.resolved?`- step ${S.step} ${S.what} (resolved at step ${S.resolved})${i.lists===void 0?`: ${S.detail.replace(/\n/g,`
|
|
73
|
-
`)}`:""}`:`- step ${S.step} ${S.what} (UNRESOLVED): ${S.detail.replace(/\n/g,`
|
|
74
|
-
`)}`)),p.push("","## Steps",...u(e.narration.map((S)=>`- ${S.step}. ${S.text}`),i.narration));let y=[...e.reads].map(([S,w])=>`- ${S} @ ${w.join(",")}`);p.push("",`## Files read (${y.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(y,i.lists));let b=[...e.searches].map(([S,w])=>`- ${S} \u2192 ${w.head||"(no output)"} (${LP(w.steps)})`);p.push("",`## Searches (${b.length})`,...u(b,i.lists));let E=e.commands.map((S)=>[`- ${S.step}. \`${S.command}\` exit=${S.exit}, ${S.lines} output lines, last ${S.tail.length}:`,...S.tail.map((w)=>` ${w}`)].join(`
|
|
75
|
-
`));if(p.push("",`## Commands (${E.length})`,...u(E,i.lists)),e.other.size){let S=[...e.other].map(([w,R])=>`- ${w} (${LP(R)})`);p.push("",`## Other tool calls (${S.length})`,...u(S,i.lists))}return p.push("</work-state>"),p.join(`
|
|
76
|
-
`)}function bl(e,o,i,u){let p=sB(e,u),g=Fc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(D(g)<=i)return g;let y={...p,narration:[]};for(let S of[Number.POSITIVE_INFINITY,20,10,5]){let w=D(Fc(y,o,{diffFiles:S}));if(w>i*0.7)continue;return Fc(p,o,{narration:Math.max(500,i-w),diffFiles:S})}let b=Math.max(300,Math.floor(i*0.1)),E=D(Fc(y,o,{diffFiles:0,lists:b}));return Fc(p,o,{narration:Math.max(500,i-E),diffFiles:0,lists:b})}function El(e){return{role:"user",content:e,timestamp:0}}function Uh(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 NP(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:El(e.input)}function au(e){let o=[];for(let i of e){let u=o.at(-1),p=i;if(u?.role==="user"&&p.role==="user"){let g=(y)=>typeof y.content==="string"?[{type:"text",text:y.content}]:y.content;o[o.length-1]={...p,content:[...g(u),{type:"text",text:`
|
|
77
|
-
|
|
78
|
-
`},...g(p)]};continue}o.push(i)}return o}function DP(e){let o=[],i=new Map;for(let u of e){let p=u;if(p.role==="toolResult"){if(!i.has(p.toolCallId))continue;let g=i.get(p.toolCallId);if(g===void 0)i.set(p.toolCallId,o.length),o.push(u);else o[g]=u;continue}if(p.role==="assistant"){if(i=new Map,p.stopReason!=="error"&&p.stopReason!=="aborted"){for(let g of p.content)if(g.type==="toolCall")i.set(g.id,void 0)}}else if(p.role==="user")i=new Map;o.push(u)}return o}function iB(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 Re(e,o,i,u={}){let p=xa(e),g=Ks(e),y=g.filter((Ee)=>yl(Ee,p)),b=Fh(g,p),E=[],S=[],w=0;for(let Ee of g){if(yl(Ee,p))continue;let ae=[];for(let de of Ee.records){if(Ee===b&&de.entry.seq<=p)continue;let qe=de.raw.role==="user"?vP(de):de.raw;w+=F(qe),E.push(qe),ae.push(qe)}if(u.inspect&&ae.length)S.push({id:`recent-${Ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Ee.id}`,tokens:ae.reduce((de,qe)=>de+F(qe),0),detail:JSON.stringify(ae,iB,2)})}if(!y.length&&!b)return{items:S,messages:au(E),visible:0,archived:0,open:w,tokens:w,untrimmed:w};let R=MP(y,i,!!b),{visible:k,archived:A}=R,C=R.tokens,q=[],X="",j="";if(b){let Ee=b.records.filter((de)=>de.entry.seq<=p),ae=Ee.filter((de)=>de.entry.type==="user"&&!de.entry.notices&&de.raw.role==="user");if(ae.length){X=[`<chunk-input id="${b.id}" status="partial">`,...ae.map((qe,xt)=>`<user-message sequence="${xt+1}">
|
|
79
|
-
${qi(qe.entry.seq,Cs(qe.raw))}
|
|
80
|
-
</user-message>`),"</chunk-input>"].join(`
|
|
81
|
-
`);let de=ae.flatMap((qe)=>{let xt=qe.raw.content;return typeof xt==="string"?[]:xt.filter((Je)=>Je.type==="image")});q.push(de.length?{role:"user",content:[{type:"text",text:X},...de],timestamp:0}:El(X))}j=bl(Ee,b,i.index,u.cwd),q.push(Uh(j,o))}let V=e.flatMap((Ee)=>{let ae=Ee.raw;if(Ee.entry.seq>p||ae?.role!=="toolResult"||ae.toolName!=="skill")return[];return[El(ae.content.filter((de)=>de.type==="text").map((de)=>de.text).join(`
|
|
82
|
-
`))]}),J="",ee=()=>{J=OP({runs:y,visible:k.map((ae)=>ae.run),archived:A,partial:!!b,tokens:C,budget:i});let Ee=[El(J)];for(let{content:ae}of k){if(ae.input)Ee.push(NP(ae));Ee.push(Uh(ae.summary,o))}return[...Ee,...V,...q]},pe=(Ee)=>Ee.reduce((ae,de)=>ae+F(de),0),H=ee(),le=pe(H)+w,he=le,{trim:$e}=u;while($e&&$e.fixed+le>$e.limit){let Ee=b||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!Ee.length)break;let ae=0,de=0;for(let qe of Ee)if(de++,ae+=qe.content.tokens,ae>=$e.fixed+le-$e.limit)break;A=[...A,...k.slice(0,de).map((qe)=>qe.run)],k=k.slice(de),C-=ae,H=ee(),le=pe(H)+w}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:F(H[0]),detail:J},...k.map(({run:Ee,content:ae})=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"sealed",tokens:(ae.input?F(NP(ae)):0)+F(Uh(ae.summary,o)),detail:[ae.input,ae.summary].filter(Boolean).join(`
|
|
83
|
-
|
|
84
|
-
`)})),...A.map((Ee)=>({id:Ee.id,label:`Chunk ${Ee.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"})),...b?[{id:b.id,label:`Chunk ${b.id}`,state:"folded",tokens:pe(q),detail:[X,j].filter(Boolean).join(`
|
|
85
|
-
|
|
86
|
-
`)}]:[],...S]:[],messages:au([...H,...E]),visible:k.length,archived:A.length,open:w,tokens:le,untrimmed:he}}function ue(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Bh=0.97,aB=0.97,qP=0.5,uB=0.05,cB=20000,mB=24000;function jc(e){return{target:cB,hard:mB,index:Math.floor(ue(e)*uB)}}function Gh(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class Uc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,i=()=>{return}){this.records=e;this.fold=o;this.cwd=i}budget(e){return jc(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(ue(e)*Bh/this.ratio)}prepare(e,o,i,u){let p=ue(i),g=jc(i),y=e.reduce((H,le)=>H+F(le),0)+Di(o),b=this.records().at(-1)?.entry.seq??0,E=()=>u?[...u,...this.records().filter((H)=>H.entry.seq>b)]:this.records(),S=()=>Re(E(),i,g,{cwd:this.cwd(),trim:{fixed:y,limit:Math.floor(p*Bh/this.ratio)}}),w=E().findLast((H)=>H.raw?.role==="assistant"),R=w?E().filter((H)=>H.entry.seq>w.entry.seq&&H.raw):[],k=w?.raw,A=()=>w!==void 0&&(w.entry.seq===this.reshapedAfter||E().some((H)=>H.entry.type==="compaction"&&H.entry.seq>w.entry.seq)),C=this.dueSeal(i);if(C!==void 0)this.fold(C,!1),this.reshapedAfter=w?.entry.seq??-1;let q=S(),X=R.reduce((H,le)=>H+F(le.raw),0);if(this.lastEstimate===0&&w&&k&&!A()){let H=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,le=y+q.untrimmed-F(k)-X;if(H>0&&le>0)this.ratio=Math.min(2,Math.max(0.5,H/le))}let V=((H)=>{let le=y+H.untrimmed,he=y+H.tokens;return((w&&k&&!A()&&Gh(k)>0?Gh(k)+Math.round(this.ratio*X):void 0)??Math.round(le*this.ratio))-Math.round((le-he)*this.ratio)})(q);if(V>p*aB){let H=V-q.open*this.ratio,le=Math.max(1000,Math.floor((p*qP-H-g.index)/this.ratio)),he=w?.entry.seq??-1,$e=E().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,Ee=Math.max(this.lastFoldSeq,$e),de=(Ee>0?E().filter((qe)=>qe.entry.seq>Ee&&qe.raw?.role==="assistant").length:999)<=1;if(!de||this.consecutivePartialFolds<2){let qe=qc(E(),le);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=de?this.consecutivePartialFolds+1:1,q=S()}}else this.consecutivePartialFolds=0;this.lastEstimate=y+q.tokens;let J=q.messages,ee=y+q.tokens;if(Math.round(ee*this.ratio)>p)J=pB(J,Math.floor((p-y)/this.ratio)),ee=y+J.reduce((H,le)=>H+F(le),0);return this.lastEstimate=ee,{messages:au([...e,...J]),estimate:ee}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(xl(o)===void 0){let i=o.findLast((b)=>b.raw?.role==="assistant"),u=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||o.some((b)=>b.entry.type==="compaction"&&b.entry.seq>i.entry.seq)),y=(i?o.filter((b)=>b.entry.seq>i.entry.seq&&b.raw):[]).reduce((b,E)=>b+F(E.raw),0);if(p||!u||Gh(u)+y<Math.floor(ue(e)*Bh))return}return iu(o)}recover(e){let o=ue(e),i=jc(e),u=Re(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((o*qP-(o-u.open*this.ratio)-i.index)/this.ratio),g=qc(this.records(),p);if(g===void 0)return!1;return this.fold(g,!0),this.reshapedAfter=this.records().findLast((y)=>y.raw?.role==="assistant")?.entry.seq??-1,!0}}function pB(e,o){let i=e.reduce((p,g)=>p+F(g),0);if(i<=o)return e;let u=[];for(let p of e){let g=p;if(g.role!=="toolResult"||i<=o){u.push(p);continue}let y=F(p);if(y<=1500){u.push(p);continue}let b=Math.max(500,Math.floor(y/2)),E=g.content.map((R)=>{if(R.type!=="text")return R;return{...R,text:Ro(R.text,b)}}),S={...g,content:E},w=F(S);i-=y-w,u.push(S)}return u}var lB=2000;function uu(e,o){let i=[];for(let u of o.replace(/\r\n/g,`
|
|
87
|
-
`).split(`
|
|
88
|
-
`))for(let p=0;p<Math.max(u.length,1);){let g=Math.min(u.length,p+lB);if(g<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(g-1)))g--;i.push({source:e,text:u.slice(p,g)}),p=g>p?g:p+1}return i}function cu(e){let o=[],i=To(e.records),u=new Map(i.map((g)=>[g.call,g])),p=new Set(i.flatMap((g)=>g.result?[g.result]:[]));for(let g of e.records){let y=g.raw;if(y.role==="user")o.push(...uu(g.entry.type==="user"&&g.entry.notices?"NOTICE":"USER",Cs(y)));else if(y.role==="assistant"){for(let b of y.content)if(b.type==="text"&&b.text.trim())o.push(...uu("ASSISTANT",b.text));else if(b.type==="toolCall"){let E=u.get(b);if(E)for(let S of hl(E))o.push(...uu(S.source,S.text))}}else if(y.role==="toolResult"&&!p.has(y))o.push(...uu(y.isError?"TOOL_ERROR":"TOOL_OUTPUT",ou(y)))}return o.map((g,y)=>({chunk:e.id,line:y,...g}))}function Sl(e,o){let i=e.find((u)=>u.entry.seq===o);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return uu("USER",Cs(i.raw)).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function wl(e,o){let i=e.find((u)=>u.entry.seq===o)?.entry;if(i?.type!=="extension"||!i.display)return;return uu("EXTENSION",i.display.text).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function Bc(e,o=""){return e.map((i,u)=>{let p=e[u-1],g=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${o}${g?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
|
|
89
|
-
`)}import{join as Og}from"path";import{existsSync as n$}from"fs";import{realpath as o$}from"fs/promises";import{dirname as s$,isAbsolute as PB,join as i$,relative as $B,resolve as Qh,sep as vB}from"path";import{existsSync as dB,watch as fB}from"fs";import{readdir as hB,stat as gB}from"fs/promises";import{basename as Kh,dirname as yB,join as FP,resolve as xB}from"path";class Hh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,i,u=150){this.host=e;this.slots=o;this.watching=i;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 i=[],u=[];for(let b of[...new Set(e)]){let E;try{E=await hB(b)}catch(S){if(S instanceof Error&&"code"in S&&S.code==="ENOENT")continue;throw S}for(let S of E.sort()){let w=FP(b,S),R=(await gB(w)).isDirectory()?FP(w,"index.ts"):w;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(k){let A=Kh(R)==="index.ts"?Kh(yB(R)):Kh(R,".ts");if(this.slots.has(A))throw Error(`Duplicate plugin: ${A}`);let C={id:A,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${A}; repair the file and reload`)}};i.push({definition:C,path:R}),this.slots.set(A,{definition:C,path:R,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let p=o.filter((b)=>![...u,...i].some((E)=>E.definition.id===b.definition.id)),g=[...p,...u],y=this.order(g.map(({definition:b})=>b));for(let b of y){let E=g.find((w)=>w.definition===b)?.path,S=p.some((w)=>w.definition===b);try{await this.host.install(b,E,S)}catch(w){this.slots.set(b.id,{definition:b,path:E,builtin:S,enabled:!0,error:w instanceof Error?w.message:String(w)})}}if(this.watching())for(let b of[...g,...i]){if(!dB(b.path))continue;let E=fB(b.path,()=>{let S=b.definition.id,w=this.debounceTimers.get(S);if(w)clearTimeout(w);let R=setTimeout(()=>{this.debounceTimers.delete(S),this.host.reload(S).catch((k)=>{let A=this.slots.get(S);if(A)A.error=k instanceof Error?k.message:String(k)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(S,R)});E.on("error",(S)=>{let w=this.slots.get(b.definition.id);if(w)w.error=S.message,this.host.changed()}),this.watchers.push(E)}}order(e,o=!1){let i=new Map;for(let b of e){if(this.validate(b),i.has(b.id)||!o&&this.slots.has(b.id))throw Error(`Duplicate plugin: ${b.id}`);i.set(b.id,b)}let u=[],p=new Set,g=new Set,y=(b)=>{if(g.has(b.id))return;if(p.has(b.id))throw Error(`Plugin dependency cycle: ${b.id}`);p.add(b.id);for(let E of b.deps??[]){let S=i.get(E);if(S)y(S);else if(!this.slots.has(E))throw Error(`Missing plugin dependency: ${E}`)}p.delete(b.id),g.add(b.id),u.push(b)};for(let b of e)y(b);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(`${xB(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 jP(e,o,i=!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([i?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((g,y)=>{p=setTimeout(()=>{u.abort(),y(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as IB}from"async_hooks";import{isDeepStrictEqual as UP}from"util";var Ia=new IB;function Ps(){let e=Ia.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function mu(e){let o=structuredClone(e),i=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let p of Object.values(u))i(p)};return i(o),o}function BP(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let E of["seq","time","session_id","raw"])if(E in o)throw Error(`Entry replacement contains protected field: ${E}`);let i=JSON.parse(JSON.stringify(o,(E,S)=>{if(typeof S==="function"||typeof S==="symbol"||typeof S==="number"&&!Number.isFinite(S))throw Error("Entry replacement must contain JSON values");return S}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let u=i,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 g={...e};for(let E of new Set([...Object.keys(e),...Object.keys(u)])){if(!p.includes(E)&&!UP(g[E],u[E]))throw Error(`Entry replacement changed protected field: ${E}`);if(["seq","time","session_id","raw"].includes(E))throw Error(`Entry replacement contains protected field: ${E}`)}let y=(E)=>E===void 0||typeof E==="string",b=!0;switch(e.type){case"user":b=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((E)=>E&&typeof E.name==="string"&&typeof E.mimeType==="string"&&Qc.includes(E.kind)&&typeof E.data==="string"));break;case"assistant":b=y(u.error)&&Array.isArray(u.parts)&&u.parts.every((E)=>E&&(["text","thinking"].includes(E.type)&&typeof E.text==="string"||E.type==="tool_call"&&typeof E.id==="string"&&typeof E.name==="string"&&("input"in E)));break;case"tool_result":b=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((E)=>E&&typeof E.mimeType==="string"&&typeof E.data==="string"));break;case"extension":{let E=u.display;b="payload"in u&&(E===void 0||E!==null&&typeof E==="object"&&("text"in E)&&typeof E.text==="string"&&(!("title"in E)||y(E.title)));break}case"notice_pending":{let S=["text"],w=g.notice,R=u.notice;if(b=!!R&&typeof R==="object"&&!Array.isArray(R),!b)break;let k=R;for(let A of new Set([...Object.keys(w),...Object.keys(k)]))if(S.includes(A)){if(typeof k[A]!=="string")b=!1}else if(!UP(w[A],k[A]))b=!1;break}case"run":b=y(u.error);break;case"compaction":break}if(!b)throw Error("Invalid entry replacement content");return i}function GP(e,o,i,u,p,g){let y=u;for(let b of i.generations)for(let E of b.hooks.get("entry.before_append")??[]){if(b.disabled)break;let S={phase:"before",violated:!1};try{let w=Ia.run(S,()=>{let R=mu(y),k=performance.now(),A=E(R,{sessionID:p,seq:g});if(A&&(typeof A==="object"||typeof A==="function")&&"then"in A&&typeof A.then==="function")throw Promise.resolve(A).catch(()=>{}),Error("entry.before_append must be synchronous");let C=A===void 0?void 0:BP(y,A);if(S.violated)throw Error("entry.before_append attempted a database write");return{validated:C,slow:performance.now()-k>e}});if(w.validated&&JSON.stringify(w.validated)!==JSON.stringify(y))y=w.validated;if(w.slow)throw Error("entry.before_append exceeded budget");b.beforeFailures=0,b.failures=0}catch(w){b.failures=b.beforeFailures++,o(b,w)}}return y}function bB(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return mu(o);return structuredClone(o)}async function KP(e,o,i,u,p,g,y,b,E="end"){let S=g;for(let w of u){if(w.disabled)continue;let R=w.hooks.get(p)??[];for(let k of R){if(w.disabled)break;let A=w.hookOptions.get(k);if(p==="prompt.fragments"&&(A?.promptPosition??"end")!==E)continue;let C=p==="prompt.fragments"?JSON.stringify([y?.id,S]):void 0,q=C===void 0?void 0:w.promptCache.get(k)?.get(C);try{let X=bB(p,S),j=A?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:y,connection:b}):j,J=await o((ee)=>k(X,{runtime:e.runtime,session:y,connection:b,signal:ee}),V);if(C!==void 0){let ee=J===void 0?S:J;if(!Array.isArray(ee)||ee.some((H)=>typeof H!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(ee))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let pe=w.promptCache.get(k)??new Map;pe.set(C,[...ee]),w.promptCache.set(k,pe)}if(w.failures=0,J!==void 0&&p!=="entry.after_append")S=J}catch(X){if(q)S=structuredClone(q);if(i(w,X),A?.errorMode==="propagate")throw X}}}return S}class Gc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,i,u,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,i,u,p)}has(e,o){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((u)=>o===void 0||(i.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...i)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((i)=>i(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let u of i.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 EB}from"fs";import{dirname as SB,resolve as HP}from"path";var Wh=new WeakMap;function WP(e){return[...e].map((o)=>{let i=Boolean(o.path&&(Boolean(o.definition.webEntry)||EB(HP(SB(HP(o.path)),"web.tsx"))));if(o.current&&!Wh.has(o.current))Wh.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:i,webRevision:o.current?Wh.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 zh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,i){this.host=e;this.deadline=o;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,i){let u=this.host.pin(),p=(async()=>{try{let g=[];for(let y of u.generations){if(y.disabled)continue;for(let b of y.hooks.get(e)??[]){let E=y.hookOptions.get(b)?.timeoutMs,S=typeof E==="function"?E({runtime:this.host.runtime,session:o,connection:i}):E;g.push(this.deadline((w)=>b(o,{runtime:this.host.runtime,session:o,connection:i,signal:w}),S,!0).catch((w)=>this.fail(y,w)))}}await Promise.all(g)}finally{await u.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,o,i){let u=i===void 0?void 0:mu(i),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Ia.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 g=()=>{if(this.pending.delete(p),this.entryQueues.get(o)===p)this.entryQueues.delete(o)};p.then(g,g)}}function zP(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 wB(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 TB(e,o){let i=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!i)throw Error("Completion session not found");let u=o.model??i?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=En(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 g=(await e.models()).models.filter((b)=>b.available===!0),y=p?tt(p):u;if(!g.some((b)=>b.id===y)){let b=g[0];if(b)p=En(e.options.models,b.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function VP(e,o){wB(o);let i=await TB(e,o),u=o.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>i.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="",g=!1;try{let y=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],b=e.options.models.streamSimple(i,{messages:y},{maxTokens:u,signal:o.signal});for await(let E of b){if(o.signal?.aborted)throw Error("cancelled");if(E.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${zP(E.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(E.type==="text_delta")p+=E.delta;if(E.type==="done"){if(E.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(E.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${E.reason}\uFF09`);g=!0}}}catch(y){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${zP(y instanceof Error?y.message:String(y))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!g)throw Error("Model completion ended without a stop response; retry");return{text:p,model:tt(i)}}var RB=["active","archived","all"];function JP(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function kB(e){let{projectID:o,children:i,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(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!RB.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 AB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function QP(e){function o(i,u={}){let{types:p,bodies:g}=u;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let y=JP(u.limit),b=u.after??0;if(!Number.isSafeInteger(b)||b<0)throw Error("sessions after must be a non-negative integer");let E=(e.get(i)?.entries(b,p,g!==!1)??[]).slice(0,y);return structuredClone(g===!1?E.map(AB):E)}return{list(i={}){kB(i);let u=i.limit===void 0?void 0:JP(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((g)=>i.projectID===void 0||g.projectID===i.projectID).filter((g)=>i.since===void 0||g.created>=i.since);return structuredClone(u===void 0?p:p.slice(0,u))},get(i){return structuredClone(e.get(i)?.info())},entries:o}}async function XP(e,o,i,u,p,g){let y={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},b=e.runtime.store.db,E=new Map,S=!1,w=!0,R=()=>{if(!w||y.disposed)throw Error("Plugin registration scope is closed")},k=(j,V)=>{if(R(),!S){E.set(j,V);return}if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)},A={get:(j)=>{R();let V=E.has(j)?E.get(j):b.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");k(j,J)},delete:(j)=>k(j,null)},C=()=>{if(R(),S)throw Error("Register resources during setup only")},q=[...o.migrations??[]].sort((j,V)=>j.version-V.version),X=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||X.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(X.add(j.version),b.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,j.version))continue;b.transaction(()=>{if(j.sql!==void 0)b.run(j.sql);else j.up({...A,db:b});for(let[V,J]of E)if(J===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,J);b.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,j.version)})(),e.runtime.store.invalidateEntryCache(),E.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:QP(e.runtime),complete:(j)=>VP(e.runtime,j),kv:A,database:b,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{C(),y.gates.push(j)},registerNoticeSource:(j,V)=>{if(C(),!j||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");y.noticeSources.set(j,{...V})},provide:(j,V)=>{if(C(),j.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(y.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);y.services.set(j.name,V)},on:(j,V,J)=>{if(C(),J?.promptPosition&&j!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let ee=y.hooks.get(j)??[];if(ee.push(V),y.hooks.set(j,ee),J)y.hookOptions.set(V,J)},registerHistoryResolver:(j)=>{C(),y.historyResolvers.push(j)},registerTool:(j,V)=>{if(C(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||CB(e,p,o.id).has(j.name.toLowerCase())||y.tools.some((ee)=>ee.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let J=i?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;y.tools.push({...j,defer:J,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(C(),!(j.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>j.path===V||j.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(j.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(y.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");y.routes.push(j)},registerWebSocket:(j)=>{if(C(),!j.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(y.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");y.websockets.push(j)},registerCommand:(j)=>{C(),y.commands.push(j)},registerWebContribution:(j)=>{C(),y.web.push(j)},registerToolPolicy:(j,V)=>{C(),y.policies.set(j,V)},appendExtension:(j,V)=>{if(Ps(),R(),!S)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{C(),y.deactivators.push(j)},onDispose:(j)=>{C(),y.disposers.push(j)}})),b.transaction(()=>{for(let[j,V]of E)if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)})(),E.clear(),S=!0,y}catch(j){throw w=!1,await g(y),j}}function CB(e,o,i){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,g]of o){if(p===i)continue;for(let y of g.current?.tools??[])u.add(y.name.toLowerCase())}return u}class Vh{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(i){e.error=i instanceof Error?i.message:String(i)}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(i){e.error=i instanceof Error?i.message:String(i)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function YP(e,o,i,u){for(let p of o){let g=p.current;if(!g||g.disabled||g.retired)continue;let y=g.websockets.find((b)=>b.path===u);if(!y)continue;return{connect:(b)=>{let E=!1;g.references++,g.connections.add(b);let S={send:(R)=>{if(E||g.retired||g.disabled)return;b.send(R)},close:(R,k)=>b.close(R,k)},w=async(R)=>{if(E||g.retired||g.disabled){b.close(1012,"Plugin unavailable");return}try{await i(R),g.failures=0}catch(k){if(g.failures++,g.error=k instanceof Error?k.message:String(k),b.close(1011,"Plugin callback failed"),g.failures>=e.failureThreshold){g.disabled=!0;for(let A of g.connections)A.close(1011,"Plugin disabled")}}};return{open:()=>w(()=>y.open?.(S)),message:(R)=>w(()=>y.message(S,R)),close:async()=>{if(E)return;E=!0,g.connections.delete(b);try{await i(()=>y.close?.(S))}catch(R){g.error=R instanceof Error?R.message:String(R)}finally{g.references--,await e.collect(g)}}}}}}return}function Jh(e,o){let i=e.split("/"),u=new URL(o.url).pathname.split("/");if(i.length!==u.length)return;let p={};return i.every((y,b)=>{let E=u[b];if(E===void 0)return!1;if(!y.startsWith(":"))return E===y;try{p[y.slice(1)]=decodeURIComponent(E)}catch{return!1}return E.length>0})?p:void 0}async function ZP(e,o,i,u,p){let g=e.pin();try{let y=g.generations.find((b)=>b.definition.id===i)?.commands.find((b)=>b.id===u);if(!y)throw new f("Plugin command is unavailable");return await o(()=>y.execute(p))}finally{await g.release()}}function e$(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((p)=>p.method===o.method&&Jh(p.path,o)!==void 0))}finally{i.release()}}function t$(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((p)=>p.public===!0&&p.method===o.method&&Jh(p.path,o)!==void 0))}finally{i.release()}}async function r$(e,o,i){let u=e.pin(),p=!0;try{for(let g of u.generations)for(let y of g.routes){if(y.method!==i.method)continue;let b=Jh(y.path,i);if(b){let E=await o(()=>y.handler(i,b),y.timeoutMs);if(!E)return;if(E.body&&E.body instanceof ReadableStream){p=!1;let S=!1,w=()=>{if(S)return;S=!0,u.release()},R=E.body.getReader(),k=new ReadableStream({async pull(A){try{let{done:C,value:q}=await R.read();if(C)A.close(),w();else A.enqueue(q)}catch(C){A.error(C),w()}},async cancel(A){try{await R.cancel(A)}finally{w()}}});return new Response(k,{status:E.status,statusText:E.statusText,headers:E.headers})}return E}}return}finally{if(p)await u.release()}}class Xh{runtime;options;slots=new Map;retirement=new Vh(this.deadline.bind(this));observers=new zh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new ll;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 Hh(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 f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=o.current.services.get(e.name);if(!e.validate(i))throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.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 i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let i of e)this.directories.add(Qh(i));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await o$(e),i=[...this.directories,i$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>i$(u.directory,".basalt","plugins"))];for(let u of i){if(!n$(u))continue;let p=$B(await o$(u),o);if(p&&p!==".."&&!p.startsWith(`..${vB}`)&&!PB(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),i=await this.checkEntry(o);if(!i.ok)throw new pt(i.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((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,i)})}async installDefinition(e,o,i=!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:i,enabled:u?.enabled!==0};if(p.enabled)p.current=await this.stage(e,i);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 b=await this.checkEntry(o.path);if(!b.ok)throw new pt(b.errors)}let i=o.builtin&&!n$(o.path)?o.definition:await this.catalog.read(o.path);if(i.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((b)=>b.definition.id===e?i:b.definition),!0),p=await this.stage(i),g=o.current;o.definition=i,o.current=p,o.error=void 0,o.discoveryFailed=!1;let y=new Map(this.slots);this.slots.clear();for(let b of u){let E=y.get(b.id);if(E)this.slots.set(b.id,E)}if(g)await this.retirement.retire(g)}catch(i){throw o.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,o){return this.exclusive(async()=>{let i=this.require(e);if(o===i.enabled&&(!o||i.current&&!i.current.disabled))return;if(!o){for(let y of this.slots.values())if(y.enabled&&y.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${y.definition.id}`)}let u=o&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.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 g=i.current;if(i.definition=u,o)i.discoveryFailed=!1;if(i.enabled=o,i.current=p,i.error=void 0,g)await this.retirement.retire(g)})}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 i of e.deps??[])if(i===e.id||!this.slots.get(i)?.current||this.slots.get(i)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${i}`);return XP(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,i){this.observers.notify(e,o,i)}resolveHistory(e,o){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let u of i.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 Gc(this,e)}async invoke(e,o,i,u,p,g="end"){return KP(this,this.deadline.bind(this),this.fail.bind(this),e,o,i,u,p,g)}pinEntry(e){if(Ia.getStore()?.phase==="after")return;let o;for(let i of this.slots.values()){let u=i.current;if(!i.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 Gc(this,o)}beforeEntry(e,o,i,u){return GP(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,i,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 i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,i){this.observers.finishEntry(e,o,i)}deadline(e,o=this.timeoutMs,i=!1){return jP(e,o,i)}appendExtension(e,o){return Ps(),new Promise((i)=>{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(),i(p)})}list(){return WP(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(i&&o.path)await this.webBuilder.build(i,s$(Qh(o.path)));return{ok:!0}}catch(o){if(o instanceof pl)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 i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!i)return;return this.webBuilder.build(i,s$(Qh(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 i=await this.webBuilder.entry(o.path,o.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,o,i){return ZP(this,this.deadline.bind(this),e,o,i)}hasRoute(e){return e$(this,e)}isPublicRoute(e){return t$(this,e)}route(e){return r$(this,this.deadline.bind(this),e)}websocket(e){return YP(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 a$}from"fs";import{join as MB}from"path";var OB=500,_B=1000,LB=3600000,NB=5000,DB=2000,qB=3,FB=1073741824;class Yh{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;constructor(e){this.options=e;if(this.indexPath=MB(e.dataDir,Si),this.features={...wi(),...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,i=o?.backfill;if(!o||!i)return{...e,state:"backfilling"};if(i.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(i.total,i.done),indexed:i.done,state:i.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+=a$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=a$(this.options.store.path).size}catch{}return Math.max(FB,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(),Yn(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.worker;if(!o)return e();Atomics.store(this.flags,He,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Et,0,NB);try{return e()}finally{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=vi(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,He,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,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<qB&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He);let o=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(DB)]),e.terminate(),this.worker=void 0,this.stopped=void 0,this.closeReader(),this.resolveFlushes(),this.prune()})();try{await this.stopping}finally{this.stopping=void 0}}resolveFlushes(){for(let e of this.flushes.values())e();this.flushes.clear()}closeReader(){this.reader?.close(),this.reader=void 0}schedulePrune(){if(this.pruneTimer)return;let e=Math.max(0,OB-(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)Yn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),LB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,_B-(performance.now()-this.lastPush)),i=()=>{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)i();else this.statusTimer=setTimeout(i,o),this.statusTimer.unref?.()}}import{existsSync as du,mkdirSync as WB,readdirSync as h$,readFileSync as p$,realpathSync as Zh,statSync as Cl,writeFileSync as eg}from"fs";import{dirname as Al,isAbsolute as tg,relative as g$,resolve as zB}from"path";import{existsSync as Kc}from"fs";import{dirname as KB,join as lu}from"path";import{mkdirSync as jB,writeFileSync as UB}from"fs";import{tmpdir as BB}from"os";import{join as u$}from"path";var Tl=2000,Pe=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function pu(e,o){return e.map((i,u)=>{let p=i.length>Tl?`${i.slice(0,Tl)}\u2026 [line truncated]`:i;return`${String(o+u).padStart(6)} ${p}`}).join(`
|
|
90
|
-
`)}function ie(e,o){if(e.length<=o)return e;let i=Math.floor(o*0.4),u=o-i,p=e.length-i-u,g=e.slice(i,e.length-u).split(`
|
|
91
|
-
`).length-1;return`${e.slice(0,i)}
|
|
92
|
-
|
|
93
|
-
\u2026 [${p} characters, ~${g} lines omitted] \u2026
|
|
94
|
-
|
|
95
|
-
${e.slice(-u)}`}var GB=0;function rt(e,o,i){if(e.length<=o)return e;let u=ie(e,o);try{let p=i?ad(i):u$(BB(),"basalt-output");jB(p,{recursive:!0});let g=u$(p,`${process.pid}-${Date.now().toString(36)}-${GB++}.txt`);return UB(g,e),`${u}
|
|
96
|
-
[Full output saved to ${g}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var c$=120000,m$=600000,ba;function HB(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function tr(){if(ba!==void 0)return ba||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let p=lu(u,"bash.exe");if(HB(p))continue;if(Kc(p))return ba=p,p}for(let u of o){let p=lu(u,"git.exe");if(Kc(p)){let g=KB(u),y=lu(g,"bin","bash.exe");if(Kc(y))return ba=y,y;let b=lu(g,"usr","bin","bash.exe");if(Kc(b))return ba=b,b}}let i=["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?lu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?lu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of i)if(Kc(u))return ba=u,u;ba="";return}class Rl{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 i=0;while(i<o.length){if(o[i]<128){i+=1;continue}let p=o[i+1];if(p===void 0)break;let g=p>=48&&p<=57?4:2;if(i+g>o.length)break;i+=g}return this.gbkPending=o.slice(i),this.gbk.decode(o.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let i=new Uint8Array(this.sniffPending.length+e.length);if(i.set(this.sniffPending),i.set(e,this.sniffPending.length),i.length<2)return this.sniffPending=i,"";this.sniffPending=void 0;let u=i[0]===255&&i[1]===254,p=!1;for(let g=1;g<i.length;g+=2)if(i[g]===0){p=!0;break}this.isUtf16=u||p,o=i}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 Ea(e,o){let i=process.platform==="win32",u=o??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[tr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=tr();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,o){let i=await je(e,o.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:u,isWindows:p}=Ea(e,o.shell),g=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,...em(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((ee)=>ee.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),y=!1,b=()=>{try{if(p)g.kill();else process.kill(-g.pid,"SIGKILL")}catch{}},E=setTimeout(()=>{y=!0,b()},o.timeout);o.signal?.addEventListener("abort",b,{once:!0});let S=Pe*2,w="",R="",k=0,A=0,C="",q=(ee=!1)=>{let pe=k-w.length-R.length,H=pe>0?`${w}
|
|
97
|
-
\u2026 [${pe} characters omitted] \u2026
|
|
98
|
-
${R}`:w+R;if(!ee)return ie(H,Pe);return rt(C.length===k?C:H,Pe,o.cwd)},X=()=>{let ee=new Rl;return async(pe)=>{for await(let le of pe){let he=ee.decode(le);if(k+=he.length,C.length<4000000)C+=he;if(w.length<S)w+=he;else R=(R+he).slice(-S);if(o.onOutput){let $e=performance.now();if($e-A>=80)A=$e,o.onOutput(q())}}let H=ee.flush();if(H){if(k+=H.length,C.length<4000000)C+=H;if(w.length<S)w+=H;else R=(R+H).slice(-S)}}},j=Promise.all([X()(g.stdout),X()(g.stderr)]),V=await g.exited;if(clearTimeout(E),o.signal?.removeEventListener("abort",b),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
|
|
99
|
-
[background processes are still running; their later output is not captured]`;return{output:q(!0),code:y?null:V,timedOut:y}}class rg{seen=new Map;mark(e,o=Cl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Cl(e).mtimeMs!==o?"changed":void 0}}var l$=2000,VB=500,JB=10485760,kl=20,QB=6,XB=40000,YB=80000;function ZB(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 y$(e,o,i=[],u){let p=(C)=>tg(C)?C:zB(e,C),g=(C)=>{let q=g$(e,C);return q&&!q.startsWith("..")&&!tg(q)?q:C},y=(C)=>{let q=C;while(!du(q)&&Al(q)!==q)q=Al(q);let X=Zh(q);if(i.some((j)=>du(j)&&f$(Zh(j),X))&&!f$(Zh(e),X))throw Error("External directories are read-only")},b=(C,q,X)=>{let j=p(C);if(!du(j))throw Error(`No such file or directory: ${j}${nG(j)}`);let V=Cl(j);if(V.isDirectory()){let de=h$(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),qe=de.slice(0,VB),xt=de.length-qe.length;return c(`${qe.join(`
|
|
100
|
-
`)}${xt>0?`
|
|
101
|
-
\u2026 and ${xt} more entries`:""}`||"(empty directory)").content}let J=p$(j),ee=ZB(J);if(ee){if(V.size>JB)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return o.mark(j),[{type:"text",text:`Read image ${g(j)} (${ee}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:ee}]}if(J.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);o.mark(j);let pe=J.toString("utf8");if(!pe)return c("(empty file)").content;let H=pe.replace(/\r?\n$/,"").split(/\r?\n/),le=(q??1)-1;if(le>=H.length)throw Error(`offset ${q} is past the end of the file (${H.length} lines)`);let he=Math.min(H.length,le+(X??l$)),$e=0,Ee=le;while(Ee<he){let de=H[Ee]?.length??0;if(Ee>le&&$e+de>XB)break;$e+=de,Ee++}let ae=pu(H.slice(le,Ee),le+1);if(Ee<he)ae+=`
|
|
102
|
-
|
|
103
|
-
(Showing lines ${le+1}-${Ee} of ${H.length} (truncated at line ${Ee} due to safety budget). Use offset/limit to read specific windows.)`;else if(le>0||Ee<H.length)ae+=`
|
|
104
|
-
|
|
105
|
-
(Showing lines ${le+1}-${Ee} of ${H.length}. Use offset/limit to read other parts.)`;return c(ae).content},E=x({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.
|
|
106
|
-
- path may be absolute or relative to the working directory.
|
|
107
|
-
- By default reads up to ${l$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
|
|
108
|
-
- Lines longer than ${Tl} characters are truncated.
|
|
109
|
-
- Reading a directory lists its entries (directories end with /).
|
|
110
|
-
- Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
|
|
111
|
-
- To read several files at once, give paths instead of path (up to ${kl}, 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.
|
|
112
|
-
- Always read a file before editing or overwriting it.`,parameters:l({path:n(a({description:"File or directory path"})),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"})),paths:n(B(l({path:a({description:"File or directory path"}),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:kl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(C,q){let X=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(X.length===0)throw Error("Give path, or paths to read several files");if(X.length===1){let pe=X[0];return{content:b(pe.path,pe.offset,pe.limit),details:void 0}}if(X.length>kl)throw Error(`Read at most ${kl} paths per call`);let j=[],V=[],J=0,ee=(pe)=>{let H=j.at(-1);if(pe.type==="text"&&H?.type==="text")H.text+=`
|
|
113
|
-
|
|
114
|
-
${pe.text}`;else j.push(pe)};for(let pe of X){let H=`==> ${g(p(pe.path))} <==`;if(J>=YB){ee({type:"text",text:`${H}
|
|
115
|
-
(Skipped due to total read safety budget; read in separate calls)`});continue}try{let le=b(pe.path,pe.offset,pe.limit);for(let he=0;he<le.length;he++){let $e=le[he];if(!$e)continue;if($e.type==="text")J+=$e.text.length,ee(he===0?{...$e,text:`${H}
|
|
116
|
-
${$e.text}`}:$e);else ee($e)}}catch(le){let he=le instanceof Error?le.message:String(le);V.push(he),ee({type:"text",text:`${H}
|
|
117
|
-
Error: ${he}`})}}if(V.length===X.length)throw Error(V.join(`
|
|
118
|
-
`));return{content:j,details:void 0}}}),S=async(C,q,X,j)=>{let V=j?.update,J=await rr(C,{cwd:e,timeout:120000,signal:X,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:V?(he)=>V(c(`${j.prefix}
|
|
119
|
-
|
|
120
|
-
$ ${C}
|
|
121
|
-
${he.trimEnd()}`)):void 0}),ee=J.output.trimEnd()||"(no output)",pe=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,H=J.timedOut||J.code!==0,le=H?`
|
|
122
|
-
${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
|
|
123
|
-
|
|
124
|
-
$ ${C}
|
|
125
|
-
${ee}
|
|
126
|
-
[${pe}]${le}`,failed:H}},w=(C,q=!1)=>{let X=o.check(C);if(X==="changed")return`Note: ${g(C)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(X==="unread"&&q)return`Note: ${g(C)} existed and had not been read; it was replaced whole.`;return},R=x({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
|
|
127
|
-
- An existing file is replaced whole, including changes made since you last read it.
|
|
128
|
-
- Prefer the edit tool for changing existing files; use write for new files or full rewrites.
|
|
129
|
-
- 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.
|
|
130
|
-
- Do not create documentation or README files unless asked.`,parameters:l({path:a({description:"File path"}),content:a({description:"The full file content"}),then_run:n(a({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(C,q,X,j){let V=p(q.path);y(V);let J=du(V),ee;if(J){if(Cl(V).isDirectory())throw Error(`${V} is a directory`);ee=w(V,!0)}WB(Al(V),{recursive:!0}),eg(V,q.content),o.mark(V);let pe=q.content?q.content.split(`
|
|
131
|
-
`).length:0,H=`${J?"Overwrote":"Created"} ${g(V)} (${pe} lines)${ee?`
|
|
132
|
-
${ee}`:""}`;if(q.then_run){let le=await S(q.then_run,`${g(V)} was written as given`,X,{prefix:H,update:j});if(H+=le.out,le.failed)return{...c(H),isError:!0}}return c(H)}}),k=(C,q,X,j)=>{let V=p(C);if(!du(V))throw Error(`File not found: ${V} (use write to create it)`);y(V);let J=w(V),ee=p$(V,"utf8"),pe=ee,H=pe.includes(`\r
|
|
133
|
-
`),le=[],he=[],$e=0,Ee=0;return q.forEach((ae,de)=>{let qe=j?`edits[${X+de}]: `:"";try{if(ae.old_string===ae.new_string)throw Error(`${qe}old_string and new_string are identical`);if(!ae.old_string)throw Error(`${qe}old_string is empty (use write to create or replace a whole file)`);let xt=H&&!ae.old_string.includes(`\r
|
|
134
|
-
`),Je=xt?ae.old_string.replace(/\n/g,`\r
|
|
135
|
-
`):ae.old_string,Yt=xt?ae.new_string.replace(/\n/g,`\r
|
|
136
|
-
`):ae.new_string,Fe=eG(pe,Je).map((Ct)=>[Ct,Ct+Je.length]);if(Fe.length===0)Fe=tG(pe,Je);if(Fe.length===0)throw Error(`${qe}old_string not found in ${g(V)}; read the relevant lines and copy the exact text.${rG(pe,Je)}`);if(Fe.length>1&&!ae.replace_all){let Ct=Fe.map(([st])=>d$(pe,st)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${Ct}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=d$(pe,Fe[0][0]),Dt=ae.replace_all?Fe:[Fe[0]],lt="",Mt=0;for(let[Ct,st]of Dt)lt+=pe.slice(Mt,Ct)+Yt,Mt=st;pe=lt+pe.slice(Mt),$e++,Ee+=Dt.length;let yr=pe.split(/\r?\n/),pr=Ue+Yt.split(/\r?\n/).length-1,jt=Math.max(1,Ue-1),ot=Math.min(yr.length,pr+1);if(ot-jt+1<=QB+2)le.push(pu(yr.slice(jt-1,ot),jt));else le.push(`${pu(yr.slice(jt-1,Ue+1),jt)}
|
|
137
|
-
\u2026 (${pr-Ue-3} lines as given)
|
|
138
|
-
${pu(yr.slice(pr-2,ot),pr-1)}`)}catch(xt){he.push(xt instanceof Error?xt.message:String(xt))}}),{path:V,original:ee,content:pe,echoes:le,applied:$e,total:Ee,count:q.length,note:J,failed:he}},A=x({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.
|
|
139
|
-
- No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
|
|
140
|
-
- 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.
|
|
141
|
-
- 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.
|
|
142
|
-
- 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.
|
|
143
|
-
- To create a file use write; to delete or move files use bash.
|
|
144
|
-
- 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.
|
|
145
|
-
- 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(a({description:"File path (the default for edits items without their own path)"})),old_string:n(a({description:"The exact text to replace (only when edits is absent)"})),new_string:n(a({description:"The replacement text (only when edits is absent)"})),replace_all:n(N({description:"Replace every occurrence (default false)"})),edits:n(B(l({path:n(a({description:"The file of this replacement, when it is not path"})),old_string:a({description:"The exact text to replace"}),new_string:a({description:"The replacement text"}),replace_all:n(N({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(a({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(C,q,X,j){let V=q.edits&&q.edits.length>0?q.edits.map((ae)=>({path:ae.path??q.path,step:ae})):q.old_string!==void 0&&q.new_string!==void 0?[{path:q.path,step:{old_string:q.old_string,new_string:q.new_string,replace_all:q.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,ee=new Map;V.forEach((ae,de)=>{if(!ae.path)throw Error(`${J?`edits[${de}]: `:""}path is required`);let qe=p(ae.path),xt=ee.get(qe)??{raw:ae.path,steps:[],offset:de};xt.steps.push(ae.step),ee.set(qe,xt)});let pe=[],H=[];for(let ae of ee.values())try{let de=k(ae.raw,ae.steps,ae.offset,J);if(de.applied>0)pe.push(de);H.push(...de.failed)}catch(de){let qe=de instanceof Error?de.message:String(de);H.push(`${J?`edits[${ae.offset}]: `:""}${qe}`)}if(pe.length===0)throw Error(H.join(`
|
|
146
|
-
`));let le=[];try{for(let ae of pe)eg(ae.path,ae.content),le.push(ae)}catch(ae){for(let de of le)eg(de.path,de.original);throw ae}for(let ae of pe)o.mark(ae.path);let $e=pe.map((ae)=>{let de=ae.total===1?"1 occurrence":`${ae.total} occurrences`,qe=ae.note?`
|
|
147
|
-
${ae.note}`:"";if(!J)return`Edited ${g(ae.path)} (${de}).${qe}
|
|
148
|
-
${ae.echoes[0]}`;let xt=ae.failed.length>0?`, ${ae.failed.length} failed`:"";return`Edited ${g(ae.path)} (${ae.applied} edits${xt}, ${de}). Regions are shown as they were right after each edit; later edits may shift line numbers.${qe}
|
|
149
|
-
${ae.echoes.map((Je,Yt)=>`--- edit ${Yt+1}
|
|
150
|
-
${Je}`).join(`
|
|
151
|
-
`)}`}).join(`
|
|
152
|
-
|
|
153
|
-
`),Ee=!1;if(q.then_run){let ae=await S(q.then_run,"The edits above were applied",X,{prefix:$e,update:j});if($e+=ae.out,ae.failed)Ee=!0}if(H.length>0)$e+=`
|
|
154
|
-
|
|
155
|
-
${H.length===1?"1 edit":`${H.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
|
|
156
|
-
- ${H.join(`
|
|
157
|
-
- `)}`,Ee=!0;return Ee?{...c($e),isError:!0}:c($e)}});return[_e(E,"cat","view","read_file","view_file","open_file","open"),_e(R,"write_file","create_file","new_file","save_file"),_e(A,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function eG(e,o){let i=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))i.push(u);return i}function d$(e,o){let i=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)i++;return i}function tG(e,o){let i=o.replace(/\r?\n$/,"").split(/\r?\n/).map((E)=>E.trimEnd()),u=[],p=e.split(`
|
|
158
|
-
`),g=0;for(let E of p)u.push(g),g+=E.length+1;let y=p.map((E)=>E.replace(/\r$/,"").trimEnd()),b=[];for(let E=0;E+i.length<=y.length;E++)if(i.every((S,w)=>y[E+w]===S)){let S=E+i.length-1,w=u[S]+p[S].replace(/\r$/,"").length,R=o.endsWith(`
|
|
159
|
-
`)&&w<e.length?e[w]==="\r"?2:1:0;b.push([u[E],w+R]),E+=i.length-1}return b}function rG(e,o){let i=(b)=>b.replace(/\s+/g," ").trim(),u=i(o);if(!u)return"";let p=e.split(/\r?\n/),g=o.split(/\r?\n/).length;for(let b=0;b+g<=p.length;b++)if(i(p.slice(b,b+g).join(`
|
|
160
|
-
`))===u)return` A match ignoring whitespace exists at line ${b+1}; copy the exact indentation and line breaks from the read output:
|
|
161
|
-
${ie(pu(p.slice(b,b+g),b+1),4000)}`;let y=o.split(/\r?\n/).find((b)=>b.trim())?.trim();if(y){let b=p.findIndex((E)=>E.includes(y));if(b!==-1)return` Its first line appears at line ${b+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 nG(e){let o=Al(e);if(!du(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let p=h$(o).filter((g)=>{let y=g.toLowerCase().replace(/\.[^.]*$/,"");return y&&(y.includes(u)||u.includes(y))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function f$(e,o){let i=g$(e,o);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!tg(i)}var ng=20,og=80,oG=5,sG=(e)=>e!==void 0&&e>0?e:void 0;function x$(e,o){let i=Sl(e,o)??wl(e,o);if(!i)throw Error(`No user message with seq ${o}`);return i}function Pl(e,o){let i=(y)=>{if(o)return o(y);if(y.source&&y.source!=="self"||y.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(y)=>{let b=i(y),E=sG(y.seq);return{scope:b,seq:E,runs:()=>Ks(b.records),reference:`session_id=${b.sessionID}`,both:E!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
162
|
-
`:""}},p=x({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
|
|
163
|
-
- 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).
|
|
164
|
-
- 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(a()),session_id:n(a({description:"Source session ID from the reference"})),pattern:a({minLength:1,description:"Text to search for"}),also:n(B(a({minLength:1}),{maxItems:oG,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(a({description:"Only search this chunk"})),seq:n(_({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(N({description:"Default false"})),head_limit:n(_({minimum:1,maximum:ng,description:`Hits to return (default ${ng})`})),offset:n(_({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(y,b){let{scope:E,seq:S,runs:w,reference:R,both:k}=u(b),A;if(S!==void 0)A=[x$(E.records,S)];else{let le=w(),he=b.chunk_id?le.filter(($e)=>$e.id===b.chunk_id):le;if(b.chunk_id&&!he.length)throw Error(`No chunk ${b.chunk_id}. Chunk IDs look like r12.`);A=he.map(cu)}let C=(le)=>b.case_sensitive?le:le.toLowerCase(),q=[b.pattern,...(b.also??[]).filter(Boolean)].map(C),X=b.head_limit??ng,j=b.offset??0,V=[],J=new Map,ee=0;for(let le of A)le.forEach((he,$e)=>{let Ee=C(he.text);if(!q.every((de)=>Ee.includes(de)))return;if(J.set(he.chunk,(J.get(he.chunk)??0)+1),ee++,ee<=j||V.length>=X)return;let ae=le.slice(Math.max(0,$e-2),$e+3);V.push(`${R} chunk ${he.chunk} line ${he.line}:
|
|
165
|
-
${Bc(ae," ")}`)});if(!ee)return c(`${k}No matches`);if(!V.length)return c(`${k}No matches at offset ${j} (total ${ee})`);let pe=ee-j-V.length,H=J.size>1?` (all matches by chunk: ${[...J].map(([le,he])=>`${le} ${he}`).join(", ")})`:"";return c(`${k}${V.join(`
|
|
166
|
-
|
|
167
|
-
`)}${pe>0?`
|
|
168
|
-
|
|
169
|
-
\u2026 ${pe} more matches${H}; continue with offset=${j+V.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),g=x({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(a()),session_id:n(a({description:"Source session ID from the reference"})),chunk_id:n(a({description:"Chunk to read"})),seq:n(_({description:"User message to read (from a user-text-reference)"})),offset:n(_({minimum:0,description:"First line (default 0)"})),limit:n(_({minimum:1,maximum:og,description:`Lines to return (default ${og})`}))}),async execute(y,b){let{scope:E,seq:S,runs:w,reference:R,both:k}=u(b),A;if(S!==void 0)A=x$(E.records,S);else if(b.chunk_id){let j=w().find((V)=>V.id===b.chunk_id);if(!j)throw Error(`No chunk ${b.chunk_id}. Chunk IDs look like r12.`);A=cu(j)}else{let j=w().map((V)=>`${R} ${V.id} (${V.status}, ${cu(V).length} lines)`);return c(j.length?`Pass chunk_id or seq. Chunks in this session:
|
|
170
|
-
${j.join(`
|
|
171
|
-
`)}`:"This session has no history yet")}let C=b.offset??0,q=A.slice(C,C+(b.limit??og));if(!q.length)return c(`No lines at offset ${C} (total ${A.length})`);let X=A.length-C-q.length;return c(`${k}${R} ${S!==void 0?`seq=${S}`:b.chunk_id}
|
|
172
|
-
${Bc(q)}${X>0?`
|
|
173
|
-
|
|
174
|
-
\u2026 ${X} more lines; continue with offset=${C+q.length}`:""}`)}});return[p,g]}import{existsSync as iG,statSync as I$}from"fs";import{isAbsolute as b$,relative as aG,resolve as E$}from"path";var $l=200,uG=30000,vl=Bun.which("rg");async function sg(e,o,i){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,g,y]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(y>1)throw Error(g.trim()||`${e[0]} exited with ${y}`);return p}function S$(e){let o=(g)=>g?b$(g)?g:E$(e,g):e,i=(g)=>{let y=aG(e,g);return y&&!y.startsWith("..")&&!b$(y)?y:g},u=x({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).
|
|
175
|
-
- Respects .gitignore and skips .git. Use it instead of find or ls -R.
|
|
176
|
-
- To search file contents, use grep.`,parameters:l({pattern:a({description:"Glob pattern, matched relative to path"}),path:n(a({description:"Directory to search (default: working directory)"}))}),async execute(g,y,b){let E=o(y.path),S=!1;try{S=I$(E).isDirectory()}catch{}if(!S)throw Error(`Directory not found: ${i(E)}`);let w;if(vl)w=(await sg([vl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",y.pattern],E,b)).split(`
|
|
177
|
-
`).filter(Boolean);else{w=[];for await(let C of new Bun.Glob(y.pattern).scan({cwd:E,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(C))w.push(C)}if(!w.length)return c("No files found");let R=w.map((C)=>{let q=E$(E,C);try{return{path:q,time:I$(q).mtimeMs}}catch{return{path:q,time:0}}});R.sort((C,q)=>q.time-C.time);let k=R.slice(0,$l).map((C)=>i(C.path)),A=w.length-k.length;return c(`${k.join(`
|
|
178
|
-
`)}${A>0?`
|
|
179
|
-
\u2026 ${A} more files; narrow the pattern`:""}`)}}),p=x({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
|
|
180
|
-
- output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
|
|
181
|
-
- Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
|
|
182
|
-
- Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
|
|
183
|
-
- Use this instead of running grep or rg through bash.`,parameters:l({pattern:a({description:"Regular expression"}),path:n(a({description:"File or directory to search (default: working directory)"})),glob:n(a({description:"Only search files matching this glob"})),output:n(m([s("files"),s("content"),s("count")],{description:"Output mode (default files)"})),ignore_case:n(N()),context:n(_({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(g,y,b){let E=o(y.path);if(!iG(E))throw Error(`Path not found: ${i(E)}`);let S=y.output??"files",w;if(vl){let A=[vl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(y.ignore_case)A.push("-i");if(y.glob)A.push("--glob",y.glob);if(S==="files")A.push("-l");else if(S==="count")A.push("-c");else if(A.push("-n","--no-heading"),y.context)A.push("-C",String(y.context));A.push("--",y.pattern,E),w=await sg(A,e,b)}else{let A=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(y.ignore_case)A.push("-i");if(y.glob)A.push(`--include=${y.glob}`);if(S==="files")A.push("-l");else if(S==="count")A.push("-c");else if(A.push("-n"),y.context)A.push(`-C${y.context}`);A.push("--",y.pattern,E),w=await sg(A,e,b)}let R=`${e}/`,k=w.split(`
|
|
184
|
-
`).filter(Boolean).map((A)=>A.startsWith(R)?A.slice(R.length):A).filter((A)=>S!=="count"||!A.endsWith(":0"));if(!k.length)return c("No matches");if(S==="files"&&k.length>$l)return c(`${k.slice(0,$l).join(`
|
|
185
|
-
`)}
|
|
186
|
-
\u2026 ${k.length-$l} more files; narrow the search`);return c(rt(k.join(`
|
|
187
|
-
`),uG,e))}});return[_e(u,"find","find_files","list_files","file_search","ls","list","list_dir"),_e(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function w$(e){return _e(x({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
|
|
188
|
-
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.
|
|
189
|
-
- Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
|
|
190
|
-
- 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.
|
|
191
|
-
- 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:B(l({content:a({minLength:1,description:"What to do, in imperative form"}),status:m(Gg.map((o)=>s(o)))}))}),async execute(o,i){let u=i.todos.map((y)=>({content:y.content,status:y.status}));e(u);let p=u.filter((y)=>y.status==="completed").length,g=u.find((y)=>y.status==="in_progress");return c(`Todo list updated (${p}/${u.length} completed${g?`; in progress: ${g.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function T$(e){let o=ue(e);return{target:o,hard:o,index:o}}class Ml{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},i){this.records=e;this.cwd=o;if(i)this.defaultPolicy=new Uc(e,i,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??T$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??ue(e)}prepare(e,o,i,u,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,i,u);let g=e.reduce((S,w)=>S+F(w),0)+Di(o),y=Math.max(0,ue(i)*this.recoveryRatio-g),b=Re(u??this.records(),i,T$(i),{cwd:this.cwd()}).messages,E=b.reduce((S,w)=>S+F(w),0);if(p&&E>y)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(E>y&&b.length>1){let S=b.shift();if(S)E-=F(S);while(b[0]?.role==="toolResult"){let w=b.shift();if(w)E-=F(w)}}if(E>y){let S=b.at(-1),w=S&&"content"in S&&typeof S.content==="string"?S.content:"[Context omitted: use history tools to retrieve earlier messages.]";b.length=0;let R=w;while(R&&F({role:"user",content:R,timestamp:0})>y)R=R.slice(Math.ceil(R.length/2));if(R)b.push({role:"user",content:R,timestamp:0});E=b.reduce((k,A)=>k+F(A),0)}return this.lastMessageCount=b.length,{messages:[...e,...b],estimate:g+E}}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 ag,readFileSync as cG}from"fs";import{homedir as mG}from"os";import{dirname as R$,join as ug,resolve as pG}from"path";var lG=`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.
|
|
192
|
-
|
|
193
|
-
# How to work
|
|
194
|
-
|
|
195
|
-
- 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.
|
|
196
|
-
- 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.
|
|
197
|
-
- 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.
|
|
198
|
-
- 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.
|
|
199
|
-
|
|
200
|
-
# Making changes
|
|
201
|
-
|
|
202
|
-
- 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.
|
|
203
|
-
- 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.
|
|
204
|
-
- 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.
|
|
205
|
-
- 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).
|
|
206
|
-
- Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
|
|
207
|
-
- 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.
|
|
208
|
-
|
|
209
|
-
# Verifying
|
|
210
|
-
|
|
211
|
-
- 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.
|
|
212
|
-
- 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.
|
|
213
|
-
- 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.
|
|
214
|
-
- 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.
|
|
215
|
-
- 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.
|
|
216
|
-
|
|
217
|
-
# Tools
|
|
218
|
-
|
|
219
|
-
- Tool calls are the only way to act; describing an action does not perform it.
|
|
220
|
-
- 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.
|
|
221
|
-
- 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.
|
|
222
|
-
- 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.
|
|
223
|
-
- 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.
|
|
224
|
-
- 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.
|
|
225
|
-
- 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 &&.
|
|
226
|
-
- 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.
|
|
227
|
-
|
|
228
|
-
# Honesty
|
|
229
|
-
|
|
230
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
231
|
-
- Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
|
|
232
|
-
- When the user asks you to run something, run it, even when you can predict the result.
|
|
233
|
-
- If a step failed, was skipped or could not be verified, say which one and why.
|
|
234
|
-
|
|
235
|
-
# Safety
|
|
236
|
-
|
|
237
|
-
- 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.
|
|
238
|
-
- 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.
|
|
239
|
-
- 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.
|
|
240
|
-
- Never print, log or commit secrets such as API keys, tokens or passwords.
|
|
241
|
-
|
|
242
|
-
# Communication
|
|
243
|
-
|
|
244
|
-
- Reply in the same language the user writes in.
|
|
245
|
-
- 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.
|
|
246
|
-
- 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.
|
|
247
|
-
- Do not use emojis unless the user does or asks for them.
|
|
248
|
-
- 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.
|
|
249
|
-
- Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,dG=`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.
|
|
250
|
-
|
|
251
|
-
# Tools
|
|
252
|
-
|
|
253
|
-
- 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.
|
|
254
|
-
- 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.
|
|
255
|
-
- Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
|
|
256
|
-
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
|
|
257
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
258
|
-
|
|
259
|
-
# Communication
|
|
260
|
-
|
|
261
|
-
- Reply in the same language the user writes in.
|
|
262
|
-
- Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
|
|
263
|
-
- Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,fG=["AGENTS.md","CLAUDE.md"],hG=20000;function k$(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?lG:dG}],i=[];if(e.globalInstructions?.trim())i.push(ig("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of gG(e.project.directory))i.push(ig(u.path,u.content));if(e.project.instructions.trim())i.push(ig(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
|
|
264
|
-
|
|
265
|
-
# Instructions from the user and project
|
|
266
|
-
|
|
267
|
-
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.
|
|
268
|
-
|
|
269
|
-
${i.join(`
|
|
270
|
-
|
|
271
|
-
`)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
|
|
272
|
-
|
|
273
|
-
${yG(e)}`}),o}function ig(e,o){return`<instructions source="${e}">
|
|
274
|
-
${ie(o.trim(),hG)}
|
|
275
|
-
</instructions>`}function gG(e){let o=[],i=e;for(let u=0;u<20;u++){for(let g of fG){let y=ug(i,g);if(ag(y)){try{o.unshift({path:y,content:cG(y,"utf8")})}catch{}break}}if(ag(ug(i,".git"))||i===mG())break;let p=R$(i);if(p===i)break;i=p}return o}function yG(e){let o=e.now??new Date,i=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:g}=Ea("",e.shell),y=[`Working directory: ${p}`,`Shell: ${g}`,`Date: ${i} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)y.push(e.git??"Git: not a git repository");return`<environment>
|
|
276
|
-
${y.join(`
|
|
277
|
-
`)}
|
|
278
|
-
</environment>`}function xG(e){let o=pG(e);while(!0){if(ag(ug(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let i=R$(o);if(i===o)return!1;o=i}}async function A$(e,o){if(o?.aborted||xG(e))return;let i=async(...E)=>{try{let S=Bun.spawn(["git",...E],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[w,R]=await Promise.all([new Response(S.stdout).text(),S.exited]);return R===0?w.trim():void 0}catch{return}},u=await i("rev-parse","--abbrev-ref","HEAD");if(u===void 0)return;let[p="",g=""]=await Promise.all([i("status","--short"),i("log","--oneline","-5")]),y=p?p.split(`
|
|
279
|
-
`):[],b=y.length>30?[...y.slice(0,30),`\u2026 ${y.length-30} more`]:y;return[`Git branch: ${u}`,`Git status at session start:${b.length?`
|
|
280
|
-
${b.join(`
|
|
281
|
-
`)}`:" clean"}`,g?`Recent commits:
|
|
282
|
-
${g}`:"Recent commits: none"].join(`
|
|
283
|
-
`)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Pl(e.records,e.history):[],u=e.directory??process.cwd();return[...y$(u,new rg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...S$(u),w$(e.onTodos),...i]}class Fi{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||!Hg.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Kg.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 i=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[u];else i[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,g=p.source??"core",y=u.name.toLowerCase(),b=p.defer??"always",E="suggestion";if(o.global)b=o.global,E="global";if(Object.hasOwn(o.sources,g))b=o.sources[g]??b,E="source";if(Object.hasOwn(o.tools,y))b=o.tools[y]??b,E="tool";if(g==="core"||p.builtin&&p.defer!=="defer")b="always",E="suggestion";return{name:u.name,source:g,mode:b,origin:E,deferred:b==="defer"}})}}function cg(e){return{name:e.name,description:e.description,parameters:e.parameters}}function mg(e,o){if(!o)return e;let i=Array.isArray(o.type)?o.type:[o.type],u=e;if(i.includes("number")||i.includes("integer")){let p=typeof u==="string"&&u.trim()?Number(u):u;if(typeof p!=="number"||!Number.isFinite(p))return u;let g=p;if(typeof o.maximum==="number"&&g>o.maximum)g=o.maximum;if(typeof o.minimum==="number"&&g<o.minimum)g=o.minimum;return g===p?u:g}if(typeof u==="string"&&(i.includes("object")||i.includes("array")))try{let p=JSON.parse(u),g=Array.isArray(p);if(typeof p==="object"&&p!==null&&!g&&i.includes("object")||g&&i.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((g)=>mg(g,p))}if(typeof u==="object"&&u!==null&&o.properties){let p={...u};for(let[g,y]of Object.entries(o.properties))if(g in p)p[g]=mg(p[g],y);return p}return u}function IG(e){let o=e.prepareArguments;return{...e,prepareArguments:(i)=>{let u=mg(i,e.parameters);return o?o(u):u}}}function bG(e,o,i){let u=e.prepareArguments?e.prepareArguments(i):i;return nu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class pg{retrieved=new Map;stub(e,o){let i=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${i}
|
|
284
|
-
(Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,p,g,y)=>{let b=JSON.stringify(cg(e)),E;try{E=bG(e,u,p??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
|
|
285
|
-
Schema: ${b}`),isError:!0}}let S=await e.execute(u,E,g,y),w=S.content.map((R)=>R.type==="text"?{...R,text:rt(R.text,Pe,o)}:R);return{...S,content:w}}}}assemble(e,o,i,u){let p=e.map(IG),g=new Set(o.filter((b)=>b.deferred).map((b)=>b.name));if(!g.size)return p;let y=p.filter((b)=>g.has(b.name)&&i(b.name)).sort((b,E)=>b.name<E.name?-1:b.name>E.name?1:0);return[...p.filter((b)=>!g.has(b.name)),...y.map((b)=>this.stub(b,u)),_e(x({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:a(),max_results:n(_({minimum:1,maximum:100}))}),execute:async(b,E)=>{let S=E.query.trim().toLowerCase(),w=S.startsWith("select:")?S.slice(7).split(",").map((k)=>k.trim()):void 0,R=y.filter((k)=>i(k.name)&&(w?w.includes(k.name.toLowerCase()):`${k.name} ${k.description}`.toLowerCase().includes(S))).slice(0,E.max_results??5);return c(JSON.stringify(R.map((k)=>{let A=JSON.stringify(cg(k)),C=this.retrieved.get(k.name);if(C?.schema===A)return{name:k.name,status:"\u5DF2\u53D6\u56DE",callID:C.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(k.name,{schema:A,callID:b}),cg(k)})))}}),"tool_search")]}}async function Ol(e,o,i,u){let p=await o.setup(e,u),g=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(g),!i)return p;if(i.has("session.setup"))p=await i.invoke("session.setup",p,e);if(i.has("tools.configure"))p=await i.invoke("tools.configure",p,e);let y=p.systemPrompt,b=p.systemParts?.at(-1);if(b?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let R=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),k=y.length-b.detail.length;y=y.slice(0,k)+R.join("")+b.detail}let E=await i.invoke("prompt.fragments",[],e),S=[...p.tools,...i.tools()],w=i.has("tools.visible")?await i.invoke("tools.visible",S,e):S;return{...p,systemPrompt:y+E.join(""),tools:w}}var EG=3,C$={attempts:10,delayMs:2000},SG=/\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 wG(e,o){if(e.stopReason!=="error")return!1;if(ca(e,o))return!1;return!SG.test(e.errorMessage??"")}function P$(e,o,i){if(ca(e,o))return!0;if(i?.preserveHistory!==!0)return!1;return e.errorMessage===(i.overflowError??"Context exceeds the request budget")}function TG(e,o){return new Promise((i,u)=>{if(o.aborted)return u(o.reason);let p=setTimeout(()=>{o.removeEventListener("abort",g),i()},e),g=()=>{clearTimeout(p),u(o.reason)};o.addEventListener("abort",g,{once:!0})})}async function $$(e,o,i,u,p,g,y,b,E=!1){let S=E?void 0:await o?.invoke("run.start",{text:g},e);if(S)g=S.text;if(b.throwIfAborted(),g===void 0)await u.resume();else await u.prompt(g,y);let w=0,R=0;while(w<EG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!P$(q,p.contextWindow,i)){if(!wG(q,p.contextWindow)||R>=C$.attempts)return;R++,await TG(C$.delayMs,b),await u.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}b.throwIfAborted(),w++,await u.retry()}let A=e.records.findLast((C)=>C.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&A?.stopReason==="error"&&P$(A,p.contextWindow,i))throw Error(i.overflowError??"Context exceeds the request budget")}async function v$(e,o,i,u,p,g){g.throwIfAborted();let y,b;try{b=await Promise.race([Ol(e,o,i(),g),new Promise((k,A)=>{y=()=>A(g.reason),g.addEventListener("abort",y,{once:!0})})])}finally{if(y)g.removeEventListener("abort",y)}g.throwIfAborted();let E=i(),S=(k)=>{if(!E)return k;return{...k,execute:async(A,C,q,X)=>{let j=u()??b.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?E.policy(j):void 0;if(j&&!V?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${j}`);let J=await E.invoke("tool.before_call",{name:k.name,callID:A,args:C},e);if(J.block)throw Error(J.block);let ee=await z.run(e,()=>k.execute(A,J.args,q,X));return E.invoke("tool.after_result",ee,e)}}};if(E)b.tools=b.tools.map(S);let w=b.tools,R=()=>{if(!w.some((A)=>A.name==="history_grep")){if(e.records.some((C)=>C.entry.type==="compaction")){let q=Pl(()=>e.records,(X)=>e.resolveHistory(X)).map(S);for(let X of q)if(!w.some((j)=>j.name===X.name))w.push(X)}}let k=new Fi(o.store).partition(w);return b.tools=p.assemble(w,k,(A)=>e.permitsTool(A),b.cwd),b.tools};return b.tools=R(),{setup:b,executionTools:w,assemble:R}}function M$(e,o,i,u,p,g,y){return{response:async(b)=>{let E=await o()?.invoke("model.after_response",b,e)??b;if(E.role==="assistant")for(let S of E.content){if(S.type!=="toolCall"||S.name.toLowerCase()!=="tool_call")continue;let w=S.arguments.name;if(typeof w==="string"){let R=y.find((k)=>k.name.toLowerCase()===w.toLowerCase());S.arguments.name=R?.name??w}}return E},payload:(b)=>o()?.invoke("model.before_request",b,e)??Promise.resolve(b),transformContext:(b)=>o()?.invoke("transformContext",b,e)??Promise.resolve(b),boundary:async()=>{if(u())return!0;let b=await o()?.invoke("step.after",{notices:[]},e);for(let S of b?.notices??[])e.notice(S);await g.work;let E=await g.flushNotices();if(E&&!p())e.agent?.steer(E)},prepare:async(b,E,S)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let w=await o()?.invoke("model.check",{},e);if(w?.error)throw Error(w.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let j of R?.notices??[])e.notice(j);await g.work,await g.flushNotices();let k=await o()?.invoke("projection.before",e.records,e),A=await o()?.invoke("projection.prefix",[],e)??[],C=e.context.prepare([...b,...A],E,S,k,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&C.estimate>ue(S))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=C.messages,X=await o()?.invoke("projection.after",q,e)??q;return au(DP(X))}}}async function O$(e,o,i){let u=o.store.pendingNotices(e.id);if(!u.length)return;let p=u,g=o.plugins?.pin();try{if(g){let A=await g.invoke("notice.deliver",u,e);p=u.map((C,q)=>({...C,text:A[q]?.text??C.text}))}}finally{await g?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let y=p.map((A)=>A.text).join(`
|
|
286
|
-
`),b=p.map((A)=>o.plugins?.noticeSource(A.sourceKind)),E=Math.max(800,...b.map((A)=>A?.summaryLimit??800)),S=y.length>E?`
|
|
287
|
-
[\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${b.find((A)=>A?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
|
|
288
|
-
${y.slice(0,E)}${S}`,k={role:"user",content:R,timestamp:Date.now()};return i({type:"user",text:R,notices:u.map(({text:A,...C})=>C)},k),k}class lg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,i,u,p,g,y,b){this.session=e;this.context=o;this.isStopped=i;this.isRunning=u;this.waiting=p;this.start=g;this.invalidateAgent=y;this.append=b}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let i of e){if(i.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:i.dedupeKey,sourceKind:i.sourceKind,sourceID:i.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((i)=>i.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((i)=>{this.failure=i}),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=O$(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 RG=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 dg(e){let o={};for(let[i,u]of Object.entries(e)){if(!RG.has(i.toLowerCase())){o[i]=u;continue}let p=/^bearer\s+/i.exec(u)?.[0];o[i]=p?`${p}***`:"***"}return o}function _$(e,o,i,u){let g=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((H,le)=>({id:`system-${le}`,label:H.label,detail:H.detail,tokens:D(H.detail)+(le===0?16:0)})),y=i.tools.map((H)=>{let le=H,he=le.defer==="defer"||H.description.includes("(Parameters not inlined: use toolsearch");return{name:H.name,description:H.description,group:le.group??"\u5185\u7F6E",schema:H.parameters,deferred:he}});g.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Di(i.tools),detail:JSON.stringify(y,null,2)});let b=g.reduce((H,le)=>H+le.tokens,0),E=u!==void 0?e.records.filter((H)=>H.entry.seq<=u):e.records,S=Re(E,o,e.context.budget(o),{inspect:!0,cwd:i.cwd,trim:{fixed:b,limit:e.context.previewLimit(o)}}),w,R=0,k=0;for(let H of E){if(H.raw?.role!=="assistant")continue;let le=H.raw.usage;w??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},w.input+=le.input,w.output+=le.output,w.cacheRead+=le.cacheRead,w.cacheWrite+=le.cacheWrite,w.cost+=le.cost.total;let he=H.entry.generationMs??H.raw.generationMs;if(typeof he==="number"&&he>0&&le.output>0)R+=he,k+=le.output}if(w){let H=w.input+w.cacheRead+w.cacheWrite;if(H>0)w.cacheHitRate=w.cacheRead/H}if(w&&R>0&&k>0)w.generationMs=R,w.tps=Number((k/(R/1000)).toFixed(1));let A=b+S.tokens,C=e.context.calibrationRatio??1,q=Math.round(A*C),X=E.findLast((H)=>H.raw?.role==="assistant"),j=X?.raw,J=(X?E.filter((H)=>H.entry.seq>X.entry.seq&&H.raw):E.filter((H)=>H.raw)).length>0,ee,pe;if(j){let H=j.usage,le=H.input+H.cacheRead+H.cacheWrite;if(le>0)ee=le,pe=H.cacheRead/le}return{contextWindow:o.contextWindow,usableWindow:ue(o),items:[...g,...S.items],calibratedTokens:q,calibrationRatio:C,lastInputTokens:ee,lastCacheHitRate:pe,hasPendingOutput:J,tools:y,usage:w}}class dt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class se extends Error{constructor(e="session"){super(`${e} is busy`)}}var fg="medium";class _l{row;ctx;events;notices;lease;policyID;discovery=new pg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Ol(this,this.ctx,e);return new Fi(this.ctx.store).partition(o.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new se;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;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,i){this.row=e;this.ctx=o;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new lg(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),g=p.findLast((b)=>b.type==="extension"&&b.namespace==="session"&&b.kind==="stop_requested"),y=p.findLast((b)=>b.type==="run"&&b.state==="start");if(g&&g.seq>(y?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let b=this.entries(u.seq,["user"],!1).length>0,E=o.store.pendingNotices(e.id).some((S)=>S.wake&&S.recovery!=="discard");if(!this.stopped&&(b||E))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new Ml(()=>this.records,()=>this.cwd,(b,E)=>this.appendCompaction(b,E)),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=En(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:dg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:dg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??fg}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:i,model:u,thinking:p,metadata:g,created:y,updated:b,todos:E}=this.row;return{id:e,title:o,projectID:i,model:u,thinking:p??fg,metadata:g,created:y,updated:b,archivedAt:this.row.archivedAt,status:this.status,todos:E,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);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,o,i){return this.ctx.store.entriesAround(this.row.id,e,o,i)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,i=!0){return this.ctx.store.entries(this.row.id,e,o,i)}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 i=En(this.ctx.models,this.row.model);if(!i)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 Ol(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new Fi(this.ctx.store).partition(p.tools),(y)=>this.permitsTool(y),p.cwd);let g=_$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:g};return g})();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 dt}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"||!En(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,Zl(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 i=Zl(o),u=_h(e,i),p=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},u);if(this.recallableSteers.set(p.seq,u),this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((g)=>g.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 i=o.raw,u=this.pendingSteers.indexOf(i);if(u<0){let g=JSON.stringify(i);u=this.pendingSteers.findIndex((y)=>JSON.stringify(y)===g)}let p=!1;if(u>=0)this.pendingSteers.splice(u,1),p=!0;else p=this.agent?.unsteer(i)??!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,i]of this.recallableSteers){if(i!==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,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new se;if(e!==void 0)this.stopped=!1;let u=En(this.ctx.models,this.row.model);if(!u&&i===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:kG(e,o)},this.ctx.store.updateSession(this.row);let g=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let y=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=y.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(i!==void 0){let b=this.records.filter((R)=>R.entry.seq>g),E=b.filter((R)=>R.entry.type==="user"&&!R.raw);if(E.length>1)return{reason:"interrupted"};let S=E[0];if(S?.entry.type==="user"){if(b.some((R)=>R.entry.seq>S.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=S.entry.text,o=S.entry.attachments,this.pendingUserSeq=S.entry.seq}for(let R of To(b.filter((k)=>k.raw))){if(R.result)continue;let k=R.message.stopReason;if(k==="error"||k==="aborted")continue;let{body:A,raw:C}=cl(R.call);this.append(A,C)}if(!S&&this.waitingForInput())return{reason:"waiting_user"};let w=this.records.findLast((R)=>R.entry.seq>g&&R.raw)?.raw;if(!S&&w?.role==="assistant")return Lh(w);if(!S&&!w&&!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 y=await this.prepareAgent(u,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let b=this.pendingSteers.shift();if(b)y.steer(b)}return await $$(this,this.lease,this.setup,y,u,e,o,p.signal,i!==void 0&&e===void 0),Lh(this.records.findLast((b)=>b.entry.seq>g&&b.raw?.role==="assistant")?.raw)}).then((y)=>p.signal.aborted?{reason:"aborted"}:y,(y)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(y)}).then(async(y)=>{try{if(!this.suspended&&y.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())y={reason:"waiting_user"};if(y.reason!=="interrupted")y=await this.lease?.invoke("run.end",{reason:y.reason,error:y.error},this)??y}}catch(b){y={reason:"error",error:String(b)}}finally{try{await this.lease?.release()}catch(b){y={reason:"error",error:String(b)}}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",...y});let b=En(this.ctx.models,this.row.model);if(b)this.context.settle(b)}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:i,executionTools:u,assemble:p}=await v$(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=i,this.row.parentID&&(!i.toolPolicy||!this.lease?.policy(i.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=i.cwd,this.agent=IP({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((g)=>!this.pendingSteers.includes(g.raw)).flatMap((g)=>g.raw?[g.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??fg,captureRequest:(g)=>{this.lastRequestSnapshot=g},captureResponse:(g)=>{this.lastResponseSnapshot=g},steerConsumed:(g)=>this.markSteerConsumed(g),hooks:{tools:p,...M$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(g,y)=>{if(this.suspended&&y.role==="assistant"&&(y.stopReason==="aborted"||y.stopReason==="error"))return;if(y.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,y);let b=this.loaded?.find((E)=>E.entry.seq===this.pendingUserSeq);if(b)b.raw=y;this.pendingUserSeq=void 0;return}if(y.role==="assistant")this.context.calibrate(y);this.append(g,y)},draft:(g)=>{this.draftParts=g,this.events.draft(g)}}})}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 i=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...i?{saved:i}:{}})}measureCompactionSavings(e,o){let i=En(this.ctx.models,this.row.model);if(!i)return;let u=this.context.budget(i),p=Re(this.records,i,u,{cwd:this.cwd}).tokens,g={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},y=Re([...this.records,g],i,u,{cwd:this.cwd}).tokens;return{before:p,after:y}}compact(){this.assertWritable();let e=iu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}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 kG(e,o){let u=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
|
|
289
|
-
`)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var N$=new Set(["user","assistant","tool_result","run","compaction"]),AG=new Set(["user","assistant","toolResult"]);function D$(e,o,i){return{format:Yl,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},...i?{project:i}:{},records:o.filter((u)=>N$.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function Bo(e){if(!gr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Yl)return CG(e);if(gr(e.info)&&Array.isArray(e.messages))return $G(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 CG(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(!gr(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 i=0,u=e.records.flatMap((p,g)=>{let y=`records[${g}]`;if(!gr(p)||!gr(p.entry))throw new t(`${y} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let b=p.entry;if(b.type==="notice_pending"||b.type==="extension")return[];if(typeof b.type!=="string"||!N$.has(b.type))throw new t(`${y} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(b.type)}`);let{seq:E,time:S}=b;if(typeof E!=="number"||!Number.isSafeInteger(E)||E<=i)throw new t(`${y} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof S!=="number"||!Number.isFinite(S))throw new t(`${y} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=E,PG(b,y);let w=p.raw;if(w!==void 0&&!(gr(w)&&typeof w.role==="string"&&AG.has(w.role)))throw new t(`${y} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:b,...w===void 0?{}:{raw:w}}]});return{title:Lr(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(F$):[],created:Hs(o.created)??Date.now(),updated:Hs(o.updated)??Date.now(),needsRaw:!1,records:u}}function PG(e,o){let i=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);switch(e.type){case"user":if(typeof e.text!=="string")throw i("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw i("\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 i("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&qg.includes(e.reason)))throw i("\u7684 state/reason \u4E0D\u5408\u6CD5");return;case"compaction":if(typeof e.through!=="number"||typeof e.partial!=="boolean")throw i("\u7F3A\u5C11 through \u6216 partial");return}}function $G(e){let o=e.info,i=gr(o.time)?o.time:{},u=gr(o.model)?o.model:void 0,p=e.messages.filter(gr).sort(vG),g=[],y=0,b=0,E=(X,j)=>{b=Math.max(b,j??b),y+=1,g.push({entry:{...X,seq:y,time:b}})},S=!1,w=(X,j)=>{if(!S)return;S=!1,E({type:"run",state:"end",reason:X,...j?{error:j}:{}},void 0)};for(let X of p){let j=gr(X.info)?X.info:{},V=Array.isArray(X.parts)?X.parts.filter(gr):[],J=Hs(gr(j.time)?j.time.created:void 0);if(j.role==="user"){w("done");let ee=MG(V);if(!ee)continue;E({type:"run",state:"start"},J),E(ee,J),S=!0}else if(j.role==="assistant"){if(!S)E({type:"run",state:"start"},J),S=!0;LG(j,V,E);let ee=q$(j.error);if(ee)w(ee.aborted?"aborted":"error",ee.aborted?void 0:ee.message)}}w("done");let R=p.findLast((X)=>gr(X.info)&&X.info.role==="assistant"),k=gr(R?.info)?R.info:void 0,A=Lr(u?.providerID)||Lr(k?.providerID),C=Lr(u?.id)||Lr(k?.modelID),q=A&&C?`${A}/${C}`:void 0;return{title:Lr(o.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(F$):[],created:Hs(i.created)??g[0]?.entry.time??Date.now(),updated:Hs(i.updated)??g.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:g}}function vG(e,o){let i=(p)=>(gr(p.info)&&gr(p.info.time)?Hs(p.info.time.created):void 0)??0,u=(p)=>gr(p.info)?Lr(p.info.id):"";return i(e)-i(o)||u(e).localeCompare(u(o))}function MG(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Lr(u.text)).join(`
|
|
290
|
-
|
|
291
|
-
`),i=e.flatMap((u)=>u.type==="file"?OG(u):[]);if(!o.trim()&&i.length===0)return;return{type:"user",text:o,...i.length?{attachments:i}:{}}}function OG(e){let o=Lr(e.mime)||"application/octet-stream",i=Lr(e.filename)||"file",u=Lr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(p){let g=p[3]??"";if(o.startsWith("image/"))return[{name:i,mimeType:o,kind:"image",data:p[2]?g:btoa(g)}];if(o.startsWith("text/")||o==="application/json"){let y=p[2]?new TextDecoder().decode(Uint8Array.from(atob(g),(b)=>b.charCodeAt(0))):g;return[{name:i,mimeType:o,kind:"text",data:y}]}return[]}if(u.startsWith("file://"))try{return[{name:i,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function _G(e){let o=[[]];for(let i of e){if(i.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")o.at(-1)?.push(i)}return o.filter((i)=>i.length>0)}function LG(e,o,i){let u=`${Lr(e.providerID)}/${Lr(e.modelID)}`,p=q$(e.error),g=_G(o);g.forEach((y,b)=>{let E=y.flatMap((R)=>{if(R.type==="reasoning")return Lr(R.text).trim()?[{type:"thinking",text:Lr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Lr(R.text).trim()?[{type:"text",text:Lr(R.text)}]:[];return[{type:"tool_call",id:L$(R.callID),name:Lr(R.tool),input:gr(R.state)&&gr(R.state.input)?R.state.input:{}}]}),S=b===g.length-1,w=NG(y);i({type:"assistant",parts:E,model:u,...S&&p&&!p.aborted?{error:p.message}:{}},w);for(let R of y){if(R.type!=="tool")continue;let k=gr(R.state)?R.state:{},A=k.status==="error",C=k.status==="pending"||k.status==="running",q=A?[Lr(k.output),Lr(k.error)].filter(Boolean).join(`
|
|
292
|
-
`):C?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Lr(k.output);i({type:"tool_result",callID:L$(R.callID),name:Lr(R.tool),output:q,isError:A||C},Hs(gr(k.time)?k.time.end:void 0))}})}function L$(e){return Lr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function q$(e){if(!gr(e))return;let o=gr(e.data)?e.data:{};return{message:Lr(o.message)||Lr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function NG(e){for(let o of e){let i=gr(o.time)?Hs(o.time.start):gr(o.state)?DG(o.state):void 0;if(i!==void 0)return i}return}function DG(e){return gr(e.time)?Hs(e.time.start):void 0}function F$(e){if(!gr(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 j$(e,o){let i={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:qG(u,p)};case"assistant":{let g=u.parts.flatMap((b)=>{if(b.type==="text")return[{type:"text",text:b.text}];if(b.type==="thinking")return[];return[{type:"toolCall",id:b.id,name:b.name,arguments:FG(b.input)}]}),y=g.some((b)=>b.type==="toolCall");return{entry:u,raw:{role:"assistant",content:g,api:o.api,provider:o.provider,model:o.id,usage:i,stopReason:u.error?"error":y?"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 qG(e,o){let i=(e.attachments??[]).flatMap((g)=>g.kind==="path"?[`<file path=${JSON.stringify(g.data)} />`]:g.kind==="text"?[`<file name=${JSON.stringify(g.name)}>
|
|
293
|
-
${g.data}
|
|
294
|
-
</file>`]:[]),u=(e.attachments??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),p=[...i,...e.text.trim()?[e.text]:[]].join(`
|
|
295
|
-
|
|
296
|
-
`);return{role:"user",content:u.length?[{type:"text",text:p},...u]:p,timestamp:o}}function gr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e==="string"?e:""}function Hs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function FG(e){return gr(e)?e:{}}function or(e,o){let i=e.at(-1)?.entry.seq??0,u,p,g;for(let{entry:S}of e){if(S.type==="run"&&S.state==="start")u=S.seq;if(S.seq===o)if(S.type==="user"&&!S.notices)i=(u??S.seq)-1;else p=u;if(S.type==="run"&&S.state==="end"){if(p!==void 0&&u===p)g=S.seq;u=void 0}}let y=e.find((S)=>S.entry.seq===o)?.entry;if(o!==void 0&&!y)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(y&&!(y.type==="user"&&!y.notices)){if(p!==void 0&&g===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=g??y.seq}else if(o===void 0&&u!==void 0)i=e.findLast(({entry:S})=>S.type==="run"&&S.state==="end")?.entry.seq??0;let b=e.filter(({entry:S})=>S.seq<=i&&(S.type!=="compaction"||S.through<=i)),E=new Map(b.map(({entry:S},w)=>[S.seq,w+1]));return b.map((S,w)=>{let R=structuredClone(S);if(R.entry.seq=w+1,R.entry.type==="compaction"){let k=R.entry.through,A=b.findLast(({entry:C})=>C.seq<=k);R.entry.through=A?E.get(A.entry.seq)??0:0}return R})}function ir(e){let o=new Map,i=[];for(let u of e){if(u.type==="assistant"){for(let y of u.parts)if(y.type==="tool_call"&&y.name==="todo")o.set(y.id,y.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 g=[];for(let y of p.todos){if(!y||typeof y!=="object"||!("content"in y)||typeof y.content!=="string"||!("status"in y)||y.status!=="pending"&&y.status!=="in_progress"&&y.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");g.push({content:y.content,status:y.status})}i=g}return i}import{Buffer as G$}from"buffer";import{createHash as jG}from"crypto";import{isDeepStrictEqual as Ll}from"util";var Nl="@blob:";function fu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function U$(e,o,i){if(typeof e!=="string"||e.length<256||e.startsWith(Nl))return;let u=G$.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let p=jG("sha256").update(u).digest("hex");return i.put(p,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Nl}${p}`}function B$(e,o){if(typeof e!=="string"||!e.startsWith(Nl))return;let i=o.get(e.slice(Nl.length));if(i===void 0)return;return G$.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Dl(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let g=U$(p.data,p.mimeType,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((p)=>{let g=U$(p.data,p.mimeType,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,images:u}}return e}function Ws(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let g=B$(p.data,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((p)=>{let g=B$(p.data,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,images:u}}return e}function Hc(e,o){if(!fu(o))return o;if(e.type==="user"){let{merged:i,images:u}=Dc(e.text,e.attachments),p=u.length>0?[{type:"text",text:i},...u]:i,g=Object.keys(o),{role:y,timestamp:b,content:E}=o;if(g.length===3&&y==="user"&&typeof b==="number"&&"content"in o&&Ll(E,p))return{role:"user",timestamp:b};return o}if(e.type==="tool_result"){let{role:i,toolCallId:u,toolName:p,isError:g,timestamp:y,content:b}=o;if(i!=="toolResult"||u!==e.callID||typeof p!=="string"||g!==e.isError||typeof y!=="number")return o;let E=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!Ll(o.details,e.meta):e.meta!==void 0)return o;let{role:w,toolCallId:R,toolName:k,content:A,details:C,isError:q,timestamp:X,...j}=o;if(Ll(b,E))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:y};if(Array.isArray(b)){let V=e.images??[],J=0,ee=!0,pe=b.map((H)=>{if(fu(H)&&H.type==="image"){let le=V[J++],he=Object.keys(H);if(le&&he.length===3&&H.mimeType===le.mimeType&&H.data===le.data)return{type:"image",mimeType:H.mimeType};ee=!1}return H});if(ee&&J===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:pe,...j,timestamp:y}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let p=!1,g=u.map((y,b)=>{let E=e.parts[b];if(fu(y)){if(y.type==="text"&&E?.type==="text"&&y.text===E.text){p=!0;let S={...y};return delete S.text,S}if(y.type==="thinking"&&E?.type==="thinking"&&y.thinking===E.text){p=!0;let S={...y};return delete S.thinking,S}if(y.type==="toolCall"&&E?.type==="tool_call"&&y.id===E.id&&y.name===E.name&&"arguments"in y&&Ll(y.arguments,E.input)){p=!0;let S={...y};return delete S.id,delete S.name,delete S.arguments,S}}return y});if(!p)return o;return{...o,content:g}}return o}function hg(e,o){if(!fu(o))return o;if(e.type==="user"){let{role:i,timestamp:u}=o;if(i==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:p,images:g}=Dc(e.text,e.attachments);return{role:"user",content:g.length>0?[{type:"text",text:p},...g]:p,timestamp:u}}return o}if(e.type==="tool_result"){let{role:i,timestamp:u}=o;if(i==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:g,toolName:y,content:b,timestamp:E,...S}=o,w;if(Array.isArray(b)){let R=e.images??[],k=0;w=b.map((A)=>{if(fu(A)&&A.type==="image"&&!("data"in A)){let C=R[k++];if(C)return{type:"image",mimeType:A.mimeType,data:C.data}}return A})}else w=[{type:"text",text:e.output},...(e.images??[]).map((R)=>({type:"image",mimeType:R.mimeType,data:R.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof y==="string"?y:e.name,content:w,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...S,timestamp:u}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u))return o;let p=!1,g=u.map((y,b)=>{let E=e.parts[b];if(fu(y)){if(y.type==="text"&&!("text"in y)&&E?.type==="text"){p=!0;let{type:S,...w}=y;return{type:S,text:E.text,...w}}if(y.type==="thinking"&&!("thinking"in y)&&E?.type==="thinking"){p=!0;let{type:S,...w}=y;return{type:S,thinking:E.text,...w}}if(y.type==="toolCall"&&!("arguments"in y)&&E?.type==="tool_call"){p=!0;let{type:S,...w}=y;return{type:S,id:E.id,name:E.name,arguments:structuredClone(E.input),...w}}}return y});if(!p)return o;return{...o,content:g}}return o}function K$(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(E,S,w){o.run(E,S,w)},get(E){return i.get(E)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),g=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),y=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),b=0;return e.transaction(()=>{for(let E of p){let S;try{S=JSON.parse(E.body)}catch{continue}let w=Ws(S,u),R=Dl(w,u),k=R===S?E.body:JSON.stringify(R),A=E.raw;if(E.raw!==null)try{let C=JSON.parse(E.raw),q=hg(w,C),X=Hc(w,q);A=JSON.stringify(X)}catch{A=E.raw}if(k!==E.body)g.run(k,A,E.session_id,E.seq),b++;else if(A!==E.raw)y.run(A,E.session_id,E.seq),b++}})(),b}import{Database as UG}from"bun:sqlite";import{chmodSync as H$,existsSync as BG,mkdirSync as GG}from"fs";import{dirname as KG}from"path";var gg=[`
|
|
297
|
-
CREATE TABLE projects (
|
|
298
|
-
id TEXT PRIMARY KEY,
|
|
299
|
-
name TEXT NOT NULL,
|
|
300
|
-
directory TEXT NOT NULL UNIQUE,
|
|
301
|
-
instructions TEXT NOT NULL DEFAULT '',
|
|
302
|
-
created INTEGER NOT NULL,
|
|
303
|
-
updated INTEGER NOT NULL
|
|
304
|
-
);
|
|
305
|
-
CREATE TABLE automations (
|
|
306
|
-
id TEXT PRIMARY KEY,
|
|
307
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
308
|
-
name TEXT NOT NULL,
|
|
309
|
-
prompt TEXT NOT NULL,
|
|
310
|
-
schedule TEXT NOT NULL,
|
|
311
|
-
model TEXT NOT NULL,
|
|
312
|
-
enabled INTEGER NOT NULL,
|
|
313
|
-
created INTEGER NOT NULL,
|
|
314
|
-
updated INTEGER NOT NULL,
|
|
315
|
-
next_run INTEGER,
|
|
316
|
-
last_run INTEGER,
|
|
317
|
-
last_session_id TEXT
|
|
318
|
-
);
|
|
319
|
-
CREATE TABLE sessions (
|
|
320
|
-
id TEXT PRIMARY KEY,
|
|
321
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
322
|
-
automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
|
|
323
|
-
title TEXT NOT NULL DEFAULT '',
|
|
324
|
-
model TEXT NOT NULL,
|
|
325
|
-
todos TEXT NOT NULL DEFAULT '[]',
|
|
326
|
-
created INTEGER NOT NULL,
|
|
327
|
-
updated INTEGER NOT NULL
|
|
328
|
-
);
|
|
329
|
-
CREATE INDEX sessions_project ON sessions(project_id);
|
|
330
|
-
CREATE TABLE entries (
|
|
331
|
-
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
332
|
-
seq INTEGER NOT NULL,
|
|
333
|
-
time INTEGER NOT NULL,
|
|
334
|
-
body TEXT NOT NULL,
|
|
335
|
-
raw TEXT,
|
|
336
|
-
PRIMARY KEY (session_id, seq)
|
|
337
|
-
) WITHOUT ROWID;
|
|
338
|
-
`,"","","",`
|
|
339
|
-
ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
|
|
340
|
-
ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
|
|
341
|
-
ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
|
|
342
|
-
CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
|
|
343
|
-
ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
|
|
344
|
-
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,
|
|
345
|
-
PRIMARY KEY (namespace, key));
|
|
346
|
-
CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
|
|
347
|
-
PRIMARY KEY (namespace, version));
|
|
348
|
-
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);
|
|
349
|
-
CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
|
|
350
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
351
|
-
END;
|
|
352
|
-
CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
|
|
353
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
|
|
354
|
-
END;
|
|
355
|
-
CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
|
|
356
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
357
|
-
END;
|
|
358
|
-
CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
|
|
359
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
360
|
-
END;
|
|
361
|
-
CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
|
|
362
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
363
|
-
END;
|
|
364
|
-
CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
|
|
365
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
|
|
366
|
-
END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
|
|
367
|
-
WHERE json_extract(body,'$.type')='compaction';
|
|
368
|
-
CREATE TABLE IF NOT EXISTS blobs (
|
|
369
|
-
hash TEXT PRIMARY KEY,
|
|
370
|
-
mime TEXT NOT NULL,
|
|
371
|
-
data BLOB NOT NULL
|
|
372
|
-
) WITHOUT ROWID;
|
|
373
|
-
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 HG=[20,50,100,200,400,800];function WG(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 yg(e){let o=0;while(!0)try{return e()}catch(i){let u=HG[o];if(u===void 0||!WG(i))throw i;o++,Bun.sleepSync(u)}}function W$(e,o){if(e!==":memory:")GG(KG(e),{recursive:!0});let i=new UG(e,{create:!0,strict:!0}),u=(g,y=!0)=>new Proxy(function(...b){return Reflect.apply(g,this,b)},{apply(b,E,S){Ps();let w=o.length===0&&!i.inTransaction,R=y?Reflect.get(g,"immediate"):void 0,k=()=>{let A=[];o.push(A);let C=!1;try{let q=typeof R==="function"?Reflect.apply(R,g,S):Reflect.apply(b,E,S);return C=!0,q}finally{o.pop();let q=o.at(-1);if(C&&q)q.push(...A);else for(let X of A)if(C)X.commit();else X.rollback()}};return w?yg(k):k()},get(b,E){let S=Reflect.get(g,E);if(["deferred","immediate","exclusive"].includes(String(E))&&typeof S==="function")return u(S,!1);return S}}),p=new Proxy(i,{get(g,y){let b=Reflect.get(g,y,g);if(typeof b!=="function")return b;return(...E)=>{Ps();let R=(y==="run"||y==="exec")&&o.length===0&&!i.inTransaction?yg(()=>Reflect.apply(b,g,E)):Reflect.apply(b,g,E);if(y==="transaction"&&typeof R==="function")return u(R,!0);if(y!=="query"&&y!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(k,A,C){let q=Reflect.get(k,A,k);if(typeof q!=="function")return q;return(...X)=>{Ps();let J=(A==="run"||A==="get"||A==="all"||A==="values")&&o.length===0&&!i.inTransaction?yg(()=>Reflect.apply(q,k,X)):Reflect.apply(q,k,X);return J===k?C:J}}})}}});if(e!==":memory:")H$(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"),zG(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 g of["-wal","-shm"]){let y=e+g;if(BG(y))H$(y,384)}return p}function zG(e,o=gg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \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=i;u<o.length;u++)e.transaction(()=>{let p=o[u]??"",g=Array.isArray(p)?p:u>=4?VG(p):[p];for(let y of g)try{if(y.trim())e.run(y)}catch(b){if(!(b instanceof Error)||!/already exists|duplicate column name/i.test(b.message))throw b}e.run(`PRAGMA user_version = ${u+1}`)})()}function VG(e){let o=[],i=0,u=0,p=[],g=!1,y=0,b=(E)=>{let S=e.slice(i,E).trim();if(S)o.push(S);i=E+1,p=[],g=!1,y=0};while(u<e.length){let E=e[u];if(E==="'"||E==='"'||E==="`"||E==="["){let S=E==="["?"]":E;u++;while(u<e.length)if(e[u]===S)if(S!=="]"&&e[u+1]===S)u+=2;else break;else u++;u++;continue}if(E==="-"&&e[u+1]==="-"){let S=e.indexOf(`
|
|
374
|
-
`,u);u=S===-1?e.length:S+1;continue}if(E==="/"&&e[u+1]==="*"){let S=e.indexOf("*/",u+2);u=S===-1?e.length:S+2;continue}if(/[A-Za-z_]/.test(E)){let S=u+1;while(S<e.length&&/[A-Za-z0-9_$]/.test(e[S]))S++;let w=e.slice(u,S).toUpperCase();if(p.length<3)p.push(w),g=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(g){if(w==="BEGIN"||w==="CASE"&&y>0)y++;else if(w==="END"&&y>0)y--}u=S;continue}if(E===";"&&y===0)b(u);u++}return b(e.length),o}var ql=({position:e,closed_at:o,...i})=>({...i,closedAt:o??null}),Fl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var jl=new Set(["user","run","extension","notice_pending","compaction"]);class Ul{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=W$(e,this.entryTransactions),this.blobs={put:(o,i,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,i,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(ql)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?ql(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?ql(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[i,u]of e.entries())o.run(i,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 i of o)this.invalidateEntryCache(i);this.db.transaction(()=>{let i=new Set;for(let u of o)for(let p of this.collectSessionBlobHashes(u))i.add(p);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(i)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(Fl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(Fl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(Fl)}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,i){this.insertSessionWithRecords(o,or(this.records(e),i))}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 i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:p}of o){let{seq:g,time:y,...b}=u,E=b,S=Dl(E,this.blobs),w=p===void 0?null:JSON.stringify(Hc(E,p));i.run(e.id,g,y,JSON.stringify(S),w)}})()}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 i=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(i)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)i.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,i=[e];while(i.length>0){let u=i.pop();if(!u)continue;for(let p of this.collectSessionBlobHashes(u))o.add(p);for(let p of this.childSessions(u))i.push(p.id)}this.db.query("DELETE FROM sessions WHERE id = ?").run(e),this.pruneCandidateBlobs(o)})()}collectSessionBlobHashes(e,o=1){let i=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 i)for(let g of p.body.matchAll(/@blob:([0-9a-f]{64})/g))if(g[1])u.add(g[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"),i=this.db.query("DELETE FROM blobs WHERE hash = ?");for(let u of e)if(!o.get(`%@blob:${u}%`))i.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,i,u){Ps();let p=this.plugins,g=p?.pinEntry(i),y;try{return y=this.db.transaction(()=>{let b=Math.max(o??0,this.lastSeq(e)+1),S=(g&&p?p.beforeEntry(g,i,e,b):void 0)??i,w=JSON.stringify(S),R=g?JSON.parse(w):S,k={...R,seq:b,time:Date.now()},A=Dl(R,this.blobs),C=A===R&&!g?w:JSON.stringify(A),q=u===void 0?null:JSON.stringify(Hc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,b,k.time,C,q),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return this.cacheAppended(e,k,C),k})(),y}finally{if(g&&p){let b={commit:()=>p.finishEntry(g,e,y),rollback:()=>p.finishEntry(g,e)},E=this.entryTransactions.at(-1);if(E)E.push(b);else b.commit()}}}setEntryRaw(e,o,i){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=Ws(JSON.parse(u.body),this.blobs),g=Hc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(g),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,i,u=!0){if(i&&i.length===0)return[];let p=i?.every((y)=>jl.has(y))?this.cachedEntries(e):void 0;if(p&&i)return p.filter((b)=>b.seq>o&&i.includes(b.type)).map((b)=>({...u?Ws(b,this.blobs):b}));return(i?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 (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...i):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((y)=>({...Ws(JSON.parse(y.body),u?this.blobs:void 0),seq:y.seq,time:y.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 i=[...jl],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 (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...i).map((p)=>({...JSON.parse(p.body),seq:p.seq,time:p.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,i){let u=this.smallEntries.get(e);if(!u||!jl.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(i),seq:o.seq,time:o.time})}entriesRange(e,o,i=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,i).map((u)=>({...Ws(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 i=this.lastSeq(e),u=(E)=>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,E),p=u(o),g=p?.type==="run"&&p.state==="start"?o+1:o;if(g>=i)return i;let y=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,g,g);if(!y)return i;if(y.end)return y.seq;let b=u(y.seq-1);return b?.type==="run"&&b.state==="start"&&y.seq-1>g?y.seq-2:y.seq-1}entriesAround(e,o,i,u){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let g=Math.min(Math.max(1,o),p),y=this.alignToUser(e,Math.max(1,g-i)),b=this.alignToTurnEnd(e,Math.min(p,g+u));return this.window(e,y,b,p)}entriesFrom(e,o,i){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 g=this.alignToTurnEnd(e,Math.min(u,p+i-1));return this.window(e,p,g,u)}window(e,o,i,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,i+1),from:o,to:i,hasBefore:p!==null,hasAfter:i<u}}replayStart(e,o,i){let u=this.lastSeq(e),p=this.lastEntry(e,"compaction"),g=p?.type==="compaction"?p.through+1:1,y=Math.max(1,u-i+1,Math.min(g,u-o+1));return this.alignToUser(e,y)}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((i)=>{let u=Ws(JSON.parse(i.body),this.blobs);return{entry:{...u,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:hg(u,JSON.parse(i.raw))}}})}lastEntry(e,o){if(jl.has(o)){let u=this.cachedEntries(e);if(u){let p=u.findLast((g)=>g.type===o);return p?{...Ws(p,this.blobs)}:void 0}}let i=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 i?{...Ws(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,o){let i=this.truncationEpoch(e),u=o;if(this.plugins){let p=this.plugins.pin();try{let g=await p.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(g===null)return!1;o={...g,dedupeKey:u.dedupeKey,wake:u.wake&&g.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!==i)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((b)=>b.type==="notice_pending"&&b.notice.dedupeKey===o.dedupeKey||b.type==="user"&&b.notices?.some((E)=>E.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,i=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let g of i)if(g.type==="user"&&g.notices)for(let y of g.notices)u.add(y.dedupeKey);else if(g.type==="extension"&&g.namespace==="basalt.notice"&&g.kind==="discarded"&&g.payload&&typeof g.payload==="object"&&"dedupeKey"in g.payload&&typeof g.payload.dedupeKey==="string")u.add(g.payload.dedupeKey);let p=[];for(let g of i)if(g.type==="notice_pending"&&!u.has(g.notice.dedupeKey))p.push(g.notice);return p}}function ne(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as JG,readdirSync as J$,statSync as Q$}from"fs";import{join as X$}from"path";function Wc(e){try{return Q$(e).size}catch{return 0}}function Y$(e){try{return Math.round(Q$(e).mtimeMs)}catch{return}}function Z$(e){let o=0,i=0;try{let u=J$(e,{withFileTypes:!0});for(let p of u){let g=X$(e,p.name);if(p.isDirectory()){let y=Z$(g);o+=y.bytes,i+=y.files}else if(p.isFile())o+=Wc(g),i+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:i}}function QG(e){if(!JG(e))return[];try{return J$(e,{withFileTypes:!0}).flatMap((o)=>{let i=X$(XG(e),o.name),u=Y$(i);if(o.isDirectory()){let p=Z$(i);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:Wc(i),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,i)=>i.bytes-o.bytes||o.name.localeCompare(i.name))}catch{return[]}}function XG(e){return e}function zs(e,o){let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return 0;let u=Object.values(i)[0];return typeof u==="number"?u:0}function z$(e,o){try{let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return;let u=Object.values(i)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var YG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},ZG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function eK(e){let o=new Map;try{let i=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let g of u)i.set(g.name,g.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let g of p){let y=i.get(g.name)??g.name;if(y.startsWith("sqlite_autoindex_")){let E=y.slice(17),S=E.lastIndexOf("_");if(S>0)y=E.slice(0,S)}let b=o.get(y)??{bytes:0,pages:0};o.set(y,{bytes:b.bytes+(Number(g.bytes)||0),pages:b.pages+(Number(g.pages)||0)})}}catch{}return o}function tK(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
|
|
375
|
-
count(*) AS total,
|
|
376
|
-
sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
|
|
377
|
-
sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
|
|
378
|
-
sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
|
|
379
|
-
sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
|
|
380
|
-
FROM sessions`).get(),u=e.db.query(`SELECT
|
|
381
|
-
count(*) AS total,
|
|
382
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
383
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
|
|
384
|
-
min(time) AS oldest_time,
|
|
385
|
-
max(time) AS newest_time
|
|
386
|
-
FROM entries`).get(),g=e.db.query(`SELECT
|
|
387
|
-
coalesce(json_extract(body, '$.type'), 'unknown') AS type,
|
|
388
|
-
count(*) AS count,
|
|
389
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
390
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes
|
|
391
|
-
FROM entries
|
|
392
|
-
GROUP BY type
|
|
393
|
-
ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((E)=>({type:String(E.type||"unknown"),count:Number(E.count)||0,bodyBytes:Number(E.body_bytes)||0,rawBytes:Number(E.raw_bytes)||0})),y=g.find((E)=>E.type==="compaction")?.count??0,b=[];try{let E=new Map,S=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let k of S)E.set(k.namespace,Number(k.max_ver)||0);let w=e.db.query(`SELECT
|
|
394
|
-
namespace,
|
|
395
|
-
count(*) AS keys,
|
|
396
|
-
coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
|
|
397
|
-
FROM plugin_kv
|
|
398
|
-
GROUP BY namespace
|
|
399
|
-
ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let k of w){R.add(k.namespace);let A=E.get(k.namespace);b.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...A!==void 0?{migrationVersion:A}:{}})}for(let[k,A]of E.entries())if(!R.has(k))b.push({namespace:k,keys:0,bytes:0,migrationVersion:A})}catch{}return{projectCount:o,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:y,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:g,pluginNamespaces:b}}function Bl(e,o){let i=zs(e,"page_size"),u=zs(e,"page_count"),p=zs(e,"freelist_count"),g=e.db.query("PRAGMA journal_mode").get(),y=e.db.query("SELECT sqlite_version() AS v").get(),b=zs(e,"synchronous"),E=zs(e,"auto_vacuum"),S=zs(e,"cache_size"),w=S<0?Math.abs(S)*1024:S*i,R=zs(e,"foreign_keys")===1,k=zs(e,"busy_timeout"),A=z$(e,"encoding")??"UTF-8",C=z$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?Y$(e.path):void 0,X=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),j=eK(e),V=QG(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((J,ee)=>J+ee.bytes,0),database:{size:Wc(e.path),walSize:Wc(`${e.path}-wal`),shmSize:Wc(`${e.path}-shm`),sqliteVersion:y?.v??"unknown",journalMode:g?.journal_mode??"unknown",synchronous:YG[b]??String(b),foreignKeys:R,busyTimeout:k,encoding:A,autoVacuum:ZG[E]??String(E),cacheSizeBytes:w,pageSize:i,pageCount:u,freelistCount:p,reclaimableBytes:p*i,schemaVersion:zs(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:C},analytics:tK(e),entries:V,tables:X.map(({name:J,sql:ee})=>{let pe=J.replaceAll('"','""'),H=e.db.query(`SELECT count(*) AS count FROM "${pe}"`).get().count,le=e.db.query(`PRAGMA table_info("${pe}")`).all().map((ae)=>ae.name),he=e.db.query(`PRAGMA index_list("${pe}")`).all().length,$e=Boolean(ee&&/WITHOUT\s+ROWID/i.test(ee)),Ee=j.get(J);return{name:J,rows:H,...Ee?{bytes:Ee.bytes,pages:Ee.pages}:{},indexes:he,columns:le,withoutRowid:$e}})}}function V$(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let g of i)for(let y of g.body.matchAll(/@blob:([0-9a-f]{64})/g)){let b=y[1];if(b)u.add(b)}let p=[];for(let g of o)if(!u.has(g.hash))p.push(g.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let g=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let y of p)g.run(y)})()}catch{return 0}return p.length}function ev(e,o,i){let u=Bl(e,o);if(i.vacuum)K$(e.db),e.invalidateEntryCache(),V$(e),e.db.run("VACUUM");else if(i.checkpoint)V$(e);if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Bl(e,o)}}var rK=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Gl{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(rK.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 tv(e,o){let i=Jr(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function rv(e,o){let u=(await e.options.models.getAvailable().catch(()=>[])).map((g)=>({...tv(tt(g),g),available:!0})),p=new Set(u.map((g)=>g.id));for(let g of[o,...e.list(!0,{archive:"all"}).map((y)=>y.model)]){if(p.has(g))continue;let y=En(e.options.models,g);if(!y)continue;p.add(g),u.push({...tv(g,y),available:!1})}return{models:u}}function nv(e,o){if(typeof o!=="string"||!En(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as nK,statSync as oK}from"fs";import{basename as sK,resolve as iK}from"path";class xg{runtime;sessions;emit;arm;constructor(e,o,i,u){this.runtime=e;this.sessions=o;this.emit=i;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new f("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=iK(e.directory.trim());if(!nK(o)||!oK(o).isDirectory())throw new t(`${o} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(o);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let u=Date.now(),p={id:ne("p"),name:e.name?.trim()||sK(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)),i=new Set(e);if(!(i.size===e.length&&i.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),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new se("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let p of i)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 AK,readFileSync as CK}from"fs";import{homedir as PK}from"os";import{join as hu}from"path";var mv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),aK={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"]},uK=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),Eg={'"':['"'],"\u201C":["\u201D",'"']},Ig=(e)=>e!==void 0&&/\s/.test(e),pv=(e)=>[...new Set(e)],zc=(e)=>[...e].length;var cK={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function mK(e,o){let i=e.trim().toLowerCase(),u=new Date(o),p=u.getFullYear(),g=u.getMonth(),y=u.getDate();if(i==="today")return{start:new Date(p,g,y).getTime(),end:new Date(p,g,y+1).getTime()};if(i==="yesterday")return{start:new Date(p,g,y-1).getTime(),end:new Date(p,g,y).getTime()};let b=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(b)return{start:o-Number(b[1])*cK[b[2]]};if(/^\d{4}$/.test(i))return{start:new Date(Number(i),0,1).getTime(),end:new Date(Number(i)+1,0,1).getTime()};let E=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!E)return null;let S=Number(E[1]),w=Number(E[3]);if(w<1||w>12)return null;if(E[4]===void 0){if(E[5]!==void 0)return null;return{start:new Date(S,w-1,1).getTime(),end:new Date(S,w,1).getTime()}}let R=Number(E[4]),k=Number(E[5]??0),A=Number(E[6]??0),C=Number(E[7]??0);if(k>23||A>59||C>59)return null;let q=new Date(S,w-1,R,k,A,C);if(q.getMonth()!==w-1||q.getDate()!==R)return null;if(E[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(S,w-1,R+1).getTime()}}var pK=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Sg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),wg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function bg(e,o,i,u,p,g){let y=i.trim(),b=(S,w)=>e.diagnostics.push({code:S,message:w,filter:o});if(!y)return b("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return b("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let E=p?[y]:y.split(",").map((S)=>S.trim()).filter(Boolean);switch(o){case"in":case"project":for(let S of E){let w=S.toLowerCase();if(o==="in"&&w==="this")e.currentSession=!0;else if(o==="in"&&w==="title")e.fields.push("title");else e.projectID.push(S)}return;case"session":for(let S of E)if(S.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(S);return;case"from":case"role":for(let S of E){let w=aK[S.toLowerCase()];if(w)e.fields.push(...w);else b("bad_filter_value",`${o}:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...E);return;case"model":e.model.push(...E);return;case"is":for(let S of E){let w=S.toLowerCase();if(w==="error")e.isError=!u;else if(w==="archived")e.archived=!u;else if(w==="compacted")e.compacted=!u;else b("bad_filter_value",`is:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let S=mK(y,g);if(!S)return b("bad_filter_value",`${o}:${y} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=Sg(e.after,S.start);else if(o==="before")e.before=wg(e.before,S.start);else if(e.after=Sg(e.after,S.start),S.end!==void 0)e.before=wg(e.before,S.end)}}}function lK(e,o){let i={},u=(C,q)=>{let X=pv([...C??[],...q]);return X.length?X:void 0},p=u(e?.projectID,o.projectID),g=u(e?.sessionID,o.sessionID),y=u(e?.fields,o.fields),b=u(e?.tools,o.tools),E=u(e?.model,o.model);if(p)i.projectID=p;if(g)i.sessionID=g;if(y)i.fields=y;if(b)i.tools=b;if(E)i.model=E;let S=o.isError??e?.isError,w=o.archived??e?.archived,R=o.compacted??e?.compacted;if(S!==void 0)i.isError=S;if(w!==void 0)i.archived=w;if(R!==void 0)i.compacted=R;let k=Sg(e?.after,o.after),A=wg(e?.before,o.before);if(k!==void 0)i.after=k;if(A!==void 0)i.before=A;if(k!==void 0&&A!==void 0&&k>=A)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function ov(e,o){let i=Eg[e[o]]??['"'],u="",p=o+1;while(p<e.length){let g=e[p],y=e[p+1];if(g==="\\"&&y!==void 0&&(y==="\\"||y==='"'||y==="\u201C"||y==="\u201D")){u+=y,p+=2;continue}if(i.includes(g))return{text:u,next:p+1,closed:!0};u+=g,p++}return{text:u,next:p,closed:!1}}function sv(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let i=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(i.length!==e.length-1)return;let u=i.toLowerCase();return mv.has(u)?u:void 0}function iv(e,o,i){let u=e==="word"&&!i&&zc(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:i,fuzzy:u}}function dK(e,o){let i=[],u=e.length,p=0;while(p<u){if(Ig(e[p])){p++;continue}let g=!1;if(e[p]==="-"){if(p+1>=u||Ig(e[p+1])){p++;continue}g=!0,p++}if(Eg[e[p]]){let A=ov(e,p);if(p=A.next,!A.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let C=A.text.trim();if(C)i.push({kind:"term",negated:g,term:iv("phrase",C,!1)});continue}let y=[],b;while(p<u&&!Ig(e[p])){let A=e[p],C=e[p+1];if(A==="\\"&&C!==void 0&&uK.has(C)){y.push({c:C,esc:!0}),p+=2;continue}let q=Eg[A]?sv(y):void 0;if(q){let X=ov(e,p);if(p=X.next,!X.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});b={key:q,value:X.text,quoted:!0};break}y.push({c:A,esc:!1}),p++}if(b){i.push({kind:"filter",negated:g,...b});continue}let E=y.findIndex((A,C)=>C>0&&!A.esc&&(A.c===":"||A.c==="\uFF1A")),S=E>0?sv(y.slice(0,E+1)):void 0;if(S){i.push({kind:"filter",negated:g,key:S,value:y.slice(E+1).map((A)=>A.c).join(""),quoted:!1});continue}if(!g&&y.length===2&&y.every((A)=>!A.esc)&&y[0]?.c==="O"&&y[1]?.c==="R"){i.push({kind:"or"});continue}let w=y[y.length-1],R=y.length>1&&w!==void 0&&!w.esc&&w.c==="*",k=(R?y.slice(0,-1):y).map((A)=>A.c).join("");if(k)i.push({kind:"term",negated:g,term:iv("word",k,R)})}return i}var fK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function av(e){let o=[];return{rest:e.replace(fK,(u,p,g,y,b)=>{let E=y.toLowerCase();if(!mv.has(E))return u;let S=b.startsWith('"')&&b.length>=2;return o.push({key:E,value:S?b.slice(1,-1).replace(/\\(["\\])/g,"$1"):b,negated:g==="-",quoted:S}),p}).trim(),filters:o}}var uv={n:`
|
|
400
|
-
`,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function hK(e){let o=[...e],i=0,u=(w)=>{let R=o.slice(i,i+w).join("");if(R.length!==w||!/^[0-9a-fA-F]+$/.test(R))return;return i+=w,String.fromCodePoint(Number.parseInt(R,16))},p=()=>{let w=o[i++];if(w===void 0)return{kind:"lit",ch:"\\"};if(w in uv)return{kind:"lit",ch:uv[w]};if("dDwWsS".includes(w))return{kind:"any"};if(w==="b"||w==="B")return{kind:"zero"};if(w>="1"&&w<="9"){while(o[i]!==void 0&&/\d/.test(o[i]))i++;return{kind:"any"}}if(w==="k"||w==="p"||w==="P"){let R=o[i];if(R==="<"||R==="{"){let k=R==="<"?">":"}",A=o.indexOf(k,i);i=A<0?o.length:A+1}return{kind:"any"}}if(w==="c")return i++,{kind:"any"};if(w==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(w==="u"){if(o[i]==="{"){let k=o.indexOf("}",i),A=k<0?"":o.slice(i+1,k).join("");if(/^[0-9a-fA-F]{1,6}$/.test(A)&&Number.parseInt(A,16)<=1114111)return i=k+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(A,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:w}},g=()=>{if(o[i]==="^")i++;while(i<o.length&&o[i]!=="]")i+=o[i]==="\\"?2:1;return i++,{kind:"any"}},y=()=>{let w="capture";if(o[i]==="?"){let k=o[i+1],A=o[i+2];if(k===":")w="plain",i+=2;else if(k==="="||k==="!")w="look",i+=2;else if(k==="<"&&(A==="="||A==="!"))w="look",i+=3;else if(k==="<"){let C=o.indexOf(">",i);i=C<0?o.length:C+1}else{w="opaque";while(i<o.length&&o[i]!==":"&&o[i]!==")")i++;if(o[i]===":")i++}}let R=S();if(o[i]===")")i++;if(w==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:w==="opaque"}},b=()=>{let w=o[i],R=1,k=!0;if(w==="*"||w==="?")R=0,i++;else if(w==="+")i++;else if(w==="{"){let A=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(i,i+24).join(""));if(!A)return{quantified:!1,min:1};R=Number(A[1]),i+=A[0].length}else return{quantified:!1,min:1};if(o[i]==="?")i++;return{quantified:k,min:R}},E=()=>{let w=[];while(i<o.length){let R=o[i];if(R==="|"||R===")")break;i++;let k;if(R==="(")k=y();else if(R==="[")k=g();else if(R==="\\")k=p();else if(R===".")k={kind:"any"};else if(R==="^"||R==="$")k={kind:"zero"};else if(R==="*"||R==="+"||R==="?")k={kind:"zero"};else k={kind:"lit",ch:R};w.push({atom:k,...b()})}return w};function S(){let w=[E()];while(o[i]==="|")i++,w.push(E());return w}return S()}function cv(e){let o=[],i="",u=()=>{if(i)o.push([i]);i=""},p=(g)=>{for(let y of g){let b=y.atom;if(b.kind==="lit")if(y.min>=1){if(i+=b.ch,y.quantified)u()}else u();else if(b.kind==="group"&&!b.opaque&&y.min>=1)if(b.alts.length===1&&!y.quantified)p(b.alts[0]);else u(),o.push(...lv(b.alts));else u()}};return p(e),u(),o}function lv(e){if(e.length===1)return cv(e[0]);let o=[];for(let i of e){let u=cv(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!u.length)return[];o.push(u.reduce((p,g)=>zc(g)>zc(p)?g:p))}return[pv(o)]}var gK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function yK(e){return!/^\s*$/.test(e)&&(zc(e)>=2||gK.test(e))}function xK(e){let o;try{o=lv(hK(e))}catch{return[]}let i=o.filter((E)=>E.every(yK)),u=i.filter((E)=>E.length===1).map((E)=>E[0]),p=i.filter((E)=>{if(E.length!==1)return!0;let S=E[0];return!u.some((w)=>w!==S&&w.includes(S))}),g=new Set,y=p.filter((E)=>{let S=JSON.stringify(E);if(g.has(S))return!1;return g.add(S),!0}),b=(E)=>Math.min(...E.map(zc));return y.sort((E,S)=>b(S)-b(E))}function IK(e){let o=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(o)}function bK(e,o){let i=`m${o?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(u){let p=u instanceof Error?u.message:String(u),g="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))g="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))g="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))g="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))g="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${g}`}}}function Kl(e,o={}){let i=o.now??Date.now(),u=e.q??"",p=pK(),g=p.diagnostics,y,b=[];if(e.mode==="regex"){let q=av(u);for(let X of q.filters)bg(p,X.key,X.value,X.negated,X.quoted,i);y=q.rest}else{let q=av(u),X=/^\/([\s\S]+)\/$/.exec(q.rest);if(X){for(let j of q.filters)bg(p,j.key,j.value,j.negated,j.quoted,i);y=X[1]}else{b=[{include:[],exclude:[]}];for(let j of dK(u,g)){let V=b[b.length-1];if(j.kind==="or")b.push({include:[],exclude:[]});else if(j.kind==="filter")bg(p,j.key,j.value,j.negated,j.quoted,i);else(j.negated?V.exclude:V.include).push(j.term)}b=b.filter((j)=>j.include.length||j.exclude.length)}}let E=b.flatMap((q)=>[...q.include,...q.exclude]),S=y!==void 0?IK(y):E.some((q)=>/\p{Lu}/u.test(q.text)),w=e.caseSensitive??S,R=e.caseSensitive===void 0&&S,k,A;if(y){let q=bK(y,w);if("message"in q)A={code:"bad_regex",message:q.message};else{let X=xK(y);k={source:y,flags:q.flags,literals:X,deepScan:X.length===0}}}let C=lK(e.filters,p);return{mode:y!==void 0?"regex":"text",branches:b,...k?{regex:k}:{},filters:C,currentSession:p.currentSession,caseSensitive:w,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:b.some((q)=>q.include.some((X)=>X.fuzzy)),hasPositive:k!==void 0||b.some((q)=>q.include.length>0),hasFilters:Object.keys(C).length>0||p.currentSession,...A?{error:A}:{},diagnostics:g}}var Rg={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},dv=new WeakMap;function fv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,i=dv.get(e);if(i?.version===o)return i.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return dv.set(e,{version:o,terms:u}),u}var Tg=32,EK=1024,Vc=(e)=>`"${e.replaceAll('"','""')}"`;function SK(e,o){let i=Array.from({length:o.length+1},(u,p)=>p);for(let u=0;u<e.length;u++){let p=[u+1];for(let g=0;g<o.length;g++)p.push(Math.min((p[g]??0)+1,(i[g+1]??0)+1,(i[g]??0)+Number(e[u]!==o[g])));i=p}return i[o.length]??e.length}function kg(e,o){let i=Tt(o.trim());if(!i||i.length>64)return[];let u=fv(e),p=u.filter((b)=>b.t.startsWith(i)).slice(0,8).map((b)=>b.t);if(p.length>=8||i.length<4)return p;let g=i.length>=8?2:1,y=[];for(let b of u){if(Math.abs(b.t.length-i.length)>g)continue;if(SK(i,b.t)<=g)y.push(b.t);if(y.length>=8)break}return[...new Set([...p,...y])].slice(0,8)}function hv(e,o){let i=!1,u=[],p=[],g=o.filters,y=(X,j)=>{if(!j?.length)return;p.push(`${X} IN (${j.map(()=>"?").join(",")})`),u.push(...j)};if(y("s.project_id",g.projectID),g.sessionID?.length){p.push(`(${g.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let X of g.sessionID)u.push(X,X)}if(g.archived!==void 0)p.push(`s.archived_at IS ${g.archived?"NOT ":""}NULL`);let b=p.length?p.join(" AND "):"1",E=[...u];if(y("r.kind",g.fields?.map((X)=>Ne[X])),y("r.tool",g.tools),g.model?.length){p.push(`(${g.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let X of g.model)u.push(X,X)}if(g.isError!==void 0)p.push("r.err = ?"),u.push(Number(g.isError));if(g.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
|
|
401
|
-
SELECT max(json_extract(body,'$.through')) FROM store.entries
|
|
402
|
-
WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
|
|
403
|
-
),0)) = ?`),u.push(Number(g.compacted));if(g.after!==void 0)p.push("r.time >= ?"),u.push(g.after);if(g.before!==void 0)p.push("r.time < ?"),u.push(g.before);let S=e.query("SELECT v FROM meta WHERE k='layout'").get(),w=S&&JSON.parse(S.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),k=(X)=>{let j=(ee)=>{let pe=Tt(ee);if(!X&&w){if([...pe].length<3){let ae=[...pe].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(pe,`${pe}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(pe);if([...pe].length===1&&ae.length>Tg)ae.length=Tg,i=!0;if(!ae.length)return Vc("__basalt_no_short_match__");return`(${ae.map((de)=>Vc(de.term)).join(" OR ")})`}return Vc(pe)}let H=/^[\p{Script=Latin}\p{N}]+$/u.test(ee)?[pe]:Pi(ee),le=H.filter((ae)=>!/^[a-z0-9]{1,2}$/.test(ae)),he=le.length?le:H;if(!he.length){R=!0;return}let $e=he.map((ae,de)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(ae),xt=he.length>2&&de>0&&de<he.length-1;if(qe||xt){let Fe=e.query("SELECT n FROM term WHERE t=?").get(ae)?.n??0;return{expression:Vc(ae),frequency:Fe}}let Je=[ae],Yt=0;for(let Fe of fv(e)){if(!Fe.t.includes(ae))continue;if(Yt+=Fe.n,Fe.t!==ae)Je.push(Fe.t);if(Je.length>=Tg){i=!0;break}}return{expression:`(${Je.map(Vc).join(" OR ")})`,frequency:Yt}});return $e.sort((ae,de)=>ae.frequency-de.frequency),`(${$e.slice(0,($e[0]?.frequency??1/0)<=EK?1:2).map((ae)=>ae.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((ee)=>ee.include.map((pe)=>pe.text));if(o.regex){let ee=V.map((pe)=>pe.map(j));if(ee.some((pe)=>pe.some((H)=>!H)))return;return ee.map((pe)=>`(${pe.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((ee)=>{let pe=ee.filter((H)=>!/^[a-z0-9]{1,2}$/i.test(H));return(pe.length?pe:ee).map(j)});if(J.some((ee)=>!ee.length||ee.some((pe)=>!pe)))return;return J.map((ee)=>`(${ee.join(" AND ")})`).join(" OR ")||void 0},A=k(!1),C=k(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:A,out:C,scan:R,where:p.length?p.join(" AND "):"1",bindings:u,forks:q,sessionWhere:b,sessionBindings:E,partial:i,candidateLimit:o.branches.some((X)=>X.include.length>0&&X.include.every((j)=>[...j.text].length<2))?512:void 0}}function gv(e){let o=1/0,i=-1/0;for(let u of e)o=Math.min(o,u.relevance),i=Math.max(i,u.relevance);return e.map((u)=>({...u,relevance:o===i?-1:-(0.5+0.5*(i-u.relevance)/(i-o))}))}function Hl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(Rg).map(([i,u])=>`WHEN ${Ne[i]} THEN ${u}`).join(" ")} ELSE 1 END) *
|
|
404
|
-
(0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function yv(e,o,i,u){let p=Math.max(0,u-i)/86400000;return Math.max(0.000000001,-e)*Rg[o]*(0.3+0.7/(1+p/30))}function Ag(e,o){return e.sort((i,u)=>(o==="best"?u.score-i.score:0)||(o==="recent"?u.time-i.time:0)||(i.sessionID<u.sessionID?-1:Number(i.sessionID>u.sessionID))||u.seq-i.seq||i.field.localeCompare(u.field))}var Pg=512;function xv(e,o,i){let u=performance.now(),p=o.partial;$g(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[g,y]of[["fts",o.msg],["fts_out",o.out]]){if(!y)continue;let b=o.candidateLimit??2000,E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
|
|
405
|
-
ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(y,o.candidateLimit?b+1:b);if(o.candidateLimit&&E.length>b)E.length=b,p=!0;else if(!o.candidateLimit&&E.length===b){let w=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
|
|
406
|
-
AND rowid NOT IN (SELECT value FROM json_each(?))`).all(y,JSON.stringify(E.map((R)=>R.doc)));for(let R of w)E.push(R)}let S=gv(E);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
|
|
407
|
-
FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(S))}return i?.("match",performance.now()-u),p}function Iv(e,o,i,u,p){let g=performance.now();if(o.candidateLimit){let b=e.query(`
|
|
408
|
-
SELECT r.session_id,r.seq,${Hl(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} LIMIT ${o.candidateLimit+1}
|
|
412
|
-
`).all(...o.bindings);if(b.length>o.candidateLimit)b.length=o.candidateLimit,o.partial=!0;let E=new Map;for(let S of b){let w=i?S.seq:0,R=JSON.stringify([S.session_id,w]),k=E.get(R);if(!k||S.score>k.score)E.set(R,{...S,seq:w})}return p?.("filter",performance.now()-g),[...E.values()].sort((S,w)=>w.score-S.score||(S.session_id<w.session_id?-1:Number(S.session_id>w.session_id))||w.seq-S.seq)}let y=e.query(`
|
|
413
|
-
SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Hl(u)}) AS score
|
|
414
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
415
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
416
|
-
WHERE ${o.where}
|
|
417
|
-
GROUP BY r.session_id${i?",r.seq":""}
|
|
418
|
-
ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
|
|
419
|
-
`).all(...o.bindings);return p?.("filter",performance.now()-g),y}var bv=new WeakMap,wK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
|
|
420
|
-
SELECT id,forked_from_id,forked_from_seq FROM store.sessions
|
|
421
|
-
WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
|
|
422
|
-
UNION
|
|
423
|
-
SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
|
|
424
|
-
FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
|
|
425
|
-
WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
|
|
426
|
-
)`;function $g(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(`${wK} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let i=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();bv.set(e,new Map(i.map((u)=>[u.ancestor,u.through])))}function Cg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
|
|
427
|
-
SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
|
|
428
|
-
JOIN store.sessions ps ON ps.id=pr.session_id
|
|
429
|
-
WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
|
|
430
|
-
AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
|
|
431
|
-
AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
|
|
432
|
-
SELECT 1 FROM store.entries original JOIN store.entries copied
|
|
433
|
-
ON copied.session_id=r.session_id AND copied.seq=r.seq
|
|
434
|
-
WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
|
|
435
|
-
))
|
|
436
|
-
))`}function Ev(e,o,i,u,p){let g=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 y=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,b=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
|
|
437
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${y>4000?"INDEXED BY ref_time":""}
|
|
438
|
-
${b} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${Cg(o)}
|
|
439
|
-
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:[],i);let E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(E===u){let S=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(S)e.query(`
|
|
440
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${b}
|
|
441
|
-
WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
|
|
442
|
-
AND ${o.where} AND ${Cg(o)} AND NOT EXISTS (
|
|
443
|
-
SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
|
|
444
|
-
)`).run(S.session_id,S.seq,...o.bindings,...o.forks?o.bindings:[]),E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-g),E}function Sv(e,o,i,u,p,g,y){let b=performance.now(),E=o.group==="none",S=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",w=e.query(`
|
|
445
|
-
SELECT r.session_id,${E?"r.seq":"0"} AS seq,
|
|
446
|
-
max(${Hl(p)}) AS relevance,max(r.time) AS time
|
|
447
|
-
FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
|
|
448
|
-
WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
|
|
449
|
-
GROUP BY r.session_id${E?",r.seq":""}
|
|
450
|
-
ORDER BY ${S},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(g),u,i);return y?.("group",performance.now()-b),w}function wv(e,o,i,u,p,g){let y=performance.now(),b=p?o:{...o,forks:!1},E=e.query(`
|
|
451
|
-
SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
|
|
452
|
-
${b.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
453
|
-
WHERE r.session_id=? ${u?"AND r.seq=?":""}
|
|
454
|
-
AND ${o.where} AND ${Cg(b)}
|
|
455
|
-
${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(i.session_id,...u?[i.seq]:[],...o.bindings,...b.forks?o.bindings:[]);return g?.("filter",performance.now()-y),E}function vg(e,o,i,u){if(!o.forks)return[];let p=bv.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
|
|
456
|
-
SELECT DISTINCT r.session_id,s.title,e.body
|
|
457
|
-
FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
|
|
458
|
-
CROSS JOIN ref r ON r.session_id=l.child
|
|
459
|
-
JOIN store.sessions s ON s.id=r.session_id
|
|
460
|
-
LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
|
|
461
|
-
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(i.session_id,i.doc,i.seq,i.part,...o.bindings).filter((g)=>{if(i.seq===0)return g.title===u;if(!g.body)return!1;let y=JSON.parse(g.body);return Ke(y,!0).some((b)=>b.part===i.part&&b.kind===eo[i.kind]&&b.text===u)}).map((g)=>g.session_id)}function TK(e,o){let i=o?e:Tt(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let u="",p=[],g=[],y=0;for(let b of e){let E=o?b:Tt(b);u+=E;for(let S=0;S<E.length;S++)p.push(y),g.push(y+b.length);y+=b.length}return{normalized:u,starts:p,ends:g}}function Wl(e,o){if(o.regex){let E=new RegExp(o.regex.source,`${o.regex.flags}g`),S=[];for(let w of e.matchAll(E)){if(o.wholeWord&&!Tv(e,w.index,w.index+w[0].length))continue;S.push([w.index,w.index+w[0].length])}return S.length?S:void 0}let{normalized:i,starts:u,ends:p}=TK(e,o.caseSensitive),g=(E)=>{let S=o.caseSensitive?E.text:Tt(E.text),w=[],R=i.indexOf(S);while(R>=0&&S){let k=u?u[R]:R,A=p?p[R+S.length-1]:R+S.length,C=k===0||k!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(k-1,k))||/[a-z0-9][A-Z]/.test(e.slice(k-1,k+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(E.text));if(k!==void 0&&A!==void 0&&(!E.prefix||C)&&(!o.wholeWord||Tv(e,k,A)))w.push([k,A]);R=i.indexOf(S,R+Math.max(1,S.length))}return w};if(!o.branches.length)return[];let y=[],b=!1;for(let E of o.branches){if(E.exclude.some((w)=>g(w).length))continue;let S=E.include.map(g);if(S.some((w)=>!w.length))continue;b=!0,y.push(...S.flat())}return b?y:void 0}function Tv(e,o,i){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(i===e.length||!u.test(e.slice(i,i+1)))}function zl(e,o){let i=e.split(`
|
|
462
|
-
`),u=new Set,p=0,g=i.map((y,b)=>{let E=p;if(o.some(([S,w])=>S<=E+y.length&&w>=E))for(let S=Math.max(0,b-1);S<=Math.min(i.length-1,b+1);S++)u.add(S);return p+=y.length+1,E});if(!u.size)u.add(0);return[...u].sort((y,b)=>y-b).slice(0,5).map((y)=>{let b=i[y]??"",E=g[y]??0,S=o.filter(([A,C])=>C>E&&A<E+b.length),w=Math.max(0,(S[0]?.[0]??E)-E-100),R=b.slice(w,w+300),k=S.map(([A,C])=>[Math.max(0,A-E-w),Math.min(R.length,C-E-w)]);return{text:R,line:y+1,ranges:k.filter(([A,C])=>A<C)}})}var Rv=3;function RK(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 kv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function kK(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===o&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let u="window"in i?i.window:0,p="seen"in i?i.seen:[],g="emitted"in i?i.emitted:[],y="after"in i?i.after:void 0;if(y!==void 0&&!RK(y))throw Error("invalid best cursor");let b=(E)=>Array.isArray(E)&&E.every((S)=>typeof S==="string"&&S.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&b(p)&&b(g))return{offset:i.offset,key:o,now:i.now,window:u,seen:p,emitted:g,after:y}}}catch{}throw Error("invalid search cursor")}function Nn(e,o){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return kK(e.cursor,i)}async function Gr(e,o,i){let u="search"in e?e.search:e,p=performance.now(),g=(Fe)=>{if(!i.signal?.aborted)i.onEvent(Fe)};if(i.signal?.aborted)return;let y=Nn(o,i.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let b=Kl(o,{now:y.now});if(b.error){g({type:"error",...b.error});return}if(b.currentSession){if(!i.sessionID){g({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}b.filters.sessionID=[i.sessionID]}if(!o.deep&&b.regex?.deepScan){g({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),i.signal?.aborted)return;let E=performance.now(),S=u.withIndex((Fe)=>hv(Fe,b));if(!S){g({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}i.onTiming?.("plan",performance.now()-E);let w=S.partial,R=y.after,k=new Map,A=new Map,C=[],q=!1,X=new Map,j=new WeakMap,V=new Map,J=new Map,{offset:ee,window:pe}=y,H=[...y.seen],le=[...y.emitted],he=!1,$e=Math.max(1,Math.min(200,o.limit??30)),Ee=Math.min(S.candidateLimit??2000,o.group==="none"?Pg:Math.min(2000,Math.max(Pg,$e*32))),ae=(Fe,Ue)=>{let Dt=k.get(Ue);if(Dt)return Dt;let lt=Fe.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Ue);if(lt)k.set(Ue,lt);return lt??void 0},de=(Fe,Ue,Dt)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(Ue.session_id))return;if(i.excludeEntry?.sessionID===Ue.session_id&&i.excludeEntry.seq===Ue.seq)return;let lt=ae(Fe,Ue.session_id);if(!lt)return;let Mt=eo[Ue.kind];if(!Mt)return;let yr=lt.title;if(Ue.seq!==0){let st=`${Ue.session_id}:${Ue.seq}`,Jt=J.get(st);if(!Jt){let mn=Dt?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!Dt&&!mn)return;let Kt=Dt??JSON.parse(mn?.body??"null");Jt=Ke(Kt,!0),J.set(st,Jt)}let Zt=Jt.find((mn)=>mn.part===Ue.part&&mn.kind===Mt);if(!Zt)return;yr=Zt.text}let pr=Wl(yr,b);if(!pr)return;let jt=A.get(lt.id);if(jt===void 0)jt=Fe.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(lt.id)?.through??0,A.set(lt.id,jt);let ot=Ue.seq>0&&Ue.seq<=jt;if(b.filters.compacted!==void 0&&ot!==b.filters.compacted)return;let Ct={sessionID:lt.id,seq:Ue.seq,time:Ue.time,field:Mt,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:yv(Ue.relevance,Mt,Ue.time,y.now),flags:{archived:lt.archived_at!==null,compacted:ot,partial:yr.length>_i+Ai}};return X.set(Ct,{text:yr,ranges:pr}),C.push(Ct),q=!0,V.set(Ct,{doc:Ue.doc,part:Ue.part}),Ct},qe=(Fe)=>{let Ue=performance.now(),Dt=[...Fe].sort((ot,Ct)=>ot.time-Ct.time||ot.sessionID.localeCompare(Ct.sessionID)),lt=[],Mt=new Map;for(let ot of Dt){let Ct=V.get(ot),Jt=k.get(ot.sessionID),Zt=new Set;while(Jt?.forked_from_id&&Jt.forked_from_seq!==null&&ot.seq<=Jt.forked_from_seq&&!Zt.has(Jt.id))Zt.add(Jt.id),Jt=k.get(Jt.forked_from_id)??u.withIndex((ko)=>ae(ko,Jt?.forked_from_id??""));let mn=`${Jt?.id??ot.sessionID}:${ot.seq}:${Ct?.part}:${Ct?.doc}`,Kt=Mt.get(mn);if(Kt){if(Kt.sessionID!==ot.sessionID)Kt.forks=[...new Set([...Kt.forks??[],ot.sessionID])]}else Mt.set(mn,ot),lt.push(ot)}let yr=[],pr=new Map,jt=new Map;for(let ot of lt){let Ct=`${ot.sessionID}:${ot.seq}`,st=jt.get(Ct);if(!st){jt.set(Ct,ot),j.set(ot,[ot]);continue}let Jt=[...j.get(st)??[st],ot],Zt=ot.score>st.score?ot:st;if(Zt.forks=[...new Set([...st.forks??[],...ot.forks??[]])],!Zt.forks.length)Zt.forks=void 0;Zt.flags={archived:st.flags.archived||ot.flags.archived,compacted:st.flags.compacted||ot.flags.compacted,partial:st.flags.partial||ot.flags.partial},jt.set(Ct,Zt),j.set(Zt,Jt)}for(let ot of Ag([...jt.values()],o.sort??"best")){let Ct=k.get(ot.sessionID);if(!Ct)continue;let st=o.group==="none"?void 0:pr.get(Ct.id);if(!st)st={session:{id:Ct.id,title:Ct.title,projectID:Ct.project_id,updated:Ct.updated},hits:[],more:0,...w&&o.group!=="none"?{moreIsLowerBound:!0}:{}},yr.push(st),pr.set(Ct.id,st);if(st.hits.length<Rv||o.group==="none")st.hits.push(ot);else st.more++}return i.onTiming?.("group",performance.now()-Ue),yr},xt=(Fe)=>{for(let Ue of Fe)for(let Dt of Ue.hits){if(i.allowedSessionIDs&&Dt.forks)Dt.forks=Dt.forks.filter((yr)=>i.allowedSessionIDs?.has(yr));let lt=performance.now(),Mt=new Map;for(let yr of j.get(Dt)??[Dt]){let pr=X.get(yr);if(!pr)continue;for(let jt of zl(pr.text,pr.ranges)){let ot=`${jt.line}:${jt.text}`,Ct=Mt.get(ot);if(!Ct)Mt.set(ot,jt);else Ct.ranges=[...new Map([...Ct.ranges,...jt.ranges].map((st)=>[st.join(":"),st])).values()]}}Dt.snippet=[...Mt.values()],i.onTiming?.("snippet",performance.now()-lt)}},Je=o.deep||S.scan,Yt=(Fe,Ue)=>{let Dt=ae(Fe,Ue.session_id);if(!Dt)return[];let lt=wv(Fe,S,Ue,o.group==="none",Dt.forked_from_id!==null,i.onTiming);if(S.candidateLimit&<.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Mt=C.length,yr=performance.now();for(let pr of lt){if(i.signal?.aborted)break;let jt=de(Fe,pr);if(!jt)continue;let ot=vg(Fe,S,pr,X.get(jt)?.text??"");if(ot.length)jt.forks=ot}return i.onTiming?.("body",performance.now()-yr),C.slice(Mt)};if(Je){w=!1;let Fe=[],Ue=new Set,Dt=u.withIndex((st)=>{$g(st,S);for(let Kt of st.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())k.set(Kt.id,Kt);let Jt=new Set(st.query(`SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}`).all(...S.sessionBindings).map((Kt)=>Kt.id)),Zt=(Kt)=>{if(Ue.has(Kt.id))return;Ue.add(Kt.id);let ko=Kt.forked_from_id?k.get(Kt.forked_from_id):void 0;if(ko)Zt(ko);if(Jt.has(Kt.id))Fe.push(Kt)};for(let Kt of k.values())Zt(Kt);return(st.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
|
|
463
|
-
SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}
|
|
464
|
-
)`).get(...S.sessionBindings)?.n??0)+Jt.size})??0,lt=0,Mt=0,yr=0;if(b.regex?.deepScan)g({type:"groups",groups:[]});let pr=new Set,jt=new Set,ot=new Map,Ct=()=>{let st=qe(C),Jt=[];for(let Zt of st){let mn=Zt.session.id,Kt=o.group==="none"?void 0:ot.get(mn);if(o.group!=="none"&&jt.has(mn)&&!Kt)continue;if(!Kt){if(jt.add(mn),Mt<y.offset){Mt++;continue}if(yr>=$e){he=!0;break}yr++,ee++}if(o.group!=="none"){let ko=(Kt?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,Rv-(Kt?.shown??0));let gu=(Kt?.shown??0)+Zt.hits.length;Zt.more=ko-gu,ot.set(mn,{shown:gu,count:ko})}Jt.push(Zt)}if(Jt.length)xt(Jt),g({type:"groups",groups:Jt});C.length=0,X.clear(),V.clear(),J.clear()};for(let st of Fe){if(i.signal?.aborted||he)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||he)break;let mn=u.withIndex((Kt)=>{let ko=Kt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(st.id,Math.max(0,Jt));if(Jt<0)ko.unshift({seq:0,time:st.updated,body:null});for(let ji of ko){if(i.signal?.aborted)break;let yu=ji.body?JSON.parse(ji.body):void 0;if(yu?.type==="assistant")Zt=yu.model;let Mv=yu?Ke(yu,!0):[{part:0,kind:"title",text:st.title}];for(let Ko of Mv){if(i.signal?.aborted)break;let $s={session_id:st.id,seq:ji.seq,part:Ko.part,doc:Number(BigInt(Bun.hash(Ko.text))&0x1fffffffffffffn),kind:Ne[Ko.kind],tool:Ko.tool??null,err:Number(Ko.err??!1),model:Ko.model??(Ko.tool?Zt:void 0)??null,time:ji.time,relevance:-1};if(!Kt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
|
|
465
|
-
JOIN store.sessions s ON s.id=r.session_id WHERE ${S.where}`).get($s.session_id,$s.seq,$s.kind,$s.tool,$s.err,$s.model,$s.time,...S.bindings))continue;let Vs=st,_g=new Set;while(Vs.forked_from_id&&Vs.forked_from_seq!==null&&ji.seq<=Vs.forked_from_seq&&!_g.has(Vs.id)){_g.add(Vs.id);let xu=k.get(Vs.forked_from_id);if(!xu)break;Vs=xu}let Lg=`${Vs.id}:${ji.seq}:${Ko.part}:${Bun.hash(Ko.text)}`;if(pr.has(Lg))continue;let Ng=de(Kt,$s,yu);if(Ng){if(pr.add(Lg),S.forks){let xu=Kt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(st.id,ji.seq,Ko.part);if(xu){let Dg=vg(Kt,S,{...$s,doc:xu.doc},Ko.text);if(Dg.length)Ng.forks=Dg}}}}}let gu=ko.at(-1);if(gu)Jt=gu.seq;return ko.length});if(mn===void 0){g({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=mn,g({type:"progress",scanned:lt,total:Dt}),i.signal?.aborted)return;if(Ct(),!mn||he)break;await Bun.sleep(0)}}}else u.withIndex((Fe)=>{if(w=xv(Fe,S,i.onTiming)||w,b.regex?b.regex.literals.every((lt)=>lt.some((Mt)=>[...Mt].length<3)):b.branches.some((lt)=>lt.include.length>0&<.include.every((Mt)=>[...Mt.text].length<3)))Fe.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let lt=Iv(Fe,S,o.group==="none",y.now,i.onTiming);if(w||=S.partial,S.candidateLimit&<.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Mt=[];for(let pr of lt){if(i.signal?.aborted)return;let jt=Mt[$e]?.key.score;if(jt!==void 0&&pr.score+0.000000000001<jt)break;let ot=C.length,Ct=Yt(Fe,pr);C.splice(ot);let st=Ag([...Ct],"best")[0];if(!st)continue;let Jt={score:st.score,sessionID:st.sessionID,seq:o.group==="none"?st.seq:0};if(y.after&&kv(Jt,y.after)<=0)continue;if(Mt.push({key:Jt,hits:Ct}),Mt.sort((Zt,mn)=>kv(Zt.key,mn.key)),Mt.length>$e+1)Mt.length=$e+1}he=Mt.length>$e;let yr=Mt.slice(0,$e);for(let pr of yr)C.push(...pr.hits);R=yr.at(-1)?.key;return}let Dt=0;for(;;){if(i.signal?.aborted)return;let lt=Ev(Fe,S,pe,Ee,i.onTiming),Mt=S.candidateLimit!==void 0&&pe+lt>=S.candidateLimit;w||=Mt;let yr=Sv(Fe,o,ee,$e-Dt+1,y.now,H,i.onTiming);he=yr.length>$e-Dt;let pr=yr.slice(0,$e-Dt);if(!pr.length){if(lt<Ee||Mt){he=!1;break}pe+=lt,ee=0,H=[...new Set([...H,...le])],le=[];continue}for(let jt of pr)if(ee++,Yt(Fe,jt).length){if(Dt++,o.group!=="none")le.push(jt.session_id)}if(Dt>=$e){he||=!Mt&<>=Ee;break}if(!he){if(lt<Ee||Mt)break;pe+=lt,ee=0,H=[...new Set([...H,...le])],le=[]}}});if(i.signal?.aborted)return;if(!Je){let Fe=qe(C);xt(Fe),g({type:"groups",groups:Fe})}if(!q){let Fe=b.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)g({type:"suggest",terms:u.withIndex((Ue)=>kg(Ue,Fe))??[]})}g({type:"done",cursor:he?Buffer.from(JSON.stringify(!Je&&o.sort!=="recent"?{...y,offset:0,window:0,seen:[],emitted:[],after:R}:{...y,offset:ee,window:pe,seen:H,emitted:le})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:w,index:u.status()})}function Fo(e,o){return e.withIndex((i)=>kg(i,o))??[]}function Av(e,o,i){let u=x({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(m([a({maxLength:2000}),$n()])),scope:n(m([s("session"),s("project"),s("all"),s(""),$n()])),fields:n(m([B(qr({type:"string",enum:[...Ln]})),$n()])),tool:n(m([a(),$n()])),isError:n(m([N(),$n()])),after:n(m([a(),Y(),$n()])),before:n(m([a(),Y(),$n()])),limit:n(m([_(),$n()])),session:n(m([a(),$n()])),seq:n(m([_(),$n()])),around:n(m([_(),$n()]))}),async execute(p,g,y){let b={query:g.query?.trim(),scope:g.scope||void 0,fields:g.fields?.length?g.fields:void 0,tool:g.tool?.trim(),isError:g.isError??void 0,after:g.after??void 0,before:g.before??void 0,limit:g.limit||void 0,session:g.session?.trim(),seq:g.seq??void 0,around:g.around??void 0},E=b.query?.trim(),S=!E&&Boolean(b.session?.trim())&&Number.isSafeInteger(b.seq)&&(b.seq??0)>=1;if(S&&b.around!==void 0&&(!Number.isInteger(b.around)||b.around<0||b.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(b.scope&&!["session","project","all"].includes(b.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(y?.aborted)throw Error("History search cancelled");let w=e.sessions().find((ae)=>ae.id===i);if(!w)throw Error("History session is unavailable");let R=(ae)=>{if(ae===void 0||ae===0||typeof ae==="string"&&!ae.trim())return;if(typeof ae==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(ae))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let de=typeof ae==="number"?ae:Date.parse(ae);if(!Number.isFinite(de)||Math.abs(de)>8640000000000000){if(typeof ae==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return de},k=S?void 0:R(b.after),A=S?void 0:R(b.before);if(k!==void 0&&A!==void 0&&k>=A)throw Error("after must precede before");let C=[];if(S&&b.session&&b.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===b.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let de=b.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(b.session,Math.max(1,b.seq-de),b.seq+de);if(!qe.some((Je)=>Je.seq===b.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:qe.map((Je)=>{let Yt={...JSON.parse(Je.body),seq:Je.seq,time:Je.time};return`[seq=${Je.seq}]
|
|
466
|
-
${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
|
|
467
|
-
`).slice(0,4000)}`}).join(`
|
|
468
|
-
|
|
469
|
-
`)||"No history content"}],details:{groups:C,count:qe.length}}}if(!E)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(b.limit)?Math.max(1,Math.min(30,Math.trunc(b.limit??10))):10,X=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,j=new Set(e.sessions().filter((ae)=>{if(b.scope==="session")return ae.id===i;if((b.scope??"project")==="project"&&w.projectID)return ae.projectID===w.projectID;return!0}).map((ae)=>ae.id)),V={q:E,filters:{tools:b.tool?.trim()?[b.tool.trim()]:void 0,isError:b.isError,after:k,before:A},group:"none",limit:q},J=Kl(V);if(J.error)throw Error(J.error.message);if(b.fields?.length){if(J.filters.fields=b.fields.filter((ae)=>(ae in Ne)),J.filters.fields.length!==b.fields.length)throw Error("Unknown search field")}if((b.scope??"project")==="session")J.filters.sessionID=[i];else if((b.scope??"project")==="project"&&w.projectID)J.filters.projectID=[w.projectID];let ee=o.status().state!=="ready",pe=!1;if(!ee){let ae=J.filters.fields??Object.keys(Ne).filter((xt)=>(xt in Ne)),de=ae.filter((xt)=>xt!=="title"),qe=de.length?[de]:[];if(ae.includes("title"))qe.push(["title"]);for(let xt of qe){if(C.length>=q&&pe)break;if(await Gr(o,{...V,limit:Math.max(1,q-C.length),filters:{...J.filters,fields:xt}},{signal:y,excludeEntry:X===void 0?void 0:{sessionID:i,seq:X},sessionID:i,allowedSessionIDs:j,onEvent(Je){if(Je.type==="groups")C.push(...Je.groups);if(Je.type==="done")pe||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")ee=!0;else throw Error(Je.message)}}),ee)break}}let H=[],le=0;if(ee){C.length=0;let ae=performance.now()+2000;e:for(let de of e.sessions()){if(!j.has(de.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(de.id))continue;if(J.filters.projectID&&(!de.projectID||!J.filters.projectID.includes(de.projectID)))continue;let qe=Number.MAX_SAFE_INTEGER,xt=!0;for(;;){let Je=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(de.id,qe);if(xt)Je.push({body:"null",seq:0,time:de.updated}),xt=!1;if(!Je.length)break;for(let Yt of Je){if(Yt.seq>0)qe=Yt.seq;if(y?.aborted)throw Error("History search cancelled");if(le>=1e4||performance.now()>ae){pe=!0;break e}if(le++,de.id===i&&Yt.seq===X)continue;if(J.filters.after!==void 0&&Yt.time<J.filters.after||J.filters.before!==void 0&&Yt.time>=J.filters.before)continue;let Fe=Yt.seq===0?[{part:0,kind:"title",text:de.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Ue of Fe){if(J.filters.fields&&!J.filters.fields.includes(Ue.kind))continue;if(J.filters.tools&&(!Ue.tool||!J.filters.tools.includes(Ue.tool)))continue;if(J.filters.isError!==void 0&&Boolean(Ue.err)!==J.filters.isError)continue;let Dt=Wl(Ue.text,J);if(!Dt)continue;if(C.length>=q&&Ue.kind!=="title"){pe=!0;break e}(Ue.kind==="title"?H:C).push({session:{id:de.id,title:de.title,projectID:de.projectID,updated:de.updated},more:0,hits:[{sessionID:de.id,seq:Yt.seq,time:Yt.time,field:Ue.kind,tool:Ue.tool,isError:Boolean(Ue.err),snippet:zl(Ue.text,Dt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(y?.aborted)throw Error("History search cancelled");if(H.length>Math.max(0,q-C.length))pe=!0;if(C.push(...H.slice(0,q)),C.sort((ae,de)=>Number(ae.hits[0]?.field==="title")-Number(de.hits[0]?.field==="title")),C.length>q)pe=!0;C.length=Math.min(C.length,q);let he=new Map;for(let ae of C)for(let de of ae.hits){let qe=he.get(ae.session.id)??[];qe.push(`[${ae.session.title.replace(/[\r\n]/g," ")} \xB7 ${de.sessionID} \xB7 ${de.seq} \xB7 ${new Date(de.time).toISOString()} \xB7 ${de.field}${de.tool?`/${de.tool}`:""}]
|
|
470
|
-
${de.snippet.slice(0,3).map((xt)=>{let Je=xt.text;for(let[Yt,Fe]of[...xt.ranges].sort((Ue,Dt)=>Dt[0]-Ue[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Fe)}\u3011${Je.slice(Fe)}`;return Je}).join(`
|
|
471
|
-
`)}`),he.set(ae.session.id,qe)}let $e="";if(ee){if($e="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")$e="\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 Ee=C.reduce((ae,de)=>ae+de.hits.length,0);return{content:[{type:"text",text:[$e,ee&&pe?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${le} \u6761`:"",[...he.values()].map((ae)=>ae.join(`
|
|
472
|
-
|
|
473
|
-
`)).join(`
|
|
474
|
-
|
|
475
|
-
`),Ee===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 ${Ee} \u6761\uFF1B${pe?"\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(`
|
|
476
|
-
`)}],details:{groups:C,count:Ee}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var Mg="basalt.git-snapshot";async function Cv(e,o,i){let u=o.projectID?e.store.project(o.projectID):void 0,p=u?.directory??process.cwd(),y=o.info().kind==="sub",b=()=>y||o.entries(0,["compaction"],!1).length>0,E=e.options.tools??nr({directory:u?.directory,records:()=>o.records,history:(R)=>e.resolveHistory(o.id,R),onTodos:(R)=>o.setTodos(R),shell:()=>e.serverShell(),hasCompacted:b});if(e.options.tools===void 0)E.push(Av(e.store,e.search,o.id));let S;if(u&&e.options.systemPrompt===void 0){let R=o.entries(0,["compaction"],!1).length,k=e.store.db,A=k.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(Mg,o.id),C;try{C=A?JSON.parse(A.value):void 0}catch{C=void 0}if(C?.compactions===R&&(C.summary===void 0||typeof C.summary==="string"))S=C.summary;else if(S=await A$(u.directory,i),!e.isClosed&&!i?.aborted)k.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(Mg,o.id,JSON.stringify({compactions:R,summary:S})),k.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(Mg)}let w=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:k$({project:u,globalInstructions:vK(e),git:S,shell:e.serverShell()});return{systemPrompt:w.map((R)=>R.detail).join(""),systemParts:w,tools:[...E,...e.tools.snapshot()],cwd:p}}var $K=[hu(".basalt","AGENTS.md"),hu(".agents","AGENTS.md"),hu(".opencode","AGENTS.md"),hu(".claude","CLAUDE.md"),hu(".codex","AGENTS.md")];function vK(e){let o=e.options.homeDir??PK();for(let i of $K){let u=hu(o,i);try{if(AK(u))return CK(u,"utf8")}catch{return}}return}class zr{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 xg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Ul(Og(e.dataDir,"basalt.db")),this.plugins=new Xh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Gl(this.plugins,()=>this.builtinToolNames()),this.search=new Yh({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 i=this.open(o,"restore");this.sessions.set(o.id,i),this.restored.add(i)}}static async create(e){let o=new zr(e);try{return await o.initialize(),o}catch(i){throw await o.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Og(this.options.dataDir,"plugins"),...this.projects().map((e)=>Og(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 rv(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{...Bl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>ev(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((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let u=o.archive??"active";return u==="all"||i.archivedAt!==null===(u==="archived")}).sort((i,u)=>u.updated-i.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 i=this.get(e);if(!i)throw new t("History session is unavailable");return i.resolveHistory(o)}openStoredSession(e,o="restore"){let i=this.open(e,o);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let o=e.model??this.defaultModel;if(!En(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),u={id:ne("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,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,i){o={...o,archivedAt:null},this.store.copySession(e,o,i);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 f("no such session");let i=o.info(),u=i.projectID?this.store.project(i.projectID):void 0;return D$(i,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 i=[o.model,e.model,this.defaultModel].find((y)=>y!==void 0&&En(this.options.models,y)!==void 0),u=i?En(this.options.models,i):void 0;if(!i||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:ne("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:i,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?j$(e.records,u):e.records);let g=this.open(p);return this.sessions.set(p.id,g),this.emit({type:"session",session:g.info()}),g}truncateHistory(e,o){let i=this.sessions.get(e.id);if(!i)throw new f("no such session");if(i.assertWritable(),i.status==="busy")throw new se;if(!En(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`);i.close();for(let y of this.sessions.values()){if(y.info().parentID!==e.id)continue;if(y.status==="busy")y.abort();y.close()}this.store.truncateSession(e,o);let u=[],p=this.store.lastEntry(e.id,"run");if(p?.type==="run"&&p.state==="start"){let y=this.store.records(e.id,p.seq).filter((b)=>b.raw);for(let b of To(y)){if(b.result)continue;let{body:E,raw:S}=cl(b.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,E,S))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let g=this.open(e,"replay");this.sessions.set(e.id,g),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let y of u)this.emit({type:"entry",sessionID:e.id,entry:y});return g}setArchived(e,o){let i=this.sessions.get(e);if(!i)throw new f("no such session");let u=i.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(i);if(p.some((g)=>g.status==="busy"))throw new se;if(i.isArchived===o)return i.info();this.store.setArchived(p.map((g)=>g.id),o?Date.now():null);for(let g of p)g.refreshArchive();for(let g of p)g.archiveChanged();return i.info()}sessionTree(e){let o=[e];for(let i=0;i<o.length;i++){let u=o[i];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 f("no such session");if(o.status==="busy")throw new se;let i=this.sessionTree(o).slice(1),u=()=>{for(let p of i)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(!i.length)return u();o.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(u)}open(e,o="create"){let i=e.id,u=new _l(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p,g)=>Cv(this,p,g)},{entry:(p)=>{this.emit({type:"entry",sessionID:i,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:i,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(p)=>this.emit({type:"draft",sessionID:i,parts:p}),changed:()=>{let p=this.sessions.get(i);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 Fi(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(!Xl.includes(e))throw new t(`Invalid shell type; must be ${Xl.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 nv(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(i){console.error("runtime listener failed",i)}}}var Ce={now:()=>Date.now(),after(e,o){let i=setTimeout(o,e);return()=>clearTimeout(i)}};var Pv=1048576,$v=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,i,u){this.cwd=e;this.outputLimit=o;this.terminal=i;this.shellPreference=u}setTerminalObserver(e){this.terminal=e}start(e,o,i){let u=i?.observer,p=i?.clock??Ce;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let X=sd(e);if(X.length>0)throw Error(id(X))}if(this.list().filter((X)=>X.state==="running").length>=$v)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${$v}\uFF09`);let y=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:b,isWindows:E}=Ea(e,y),S=Bun.spawn(b,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!E,windowsHide:!0,env:{...process.env,...em(this.cwd)}}),w={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:S,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(w.id,w);let R=()=>{for(let X of w.waiters.splice(0))X()},k=async(X,j)=>{let V=new Rl;for await(let ee of X){let pe=V.decode(ee);w.output+=pe,u?.output(pe,j);let H=Buffer.from(w.output);if(H.length>Pv){let le=H.length-Pv;while(le<H.length&&(H[le]??0)>>6===2)le++;let he=H.subarray(le).toString(),$e=w.output.length-he.length;w.unreadDroppedBytes+=Buffer.byteLength(w.output.slice(Math.max(0,w.readAt-w.dropped),$e)),w.output=he,w.dropped+=$e}R()}let J=V.flush();if(w.output+=J,J)u?.output(J,j)},A,C=Promise.all([k(S.stdout,"stdout"),k(S.stderr,"stderr")]).catch((X)=>{A=X,this.kill(w)}),q=!1;if(w.done=(async()=>{if(w.code=await S.exited,w.timer?.(),this.kill(w),await C,A)throw A;if(w.state==="running")w.state="exited";if(q=!0,u?.end(w.state,w.code),!u&&w.state!=="killed")this.terminal?.(w);R()})().catch((X)=>{if(w.state="exited",w.output+=`
|
|
477
|
-
[\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(X)}]`,!q)u?.end(w.state,w.code);if(u)throw X;if(!u)this.terminal?.(w,X);R()}),o!==void 0)w.timer=p.after(o,()=>{if(w.state==="running")w.state="timeout",this.kill(w)});return w}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128)try{e.proc.kill()}catch{}}else process.kill(-e.proc.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,o,i=0,u=!1,p){let g=this.find(e),y=o?new RegExp(o):void 0,b=Date.now()+i;p?.throwIfAborted();while(g.state==="running"){p?.throwIfAborted();let k=g.output.slice(Math.max(0,g.readAt-g.dropped));if((y?y.test(k):!u)||Date.now()>=b)break;await new Promise((A,C)=>{let q=()=>{clearTimeout(j);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);C(p?.reason)},X=()=>{clearTimeout(j),p?.removeEventListener("abort",q);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);A()},j=setTimeout(X,Math.max(0,b-Date.now()));g.waiters.push(X),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let E=g.unreadDroppedBytes;g.unreadDroppedBytes=0;let S=g.output.slice(Math.max(0,g.readAt-g.dropped));g.readAt=g.dropped+g.output.length;let w=S.slice(-this.outputLimit),R=E+Buffer.byteLength(S.slice(0,S.length-w.length));return{job:g,output:`${R?`[truncated ${R} bytes]
|
|
478
|
-
`:""}${w}`}}async write(e,o,i=!1,u){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let g=p.proc.stdin;if(!g||typeof g==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let y=await je(o,u);if(y)throw Error(y);g.write(o)}if(i)await g.end();else await g.flush()}async stop(e){let o=this.find(e);if(o.state==="running")o.state="killed",this.kill(o);return await o.done,{id:o.id,state:o.state,code:o.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var Vl=new WeakMap,Jl=new WeakMap;function sr(e,o){let i=Vl.get(e);if(!i)i=o(),Vl.set(e,i);return i}function ar(e){Jl.set(e,(Jl.get(e)??0)+1)}function lr(e,o){let i=(Jl.get(o)??1)-1;if(Jl.set(o,i),i>0)return!1;if(o.close(),Vl.get(e)===o)Vl.delete(e);return!0}async function I(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function v(e,o){let i=e[o];if(!i)throw new t(`${o} is required`);return i}var Dn=100,cr=1e4,MK=60000,OK=200,kn=()=>a(),vv=()=>n(_({minimum:1,maximum:cr})),Jc=()=>n(a({minLength:1,maxLength:128})),_K=m([l({click:m([kn(),l({selector:kn()})])}),l({type:l({label:kn(),text:kn()})}),l({waitText:kn(),timeoutMs:vv()}),l({expectText:kn(),within:n(kn())}),l({waitSelector:kn(),timeoutMs:vv()}),l({expectCount:l({selector:kn(),n:_({minimum:0})})}),l({snapshot:l({selector:kn(),depth:n(_({minimum:0,maximum:OK}))})}),l({expectCalls:l({onOpen:n(B(kn())),onClose:n(_({minimum:0}))})}),l({expectValue:l({label:kn(),value:kn()})})]),LK=l({status:_({minimum:100,maximum:599}),body:Rr(),delayMs:n(_({minimum:0,maximum:cr}))}),NK=m([s("paths"),s("request"),s("verify"),s("ui_test"),s("list"),s("docs"),s("check"),s("load"),s("reload"),s("enable"),s("disable")]),DK=m([s("page"),s("tab"),s("card"),s("sidebar")]),gi=l({action:NK,path:n(a({minLength:1,maxLength:4096})),method:n(kn()),body:n(bs(kn(),Rr())),importTimeoutMs:n(_({minimum:1,maximum:cr})),timeoutMs:n(_({minimum:1,maximum:MK})),sessionID:Jc(),scope:n(m([s("user"),s("all")])),id:Jc(),slot:Jc(),view:Jc(),codeBlock:Jc(),kind:n(DK),props:n(bs(kn(),Rr())),context:n(bs(kn(),Rr())),steps:n(B(_K,{maxItems:Dn})),mockRoutes:n(bs(kn(),LK)),topic:n(a({maxLength:100})),grep:n(a({minLength:1,maxLength:200}))});
|
|
479
|
-
export{t,f,Fr,Wr,li,$r,er,Io,Ln,ci,ui,pi,Bt,di,mi,Hr,Mo,hi,Be,fi,ut,Ft,z,Lo,je,et,B,n,l,qr,N,_,s,Y,a,m,h,ce,On,Oo,No,Do,Uo,_e,x,tt,pt,P,D,F,Re,ue,Pe,c,ie,rt,tr,rr,nr,dt,se,Bo,or,ir,ne,Nn,Gr,Fo,zr,Ce,Wt,sr,ar,lr,I,v,Wo,Dn,cr,gi};
|