@bkm016/basalt 0.1.0 → 0.1.2
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/README.md +16 -22
- package/chunk-06hdzq5n.js +2 -0
- package/chunk-09rj27b2.js +2 -0
- package/{chunk-qnr1f5pj.js → chunk-0y7ne3d0.js} +2 -2
- package/{chunk-8wjgbd9k.js → chunk-10xzzn07.js} +2 -2
- package/{chunk-bj14jshr.js → chunk-1qpces5a.js} +2 -2
- package/chunk-1zdwrgd4.js +2 -0
- package/chunk-27gntzs5.js +5 -0
- package/chunk-2esbgxps.js +25 -0
- package/{chunk-913tfr9c.js → chunk-362g64pd.js} +1 -1
- package/{chunk-rjdhaasf.js → chunk-3cjsd292.js} +2 -2
- package/chunk-5c9j8qe4.js +478 -0
- package/chunk-5j1krv9v.js +2 -0
- package/{chunk-vkkj4awb.js → chunk-6hssbcgj.js} +1 -1
- package/chunk-75m78j7x.js +10 -0
- package/{chunk-zt1wvkyf.js → chunk-8296hw9m.js} +1 -1
- package/{chunk-9y69ywyg.js → chunk-8d46jtbj.js} +2 -2
- package/{chunk-sf13azm4.js → chunk-8tjad3r0.js} +4 -4
- package/{chunk-agntrqs9.js → chunk-97rzj7f6.js} +1 -1
- package/{chunk-k7w7ac9q.js → chunk-981f9dw8.js} +8 -8
- package/chunk-9mmz6wt3.js +2 -0
- package/chunk-aefadsy6.js +3 -0
- package/chunk-bannb9xm.js +3 -0
- package/chunk-bpw6q7g0.js +3 -0
- package/{chunk-3jz9g8ab.js → chunk-c7x1zq39.js} +3 -3
- package/{chunk-rv06x0kn.js → chunk-cjc90f84.js} +1 -1
- package/{chunk-6gyhajhx.js → chunk-d2j735sd.js} +2 -2
- package/{chunk-qcwnkr5y.js → chunk-d8gtbw9g.js} +1 -1
- package/{chunk-rm3kcxq9.js → chunk-fjtvjrkg.js} +13 -13
- package/{chunk-qbf8x2ft.js → chunk-fm0k0qtz.js} +1 -1
- package/{chunk-1yzt0qm0.js → chunk-fw2bpqmw.js} +1 -1
- package/{chunk-kgdrjqsy.js → chunk-g2t6t8fk.js} +2 -2
- package/{chunk-wc5j0hfw.js → chunk-gp7y0fja.js} +13 -13
- package/{chunk-5fdgy0q2.js → chunk-gzxnene8.js} +10 -10
- package/{chunk-y9xe9ct2.js → chunk-hwr56pfj.js} +1 -1
- package/{chunk-0hbjv3y6.js → chunk-jwdb0ccj.js} +3 -3
- package/{chunk-x9982ek7.js → chunk-k23t7vhs.js} +5 -5
- package/{chunk-qffb7een.js → chunk-k506w58v.js} +2 -2
- package/{chunk-0tdv0t5q.js → chunk-k6w6y71k.js} +2 -2
- package/chunk-m40gxwq4.js +5 -0
- package/chunk-m8vkwdgr.js +5 -0
- package/{chunk-7yw8aa5j.js → chunk-mvfsxdx6.js} +13 -13
- package/{chunk-3p7q2pyp.js → chunk-nbb9trwz.js} +1 -1
- package/{chunk-0szjy61m.js → chunk-pbcy6zdt.js} +1 -1
- package/chunk-pmqtkqsf.js +2 -0
- package/{chunk-hat3s3pr.js → chunk-pxsrqrd0.js} +1 -1
- package/{chunk-xsbxykr4.js → chunk-qe0teyn1.js} +1 -1
- package/{chunk-2zqny2sy.js → chunk-r7fpkb49.js} +1 -1
- package/{chunk-xhk54h2q.js → chunk-rtzqqngy.js} +4 -4
- package/chunk-ry0z4ev6.js +2 -0
- package/{chunk-0rya8cxe.js → chunk-shadcb9z.js} +2 -2
- package/chunk-shhrr741.js +3753 -0
- package/{chunk-tnrqkc7b.js → chunk-t6zs4kw0.js} +2 -2
- package/chunk-tvm4zmgj.js +3 -0
- package/{chunk-hcn9cf6v.js → chunk-v258nxcz.js} +1 -1
- package/{chunk-a6r4z44b.js → chunk-vk1gxk1t.js} +1 -1
- package/{chunk-d913kpyw.js → chunk-vv7fp27r.js} +2 -2
- package/{chunk-g2k3yhgh.js → chunk-x1xss1d7.js} +3 -3
- package/{chunk-dakrpbe6.js → chunk-x4874m8e.js} +2 -2
- package/{chunk-wx7kdf0b.js → chunk-xfvvh1s5.js} +1 -1
- package/{chunk-1egbcp85.js → chunk-y0m980k3.js} +7 -7
- package/{chunk-5wp4egky.js → chunk-y58ygzn9.js} +4 -4
- package/{chunk-kjr81mrd.js → chunk-y648fzx0.js} +5 -5
- package/{chunk-32at88hc.js → chunk-y7nma9rk.js} +1 -1
- package/{chunk-wd9zxhza.js → chunk-ykens1hy.js} +1 -1
- package/chunk-z55bmysw.js +2 -0
- package/chunk-zmsgwr3s.js +2 -0
- package/{chunk-501zkf9b.js → chunk-ztsjgssj.js} +1 -1
- package/cli.js +89 -0
- package/compiled.js +12 -3762
- package/package.json +4 -3
- package/ui-test-worker.js +67 -67
- package/web/chunk-0sewdyz1.js +1 -0
- package/web/{chunk-g9qv15hq.js → chunk-1z5p7a1h.js} +1 -1
- package/web/chunk-21ke27j6.js +1 -0
- package/web/{chunk-svmhj9hd.js → chunk-24k0r5aq.js} +1 -1
- package/web/{chunk-vqjs551t.js → chunk-284a17k8.js} +1 -1
- package/web/{chunk-3cfabjey.js → chunk-2pjdtesn.js} +14 -14
- package/web/{chunk-ngpq43vn.js → chunk-3mvr2gwh.js} +1 -1
- package/web/chunk-3t3zwx9j.js +1 -0
- package/web/{chunk-ezyvv4ab.js → chunk-3z93efr4.js} +1 -1
- package/web/{chunk-rkesqprv.js → chunk-43jqvsrg.js} +1 -1
- package/web/{chunk-4y2td14d.js → chunk-4bry4xds.js} +2 -2
- package/web/{chunk-ea9swkkt.js → chunk-5e7ygjdn.js} +1 -1
- package/web/{chunk-3ahpr030.js → chunk-5jbf7n5q.js} +1 -1
- package/web/{chunk-bhe4jzha.js → chunk-5rx8rtsa.js} +1 -1
- package/web/chunk-5xc9d5ft.js +1 -0
- package/web/{chunk-fdkp6tzq.js → chunk-693m9kt7.js} +3 -3
- package/web/{chunk-mq92vqb1.js → chunk-6qejm5s2.js} +1 -1
- package/web/{chunk-z1jtv4c0.js → chunk-8ah6ce1b.js} +2 -2
- package/web/{chunk-zk2f7x5e.js → chunk-8e43yaq3.js} +3 -3
- package/web/{chunk-hejz98gw.js → chunk-8wye0wbb.js} +1 -1
- package/web/{chunk-pz934t6t.js → chunk-986z0p48.js} +5 -5
- package/web/{chunk-jtwhjp20.js → chunk-9dd1c37b.js} +77 -77
- package/web/{chunk-sc63gh9d.js → chunk-9re6yttj.js} +2 -2
- package/web/{chunk-1t760bg0.js → chunk-abbvjt4e.js} +1 -1
- package/web/{chunk-1v3d60pp.js → chunk-agmkx996.js} +3 -3
- package/web/{chunk-kbtbbarw.js → chunk-anbn2ttv.js} +2 -2
- package/web/chunk-aqm3spxt.js +1139 -0
- package/web/{chunk-jvhmna7z.js → chunk-avwpjsxw.js} +5 -5
- package/web/chunk-b470hvpk.js +1 -0
- package/web/{chunk-29e1trsq.js → chunk-bt1m87ck.js} +2 -2
- package/web/chunk-cqp1d4p0.js +1 -0
- package/web/{chunk-b5brnfv9.js → chunk-ctcrk3qn.js} +2 -2
- package/web/{chunk-zakv2xdf.js → chunk-ctd8bfg2.js} +1 -1
- package/web/{chunk-5hex8g0y.js → chunk-cwvtraca.js} +1 -1
- package/web/{chunk-1x8fn8w9.js → chunk-dk90px7g.js} +1 -1
- package/web/{chunk-0mrkjnte.js → chunk-ds7srg4p.js} +1 -1
- package/web/{chunk-6r912gfj.js → chunk-dt8ss97f.js} +5 -5
- package/web/{chunk-ykxpb3wv.js → chunk-ezkqa7we.js} +1 -1
- package/web/{chunk-svdzmaxb.js → chunk-f078k1ej.js} +1 -1
- package/web/chunk-fekjj24p.css +1 -0
- package/web/{chunk-v6v831tc.js → chunk-fqj9kry9.js} +5 -5
- package/web/chunk-frjfamx7.js +8 -0
- package/web/{chunk-rz6wwdd5.js → chunk-fy8ey195.js} +1 -1
- package/web/{chunk-p8y0hjx9.js → chunk-g8ee1csm.js} +1 -1
- package/web/{chunk-ktqt87qw.js → chunk-h31p43qa.js} +1 -1
- package/web/chunk-h5p5jsrw.js +1 -0
- package/web/chunk-h9fmr6ch.js +1 -0
- package/web/{chunk-x9q4kh67.js → chunk-jf2ehmvp.js} +2 -2
- package/web/{chunk-canbct9d.js → chunk-jmnaq7c1.js} +1 -1
- package/web/chunk-jq0pw0k2.js +1 -0
- package/web/{chunk-ghxe4gam.js → chunk-jvj66qhs.js} +2 -2
- package/web/{chunk-7f0m2yrd.js → chunk-jzmzhj8z.js} +4 -4
- package/web/chunk-k4cfnvyq.js +1 -0
- package/web/{chunk-942prjb6.js → chunk-kgerjbn4.js} +1 -1
- package/web/{chunk-3bqh2dkw.js → chunk-kww4azv5.js} +5 -5
- package/web/chunk-m29dhjkh.js +1 -0
- package/web/chunk-mj6tee5h.js +1 -0
- package/web/{chunk-a3xt6840.js → chunk-mjpjkyd1.js} +1 -1
- package/web/{chunk-20q90epj.js → chunk-n8sky2q6.js} +1 -1
- package/web/{chunk-3pf33xsm.js → chunk-pk3ap3wh.js} +4 -4
- package/web/{chunk-tfyxp2qs.js → chunk-q1pkntc6.js} +4 -4
- package/web/{chunk-gxn0bey7.js → chunk-qryrg2pq.js} +2 -2
- package/web/{chunk-0xck277j.js → chunk-r92sbgwv.js} +5 -5
- package/web/{chunk-ev1g5cqw.js → chunk-raqqscwa.js} +2 -2
- package/web/{chunk-c85wxnpw.js → chunk-rc2vq9wz.js} +3 -3
- package/web/{chunk-rsn8j7xv.js → chunk-rkj743fg.js} +3 -3
- package/web/{chunk-v47rhg7b.js → chunk-rrws61wf.js} +1 -1
- package/web/{chunk-ytpwz01r.js → chunk-s3hwejnr.js} +2 -2
- package/web/{chunk-bwyw10wx.js → chunk-s3rdx28k.js} +2 -2
- package/web/{chunk-hryhthxr.js → chunk-shbw6wg8.js} +1 -1
- package/web/chunk-szcy5z56.js +1 -0
- package/web/{chunk-ejd43q75.js → chunk-t1xk6hca.js} +4 -4
- package/web/chunk-t2hhdg9r.js +1 -0
- package/web/chunk-tj4cmkwe.js +1 -0
- package/web/{chunk-mdsgekpk.js → chunk-tn1xzmgx.js} +1 -1
- package/web/{chunk-0k0hvh59.js → chunk-tnv7z83q.js} +1 -1
- package/web/chunk-v2b5q0n5.js +1 -0
- package/web/{chunk-haphmhz8.js → chunk-vj6kstpp.js} +5 -5
- package/web/{chunk-e5rmr47n.js → chunk-vjqmnkh2.js} +1 -1
- package/web/{chunk-vfqe8298.js → chunk-vkc149rb.js} +1 -1
- package/web/{chunk-n5fn9khr.js → chunk-vny496ba.js} +1 -1
- package/web/{chunk-s8vapqgr.js → chunk-vz5ck6x9.js} +1 -1
- package/web/{chunk-6atq9qtt.js → chunk-xa88zgkr.js} +1 -1
- package/web/{chunk-d4d3mnak.js → chunk-xdcs8qz3.js} +4 -4
- package/web/chunk-y5x74t89.js +1 -0
- package/web/{chunk-x3zwjkwg.js → chunk-yen2kkn2.js} +1 -1
- package/web/{chunk-vadqkz3x.js → chunk-yjv2c45j.js} +4 -4
- package/web/chunk-yx3dh5hg.js +1 -0
- package/web/chunk-yz4fmtk2.js +1 -0
- package/web/{chunk-4b5mt5pd.js → chunk-z24vs8q9.js} +3 -3
- package/web/chunk-z5j6x6j8.js +2 -0
- package/web/chunk-z5stjrhc.js +1 -0
- package/web/{chunk-3pm4645m.js → chunk-z760wagr.js} +1 -1
- package/web/{chunk-nerx2q12.js → chunk-znvnb9dh.js} +1 -1
- package/web/{chunk-55kw67nv.js → chunk-zrzq29e6.js} +1 -1
- package/web/{icon-yx2p2pye.svg → icon-1wgy7kzy.svg} +13 -13
- package/web/icon.svg +13 -13
- package/web/index.html +2 -2
- package/web/install.sh +0 -0
- package/web/sw.js +9 -0
- package/worker.js +1 -1
- package/chunk-1fv27j4b.js +0 -3
- package/chunk-356q8e0y.js +0 -10
- package/chunk-58vz2qsq.js +0 -2
- package/chunk-665jzf2w.js +0 -25
- package/chunk-97kjn55j.js +0 -2
- package/chunk-b9bg5fhd.js +0 -2
- package/chunk-c25s4w6a.js +0 -5
- package/chunk-j2x0g1vg.js +0 -2
- package/chunk-k0t23cmx.js +0 -2
- package/chunk-m38ber71.js +0 -2
- package/chunk-rad3dm0q.js +0 -2
- package/chunk-sytpmbfp.js +0 -471
- package/chunk-t057xfrt.js +0 -5
- package/chunk-tjpvayr1.js +0 -2
- package/chunk-ve7qx8wm.js +0 -3
- package/chunk-y8ced1jm.js +0 -5
- package/chunk-yb1jxgnk.js +0 -2
- package/web/chunk-00mq7bhx.js +0 -1
- package/web/chunk-0atfn8jf.js +0 -1
- package/web/chunk-310yey4q.js +0 -1
- package/web/chunk-32ezm0ry.js +0 -1136
- package/web/chunk-3hvgs5aw.js +0 -1
- package/web/chunk-3kh6zefg.js +0 -1
- package/web/chunk-401v5ht6.js +0 -8
- package/web/chunk-5r5kv4gh.js +0 -1
- package/web/chunk-95q1bwxn.js +0 -1
- package/web/chunk-9s7c178f.js +0 -1
- package/web/chunk-benmmqt2.js +0 -1
- package/web/chunk-bgqdcnke.js +0 -1
- package/web/chunk-eqegxtdt.js +0 -1
- package/web/chunk-gmfp7fg4.js +0 -1
- package/web/chunk-gxay64d5.js +0 -1
- package/web/chunk-jg6nzn6q.js +0 -1
- package/web/chunk-kx2xk3bb.js +0 -1
- package/web/chunk-ry9256r7.js +0 -1
- package/web/chunk-vfqdy860.js +0 -1
- package/web/chunk-wtawdeej.css +0 -1
- package/web/chunk-x59p8sg2.js +0 -1
- package/web/chunk-y7z144e3.js +0 -1
- package/web/chunk-ydgqrfvw.js +0 -2
- package/web/chunk-yj1a2d37.js +0 -1
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Do,zr,F}from"./chunk-m8vkwdgr.js";import{Wo,$e,Tt,$o,Qn,qo,Ai,Ei,ft,Ho,Oe,Qr,Ke}from"./chunk-k23t7vhs.js";import{$n,_i,Gr}from"./chunk-8d46jtbj.js";import{Ie,te,Uo,qn,C,Hn,mt,Ce,ur,N,Me,Gn,ht,pe,$t,ne,jr,Fo,Le,re,nt,zn,Bo,ge,Pi,xi,ye,jn,d,Ti,Q,Vr,H,ki}from"./chunk-8tjad3r0.js";import{Vn,M,Kn,Ve,wi,qt,Te}from"./chunk-shadcb9z.js";import{r,Ye}from"./chunk-0y7ne3d0.js";var Fg=r(function(HK,qg){var TM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Xl=/[\n\r\u2028\u2029]/,RM=/[\s#!"$&'():;<=>@\\^`|~]/g;qg.exports=function(n){var i=!1;return n.map(function(c){if(i&&typeof c==="string"&&Xl.test(c))throw TypeError("a token after a `comment` must not contain line terminators");if(c==="")return"''";if(c&&typeof c==="object"){if("op"in c&&c.op==="glob"){if(typeof c.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Xl.test(c.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(c.pattern==="")return"''";return c.pattern.replace(RM,"\\$&")}if("op"in c&&typeof c.op==="string"){if(TM.indexOf(c.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(c.op));return c.op.replace(/[\s\S]/g,"\\$&")}if("comment"in c&&typeof c.comment==="string"){if(Xl.test(c.comment))throw TypeError("`comment` must not contain line terminators");return i=!0,"#"+c.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(c)&&/!/.test(c))return"'"+c.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(c)&&!/'/.test(c))return"'"+c+"'";if(/["'\s]/.test(c))return'"'+c.replace(/(["\\$`])/g,"\\$1")+'"';return String(c).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var zg=r(function(WK,Wg){var Kg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",jg=new RegExp("^"+Kg+"$"),Ug="|&;()<> \\t",kM="'([^']*?)'",Hg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Bg="\\$'"+Hg+"'",em=new RegExp("\\$'"+Hg+"(?:(')|\\\\?$)","g"),AM="abeEfnrtv",CM=`\x07\b\x1B\x1B\f
|
|
3
|
+
\r \v`,$M=/^#$/,Yl="'",Gg='"',Iu="$",ji="",PM=4294967296;for(Zc=0;Zc<4;Zc++)ji+=(PM*Math.random()).toString(16);var Zc,MM=new RegExp("^"+ji);function vM(e,n){var i=n.lastIndex,c=[],p;while(p=n.exec(e))if(c[c.length]=p,n.lastIndex===p.index)n.lastIndex+=1;return n.lastIndex=i,c}function OM(e,n,i){var c=typeof e==="function"?e(i):e[i];if(typeof c>"u"&&i!="")c="";else if(typeof c>"u")c="$";if(typeof c==="object")return n+ji+JSON.stringify(c)+ji;return n+c}var _M=/\\([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 LM(e,n){var i=n.charAt(0);if(i==="c"){var c=n.charAt(1);return c==="?"?"\x7F":String.fromCharCode(c.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var p=parseInt(n.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(n,8)&255);var f=AM.indexOf(n);return f<0?n:CM.charAt(f)}function NM(e){return e.replace(_M,LM).split("\x00")[0]}function DM(e,n){return em.lastIndex=n,!!em.exec(e)[1]}function qM(e,n,i){if(!i)i={};var c=i.escape||"\\",p=i.splitUnquoted===!0?`
|
|
4
|
+
`:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",f="(\\"+c+`['"$\\`+c+Ug+"]|\\$\\$|\\$(?!"+Bg.slice(2)+`)|[^\\s'"$`+Ug+"])+",g='"(?:\\'+c+'[\\s\\S]|[^"\\'+c+'])*"',x=new RegExp(["("+Kg+")","("+Bg+"|"+f+"|"+g+"|"+kM+")+"].join("|"),"g"),I=vM(e,x);if(I.length===0)return[];if(!n)n={};var b=!1;return I.map(function(E){var T=E[0];if(!T||b)return;if(jg.test(T))return{op:T};var k=!1,A=!1,L="",q=[],Y=!1,j=null,V=!1,X;function se(){X+=1;var me,qe,xt=T.charAt(X);if(xt==="{"){if(X+=1,T.charAt(X)==="}")throw Error("Bad substitution: "+T.slice(X-2,X+1));var Je=1;me=X;while(Je>0&&me<T.length){if(T.charAt(me)==="{"&&T.charAt(me-1)==="$")Je+=1;else if(T.charAt(me)==="}")Je-=1;me+=1}if(Je!==0)throw Error("Bad substitution: "+T.slice(X));me-=1,qe=T.slice(X,me),X=me}else if(/[*@#?$!-]/.test(xt))qe=xt;else{var Yt=T.slice(X);if(me=Yt.match(/[^\w\d_]/),!me)qe=Yt,X=T.length;else qe=Yt.slice(0,me.index),X+=me.index-1}return OM(n,"",qe)}function Z(){if(j===null)return;if(j===0){if(L!=="")q[q.length]=L,L=""}else{q[q.length]=L,L="";for(var me=1;me<j;me+=1)q[q.length]=""}j=null}for(X=0;X<T.length;X++){var z=T.charAt(X);if(p&&z!==Iu)Z();if(V=V||!k&&(z==="*"||z==="?"),A)L+=z,A=!1;else if(k)if(z===k)k=!1;else if(k==Yl)L+=z;else if(z===c)if(X+=1,z=T.charAt(X),z===Gg||z===c||z===Iu)L+=z;else L+=c+z;else if(z===Iu)L+=se();else L+=z;else if(z===Gg||z===Yl)k=z,Y=!0;else if(jg.test(z))return{op:T};else if($M.test(z)){b=!0;var ce={comment:e.slice(E.index+X+1)};if(L.length)return[L,ce];return[ce]}else if(z===c)A=!0;else if(z===Iu&&T.charAt(X+1)===Yl&&DM(T,X))Z(),Y=!0,L+=NM(T.slice(X+2,em.lastIndex-1)),X=em.lastIndex-1;else if(z===Iu){var he=se();if(!p)L+=he;else for(var ve=0;ve<he.length;ve+=1){var fe=he.charAt(ve);if(p.indexOf(fe)<0)Z(),L+=fe;else if(j===null)j=fe===" "||fe==="\t"||fe===`
|
|
5
|
+
`?0:1;else if(fe!==" "&&fe!=="\t"&&fe!==`
|
|
6
|
+
`)j+=1}}else L+=z}if(V)return{op:"glob",pattern:L};if(p){if(j!==null&&j>0){q[q.length]=L,L="";for(var ie=1;ie<j;ie+=1)q[q.length]=""}if(L!==""||Y&&q.length===0)q[q.length]=L;return q}return L}).reduce(function(E,T){if(typeof T>"u")return E;return[].concat(T).forEach(function(k){E[E.length]=k}),E},[])}Wg.exports=function(n,i,c){var p=qM(n,i,c);if(typeof i!=="function")return p;return p.reduce(function(f,g){if(typeof g==="object")return f[f.length]=g,f;var x=g.split(RegExp("("+ji+".*?"+ji+")","g"));if(x.length===1)return f[f.length]=x[0],f;return x.filter(Boolean).forEach(function(I){f[f.length]=MM.test(I)?JSON.parse(I.split(ji)[1]):I}),f},[])}});var No={};Ye(No,{ArchivedError:()=>pt,BadRequestError:()=>t,BusyError:()=>oe,DEFAULT_TIMEOUT:()=>tP,FoldingPolicy:()=>Uc,MAX_ATTACHMENTS:()=>et,MAX_TIMEOUT:()=>rP,MAX_TOOL_OUTPUT:()=>Pe,NotFoundError:()=>y,PluginCheckError:()=>ut,ProcessRegistry:()=>Wt,Type:()=>ro,aliased:()=>we,budget:()=>jc,calls:()=>us,clip:()=>je,clipSaved:()=>rt,dataDir:()=>Pt,definePlugin:()=>R,estimateMessage:()=>U,estimateTokens:()=>O,estimateTools:()=>Li,extensionTranscript:()=>Gc,findWindowsBash:()=>wl,foldPoint:()=>qc,foldedThrough:()=>ha,formatLines:()=>Kc,gateShellCommand:()=>ze,groupRuns:()=>$s,historyTodos:()=>nr,newID:()=>ue,normalizeRunRecords:()=>_h,processRegistry:()=>or,project:()=>ke,projectUserText:()=>Ni,releaseProcesses:()=>sr,requestBody:()=>G,resolveShellCommand:()=>xa,retainProcesses:()=>ir,routeParam:()=>P,runShell:()=>er,sealPoint:()=>ou,selectHistory:()=>rr,sessionTools:()=>tr,staleFold:()=>xl,text:()=>u,timerClock:()=>Re,tool:()=>v,toolSession:()=>K,transcript:()=>uu,usable:()=>We,userTranscript:()=>Bc,validAttachment:()=>_t,workState:()=>bl});var Mo={};Ye(Mo,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>yR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>bR,EventStream:()=>Vn,InMemoryCredentialStore:()=>qn,InMemoryModelsStore:()=>Hn,ModelsError:()=>C,StringEnum:()=>Cq,Type:()=>ro,appendAssistantMessageDiagnostic:()=>Te,calculateCost:()=>Q,clampThinkingLevel:()=>H,cleanupSessionResources:()=>_i,collapseSystemMessages:()=>Le,contentText:()=>ur,createAssistantMessageDiagnostic:()=>qt,createAssistantMessageEventStream:()=>Kn,createFauxCore:()=>gR,createInitialSystemMessage:()=>Gn,createModels:()=>jn,createProvider:()=>d,declarationsEqual:()=>zn,defaultProviderAuthContext:()=>Uo,envApiKeyAuth:()=>h,extractDiagnosticError:()=>wi,fauxAssistantMessage:()=>Io,fauxProvider:()=>Co,fauxText:()=>Cn,fauxThinking:()=>Ro,fauxToolCall:()=>aq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>jr,getCurrentSystemPrompt:()=>Fo,getCurrentTools:()=>ne,getDeclaredTools:()=>ge,getInitialSystemMessage:()=>pe,getModelType:()=>mt,getOverflowPatterns:()=>wq,getSupportedThinkingLevels:()=>Vr,getSystemMessageText:()=>N,getToolStateChanges:()=>Bo,hasApi:()=>Ti,hasNonAdditiveToolChanges:()=>xi,hasToolRedefinitions:()=>Pi,isContextOverflow:()=>li,isModelType:()=>Ce,isRecoverableLength:()=>Sq,isRetryableAssistantError:()=>SR,lazyApi:()=>te,lazyOAuth:()=>ae,lazyStream:()=>Ie,modelsAreEqual:()=>ki,normalizeContext:()=>ht,parseJsonWithRepair:()=>zr,parseStreamingJson:()=>F,reduceAssistantMessageFrames:()=>Iq,registerSessionResourceCleanup:()=>$n,renderSystemMessageUpdate:()=>Me,repairJson:()=>Do,resolveTranscript:()=>re,resolveTranscriptTools:()=>ye,retryAssistantCall:()=>Aq,retryDelayMs:()=>ER,toToolDeclaration:()=>nt,uuidv7:()=>Gr,validateToolArguments:()=>tu,validateToolCall:()=>dU,withoutInitialSystemMessage:()=>$t});var B={};Ye(B,{Counted:()=>ad,Entries:()=>cn,EntriesRegExp:()=>ud,Every:()=>nn,EveryAll:()=>Rn,GraphemeCount:()=>mv,HasPropertyKey:()=>le,IsArray:()=>Be,IsBigInt:()=>_r,IsBoolean:()=>un,IsClassInstance:()=>my,IsConstructor:()=>sd,IsDeepEqual:()=>Sa,IsEqual:()=>_,IsFunction:()=>ms,IsGreaterEqualThan:()=>ba,IsGreaterThan:()=>Bi,IsInteger:()=>nm,IsLessEqualThan:()=>ps,IsLessThan:()=>Su,IsMaxLength:()=>py,IsMinLength:()=>ly,IsMultipleOf:()=>cy,IsNull:()=>mo,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>zo,IsString:()=>gt,IsSymbol:()=>id,IsUndefined:()=>Gt,IsUnsafePropertyKey:()=>wu,IsValueLike:()=>Gi,Keys:()=>Ee,ShiftLeft:()=>It,Some:()=>Ea,SomeAll:()=>dy,Symbols:()=>fy,Values:()=>cd});var Qi={};Ye(Qi,{Hash:()=>gd,HashCode:()=>Vy});var Lt={};Ye(Lt,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Se,ExtendsUnion:()=>qd,IsExtendsFalse:()=>Ud,IsExtendsTrue:()=>jd,IsExtendsTrueLike:()=>to,IsExtendsUnion:()=>Fd,Match:()=>xr});var ro={};Ye(ro,{Any:()=>ka,Array:()=>W,BigInt:()=>$u,Boolean:()=>D,Call:()=>aw,Capitalize:()=>fw,Codec:()=>dm,Conditional:()=>Sw,Constructor:()=>ds,ConstructorParameters:()=>Tw,Cyclic:()=>gs,Decode:()=>Yy,DecodeBuilder:()=>lm,Dependent:()=>Ji,Encode:()=>Zy,EncodeBuilder:()=>pm,Enum:()=>qy,Evaluate:()=>wn,Exclude:()=>kw,Extends:()=>Sn,ExtendsResult:()=>Lt,Extract:()=>Cw,Function:()=>fs,Generic:()=>Xs,Identifier:()=>Pu,Immutable:()=>ex,Index:()=>vw,Infer:()=>Cu,InstanceType:()=>nT,Instantiate:()=>wo,Integer:()=>w,Interface:()=>BS,Intersect:()=>An,IsAny:()=>Cr,IsArray:()=>St,IsBigInt:()=>io,IsBoolean:()=>Wn,IsCall:()=>qa,IsCodec:()=>Bn,IsConstructor:()=>Xr,IsCyclic:()=>Qt,IsDependent:()=>Lr,IsEnum:()=>tn,IsEnumValue:()=>Dy,IsFunction:()=>Yr,IsGeneric:()=>Ra,IsIdentifier:()=>ox,IsImmutable:()=>Xi,IsInfer:()=>en,IsInteger:()=>pn,IsIntersect:()=>He,IsKind:()=>Ae,IsLiteral:()=>yt,IsNever:()=>so,IsNull:()=>xs,IsNumber:()=>Tr,IsObject:()=>Qe,IsOptional:()=>sn,IsParameter:()=>ux,IsReadonly:()=>Zi,IsRecord:()=>Kt,IsRef:()=>jt,IsRefine:()=>fm,IsRest:()=>ni,IsSchema:()=>Ar,IsString:()=>rn,IsSymbol:()=>Is,IsTemplateLiteral:()=>cr,IsThis:()=>Cm,IsTuple:()=>lt,IsUndefined:()=>Yo,IsUnion:()=>be,IsUnknown:()=>Zr,IsUnsafe:()=>mm,IsVoid:()=>ao,KeyOf:()=>sT,Literal:()=>a,Lowercase:()=>hw,Mapped:()=>dT,Module:()=>tR,Never:()=>zt,NonNullable:()=>yT,Null:()=>Pn,Number:()=>J,Object:()=>s,Omit:()=>IT,Optional:()=>o,Parameter:()=>ea,Parameters:()=>ST,Partial:()=>TT,Pick:()=>MT,Readonly:()=>tx,ReadonlyObject:()=>yf,ReadonlyType:()=>_T,Record:()=>bs,RecordKey:()=>ri,RecordPattern:()=>ln,RecordValue:()=>lr,Ref:()=>on,Refine:()=>rx,Required:()=>JT,Rest:()=>ra,ReturnType:()=>XT,Script:()=>sR,String:()=>l,Symbol:()=>$a,TemplateLiteral:()=>cS,This:()=>Am,Tuple:()=>Dr,Uncapitalize:()=>gw,Undefined:()=>va,Union:()=>m,Unknown:()=>wr,Unsafe:()=>Br,Uppercase:()=>yw,Void:()=>$m,With:()=>dp});var Ya={};Ye(Ya,{Clear:()=>qk,Entries:()=>LF,Get:()=>qF,Has:()=>DF,IsDate:()=>Ja,IsDateTime:()=>Sp,IsDuration:()=>wp,IsEmail:()=>Tp,IsHostname:()=>vp,IsIPv4:()=>Lp,IsIPv6:()=>Np,IsIdnEmail:()=>Op,IsIdnHostname:()=>_p,IsIri:()=>qp,IsIriReference:()=>Dp,IsJsonPointer:()=>jp,IsJsonPointerUriFragment:()=>Fp,IsRegex:()=>Up,IsRelativeJsonPointer:()=>Bp,IsTime:()=>Qa,IsUri:()=>Hp,IsUriReference:()=>Gp,IsUriTemplate:()=>Kp,IsUrl:()=>Wp,IsUuid:()=>zp,Reset:()=>jk,Set:()=>NF,Test:()=>Fk});var xu="shell-guard",Pg=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class y extends Error{constructor(e){super(e);this.name="NotFoundError"}}function Mg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function vg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function bM(e,n){if(e===n)return 0;let i=Array.from({length:n.length+1},(c,p)=>p);for(let c=1;c<=e.length;c++){let p=i[0]??0;i[0]=c;for(let f=1;f<=n.length;f++){let g=i[f]??0;i[f]=Math.min((i[f]??0)+1,(i[f-1]??0)+1,p+(e[c-1]===n[f-1]?0:1)),p=g}}return i[n.length]??0}function Og(e,n){let i=Mg(e);if(!i)return[];let c=vg(e),p=[];for(let f of n){let g=f.id.indexOf("/"),x=g>=0?f.id.slice(g+1):"",b=[f.id,f.name,x].filter(Boolean).map((T)=>({compact:Mg(T),tokens:vg(T)})).filter((T)=>T.compact.length>0),E=Number.POSITIVE_INFINITY;for(let T of b)if(T.compact===i)E=Math.min(E,0);else if(T.compact.includes(i)||i.includes(T.compact)){let k=Math.abs(T.compact.length-i.length);E=Math.min(E,1+k/Math.max(T.compact.length,i.length))}else{let k=0;for(let A of c)if(T.tokens.has(A))k++;if(k>0){let A=k/Math.max(c.size,T.tokens.size);E=Math.min(E,10+(1-A)*10)}}if(!Number.isFinite(E)&&i.length>=4){let T=Math.max(2,Math.floor(i.length*0.34));for(let k of b){if(Math.abs(k.compact.length-i.length)>T)continue;let A=bM(i,k.compact);if(A<=T)E=Math.min(E,100+A)}}if(Number.isFinite(E))p.push({model:f,score:E})}return p.sort((f,g)=>f.score-g.score||f.model.id.localeCompare(g.model.id))}function EM(e,n,i=5){return Og(e,n).slice(0,Math.max(1,i)).map((c)=>c.model)}function ci(e,n){let i=Og(e,n);if(i.length===0)return;let c=i.filter((f)=>f.score===0);if(c.length===1&&c[0])return c[0].model;if(c.length>1)return;let p=i.filter((f)=>f.score<10);if(p.length===1&&p[0])return p[0].model;return}function ui(e,n){let i=[...n].sort((g,x)=>g.id.localeCompare(x.id)),c=(g)=>g.name===g.id?g.id:`${g.id} (${g.name})`,p=EM(e,i).map(c),f=i.map(c);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${f.length}): ${f.length>0?f.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
|
|
7
|
+
`)}var pi=["openai-completions","openai-responses","anthropic-messages"];function Ur(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let n=e.trim().toLowerCase();if(!n)return;let i=n.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let c=Number.parseFloat(i[1]??"");if(!Number.isFinite(c)||c<=0)return;let p=i[2];if(p==="k")return Math.round(c*1000);if(p==="m")return Math.round(c*1e6);return Math.round(c)}function Vl(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 SM(e){let n=e.trim();if(!n)return;let i,c,p=n,f=p.match(/\s*\[(.*?)\]\s*$/);if(f&&f.index!==void 0){p=p.slice(0,f.index).trim();let E=f[1]?.split(",").map((k)=>k.trim()).filter(Boolean)??[],T=0;for(let k of E){let A=k.indexOf("=");if(A>=0){let L=k.slice(0,A).trim().toLowerCase(),q=Ur(k.slice(A+1).trim());if(L==="context"||L==="ctx"||L==="window"||L==="contextwindow")i=q;else if(L==="max"||L==="output"||L==="maxtokens")c=q}else{let L=Ur(k);if(T===0)i=L;else if(T===1)c=L;T++}}}else{let E=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(E?.[1]&&E[2])p=E[1].trim(),i=Ur(E[2])}let g=p.indexOf("="),x,I;if(g<0)x=p.trim(),I=x;else x=p.slice(0,g).trim(),I=p.slice(g+1).trim()||x;if(!x)return;let b={id:x,name:I};if(i!==void 0)b.contextWindow=i;if(c!==void 0)b.maxTokens=c;return b}function Fr(e){return e.split(/\r?\n/).map(SM).filter((n)=>n!==void 0)}function Po(e){return e.map((n)=>{let i=n.name===n.id?n.id:`${n.id}=${n.name}`,c=[];if(n.contextWindow!==void 0)c.push(Vl(n.contextWindow));if(n.maxTokens!==void 0)if(n.contextWindow!==void 0)c.push(Vl(n.maxTokens));else c.push(`max=${Vl(n.maxTokens)}`);return c.length>0?`${i} [${c.join(", ")}]`:i}).join(`
|
|
8
|
+
`)}var _g=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var In=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],di=["text","regex"],mi=["best","recent"],hi=["session","none"];var Bt=4,fi="https://basalt.work",gi=["https://basalt.work","https://www.basalt.work"],yi=7420;var Jl=["auto","bash","powershell","cmd"],bi="Bkm016/Basalt";var To=["active","archived","all"];var Lg=["pending","in_progress","completed"],Ql="basalt-session",Yc=["image","text","path"];var Ng=["defer","always"],Dg=["global","tool","source"];function _e(e,n){if(e.toLowerCase()!=="tool_call"||!n||typeof n!=="object")return{name:e,input:n};let i=n;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:n};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:n}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:n};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:n}}}var et=10,wM=15000000;function _t(e){if(!e||typeof e!=="object")return!1;let n=e;return typeof n.name==="string"&&n.name.length>0&&n.name.length<=255&&typeof n.mimeType==="string"&&n.mimeType.length>0&&typeof n.kind==="string"&&Yc.includes(n.kind)&&typeof n.data==="string"&&n.data.length>0&&n.data.length<=wM}var FM=Fg(),Zl=zg();import{AsyncLocalStorage as jM}from"async_hooks";var K=new jM;var UM=3,Vg=160,BM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),GM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),Xg=/^[A-Za-z_][A-Za-z0-9_]*=/,KM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),HM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),WM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,zM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),VM=new Set(["command","builtin","nohup","time","exec"]),JM=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 tm(e){return{out:e.out,depth:e.depth+1}}function Jg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function ed(e,n,i,c){let p=e.length,f=0,g=n;while(g<p){let x=e.charAt(g);if(x==="\\"){g+=2;continue}if(x==="'"||x==='"'||x==="`"){let I=g+1;while(I<p){let b=e.charAt(I);if(b==="\\"){I+=2;continue}if(b===x)break;I++}g=I+1;continue}if(x===i)f++;else if(x===c){if(f--,f===0)return g+1}g++}return p}function QM(e){let n={text:"",subs:[],heredocs:[]},i=[],c=[],p=e.length,f=0,g=0,x=null,I=(b)=>{if(e.charAt(b)==="`"){let A=b+1;while(A<p){let L=e.charAt(A);if(L==="\\"){A+=2;continue}if(L==="`")break;A++}return n.subs.push(e.slice(b+1,A)),A<p?A+1:p}if(e.charAt(b+1)==="("){let A=ed(e,b+1,"(",")");if(e.charAt(b+2)==="(")return i.push(e.slice(b,A)),A;return n.subs.push(e.slice(b+2,A-1)),A}let T=ed(e,b+1,"{","}"),k=e.slice(b+2,T-1);for(let A=0;A<k.length;A++){let L=k.charAt(A);if(L==="\\"){A++;continue}if(L==="`"){let q=k.indexOf("`",A+1);n.subs.push(q<0?k.slice(A+1):k.slice(A+1,q)),A=q<0?k.length:q;continue}if(L==="$"&&k.charAt(A+1)==="("){let q=ed(k,A+1,"(",")");n.subs.push(k.slice(A+2,q-1)),A=q-1}}return T};while(f<p){let b=e.charAt(f);if(x==="'"){if(b==="'")x=null;i.push(b),f++;continue}if(x==='"'){if(b==="\\"){if(!'$`"\\\n'.includes(e.charAt(f+1)))i.push("\\");i.push(b,e.charAt(f+1)),f+=2;continue}if(b==='"'){x=null,i.push(b),f++;continue}if(b==="`"||b==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=I(f);continue}i.push(b),f++;continue}if(b==="'"||b==='"'){x=b,i.push(b),f++;continue}if(b==="\\"){i.push(b,e.charAt(f+1)),f+=2;continue}if(b==="`"||b==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=I(f);continue}if(b==="#"){let E=i.at(-1);if(E===void 0||`
|
|
9
|
+
;&|()`.includes(E)){while(f<p&&e.charAt(f)!==`
|
|
10
|
+
`)f++;continue}i.push(b),f++;continue}if(b==="<"&&e.charAt(f+1)==="<"&&e.charAt(f+2)!=="<"){let E=f+2;if(e.charAt(E)==="-")E++;i.push(e.slice(f,E));let T=E;while(T<p&&(e.charAt(T)===" "||e.charAt(T)==="\t"))T++;let k="";while(T<p){let A=e.charAt(T);if(A==="'"||A==='"'){let L=e.indexOf(A,T+1);if(L<0)break;k+=e.slice(T+1,L),T=L+1;continue}if(A==="\\"){k+=e.charAt(T+1),T+=2;continue}if(` \r
|
|
11
|
+
;&|()<>`.includes(A))break;k+=A,T++}if(k)c.push(k);f=E;continue}if(b===`
|
|
12
|
+
`){if(c.length>0){let E=WM.test(i.slice(g).join(""));f++;for(let T of c.splice(0)){let k=f,A=p;while(f<p){let L=e.indexOf(`
|
|
13
|
+
`,f),q=L<0?p:L;if(e.slice(f,q).trim()===T){A=f,f=L<0?p:L+1;break}f=L<0?p:L+1}if(E&&A>k)n.heredocs.push(e.slice(k,A))}}else f++;i.push(";",`
|
|
14
|
+
`),g=i.length;continue}i.push(b),f++}return n.text=i.join(""),n}function bu(e,n){if(n.depth>UM)return;let i=QM(e),c;try{c=Zl(i.text)}catch{return}let p=[];for(let f of c){if(typeof f==="string"){p.push({kind:"word",text:f});continue}if("pattern"in f){p.push({kind:"word",text:f.pattern});continue}if("op"in f)p.push({kind:"op",text:f.op})}XM(p,n);for(let f of i.subs)bu(f,tm(n));for(let f of i.heredocs)bu(f,tm(n))}function XM(e,n){let i=[],c=()=>{if(i.length>0)YM(i,n);i=[]};for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;if(f.kind==="op"){if(KM.has(f.text)){c();continue}if(HM.has(f.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(f.text)}c()}function YM(e,n){let i=0;for(;;){let g=e[i];if(g===void 0)return;if(GM.has(g)||Xg.test(g)){i++;continue}let x=ev(Jg(g),e,i);if(x===i)break;i=x}let c=e[i];if(c===void 0)return;let p=Jg(c),f=e.slice(i+1);if(p==="git"){rv(c,f,n);return}if(BM.has(p)){ZM(f,n);return}if(p==="powershell"||p==="pwsh")Qg(f,/^-(command|c)$/i,n);if(p==="cmd")Qg(f,/^\/[ck]$/i,n)}function Qg(e,n,i){for(let c=0;c<e.length;c++)if(n.test(e[c]??"")){let p=e.slice(c+1).join(" ");if(p.trim())bu(p,tm(i));return}}function ZM(e,n){for(let i=0;i<e.length;i++){let c=e[i]??"";if(c==="-o"||c==="-O"||c==="--init-file"||c==="--rcfile"){i++;continue}if(c.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(c);if(p){let f=p[1]||e[i+1];if(f)bu(f,tm(n));return}if(c.startsWith("-")||c==="")continue;return}}function ev(e,n,i){if(VM.has(e)){let f=i+1;while(n[f]?.startsWith("-"))f++;return f}let c=JM.get(e);if(!c)return i;let p=i+1;for(;;){let f=n[p];if(f===void 0)return p;if(c.includes(f)){p+=2;continue}if(Xg.test(f)||f.startsWith("-")){p++;continue}return p}}function Ko(e,n){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(n))}function Yn(e,n){return e.some((i)=>i===`--${n}`||i.startsWith(`--${n}=`))}var tv={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Ko(e,"f")||Ko(e,"i")||Yn(e,"force")||Yn(e,"interactive"))&&!(Ko(e,"n")||Yn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Ko(e,"f")||Yn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Ko(e,"f")||Yn(e,"force")||Ko(e,"C")||Yn(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)=>Ko(e,"f")||Yn(e,"force")||Yn(e,"force-with-lease")||Yn(e,"force-if-includes")||Yn(e,"delete")||Yn(e,"mirror")||e.some((n)=>n.startsWith("+")||n.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>Yn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Ko(e,"D")||Ko(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)=>Yn(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)=>Ko(e,"f")||Yn(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"&&(Ko(e,"f")||Yn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function rv(e,n,i){let c=0;for(;;){let I=n[c];if(I===void 0)break;if(zM.has(I)){c+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(I)||/^-[Cc].+/.test(I)||I.startsWith("-")){c++;continue}break}let p=n[c]?.toLowerCase();if(!p)return;let f=tv[p];if(!f)return;let g=f(n.slice(c+1));if(!g)return;let x=[e,...n.slice(c)].join(" ");i.out.push({rule:p,fragment:x.length>Vg?`${x.slice(0,Vg)}\u2026`:x,reason:g})}function rd(e){let n={out:[],depth:0};return bu(e,n),n.out}function Yg(e){let n=e.slice(0,5).map((c)=>`${c.fragment}\uFF08${c.reason}\uFF09`),i=e.length>n.length?` \u7B49 ${e.length} \u5904`:"";return`${n.join("\uFF1B")}${i}`}var td=new Map;function nv(e,n,i,c,p){let f=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((g)=>{let x=(b)=>{if(!td.delete(f))return;p?.removeEventListener("abort",I),g(b)},I=()=>{Zg(e,f),x("aborted")};if(td.set(f,{session:e,finish:x}),e.appendExtension({namespace:xu,kind:"requested",schemaVersion:1,payload:{id:f,sessionID:e.id,command:n.slice(0,4000),summary:c.slice(0,5).map(({fragment:b,reason:E})=>({fragment:b,reason:E})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)I();else p?.addEventListener("abort",I,{once:!0})})}function Zg(e,n){try{e.appendExtension({namespace:xu,kind:"cancelled",schemaVersion:1,payload:{id:n,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function ko(e,n,i){let c=td.get(n);if(!c||c.session!==e){if(!ov(e,n))return"unknown";return Zg(e,n),"expired"}return e.appendExtension({namespace:xu,kind:"answered",schemaVersion:1,payload:{id:n,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),c.finish(i?"approved":"denied"),"answered"}function ov(e,n){let i=!1;for(let c of e.entries()){if(c.type!=="extension"||c.namespace!==xu)continue;let p=c.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==n)continue;if(c.kind==="requested")i=!0;else if(c.kind==="answered"||c.kind==="cancelled")return!1}return i}function nd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${Yg(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 ze(e,n){let i=rd(e);if(!i.at(0))return;let p=Yg(i),f=K.getStore();if(f?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(n?.aborted)return`${nd(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let g=await nv(f,e,p,i,n);if(g==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${g==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{homedir as sv}from"os";import{join as Eu}from"path";function Pt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let n=sv();if(process.platform==="win32")return Eu(e.LOCALAPPDATA??Eu(n,"AppData","Local"),"basalt");if(process.platform==="darwin")return Eu(n,"Library","Application Support","basalt");return Eu(e.XDG_DATA_HOME??Eu(n,".local","share"),"basalt")}var cs={assign:0,create:0,clone:0,discard:0,update:0};function Ui(e,n,i){return e>=n&&e<=i}function ry(e){return e===8205}function iv(e){return Ui(e,55296,56319)}function ey(e){return Ui(e,127462,127487)}function ny(e){return Ui(e,65024,65039)}function oy(e){return Ui(e,768,879)||Ui(e,6832,6911)||Ui(e,7616,7679)||Ui(e,65056,65071)}function rm(e){return e>65535?2:1}function ty(e,n){while(n<e.length){let i=e.codePointAt(n);if(oy(i)||ny(i))n+=rm(i);else break}return n}function od(e,n){let i=e.codePointAt(n),c=n+rm(i);c=ty(e,c);while(c<e.length-1&&ry(e.codePointAt(c))){let p=e.codePointAt(c+1);c+=1+rm(p),c=ty(e,c)}if(ey(i)&&c<e.length&&ey(e.codePointAt(c)))c+=rm(e.codePointAt(c));return c}function sy(e){return e>=768&&(iv(e)||oy(e)||ny(e)||ry(e))}function iy(e){let n=0,i=0;while(i<e.length)i=od(e,i),n++;return n}function av(e,n){let i=0,c=0;while(c<e.length)if(c=od(e,c),++i>=n)return!0;return!1}function uv(e,n){let i=0,c=0;while(c<e.length)if(c=od(e,c),++i>n)return!1;return!0}function ay(e,n){if(n===0)return!0;if(e.length<n)return!1;let i=0;while(!0){if(sy(e.charCodeAt(i)))return av(e,n);if(++i>=n)return!0}}function uy(e,n){if(e.length<=n)return!0;let i=0;while(!0){if(sy(e.charCodeAt(i)))return uv(e,n);if(++i>n)return!1}}function Be(e){return Array.isArray(e)}function _r(e){return _(typeof e,"bigint")}function un(e){return _(typeof e,"boolean")}function sd(e){if(Gt(e)||!ms(e))return!1;let n=Function.prototype.toString.call(e);if(/^class\s/.test(n))return!0;if(/\[native code\]/.test(n))return!0;return!1}function ms(e){return _(typeof e,"function")}function nm(e){return Number.isInteger(e)}function mo(e){return _(e,null)}function Ot(e){return Number.isFinite(e)}function zo(e){return at(e)&&!Be(e)}function at(e){return _(typeof e,"object")&&!mo(e)}function gt(e){return _(typeof e,"string")}function id(e){return _(typeof e,"symbol")}function Gt(e){return _(e,void 0)}function _(e,n){return e===n}function Bi(e,n){return e>n}function Su(e,n){return e<n}function ps(e,n){return e<=n}function ba(e,n){return e>=n}function cy(e,n){if(_r(e)||_r(n))return BigInt(e)%BigInt(n)===0n;let i=0.0000000001;if(!Ot(e))return!0;if(nm(e)&&1/n%1===0)return!0;let c=e%n;return Math.min(Math.abs(c),Math.abs(c-n),Math.abs(c+n))<i}function my(e){if(!at(e))return!1;let n=globalThis.Object.getPrototypeOf(e);if(mo(n))return!1;return _(typeof n.constructor,"function")&&!(_(n.constructor,globalThis.Object)||_(n.constructor.name,"Object"))}function Gi(e){return _r(e)||un(e)||mo(e)||Ot(e)||gt(e)||Gt(e)}function mv(e){return iy(e)}function py(e,n){return uy(e,n)}function ly(e,n){return ay(e,n)}function nn(e,n,i){return e.every((c,p)=>p<n||i(c,p))}function Rn(e,n,i){let c=!0;return e.forEach((p,f)=>{if(f>=n&&!i(p,f))c=!1}),c}function Ea(e,n){return e.some((i,c)=>n(i,c))}function dy(e,n){let i=!1;return e.forEach((c,p)=>{if(n(c,p))i=!0}),i}function ad(e,n){return e.reduce((i,c,p)=>n(c,p)?++i:i,0)}function It(e,n,i){return _(e.length,0)?i():n(e[0],e.slice(1))}function wu(e){return _(e,"__proto__")||_(e,"constructor")||_(e,"prototype")}function le(e,n){return wu(n)?Object.prototype.hasOwnProperty.call(e,n):(n in e)}function ud(e){return Ee(e).map((n)=>[new RegExp(`^${n}$`),e[n]])}function cn(e){return Object.entries(e)}function Ee(e){return Object.getOwnPropertyNames(e)}function fy(e){return Object.getOwnPropertySymbols(e)}function cd(e){return Object.values(e)}function pv(e,n){if(!at(n))return!1;let i=Ee(e);return _(i.length,Ee(n).length)&&i.every((c)=>Sa(e[c],n[c]))}function lv(e,n){return Be(n)&&_(e.length,n.length)&&e.every((i,c)=>Sa(e[c],n[c]))}function Sa(e,n){return Be(e)?lv(e,n):at(e)?pv(e,n):_(e,n)}var dv=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function fv(e){return dv.test(e)}function bn(e,n){return`(${e} && ${n})`}function gr(e,n){return`(${e} || ${n})`}function Fn(e){return`!(${e})`}function om(e){return`Array.isArray(${e})`}function hy(e){return`typeof ${e} === "bigint"`}function hv(e){return`typeof ${e} === "boolean"`}function gv(e){return`Number.isInteger(${e})`}function yv(e){return`${e} === null`}function gy(e){return`Number.isFinite(${e})`}function yy(e){return bn(xy(e),Fn(om(e)))}function xy(e){return`typeof ${e} === "object" && ${e} !== null`}function Iy(e){return`typeof ${e} === "string"`}function xv(e){return`typeof ${e} === "symbol"`}function md(e){return`${e} === undefined`}function Iv(e){return`typeof ${e} === "function"`}function bv(e){return`Guard.IsConstructor(${e})`}function oo(e,n){return`${e} === ${n}`}function by(e,n){return`${e} > ${n}`}function pd(e,n){return`${e} < ${n}`}function Ki(e,n){return`${e} <= ${n}`}function Tu(e,n){return`${e} >= ${n}`}function Ev(e,n){return`Guard.IsMinLength(${e}, ${n})`}function Sv(e,n){return`Guard.IsMaxLength(${e}, ${n})`}function ls(e,n,i,c){return _(n,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${c}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${n}) || (${c}))`}function wv(e,n,i){return`${e}.some((${n[0]}, ${n[1]}) => ${i})`}function Tv(e,n,i){return`((value) => { let result = false; value.forEach((${n[0]}, ${n[1]}) => { if (${i}) result = true }); return result })(${e})`}function sm(e,n,i){return`${e}.reduce((result, ${n[0]}, ${n[1]}) => (${i}) ? ++result : result, 0)`}function Ey(e){return`Object.entries(${e})`}function Hi(e){return`Object.getOwnPropertyNames(${e})`}function Wi(e,n){return _(n,'"__proto__"')||_(n,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${n})`:`${n} in ${e}`}function Sy(e,n){return`Guard.IsDeepEqual(${e}, ${n})`}function Rv(e){return`[${e.join(", ")}]`}function Vs(e,n){return`((${e.join(", ")}) => ${n})`}function yr(e,n){return`${e}(${n.join(", ")})`}function ld(e,n){return`new ${e}(${n.join(", ")})`}function bt(e,n){return`${e}${fv(n)?`.${n}`:`[${De(n)}]`}`}function De(e){if(!Gi(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function kv(e,n,i){return`(${e} ? ${n} : ${i})`}function im(e){return`{ ${e.join("; ")}; }`}function vs(e,n){return`const ${e} = ${n}`}function wy(e,n){return`if(${e}) { ${n} }`}function am(e){return`return ${e}`}function kn(e){return _(e.length,0)?"true":e.reduce((n,i)=>bn(n,i))}function dd(e){return _(e.length,0)?"false":e.reduce((n,i)=>gr(n,i))}function Av(e,n){return`Guard.IsMultipleOf(${e}, ${n})`}function Cv(e){return e instanceof Boolean}function $v(e){return e instanceof Number}function Pv(e){return e instanceof String}function Ty(e){return globalThis.ArrayBuffer.isView(e)}function Ry(e){return e instanceof globalThis.RegExp}function Mv(e){return e instanceof globalThis.Date}function vv(e){return e instanceof globalThis.Set}function Ov(e){return e instanceof globalThis.Map}var Lv={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Vo(){return Lv}function Js(e){return Vo().immutableTypes?Object.freeze(e):e}function mn(e,n){return cs.assign+=1,Js({...e,...n})}function Nv(e){return e}function Dv(e){return le(e,"~kind")||le(e,"~unsafe")}function qv(e){let n={};for(let i of Ee(e)){if(wu(i))continue;let c=Object.getOwnPropertyDescriptor(e,i);if(c.value=zi(c.value),_(c.enumerable,!0))n[i]=c.value;else Object.defineProperty(n,i,c)}return n}function Fv(e){let n={};for(let i of Ee(e)){if(wu(i))continue;n[i]=zi(e[i])}for(let i of fy(e))n[i]=zi(e[i]);return n}function jv(e){return my(e)?Nv(e):Dv(e)?qv(e):Fv(e)}function Uv(e){return e.map((n)=>zi(n))}function Bv(e){return e.slice()}function Gv(e){return new RegExp(e.source,e.flags)}function Kv(e){return new Map(zi([...e.entries()]))}function Hv(e){return new Set(zi([...e.values()]))}function zi(e){return Ty(e)?Bv(e):Ry(e)?Gv(e):Ov(e)?Kv(e):vv(e)?Hv(e):Be(e)?Uv(e):at(e)?jv(e):e}function wa(e){return cs.clone+=1,zi(e)}function Wv(e,n){for(let i of Object.keys(n))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:n[i]});return e}function ky(e,n){return{...e,...n}}function Ct(e,n,i={}){cs.create+=1;let c=ky(n,i),p=Vo().enumerableKind?ky(c,e):Wv(c,e);return Js(p)}function Jo(e,n){cs.discard+=1;let i={};for(let c of Ee(e)){if(n.includes(c))continue;let p=Object.getOwnPropertyDescriptor(e,c);p.value=wa(p.value),Object.defineProperty(i,c,p)}return Js(i)}function Et(e,n,i){cs.update+=1;let c=Vo(),p=wa(e);for(let f of Object.keys(n))Object.defineProperty(p,f,{configurable:!0,writable:!0,enumerable:c.enumerableKind,value:n[f]});for(let f of Object.keys(i))Object.defineProperty(p,f,{configurable:!0,enumerable:!0,writable:!0,value:i[f]});return Js(p)}function Ae(e,n){return at(e)&&le(e,"~kind")&&_(e["~kind"],n)}function Ar(e){return at(e)}function Ne(e,n,i){return Ct({"~kind":"Deferred"},{type:"deferred",action:e,parameters:n,options:i},{})}function Qs(e){return Ae(e,"Deferred")}function zv(e){return Et(e,{"~readonly":!0},{})}function ku(e,n){return Et(zv(e),{},n)}function Ay(e,n,i,c){let p=de(e,n,i);return ku(p,c)}function Vv(e){return Et(e,{"~optional":!0},{})}function Au(e,n){return Et(Vv(e),{},n)}function Cy(e,n,i,c){let p=de(e,n,i);return Au(p,c)}function W(e,n){return Ct({"~kind":"Array"},{type:"array",items:e},n)}function St(e){return Ae(e,"Array")}function Ta(e){return Jo(e,["~kind","type","items"])}function ds(e,n,i={}){return Ct({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:n},i)}function Xr(e){return Ae(e,"Constructor")}function $y(e){return Jo(e,["~kind","type","parameters","instanceType"])}function fs(e,n,i={}){return Ct({["~kind"]:"Function"},{type:"function",parameters:e,returnType:n},i)}function Yr(e){return Ae(e,"Function")}function Py(e){return Jo(e,["~kind","type","parameters","returnType"])}function on(e,n){return Ct({["~kind"]:"Ref"},{$ref:e},n)}function jt(e){return Ae(e,"Ref")}function Xs(e,n){return Ct({"~kind":"Generic"},{type:"generic",parameters:e,expression:n})}function Ra(e){return Ae(e,"Generic")}function ka(e){return Ct({["~kind"]:"Any"},{},e)}function Cr(e){return Ae(e,"Any")}var My="(?!)";function zt(e){return Ct({"~kind":"Never"},{not:{}},e)}function so(e){return Ae(e,"Never")}function hs(e,n={}){return Ne("AddOptional",[e],n)}function Vi(e,n={}){return Au(e,n)}function o(e){return Vi(e)}function sn(e){return Ar(e)&&le(e,"~optional")}function vy(e){return Ee(e).filter((n)=>!sn(e[n]))}function um(e){return Ee(e)}function cm(e){return cd(e)}function s(e,n={}){let i=vy(e),c=i.length>0?{required:i}:{};return Ct({"~kind":"Object"},{type:"object",...c,properties:e},n)}function Qe(e){return Ae(e,"Object")}function Oy(e){return Jo(e,["~kind","type","properties","required"])}function wr(e){return Ct({["~kind"]:"Unknown"},{},e)}function Zr(e){return Ae(e,"Unknown")}function gs(e,n,i){let c=Ee(e).reduce((p,f)=>({...p,[f]:Et(e[f],{},{$id:f})}),{});return Ct({["~kind"]:"Cyclic"},{$defs:c,$ref:n},i)}function Qt(e){return Ae(e,"Cyclic")}function Br(e){return Et(e,{["~unsafe"]:null},{})}function mm(e){return zo(e)&&le(e,"~unsafe")&&mo(e["~unsafe"])}function En(e,n){return n[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Cu(...e){let[n,i]=En(e,{2:(c,p)=>[c,p,p],1:(c)=>[c,wr(),wr()]});return Ct({["~kind"]:"Infer"},{type:"infer",name:n,extends:i},{})}function en(e){return Ae(e,"Infer")}function Ji(e,n,i,c={}){return Ct({"~kind":"Dependent"},{if:e,then:n,else:i},c)}function Lr(e){return Ae(e,"Dependent")}function _y(e){return Jo(e,["~kind","if","then","else"])}function Ly(e){return zo(e)}function Ny(e){return Ee(e).filter((i)=>isNaN(i)).reduce((i,c)=>[...i,e[c]],[])}function Dy(e){return gt(e)||Ot(e)}function qy(e,n){let i=Ly(e)?Ny(e):e;return Ct({"~kind":"Enum"},{enum:i},n)}function tn(e){return Ae(e,"Enum")}function An(e,n={}){return Ct({"~kind":"Intersect"},{allOf:e},n)}function He(e){return Ae(e,"Intersect")}function Fy(e){return Jo(e,["~kind","allOf"])}var fd=void 0;function Jv(){try{return Uy("null")(),!0}catch{return!1}}function jy(){if(Gt(fd))fd=Jv();return fd&&Vo().useAcceleration}function Uy(...e){return new globalThis.Function(...e)}function Nr(){throw Error("Unreachable")}function Qv(e){let n=new Set,i=e;while(i&&i!==Object.prototype){for(let c of Reflect.ownKeys(i))if(c!=="constructor"&&typeof c!=="symbol")n.add(c);i=Object.getPrototypeOf(i)}return[...n]}function Xv(e){return typeof e==="number"}var Un;(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"})(Un||(Un={}));var Aa=BigInt("14695981039346656037"),[Yv,Zv]=[BigInt("1099511628211"),BigInt("18446744073709551616")],eO=Array.from({length:256}).map((e,n)=>BigInt(n)),Hy=new Float64Array(1),Wy=new DataView(Hy.buffer),zy=new Uint8Array(Hy.buffer);function gn(e){Aa=Aa^eO[e],Aa=Aa*Yv%Zv}function tO(e){gn(Un.Array);for(let n of e)Ys(n)}function rO(e){gn(Un.BigInt),Wy.setBigInt64(0,e);for(let n of zy)gn(n)}function Gy(e){gn(Un.Boolean),gn(e?1:0)}function nO(e){gn(Un.Constructor),Ys(e.toString())}function oO(e){gn(Un.Date),Ys(e.getTime())}function sO(e){gn(Un.Function),Ys(e.toString())}function iO(e){gn(Un.Null)}function Ky(e){gn(Un.Number),Wy.setFloat64(0,e,!0);for(let n of zy)gn(n)}function aO(e){gn(Un.Object);for(let n of Qv(e).sort())Ys(n),Ys(e[n])}function uO(e){gn(Un.RegExp),hd(e.toString())}var cO=new TextEncoder;function hd(e){gn(Un.String);for(let n of cO.encode(e))gn(n)}function mO(e){gn(Un.Symbol),Ys(e.toString())}function pO(e){gn(Un.TypeArray);let n=new Uint8Array(e.buffer);for(let i=0;i<n.length;i++)gn(n[i])}function lO(e){return gn(Un.Undefined)}function Ys(e){return Ty(e)?pO(e):Mv(e)?oO(e):Ry(e)?uO(e):Cv(e)?Gy(e.valueOf()):Pv(e)?hd(e.valueOf()):$v(e)?Ky(e.valueOf()):Xv(e)?Ky(e):Be(e)?tO(e):un(e)?Gy(e):_r(e)?rO(e):sd(e)?nO(e):mo(e)?iO(e):at(e)?aO(e):gt(e)?hd(e):id(e)?mO(e):Gt(e)?lO(e):ms(e)?sO(e):Nr()}function Vy(e){return Aa=BigInt("14695981039346656037"),Ys(e),Aa}function gd(e){return Vy(e).toString(16).padStart(16,"0")}function Jy(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 dO=Jy;function Qy(){return dO}class pm{constructor(e,n){this.type=e,this.decode=n}Encode(e){let n=this.type,i=Bn(n)?(f)=>this.decode(n["~codec"].decode(f)):this.decode,c=Bn(n)?(f)=>n["~codec"].encode(e(f)):e,p={decode:i,encode:c};return Et(this.type,{"~codec":p},{})}}class lm{constructor(e){this.type=e}Decode(e){return new pm(this.type,e)}}function dm(e){return new lm(e)}function Yy(e,n){return dm(e).Decode(n).Encode(()=>{throw Error("Encode not implemented")})}function Zy(e,n){return dm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(n)}function Bn(e){return Ar(e)&&le(e,"~codec")&&at(e["~codec"])&&le(e["~codec"],"encode")&&le(e["~codec"],"decode")}function ex(e){return Ca(e)}function Xi(e){return Ar(e)&&le(e,"~immutable")}function ys(e,n={}){return Ne("AddReadonly",[e],n)}function Yi(e,n={}){return ku(e,n)}function tx(e){return Yi(e)}function Zi(e){return Ar(e)&&le(e,"~readonly")}function hO(e,n){let i=fm(e)?[...e["~refine"],n]:[n];return Et(e,{"~refine":i},{})}function rx(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[p,f,()=>"Refine Error"]});return hO(n,{check:i,error:c})}function gO(e){return zo(e)&&le(e,"check")&&le(e,"error")&&ms(e.check)&&ms(e.error)}function fm(e){return Ar(e)&&le(e,"~refine")&&Be(e["~refine"])&&nn(e["~refine"],0,(n)=>gO(n))}var nx="-?(?:0|[1-9][0-9]*)n";function $u(e){return Ct({"~kind":"BigInt"},{type:"bigint"},e)}function io(e){return Ae(e,"BigInt")}function D(e){return Ct({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return Ae(e,"Boolean")}function Pu(e){return Ct({"~kind":"Identifier"},{name:e})}function ox(e){return Ae(e,"Identifier")}var hm="-?(?:0|[1-9][0-9]*)";function w(e){return Ct({"~kind":"Integer"},{type:"integer"},e)}function pn(e){return Ae(e,"Integer")}class sx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function yO(e){return _r(e)?"bigint":un(e)?"boolean":Ot(e)?"number":gt(e)?"string":(()=>{throw new sx(e)})()}function a(e,n){return Ct({"~kind":"Literal"},{type:yO(e),const:e},n)}function gm(e){return _r(e)||un(e)||Ot(e)||gt(e)}function ix(e){return yt(e)&&_r(e.const)}function ax(e){return yt(e)&&un(e.const)}function ym(e){return yt(e)&&Ot(e.const)}function xm(e){return yt(e)&>(e.const)}function yt(e){return Ae(e,"Literal")}function Pn(e){return Ct({"~kind":"Null"},{type:"null"},e)}function xs(e){return Ae(e,"Null")}var Im="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function J(e){return Ct({"~kind":"Number"},{type:"number"},e)}function Tr(e){return Ae(e,"Number")}function $a(e){return Ct({"~kind":"Symbol"},{type:"symbol"},e)}function Is(e){return Ae(e,"Symbol")}function ea(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[p,f,f],1:(p)=>[p,wr(),wr()]});return Ct({"~kind":"Parameter"},{name:n,extends:i,equals:c},{})}function ux(e){return Ae(e,"Parameter")}var bm=".*";function l(e){return Ct({"~kind":"String"},{type:"string"},e)}function rn(e){return Ae(e,"String")}function m(e,n={}){return Ct({"~kind":"Union"},{anyOf:e},n)}function be(e){return Ae(e,"Union")}function cx(e){return Jo(e,["~kind","anyOf"])}function Mu(e){let n=mx(e);return _(n.length,2)?n[0]:[]}function xO(e){return!0}function px(e){return It(e,(n,i)=>IO(n)?px(i):!1,()=>!0)}function lx(e){return _(e.length,0)?!1:px(e)}function IO(e){return be(e)?lx(e.anyOf):yt(e)?xO(e.const):!1}function Em(e){return lx(e)}function Sm(e){return Ct({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function dx(e,n,i=[]){return It(e,(c,p)=>dx(p,n,[...i,`${c}${n}`]),()=>i)}function bO(e,n){return _(e.length,0)?[`${n}`]:dx(e,n)}function fx(e,n,i=[]){return It(n,(c,p)=>fx(e,p,[...i,...hx(e,c)]),()=>i)}function hx(e,n){return be(n)?fx(e,n.anyOf):yt(n)?bO(e,n.const):Nr()}function gx(e,n){return It(n,(i,c)=>gx(hx(e,i),c),()=>e)}function EO(e){return e.map((n)=>a(n))}function SO(e){let n=gx([],e),i=EO(n);return m(i)}function wO(e){return _(e.length,0)?Nr():_(e.length,1)&&yt(e[0])?e[0]:SO(e)}function yd(e){let n=Mu(e);return _(n.length,0)?l():Em(n)?wO(n):Sm(e)}function vu(e){let n=yd(e);return cr(n)?l():n}function Zn(e,n){let c={[e]:n};return Ct({["~kind"]:"Record"},{type:"object",patternProperties:c})}function yx(e){return Zn(Qo,e)}function xx(e){return s({true:e,false:e})}function Dr(e,n={}){let[i,c,p]=[e,e.length,!1];return Ct({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:c},n)}function lt(e){return Ae(e,"Tuple")}function Ix(e){return Jo(e,["~kind","type","items","minItems","additionalItems"])}function TO(e){return Jo(e,["~readonly"])}function xd(e,n){return Et(TO(e),{},n)}function bx(e,n,i,c){let p=de(e,n,i);return xd(p,c)}function Ex(e,n={}){return Ne("RemoveReadonly",[e],n)}function Sx(e,n={}){return xd(e,n)}function RO(e){return Jo(e,["~optional"])}function Id(e,n){return Et(RO(e),{},n)}function wx(e,n,i,c){let p=de(e,n,i);return Id(p,c)}function Tx(e,n={}){return Ne("RemoveOptional",[e],n)}function wm(e,n={}){return Id(e,n)}function bd(e){return e.reduceRight((i,c,p)=>({[p]:c,...i}),{})}function Rx(e){let n=bd(e.items);return s(n)}function Ed(e){return Qe(e)||lt(e)}function kO(e,n){return Zi(e)?Zi(n)?!0:!1:!1}function AO(e,n){return sn(e)?sn(n)?!0:!1:!1}function CO(e,n){let i=kO(e,n),c=AO(e,n),p=Rr([e,n]),f=Sx(wm(p));return i&&c?Yi(Vi(f)):i&&!c?Yi(f):!i&&c?Vi(f):f}function $O(e,n,i){return i in e?i in n?CO(e[i],n[i]):e[i]:(i in n)?n[i]:zt()}function PO(e,n){return[...new Set([...Ee(e),...Ee(n)])].reduce((p,f)=>({...p,[f]:$O(e,n,f)}),{})}function kx(e){return Qe(e)?e.properties:lt(e)?bd(e.items):{}}function Ax(e,n){let i=kx(e),c=kx(n),p=PO(i,c);return s(p)}function MO(e,n){let i=Pa(e,n);return _(i,_u)?e:_(i,Lu)?n:_(i,Ou)?n:zt()}function vO(e,n){let i=Ed(e),c=Ed(n);return i&&c?Ax(e,n):i&&!c?e:!i&&c?n:MO(e,n)}function Cx(e,n){return so(e)?e:Cr(e)?e:Zr(e)?n:so(n)?n:Cr(n)?n:Zr(n)?e:vO(e,n)}function OO(e,n){return be(e)||be(n)}function _O(e,n){let i=So(e),c=So(n);return OO(i,c)?Rr([i,c]):Cx(i,c)}function $x(e,n,i=[]){return It(n,(c,p)=>$x(e,p,[...i,_O(c,e)]),()=>_(i.length,0)?[e]:i)}function Px(e,n,i=[]){return It(e,(c,p)=>Px(p,n,[...i,...Nu([c],n)]),()=>i)}function Nu(e,n=[]){return It(e,(i,c)=>be(i)?Nu(c,Px(i.anyOf,n)):Nu(c,$x(i,n)),()=>n)}function LO(e,n){let i=Sn({},e,n);return to(i)?[]:[e]}function Mx(e,n,i=[]){return It(e,(c,p)=>Mx(p,n,[...i,...LO(c,n)]),()=>i)}function Tm(e,n){let i=So(e),c=be(i)?i.anyOf:[i],p=Mx(c,n);return eo(p)}function Xo(e,n,i){let c=Rr([e,n]),p=Tm(i,e);return eo([c,p])}function Jn(e,n=[]){return It(e,(i,c)=>Jn(c,[...n,a(i)]),()=>eo(n))}function Rr(e){let n=Nu(e),i=Sd(n);return eo(i)}function vn(e){let n=vu(e);return So(n)}function eo(e){let n=Sd(e);return Zs(n)}function So(e){return Lr(e)?Xo(e.if,e.then,e.else):tn(e)?Jn(e.enum):He(e)?Rr(e.allOf):cr(e)?vn(e.pattern):be(e)?eo(e.anyOf):e}function Zs(e){return _(e.length,1)?e[0]:_(e.length,0)?zt():m(e)}function vx(e,n){let i=Jn(e);return ei(i,n)}function Ox(e,n){return Zn(ti,n)}function _x(e,n){let i=Rr(e);return ei(i,n)}function Lx(e,n){return gt(e)||Ot(e)?s({[e]:n}):_(e,!1)?s({false:n}):_(e,!0)?s({true:n}):s({})}function Nx(e,n){return Zn(Ma,n)}function Dx(e,n){return le(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?Zn(e.pattern.toString(),n):Zn(Qo,n)}function qx(e,n){let i=Mu(e);return Em(i)?ei(vn(e),n):Zn(e,n)}function NO(e){return be(e)?ta(e.anyOf):[e]}function ta(e,n=[]){return It(e,(i,c)=>ta(c,[...n,...NO(i)]),()=>n)}function DO(e){return e.some((n)=>rn(n)||Tr(n)||pn(n))}function qO(e,n){return _(DO(e),!0)?Zn(Qo,n):void 0}function FO(e,n){return e.reduce((i,c)=>yt(c)&&(gt(c.const)||Ot(c.const))?{...i,[c.const]:n}:i,{})}function jO(e,n){let i=FO(e,n);return s(i)}function Fx(e,n){let i=ta(e),c=qO(i,n);return Ar(c)?c:jO(i,n)}function ei(e,n){return Cr(e)?yx(n):Wn(e)?xx(n):tn(e)?vx(e.enum,n):pn(e)?Ox(e,n):He(e)?_x(e.allOf,n):yt(e)?Lx(e.const,n):Tr(e)?Nx(e,n):be(e)?Fx(e.anyOf,n):rn(e)?Dx(e,n):cr(e)?qx(e.pattern,n):s({})}function wd(e,n,i){return ct([e])?Et(ei(e,n),{},i):Rm(e,n,i)}function jx(e,n,i,c,p){let f=de(e,n,i),g=de(e,n,c);return wd(f,g,p)}var ti=`^${hm}$`,Ma=`^${Im}$`,Qo=`^${bm}$`;function Rm(e,n,i={}){return Ne("Record",[e,n],i)}function bs(e,n,i={}){return wd(e,n,i)}function Ux(e,n){return Zn(e,n)}function km(e){return _(e,Qo)?l():_(e,ti)?w():_(e,Ma)?J():yd(e)}function ln(e){return Ee(e.patternProperties)[0]}function ri(e){let n=ln(e);return km(n)}function lr(e){return e.patternProperties[ln(e)]}function Kt(e){return Ae(e,"Record")}function ra(e){return Ct({"~kind":"Rest"},{type:"rest",items:e},{})}function ni(e){return Ae(e,"Rest")}function Am(e){return Ct({["~kind"]:"This"},{$ref:"#"},e)}function Cm(e){return Ae(e,"This")}function va(e){return Ct({"~kind":"Undefined"},{type:"undefined"},e)}function Yo(e){return Ae(e,"Undefined")}function $m(e){return Ct({"~kind":"Void"},{type:"void"},e)}function ao(e){return Ae(e,"Void")}function BO(e,n){return _(e,"Array")?W(n[0]):_(e,"Capitalize")?Mm(n[0]):_(e,"ConstructorParameters")?Nm(n[0]):_(e,"Evaluate")?oE(n[0]):_(e,"Exclude")?Dm(n[0],n[1]):_(e,"Extract")?qm(n[0],n[1]):_(e,"Index")?ju(n[0],n[1]):_(e,"InstanceType")?Fm(n[0]):_(e,"Lowercase")?vm(n[0]):_(e,"NonNullable")?jm(n[0]):_(e,"Omit")?Um(n[0],n[1]):_(e,"Parameters")?Bm(n[0]):_(e,"Partial")?Gm(n[0]):_(e,"Pick")?Km(n[0],n[1]):_(e,"Readonly")?Hm(n[0]):_(e,"KeyOf")?Uu(n[0]):_(e,"Record")?Rm(n[0],n[1]):_(e,"Required")?Wm(n[0]):_(e,"ReturnType")?zm(n[0]):_(e,"Uncapitalize")?Om(n[0]):_(e,"Uppercase")?_m(n[0]):Fu(on(e),n)}function na(){throw Error("Unreachable")}function Wx(e,n=[]){return It(e,(i,c)=>Wx(c,[...n,i[1]]),()=>n)}function Os(e){return _(e.length,3)?[e[0],...Wx(e[1])]:[]}function zx(e){return ea(e[0],e[2],e[4])}function Vx(e){return ea(e[0],e[2],e[2])}function Jx(e){return ea(e[0],wr(),e[2])}function Qx(e){return ea(e,wr(),wr())}function Xx(e){return e}function Yx(e){return Os(e)}function Zx(e){return e[1]}function eI(e){return Os(e)}function tI(e){return e[1]}function rI(e){return BO(e[0],e[1])}function nI(e){return null}function oI(e){return l()}function sI(e){return J()}function iI(e){return D()}function aI(e){return va()}function uI(e){return Pn()}function cI(e){return w()}function mI(e){return $u()}function pI(e){return wr()}function lI(e){return ka()}function dI(e){return s({})}function fI(e){return zt()}function hI(e){return $a()}function gI(e){return $m()}function yI(e){return Am()}function xI(e){return a(BigInt(e))}function II(e){return a(_(e,"true"))}function bI(e){return a(parseFloat(e))}function EI(e){return a(e)}function SI(e){return e[1]}function wI(e){return a(e)}function TI(e){return _(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function RI(e){return e[1]}function kI(e){return Pm(e)}function AI(e){return _(e.length,6)?Ji(e[1],e[3],e[5]):Ji(e[1],e[3],wr())}function CI(e){return e.length>0}function $I(e){return e.reduce((n,i)=>_(i.length,3)?[...n,[i[1]]]:[...n,[]],[])}function PI(e){return _(e.length,6)?[e[1],e[3],e[5]]:[]}function MI(e){return Be(e)&&_(e.length,3)?e[1]:e}function vI(e){return _(e.length,2)?e[1]:[]}function Bx(e,n){return n.reduce((i,c)=>{let p=c;return _(p.length,1)?ju(i,p[0]):_(p.length,0)?W(i):na()},e)}function Gx(e,n){return _(n.length,3)?Lm(e,n[0],n[1],n[2]):e}function GO(e,n){return Be(n)&&_(n.length,0)?e:Vm(e,n)}function OI(e){let[n,i,c,p,f]=e;return GO(n?Gx(Uu(Bx(i,c)),p):Gx(Bx(i,c),p),f)}function Td(e,n){return _(n.length,3)?(()=>{let[i,c,p]=n,f=Td(c,p);if(_(i,"&"))return He(f)?An([e,...f.allOf]):An([e,f]);if(_(i,"|"))return be(f)?m([e,...f.anyOf]):m([e,f]);na()})():e}function _I(e){return e}function LI(e){let[n,i]=e;return Td(n,i)}function NI(e){return e}function DI(e){let[n,i]=e;return Td(n,i)}function qI(e){return nE(e[1])}function FI(e){return e[1]}function jI(e){return Xs(e[0],e[2])}function UI(e){return _(e.length,4)?Cu(e[1],e[3]):_(e.length,2)?Cu(e[1],wr()):na()}function BI(e){return e}function GI(e){return`${e}`}function KI(e){return e}function HI(e){return e}function WI(e){return pn(e[3])?ti:Tr(e[3])?Ma:Is(e[3])?Qo:rn(e[3])?Qo:na()}function zI(e){return e}function VI(e){return e.length>0}function JI(e){return e.length>0}function QI(e){let[n,i,c,p,f]=e;return{[i]:n&&c?ys(hs(f)):n&&!c?ys(f):!n&&c?hs(f):f}}function XI(e){return e}function YI(e){return Os(e)}function ZI(e){return e.reduce((n,i)=>le(i,ti)||le(i,Ma)||le(i,Qo)?[n[0],mn(n[1],i)]:[mn(n[0],i),n[1]],[{},{}])}function eb(e){return ZI(e[1])}function tb(e){let[n,i]=e,c=_(Ee(i).length,0)?{}:{patternProperties:i};return s(n,c)}function rb(e){return _(e.length,5)?ys(hs(e[4])):_(e.length,3)?e[2]:_(e.length,4)?_(e[2],"readonly")?ys(e[3]):hs(e[3]):na()}function nb(e){if(!Be(e)||!_(e.length,3))return e;let[n,i,c]=e;return n&&c?ys(hs(i)):n&&!c?ys(i):!n&&c?hs(i):i}function ob(e){return _(e.length,2)?ra(e[1]):_(e.length,1)?e[0]:na()}function sb(e){return Os(e)}function ib(e){return Dr(e[1])}function ab(e){return ys(hs(e[4]))}function ub(e){return ys(e[3])}function cb(e){return hs(e[3])}function mb(e){return e[2]}function pb(e){return e}function lb(e){return _(e.length,2)?ra(e[1]):_(e.length,1)?e[0]:na()}function db(e){return Os(e)}function fb(e){return fs(e[1],e[4])}function hb(e){return ds(e[2],e[5])}function Kx(e,n){return _(e,"remove")?Ex(n):_(e,"add")?ys(n):n}function gb(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function Hx(e,n){return _(e,"remove")?Tx(n):_(e,"add")?hs(n):n}function yb(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function xb(e){return _(e.length,2)?[e[1]]:[]}function Ib(e){return Be(e[6])&&_(e[6].length,1)?Du(Pu(e[3]),e[5],e[6][0],Kx(e[1],Hx(e[8],e[10]))):Du(Pu(e[3]),e[5],on(e[3]),Kx(e[1],Hx(e[8],e[10])))}function bb(e){return on(e)}function Eb(e){return BigInt(e)}function Sb(e){return parseFloat(e)}function wb(e){return _(e,"true")}function Tb(e){return e}function Rb(e){return null}function kb(e){return}function Ab(e){return{[e[0]]:e[2]}}function Cb(e){return Os(e)}function KO(e){return e.reduce((n,i)=>mn(n,i),{})}function $b(e){return KO(e[1])}function Pb(e){return Os(e)}function Mb(e){return e[1]}function vb(e){return e}function Ob(e){return $u()}function _b(e){return l()}function Lb(e){return J()}function Nb(e){return w()}function Db(e){return zt()}function qb(e){return a(e)}function Fb(e){return e}function jb(e){return m(e[1])}function Ub(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Bb(e){return[e[0],...e[1]]}function Gb(e){return e}function Kb(e){return e[1]}function Hb(e){return Os(e)}function Wb(e){return _(e.length,2)?e[1]:[]}function zb(e){let n=e[2],i=e[3],[c,p]=e[4],f=_(Ee(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Xs(n,qu(i,c,f))}}function Vb(e){let n=e[2],[i,c]=e[3],p=_(Ee(c).length,0)?{}:{patternProperties:c};return{[e[1]]:qu(n,i,p)}}function Jb(e){return{[e[1]]:Xs(e[2],e[4])}}function Qb(e){return{[e[1]]:e[3]}}function Xb(e){return null}function Yb(e){return e}function Zb(e){return Os(e)}function eE(e){return e[1]}function tE(e){let[n,i]=[e[0],e[1]];return sE(mn(n,ZI(i)[0]))}function rE(e){return e}function Bu(e){return _(e.length,2)}function wt(e,n,i){return Bu(e)?n(e[0],e[1]):i()}function zO(e,n){return _(n.indexOf(e),0)?[e,n.slice(e.length)]:[]}function Mr(e,n){for(let i=0;i<e.length;i++){let c=zO(e[i],n);if(Bu(c))return c}return[]}function Rd(e,n){return Array.from({length:n-e+1},(i,c)=>String.fromCharCode(e+c))}var iE=[...Rd(97,122),...Rd(65,90)],kd="0",Ad=Rd(49,57),Oa=[kd,...Ad],aE=" ",_a=`
|
|
15
|
+
`;var oi="_",Jm=".",uE="$",Qm="-";var cE="//",mE="/*",JO="*/";function pE(e){let n=e.indexOf(JO);return _(n,-1)?"":e.slice(n+2)}function lE(e){let n=e.indexOf(_a);return _(n,-1)?"":e.slice(n)}function QO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Xm(e){let n=QO(e);return n.startsWith(mE)?Xm(pE(n.slice(2))):n.startsWith(cE)?Xm(lE(n.slice(2))):n}function yn(e){let n=e.trimStart();return n.startsWith(mE)?yn(pE(n.slice(2))):n.startsWith(cE)?yn(lE(n.slice(2))):n}function Ym(e,n){return wt(Mr([e],n),(i,c)=>[i,c],()=>["",n])}function XO(e,n){return e.includes(n)}function La(e,n,i,c=""){return wt(Mr(e,i),(p,f)=>XO(n,p)?La(e,n,f,c):La(e,n,f,`${c}${p}`),()=>[c,i])}function YO(e){return Mr(Ad,e)}var ZO=[...Oa,oi];function e_(e){return La(ZO,[oi],e)}function t_(e){return wt(Mr([kd],e),(n,i)=>[n,i],()=>wt(YO(e),(n,i)=>wt(e_(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[]))}function Zm(e){return t_(yn(e))}function r_(e){return Ym(Qm,e)}function n_(e){return wt(r_(e),(n,i)=>wt(Zm(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function dE(e){return n_(yn(e))}function o_(e){return wt(dE(e),(n,i)=>wt(Mr(["n"],i),(c,p)=>[`${n}`,p],()=>[]),()=>[])}function Cd(e){return o_(e)}function $d(e,n){return Mr([e],n)}function ee(e,n){return _(e,"")?["",n]:e.startsWith(_a)?$d(e,Xm(n)):e.startsWith(aE)?$d(e,n):$d(e,yn(n))}var fE=[...iE,oi,uE];function s_(e){return Mr(fE,e)}var i_=[...fE,...Oa];function hE(e,n=""){return wt(Mr(i_,e),(i,c)=>hE(c,`${n}${i}`),()=>[n,e])}function a_(e){return wt(s_(e),(n,i)=>wt(hE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function qr(e){return a_(yn(e))}var u_=[...Oa,oi];function c_(e){return Bu(Mr([Jm],e))}function gE(e){return wt(La(u_,[oi],e),(n,i)=>_(n,"")?[]:[n,i],()=>[])}function m_(e){return wt(Mr([Jm],e),(n,i)=>wt(gE(i),(c,p)=>[`0${n}${c}`,p],()=>[]),()=>[])}function p_(e){return wt(Zm(e),(n,i)=>wt(Mr([Jm],i),(c,p)=>wt(gE(p),(f,g)=>[`${n}${c}${f}`,g],()=>[`${n}`,p]),()=>[`${n}`,i]),()=>[])}function l_(e){return c_(e)?m_(e):p_(e)}function yE(e){return l_(yn(e))}function d_(e){return Ym(Qm,e)}function f_(e){return wt(d_(e),(n,i)=>wt(yE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function ep(e){return f_(yn(e))}function h_(e){return _(e,"")?[]:[e.slice(0,1),e.slice(1)]}function xE(e,n){return It(e,(i,c)=>n.startsWith(i)?!0:xE(c,n),()=>!1)}function si(e,n,i=""){return wt(h_(n),(c,p)=>xE(e,n)?[i,n]:si(e,p,`${i}${c}`),()=>[])}function g_(e,n,i){return wt(Mr([e],i),(c,p)=>wt(si([n],p),(f,g)=>wt(Mr([n],g),(x,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function y_(e,n,i){return wt(Mr([e],i),(c,p)=>wt(si([_a,n],p),(f,g)=>wt(Mr([n],g),(x,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function IE(e,n,i,c){return i?g_(e,n,yn(c)):y_(e,n,yn(c))}function x_(e,n){return Mr(e,n)}function I_(e,n){return IE(e,e,!1,n)}function b_(e,n){return wt(x_(e,n),(i,c)=>I_(i,`${i}${c}`),()=>[])}function tp(e,n){return b_(e,yn(n))}function bE(e,n){return wt(si(e,n),(i,c)=>_(i,"")?[]:[i,c],()=>[])}var S=(e,n,i=()=>[])=>e.length===2?n(e):i(),S_=(e)=>S(S(qr(e),([n,i])=>S(ee("extends",i),([c,p])=>S(Mt(p),([f,g])=>S(ee("=",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[zx(n),i]),w_=(e)=>S(S(qr(e),([n,i])=>S(ee("extends",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Vx(n),i]),T_=(e)=>S(S(qr(e),([n,i])=>S(ee("=",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Jx(n),i]),R_=(e)=>S(qr(e),([n,i])=>[Qx(n),i]),wE=(e)=>S(S(S_(e),([n,i])=>[n,i],()=>S(w_(e),([n,i])=>[n,i],()=>S(T_(e),([n,i])=>[n,i],()=>S(R_(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[Xx(n),i]),TE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(wE(c),([p,f])=>[[i,p],f])),([i,c])=>TE(c,[...n,i]),()=>[n,e]),k_=(e)=>S(S(S(wE(e),([n,i])=>S(TE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Yx(n),i]),vd=(e)=>S(S(ee("<",e),([n,i])=>S(k_(i),([c,p])=>S(ee(">",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Zx(n),i]),RE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(Mt(c),([p,f])=>[[i,p],f])),([i,c])=>RE(c,[...n,i]),()=>[n,e]),A_=(e)=>S(S(S(Mt(e),([n,i])=>S(RE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[eI(n),i]),C_=(e)=>S(S(ee("<",e),([n,i])=>S(A_(i),([c,p])=>S(ee(">",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[tI(n),i]),$_=(e)=>S(S(qr(e),([n,i])=>S(C_(i),([c,p])=>[[n,c],p])),([n,i])=>[rI(n),i]),kE=(e)=>S(S(S(ee(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[nI(n),i]),AE=(e)=>S(ee("string",e),([n,i])=>[oI(n),i]),CE=(e)=>S(ee("number",e),([n,i])=>[sI(n),i]),P_=(e)=>S(ee("boolean",e),([n,i])=>[iI(n),i]),M_=(e)=>S(ee("undefined",e),([n,i])=>[aI(n),i]),v_=(e)=>S(ee("null",e),([n,i])=>[uI(n),i]),$E=(e)=>S(ee("integer",e),([n,i])=>[cI(n),i]),O_=(e)=>S(ee("bigint",e),([n,i])=>[mI(n),i]),__=(e)=>S(ee("unknown",e),([n,i])=>[pI(n),i]),L_=(e)=>S(ee("any",e),([n,i])=>[lI(n),i]),N_=(e)=>S(ee("object",e),([n,i])=>[dI(n),i]),D_=(e)=>S(ee("never",e),([n,i])=>[fI(n),i]),PE=(e)=>S(ee("symbol",e),([n,i])=>[hI(n),i]),q_=(e)=>S(ee("void",e),([n,i])=>[gI(n),i]),F_=(e)=>S(ee("this",e),([n,i])=>[yI(n),i]),j_=(e)=>S(S(ee("${",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("}",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[SI(n),i]),Pd=(e)=>S(si(["${","`"],e),([n,i])=>[wI(n),i]),ME=(e)=>S(S(S(Pd(e),([n,i])=>S(j_(i),([c,p])=>S(ME(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S(S(Pd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(Pd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[TI(n),i]),Od=(e)=>S(S(ee("`",e),([n,i])=>S(ME(i),([c,p])=>S(ee("`",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[RI(n),i]),U_=(e)=>S(Od(e),([n,i])=>[kI(n),i]),B_=(e)=>S(S(S(ee("if",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("then",p),([f,g])=>S(Mt(g),([x,I])=>S(ee("else",I),([b,E])=>S(Mt(E),([T,k])=>[[n,c,f,x,b,T],k])))))),([n,i])=>[n,i],()=>S(S(ee("if",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("then",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>[])),([n,i])=>[AI(n),i]),G_=(e)=>S(Cd(e),([n,i])=>[xI(n),i]),K_=(e)=>S(S(ee("true",e),([n,i])=>[n,i],()=>S(ee("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[II(n),i]),H_=(e)=>S(ep(e),([n,i])=>[bI(n),i]),W_=(e)=>S(tp(["'",'"'],e),([n,i])=>[EI(n),i]),z_=(e)=>S(S(S(ee("keyof",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[CI(n),i]),vE=(e,n=[])=>S(S(S(ee("[",e),([i,c])=>S(Mt(c),([p,f])=>S(ee("]",f),([g,x])=>[[i,p,g],x]))),([i,c])=>[i,c],()=>S(S(ee("[",e),([i,c])=>S(ee("]",c),([p,f])=>[[i,p],f])),([i,c])=>[i,c],()=>[])),([i,c])=>vE(c,[...n,i]),()=>[n,e]),V_=(e)=>S(vE(e),([n,i])=>[$I(n),i]),J_=(e)=>S(S(S(ee("extends",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("?",p),([f,g])=>S(Mt(g),([x,I])=>S(ee(":",I),([b,E])=>S(Mt(E),([T,k])=>[[n,c,f,x,b,T],k])))))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[PI(n),i]),Q_=(e)=>S(S(S(ee("(",e),([n,i])=>S(Mt(i),([c,p])=>S(ee(")",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S(AE(e),([n,i])=>[n,i],()=>S(CE(e),([n,i])=>[n,i],()=>S(P_(e),([n,i])=>[n,i],()=>S(M_(e),([n,i])=>[n,i],()=>S(v_(e),([n,i])=>[n,i],()=>S($E(e),([n,i])=>[n,i],()=>S(O_(e),([n,i])=>[n,i],()=>S(__(e),([n,i])=>[n,i],()=>S(L_(e),([n,i])=>[n,i],()=>S(N_(e),([n,i])=>[n,i],()=>S(D_(e),([n,i])=>[n,i],()=>S(PE(e),([n,i])=>[n,i],()=>S(q_(e),([n,i])=>[n,i],()=>S(F_(e),([n,i])=>[n,i],()=>S(G_(e),([n,i])=>[n,i],()=>S(K_(e),([n,i])=>[n,i],()=>S(H_(e),([n,i])=>[n,i],()=>S(W_(e),([n,i])=>[n,i],()=>S(U_(e),([n,i])=>[n,i],()=>S(B_(e),([n,i])=>[n,i],()=>S(aL(e),([n,i])=>[n,i],()=>S(mL(e),([n,i])=>[n,i],()=>S(gL(e),([n,i])=>[n,i],()=>S(hL(e),([n,i])=>[n,i],()=>S(bL(e),([n,i])=>[n,i],()=>S($_(e),([n,i])=>[n,i],()=>S(EL(e),([n,i])=>[n,i],()=>[])))))))))))))))))))))))))))),([n,i])=>[MI(n),i]),X_=(e)=>S(S(S(ee("with",e),([n,i])=>S(JE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[vI(n),i]),OE=(e)=>S(S(z_(e),([n,i])=>S(Q_(i),([c,p])=>S(V_(p),([f,g])=>S(J_(g),([x,I])=>S(X_(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[OI(n),i]),_E=(e)=>S(S(S(ee("&",e),([n,i])=>S(OE(i),([c,p])=>S(_E(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[_I(n),i]),LE=(e)=>S(S(OE(e),([n,i])=>S(_E(i),([c,p])=>[[n,c],p])),([n,i])=>[LI(n),i]),NE=(e)=>S(S(S(ee("|",e),([n,i])=>S(LE(i),([c,p])=>S(NE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[NI(n),i]),rp=(e)=>S(S(LE(e),([n,i])=>S(NE(i),([c,p])=>[[n,c],p])),([n,i])=>[DI(n),i]),Y_=(e)=>S(S(ee("readonly",e),([n,i])=>S(rp(i),([c,p])=>[[n,c],p])),([n,i])=>[qI(n),i]),Z_=(e)=>S(S(ee("|",e),([n,i])=>S(rp(i),([c,p])=>[[n,c],p])),([n,i])=>[FI(n),i]),eL=(e)=>S(S(vd(e),([n,i])=>S(ee("=",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[jI(n),i]),tL=(e)=>S(S(S(ee("infer",e),([n,i])=>S(qr(i),([c,p])=>S(ee("extends",p),([f,g])=>S(rp(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>S(S(ee("infer",e),([n,i])=>S(qr(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>[])),([n,i])=>[UI(n),i]),Mt=(e)=>S(S(tL(e),([n,i])=>[n,i],()=>S(Z_(e),([n,i])=>[n,i],()=>S(Y_(e),([n,i])=>[n,i],()=>S(rp(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[BI(n),i]),rL=(e)=>S(ep(e),([n,i])=>[GI(n),i]),nL=(e)=>S(qr(e),([n,i])=>[KI(n),i]),oL=(e)=>S(tp(["'",'"'],e),([n,i])=>[HI(n),i]),sL=(e)=>S(S(ee("[",e),([n,i])=>S(qr(i),([c,p])=>S(ee(":",p),([f,g])=>S(S($E(g),([x,I])=>[x,I],()=>S(CE(g),([x,I])=>[x,I],()=>S(AE(g),([x,I])=>[x,I],()=>S(PE(g),([x,I])=>[x,I],()=>[])))),([x,I])=>S(ee("]",I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[WI(n),i]),DE=(e)=>S(S(rL(e),([n,i])=>[n,i],()=>S(nL(e),([n,i])=>[n,i],()=>S(oL(e),([n,i])=>[n,i],()=>S(sL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[zI(n),i]),qE=(e)=>S(S(S(ee("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[VI(n),i]),FE=(e)=>S(S(S(ee("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[JI(n),i]),jE=(e)=>S(S(qE(e),([n,i])=>S(DE(i),([c,p])=>S(FE(p),([f,g])=>S(ee(":",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[QI(n),i]),np=(e)=>S(S(S(ee(",",e),([n,i])=>S(ee(`
|
|
16
|
+
`,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee(";",e),([n,i])=>S(ee(`
|
|
17
|
+
`,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee(",",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(ee(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(ee(`
|
|
18
|
+
`,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))))),([n,i])=>[XI(n),i]),UE=(e,n=[])=>S(S(np(e),([i,c])=>S(jE(c),([p,f])=>[[i,p],f])),([i,c])=>UE(c,[...n,i]),()=>[n,e]),iL=(e)=>S(S(S(jE(e),([n,i])=>S(UE(i),([c,p])=>S(S(np(p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[YI(n),i]),_d=(e)=>S(S(ee("{",e),([n,i])=>S(iL(i),([c,p])=>S(ee("}",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[eb(n),i]),aL=(e)=>S(_d(e),([n,i])=>[tb(n),i]),uL=(e)=>S(S(S(qr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(ee("readonly",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[n,i],()=>S(S(qr(e),([n,i])=>S(ee(":",i),([c,p])=>S(ee("readonly",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>S(S(qr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>S(S(qr(e),([n,i])=>S(ee(":",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>[])))),([n,i])=>[rb(n),i]),EE=(e)=>S(S(uL(e),([n,i])=>[n,i],()=>S(S(qE(e),([n,i])=>S(Mt(i),([c,p])=>S(FE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>[])),([n,i])=>[nb(n),i]),BE=(e)=>S(S(S(ee("...",e),([n,i])=>S(EE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(EE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[ob(n),i]),GE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(BE(c),([p,f])=>[[i,p],f])),([i,c])=>GE(c,[...n,i]),()=>[n,e]),cL=(e)=>S(S(S(BE(e),([n,i])=>S(GE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[sb(n),i]),mL=(e)=>S(S(ee("[",e),([n,i])=>S(cL(i),([c,p])=>S(ee("]",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[ib(n),i]),pL=(e)=>S(S(qr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(ee("readonly",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[ab(n),i]),lL=(e)=>S(S(qr(e),([n,i])=>S(ee(":",i),([c,p])=>S(ee("readonly",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[ub(n),i]),dL=(e)=>S(S(qr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[cb(n),i]),fL=(e)=>S(S(qr(e),([n,i])=>S(ee(":",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[mb(n),i]),SE=(e)=>S(S(pL(e),([n,i])=>[n,i],()=>S(lL(e),([n,i])=>[n,i],()=>S(dL(e),([n,i])=>[n,i],()=>S(fL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[pb(n),i]),KE=(e)=>S(S(S(ee("...",e),([n,i])=>S(SE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(SE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[lb(n),i]),HE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(KE(c),([p,f])=>[[i,p],f])),([i,c])=>HE(c,[...n,i]),()=>[n,e]),WE=(e)=>S(S(S(KE(e),([n,i])=>S(HE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[db(n),i]),hL=(e)=>S(S(ee("(",e),([n,i])=>S(WE(i),([c,p])=>S(ee(")",p),([f,g])=>S(ee("=>",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[fb(n),i]),gL=(e)=>S(S(ee("new",e),([n,i])=>S(ee("(",i),([c,p])=>S(WE(p),([f,g])=>S(ee(")",g),([x,I])=>S(ee("=>",I),([b,E])=>S(Mt(E),([T,k])=>[[n,c,f,x,b,T],k])))))),([n,i])=>[hb(n),i]),yL=(e)=>S(S(S(ee("+",e),([n,i])=>S(ee("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("-",e),([n,i])=>S(ee("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[gb(n),i]),xL=(e)=>S(S(S(ee("+",e),([n,i])=>S(ee("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("-",e),([n,i])=>S(ee("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[yb(n),i]),IL=(e)=>S(S(S(ee("as",e),([n,i])=>S(Mt(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[xb(n),i]),bL=(e)=>S(S(ee("{",e),([n,i])=>S(yL(i),([c,p])=>S(ee("[",p),([f,g])=>S(qr(g),([x,I])=>S(ee("in",I),([b,E])=>S(Mt(E),([T,k])=>S(IL(k),([A,L])=>S(ee("]",L),([q,Y])=>S(xL(Y),([j,V])=>S(ee(":",V),([X,se])=>S(Mt(se),([Z,z])=>S(kE(z),([ce,he])=>S(ee("}",he),([ve,fe])=>[[n,c,f,x,b,T,A,q,j,X,Z,ce,ve],fe]))))))))))))),([n,i])=>[Ib(n),i]),EL=(e)=>S(qr(e),([n,i])=>[bb(n),i]),SL=(e)=>S(Cd(e),([n,i])=>[Eb(n),i]),wL=(e)=>S(ep(e),([n,i])=>[Sb(n),i]),TL=(e)=>S(S(ee("true",e),([n,i])=>[n,i],()=>S(ee("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[wb(n),i]),RL=(e)=>S(tp(['"',"'"],e),([n,i])=>[Tb(n),i]),kL=(e)=>S(ee("null",e),([n,i])=>[Rb(n),i]),AL=(e)=>S(ee("undefined",e),([n,i])=>[kb(n),i]),zE=(e)=>S(S(DE(e),([n,i])=>S(ee(":",i),([c,p])=>S(Ld(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Ab(n),i]),VE=(e,n=[])=>S(S(np(e),([i,c])=>S(zE(c),([p,f])=>[[i,p],f])),([i,c])=>VE(c,[...n,i]),()=>[n,e]),CL=(e)=>S(S(S(zE(e),([n,i])=>S(VE(i),([c,p])=>S(S(np(p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Cb(n),i]),JE=(e)=>S(S(ee("{",e),([n,i])=>S(CL(i),([c,p])=>S(ee("}",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[$b(n),i]),QE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(Ld(c),([p,f])=>[[i,p],f])),([i,c])=>QE(c,[...n,i]),()=>[n,e]),$L=(e)=>S(S(S(Ld(e),([n,i])=>S(QE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Pb(n),i]),PL=(e)=>S(S(ee("[",e),([n,i])=>S($L(i),([c,p])=>S(ee("]",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Mb(n),i]),Ld=(e)=>S(S(SL(e),([n,i])=>[n,i],()=>S(wL(e),([n,i])=>[n,i],()=>S(TL(e),([n,i])=>[n,i],()=>S(RL(e),([n,i])=>[n,i],()=>S(kL(e),([n,i])=>[n,i],()=>S(AL(e),([n,i])=>[n,i],()=>S(JE(e),([n,i])=>[n,i],()=>S(PL(e),([n,i])=>[n,i],()=>[])))))))),([n,i])=>[vb(n),i]),ML=(e)=>S(ee("-?(?:0|[1-9][0-9]*)n",e),([n,i])=>[Ob(n),i]),vL=(e)=>S(ee(".*",e),([n,i])=>[_b(n),i]),OL=(e)=>S(ee("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([n,i])=>[Lb(n),i]),_L=(e)=>S(ee("-?(?:0|[1-9][0-9]*)",e),([n,i])=>[Nb(n),i]),LL=(e)=>S(ee("(?!)",e),([n,i])=>[Db(n),i]),NL=(e)=>S(bE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([n,i])=>[qb(n),i]),DL=(e)=>S(S(ML(e),([n,i])=>[n,i],()=>S(vL(e),([n,i])=>[n,i],()=>S(OL(e),([n,i])=>[n,i],()=>S(_L(e),([n,i])=>[n,i],()=>S(LL(e),([n,i])=>[n,i],()=>S(qL(e),([n,i])=>[n,i],()=>S(NL(e),([n,i])=>[n,i],()=>[]))))))),([n,i])=>[Fb(n),i]),qL=(e)=>S(S(ee("(",e),([n,i])=>S(Nd(i),([c,p])=>S(ee(")",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[jb(n),i]),XE=(e)=>S(S(S(Md(e),([n,i])=>S(ee("|",i),([c,p])=>S(XE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S(S(Md(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[]))),([n,i])=>[Ub(n),i]),Md=(e)=>S(S(DL(e),([n,i])=>S(Nd(i),([c,p])=>[[n,c],p])),([n,i])=>[Bb(n),i]),Nd=(e)=>S(S(XE(e),([n,i])=>[n,i],()=>S(Md(e),([n,i])=>[n,i],()=>[])),([n,i])=>[Gb(n),i]),mx=(e)=>S(S(ee("^",e),([n,i])=>S(Nd(i),([c,p])=>S(ee("$",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Kb(n),i]),YE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(Mt(c),([p,f])=>[[i,p],f])),([i,c])=>YE(c,[...n,i]),()=>[n,e]),FL=(e)=>S(S(S(Mt(e),([n,i])=>S(YE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Hb(n),i]),ZE=(e)=>S(S(S(ee("extends",e),([n,i])=>S(FL(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Wb(n),i]),jL=(e)=>S(S(ee("interface",e),([n,i])=>S(qr(i),([c,p])=>S(vd(p),([f,g])=>S(ZE(g),([x,I])=>S(_d(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[zb(n),i]),UL=(e)=>S(S(ee("interface",e),([n,i])=>S(qr(i),([c,p])=>S(ZE(p),([f,g])=>S(_d(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[Vb(n),i]),BL=(e)=>S(S(ee("type",e),([n,i])=>S(qr(i),([c,p])=>S(vd(p),([f,g])=>S(ee("=",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[Jb(n),i]),GL=(e)=>S(S(ee("type",e),([n,i])=>S(qr(i),([c,p])=>S(ee("=",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[Qb(n),i]),KL=(e)=>S(S(S(ee("export",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Xb(n),i]),eS=(e)=>S(S(S(ee(";",e),([n,i])=>S(ee(`
|
|
19
|
+
`,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(ee(`
|
|
20
|
+
`,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[Yb(n),i]),tS=(e,n=[])=>S(S(eS(e),([i,c])=>S(Dd(c),([p,f])=>[[i,p],f])),([i,c])=>tS(c,[...n,i]),()=>[n,e]),HL=(e)=>S(S(S(Dd(e),([n,i])=>S(tS(i),([c,p])=>S(S(eS(p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Zb(n),i]),Dd=(e)=>S(S(KL(e),([n,i])=>S(S(jL(i),([c,p])=>[c,p],()=>S(UL(i),([c,p])=>[c,p],()=>S(BL(i),([c,p])=>[c,p],()=>S(GL(i),([c,p])=>[c,p],()=>[])))),([c,p])=>S(kE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[eE(n),i]),WL=(e)=>S(S(Dd(e),([n,i])=>S(HL(i),([c,p])=>[[n,c],p])),([n,i])=>[tE(n),i]),rS=(e)=>S(S(WL(e),([n,i])=>[n,i],()=>S(eL(e),([n,i])=>[n,i],()=>S(Mt(e),([n,i])=>[n,i],()=>[]))),([n,i])=>[rE(n),i]);function nS(e){let n=Od(`\`${e}\``);return _(n.length,2)?n[0]:Nr()}function VL(e){return e.join("|")}function JL(e){return e.slice(1,e.length-1)}function QL(e,n,i){return ii(n,`${i}${e}`)}function XL(e,n){return ii(e,`${n}${nx}`)}function YL(e,n){return ii(e,`${n}${hm}`)}function ZL(e,n){return ii(e,`${n}${Im}`)}function eN(e,n){return Gu(m([a("false"),a("true")]),e,n)}function tN(e,n){return ii(e,`${n}${bm}`)}function rN(e,n,i){return ii(n,`${i}${JL(e)}`)}function nN(e,n,i){let c=Ku(e,{});return Gu(c,n,i)}function oN(e,n,i){let c=Jn(e);return Gu(c,n,i)}function oS(e,n,i,c=[]){return It(e,(p,f)=>oS(f,n,i,[...c,Gu(p,[],"")]),()=>ii(n,`${i}(${VL(c)})`))}function Gu(e,n,i){return tn(e)?oN(e.enum,n,i):pn(e)?YL(n,i):yt(e)?QL(e.const,n,i):io(e)?XL(n,i):Wn(e)?eN(n,i):Tr(e)?ZL(n,i):rn(e)?tN(n,i):cr(e)?rN(e.pattern,n,i):iS(e)?nN(e.parameters[0],n,i):be(e)?oS(e.anyOf,n,i):My}function ii(e,n){return It(e,(i,c)=>Gu(i,c,n),()=>n)}function sN(e){return`^${ii(e,"")}$`}function sS(e){let n=sN(e);return Sm(n)}function Ku(e,n){return ct(e)?Et(sS(e),{},n):Pm(e,n)}function aS(e,n,i,c){let p=lo(e,n,i);return Ku(p,c)}function Pm(e,n={}){return Ne("TemplateLiteral",[e],n)}function iS(e){return Ar(e)&&le(e,"action")&&_(e.action,"TemplateLiteral")}function uS(e){return Ku(e,{})}function iN(e){let n=nS(e);return uS(n)}function cS(e,n={}){let i=gt(e)?iN(e):uS(e);return Et(i,{},n)}function cr(e){return Ae(e,"TemplateLiteral")}function qd(e){return Ct({["~kind"]:"ExtendsUnion"},{inferred:e})}function Fd(e){return at(e)&&le(e,"~kind")&&le(e,"inferred")&&_(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function Se(e){return Ct({["~kind"]:"ExtendsTrue"},{inferred:e})}function jd(e){return at(e)&&le(e,"~kind")&&le(e,"inferred")&&_(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ze(){return Ct({["~kind"]:"ExtendsFalse"},{})}function Ud(e){return at(e)&&le(e,"~kind")&&_(e["~kind"],"ExtendsFalse")}function to(e){return Fd(e)||jd(e)}function xr(e,n,i){return to(e)?n(e.inferred):i()}function aN(e,n,i,c){return xr(Rt(e,i,c),(p)=>Se(mn(mn(e,p),{[n]:i})),()=>Ze())}function uN(e,n){return Se(e)}function cN(e,n,i,c,p){return xr(Rt(e,n,i),(f)=>xr(Rt(f,n,c),(g)=>Se(g),()=>Ze()),()=>xr(Rt(e,n,p),(f)=>Se(f),()=>Ze()))}function mN(e,n,i){let c=Jn(i);return Rt(e,n,c)}function mS(e,n,i){return It(i,(c,p)=>xr(Rt(e,n,c),(f)=>mS(f,n,p),()=>Ze()),()=>Se(e))}function pN(e,n,i){let c=vn(i);return Rt(e,n,c)}function pS(e,n,i){return It(i,(c,p)=>xr(Rt(e,n,c),(f)=>Se(f),()=>pS(e,n,p)),()=>Ze())}function Dt(e,n,i){return Cr(i)?uN(e,n):Lr(i)?cN(e,n,i.if,i.then,i.else):tn(i)?mN(e,n,i.enum):en(i)?aN(e,i.name,n,i.extends):He(i)?mS(e,n,i.allOf):cr(i)?pN(e,n,i.pattern):be(i)?pS(e,n,i.anyOf):Zr(i)?Se(e):Ze()}function lS(e,n,i){return en(i)?Dt(e,n,i):Cr(i)?Se(e):Zr(i)?Se(e):qd(e)}function lN(e,n){let i=Xi(e),c=Xi(n);return i&&c?!0:!i&&c?!0:i&&!c?!1:!0}function dS(e,n,i,c){return St(c)?lN(n,c)?Rt(e,i,c.items):Ze():Dt(e,n,c)}function fS(e,n,i){return io(i)?Se(e):Dt(e,n,i)}function hS(e,n,i){return Wn(i)?Se(e):Dt(e,n,i)}function dN(e,n,i,c,p){let f=en(c)?n:c,g=en(c)?c:n,x=sn(n),I=sn(c);return!x&&I?Ze():xr(Rt(e,f,g),(b)=>Hu(b,i,p),()=>Ze())}function fN(e,n,i,c){return It(c,(p,f)=>dN(e,n,i,p,f),()=>sn(n)?Se(e):Ze())}function hN(e,n,i){return It(n,(c,p)=>fN(e,c,p,i),()=>Se(e))}function Hu(e,n,i){return hN(e,n,i)}function op(e,n,i){return ao(i)?Se(e):Rt(e,n,i)}function gS(e,n,i,c){return Cr(c)?Se(e):Zr(c)?Se(e):Xr(c)?xr(Hu(e,n,c.parameters),(p)=>op(p,i,c.instanceType),()=>Ze()):Ze()}function yS(e,n,i,c,p){return xr(Rt(e,n,p),()=>Rt(e,i,p),()=>Rt(e,c,p))}function xS(e,n,i){let c=Jn(n);return Rt(e,c,i)}function IS(e,n,i,c){return Cr(c)?Se(e):Zr(c)?Se(e):Yr(c)?xr(Hu(e,n,c.parameters),(p)=>op(p,i,c.returnType),()=>Ze()):Ze()}function bS(e,n,i){return pn(i)?Se(e):Tr(i)?Se(e):Dt(e,n,i)}function ES(e,n,i){let c=Rr(n);return Rt(e,c,i)}function sp(e,n,i){return n===i?Se(e):Ze()}function gN(e,n,i){return yt(i)?sp(e,n,i.const):io(i)?Se(e):Dt(e,a(n),i)}function yN(e,n,i){return yt(i)?sp(e,n,i.const):Wn(i)?Se(e):Dt(e,a(n),i)}function xN(e,n,i){return yt(i)?sp(e,n,i.const):Tr(i)?Se(e):Dt(e,a(n),i)}function IN(e,n,i){return yt(i)?sp(e,n,i.const):rn(i)?Se(e):Dt(e,a(n),i)}function SS(e,n,i){return _r(n.const)?gN(e,n.const,i):un(n.const)?yN(e,n.const,i):Ot(n.const)?xN(e,n.const,i):gt(n.const)?IN(e,n.const,i):Nr()}function wS(e,n,i){return en(i)?Dt(e,n,i):Se(e)}function TS(e,n,i){return xs(i)?Se(e):Dt(e,n,i)}function RS(e,n,i){return Tr(i)?Se(e):Dt(e,n,i)}function bN(e,n,i){return sn(n)?sn(i)?Se(e):Ze():Se(e)}function EN(e,n,i){return en(i)&&so(i.extends)?Ze():xr(Rt(e,n,i),(c)=>bN(c,n,i),()=>Ze())}function SN(e,n){return e.reduce((i,c)=>(c in n)?to(n[c])?{...i,...n[c].inferred}:Nr():Nr(),{})}function wN(e,n,i){let c={};for(let g of Ee(i))c[g]=g in n?EN({},n[g],i[g]):sn(i[g])?en(i[g])?Se(mn(e,{[i[g].name]:i[g].extends})):Se(e):Ze();let p=cd(c).every((g)=>to(g)),f=p?SN(Ee(c),c):{};return p?Se(f):Ze()}function TN(e,n,i){let c=wN(e,n,i);return to(c)?Se(mn(e,c.inferred)):Ze()}function RN(e,n,i){return TN(e,n,i)}function kN(e,n){return Ee(n).reduce((i,c)=>({...i,[c]:le(e,c)?be(i[c])?m([...i[c].anyOf,n[c]]):m([e[c],n[c]]):n[c]}),e)}function kS(e,n,i,c){return It(n,(p,f)=>xr(Rt({},e[p],i),(g)=>kS(e,f,i,kN(c,g)),()=>Ze()),()=>Se(c))}function AN(e,n,i,c){let p=Ee(n);return kS(n,p,c,e)}function AS(e,n,i){return Kt(i)?AN(e,n,ln(i),lr(i)):Qe(i)?RN(e,n,i.properties):Dt(e,s(n),i)}function CN(e,n){return _(Ee(n).length,0)?Se(e):Ze()}function $N(e,n,i,c,p){return Rt(e,i,p)}function CS(e,n,i,c){return Kt(c)?$N(e,km(n),i,km(ln(c)),lr(c)):Qe(c)?CN(e,c.properties):Cr(c)?Se(e):Zr(c)?Se(e):Ze()}function $S(e,n,i){return rn(i)?Se(e):Dt(e,n,i)}function PS(e,n,i){return Is(i)?Se(e):Dt(e,n,i)}function MS(e,n,i){let c=vn(n);return Rt(e,c,i)}function Bd(e,n){return Ct({"~kind":"Inferrable"},{name:e,type:n},{})}function Wu(e){return at(e)&&le(e,"~kind")&&le(e,"name")&&le(e,"type")&&_(e["~kind"],"Inferrable")&>(e.name)&&at(e.type)}function Gd(e){return ni(e)?en(e.items)?St(e.items.extends)?Bd(e.items.name,e.items.extends.items):Zr(e.items.extends)?Bd(e.items.name,e.items.extends):void 0:Nr():void 0}function ip(e){return en(e)?Bd(e.name,e.extends):void 0}function Kd(e,n,i=[]){return It(e,(c,p)=>xr(Rt({},c,n),()=>Kd(p,n,[...i,c]),()=>{return}),()=>i)}function vS(e,n,i,c){let p=Kd(i,c);return Be(p)?Se(mn(e,{[n]:Dr(p)})):Ze()}function ap(e,n,i,c){let p=Kd(i,c);return Be(p)?Se(mn(e,{[n]:m(p)})):Ze()}function PN(e){return[...e].reverse()}function Hd(e,n){return n?PN(e):e}function MN(e){let n=e.length>0?e[0]:void 0,i=Ar(n)?Gd(n):void 0;return Ar(i)}function vN(e,n,i,c,p,f){return xr(Rt(e,i,p),(g)=>OS(g,n,c,f),()=>Ze())}function ON(e,n,i,c,p){let f=Gd(c);return Wu(f)?vS(e,f.name,Hd(i,n),f.type):It(i,(g,x)=>vN(e,n,g,x,c,p),()=>Ze())}function _N(e,n,i,c){return It(c,(p,f)=>ON(e,n,i,p,f),()=>_(i.length,0)?Se(e):Ze())}function OS(e,n,i,c){return _N(e,n,i,c)}function LN(e,n,i){let c=ai(e,dr([],[]),i),p=MN(c);return OS(e,p,Hd(n,p),Hd(c,p))}function _S(e,n,i){let c=ip(i);return Wu(c)?ap(e,c.name,n,c.type):It(n,(p,f)=>xr(Rt(e,p,i),(g)=>_S(g,f,i),()=>Ze()),()=>Se(e))}function LS(e,n,i){let c=ai(e,dr([],[]),n);return lt(i)?LN(e,c,i.items):St(i)?_S(e,c,i.items):Dt(e,Dr(c),i)}function NS(e,n,i){return ao(i)?Se(e):Yo(i)?Se(e):Dt(e,n,i)}function DS(e,n,i){return It(i,(c,p)=>xr(Rt(e,n,c),(f)=>Se(f),()=>DS(e,n,p)),()=>Ze())}function Wd(e,n,i){return It(n,(c,p)=>xr(DS(e,c,i),(f)=>Wd(f,p,i),()=>Ze()),()=>Se(e))}function qS(e,n,i){let c=ip(i);return Wu(c)?ap(e,c.name,n,c.type):be(i)?Wd(e,n,i.anyOf):Wd(e,n,[i])}function FS(e,n,i){return en(i)?Dt(e,n,i):Cr(i)?Se(e):Zr(i)?Se(e):Ze()}function jS(e,n,i){return ao(i)?Se(e):Dt(e,n,i)}function Rt(e,n,i){return Cr(n)?lS(e,n,i):St(n)?dS(e,n,n.items,i):io(n)?fS(e,n,i):Wn(n)?hS(e,n,i):Xr(n)?gS(e,n.parameters,n.instanceType,i):Lr(n)?yS(e,n.if,n.then,n.else,i):tn(n)?xS(e,n.enum,i):Yr(n)?IS(e,n.parameters,n.returnType,i):pn(n)?bS(e,n,i):He(n)?ES(e,n.allOf,i):yt(n)?SS(e,n,i):so(n)?wS(e,n,i):xs(n)?TS(e,n,i):Tr(n)?RS(e,n,i):Qe(n)?AS(e,n.properties,i):Kt(n)?CS(e,ln(n),lr(n),i):rn(n)?$S(e,n,i):Is(n)?PS(e,n,i):cr(n)?MS(e,n.pattern,i):lt(n)?LS(e,n.items,i):Yo(n)?NS(e,n,i):be(n)?qS(e,n.anyOf,i):Zr(n)?FS(e,n,i):ao(n)?jS(e,n,i):Ze()}function NN(e,n){return Rr([...e,s(n)])}function zd(e,n,i){return ct(e)?Et(NN(e,n),{},i):qu(e,n,i)}function US(e,n,i,c,p){let f=lo(e,n,i),g=zu(e,n,c);return zd(f,g,p)}function qu(e,n,i={}){return Ne("Interface",[e,n],i)}function Na(e){return Ar(e)&&le(e,"action")&&_(e.action,"Interface")}function BS(e,n,i={}){return zd(e,n,i)}function DN(e,n,i){return e.includes(i)?!0:Vu([...e,i],n,n[i])}function GS(e,n,i){let c=cm(i);return oa(e,n,c)}function oa(e,n,i){return It(i,(c,p)=>Vu(e,n,c)?!0:oa(e,n,p),()=>!1)}function Vu(e,n,i){return jt(i)?DN(e,n,i.$ref):St(i)?Vu(e,n,i.items):Xr(i)?oa(e,n,[...i.parameters,i.instanceType]):Yr(i)?oa(e,n,[...i.parameters,i.returnType]):Na(i)?GS(e,n,i.parameters[1]):He(i)?oa(e,n,i.allOf):Qe(i)?GS(e,n,i.properties):be(i)?oa(e,n,i.anyOf):lt(i)?oa(e,n,i.items):Kt(i)?Vu(e,n,lr(i)):!1}function KS(e,n,i){return Vu(e,n,i)}function qN(e,n){return n.reduce((i,c)=>KS([c],e,e[c])?[...i,c]:i,[])}function HS(e){let n=um(e);return qN(e,n)}function FN(e,n,i){return i.includes(n)?i:(n in e)?Ju(e,e[n],[...i,n]):Nr()}function WS(e,n,i){let c=cm(n);return Da(e,c,i)}function Da(e,n,i){return n.reduce((c,p)=>Ju(e,p,c),i)}function Ju(e,n,i){return jt(n)?FN(e,n.$ref,i):St(n)?Ju(e,n.items,i):Xr(n)?Da(e,[...n.parameters,n.instanceType],i):Yr(n)?Da(e,[...n.parameters,n.returnType],i):Na(n)?WS(e,n.parameters[1],i):He(n)?Da(e,n.allOf,i):Qe(n)?WS(e,n.properties,i):be(n)?Da(e,n.anyOf,i):lt(n)?Da(e,n.items,i):Kt(n)?Ju(e,lr(n),i):i}function zS(e,n,i){return Ju(e,i,[n])}function jN(e){return ka()}function UN(e){return Ee(e).reduce((n,i)=>({...n,[i]:sa(e[i])}),{})}function Qu(e){return e.reduce((n,i)=>[...n,sa(i)],[])}function sa(e){return jt(e)?jN(e.$ref):St(e)?W(sa(e.items),Ta(e)):Xr(e)?ds(Qu(e.parameters),sa(e.instanceType)):Yr(e)?fs(Qu(e.parameters),sa(e.returnType)):He(e)?An(Qu(e.allOf)):Qe(e)?s(UN(e.properties)):Kt(e)?bs(ri(e),sa(lr(e))):be(e)?m(Qu(e.anyOf)):lt(e)?Dr(Qu(e.items)):e}function BN(e,n){return n in e?sa(e[n]):wr()}function VS(e){return BN(e.$defs,e.$ref)}function GN(e,n,i){let c=lo(e,dr([],[]),n),p=zu({},dr([],[]),i);return Rr([...c,s(p)])}function KN(e,n){return Ee(e).filter((c)=>n.includes(c)).reduce((c,p)=>{let f=e[p],g=Na(f)?GN(e,f.parameters[0],f.parameters[1]):f;return{...c,[p]:g}},{})}function JS(e,n,i){let c=zS(e,n,i),p=KN(e,c);return gs(p,n)}function QS(e,n){return n in e?jt(e[n])?QS(e,e[n].$ref):e[n]:zt()}function Es(e,n){return QS(e,n)}function XS(e){return Qt(e)?VS(e):mm(e)?wr():e}function Sn(e,n,i){let c=XS(n),p=XS(i);return Rt(e,c,p)}var Ou=0,Xu=1,_u=2,Lu=3;function Pa(e,n){let i=[Sn({},e,n),Sn({},n,e)];return to(i[0])&&to(i[1])?Ou:to(i[0])&&Ud(i[1])?_u:Ud(i[0])&&to(i[1])?Lu:Xu}function Vd(e,n,i=[],c=n){return It(n,(p,f)=>{let g=Pa(e,p);return _(g,_u)||_(g,Ou)?c:_(g,Xu)?Vd(e,f,[...i,p],c):Vd(e,f,i,c)},()=>[...i,e])}function HN(e,n,i){let c=So(e);return Cr(c)?[c]:Zr(c)?[c]:so(c)?up(n,i):Qe(c)?up(n,[...i,c]):up(n,Vd(c,i))}function up(e,n=[]){return It(e,(i,c)=>HN(i,c,n),()=>n)}function Sd(e){let n=up(e);return ta(n)}function Jd(e,n){return Et(So(e),{},n)}function YS(e,n,i,c){let p=de(e,n,i);return Jd(p,c)}function Yu(e,n=[]){return Qs(e)&&_(e.action,"Conditional")?jt(e.parameters[0])?Yu(e.parameters[2],Yu(e.parameters[3],[...n,e.parameters[0].$ref])):Yu(e.parameters[2],Yu(e.parameters[3],n)):Qs(e)&&_(e.action,"Mapped")?Qs(e.parameters[1])&&_(e.parameters[1].action,"KeyOf")&&jt(e.parameters[1].parameters[0])?[...n,e.parameters[1].parameters[0].$ref]:n:n}function WN(e,n){return e.reduce((i,c)=>[...i,n.includes(c.name)],[])}function tw(e,n,i=[]){return It(e,(c,p)=>It(n,(f,g)=>tw(p,g,[...i,[f,c]]),()=>i),()=>i)}function zN(e){return cr(e)?vn(e.pattern):tn(e)?Jn(e.enum):e}function VN(e){let n=zN(e);return be(n)?[...n.anyOf]:[n]}function JN(e,n){return e.reduce((i,c)=>[...i,[...c,n]],[])}function ZS(e,n){return n.reduce((i,c)=>[...i,...JN(e,c)],[])}function ew(e){return e.reduce((n,i)=>_(i[0],!0)?ZS(n,VN(i[1])):ZS(n,[i[1]]),[[]])}function rw(e,n,i){let c=Yu(i),p=WN(e,c),f=tw(n,p);return Qs(i)&&_(i.action,"Conditional")?ew(f):Qs(i)&&_(i.action,"Mapped")?ew(f):[n]}function QN(){return["(not-resolvable)",zt()]}function XN(){return["(not-generic)",zt()]}function YN(e,n,i){return[e,Xs(n,i)]}function ZN(e,n,i){return n in e?nw(e,n,e[n],i):QN()}function nw(e,n,i,c){return Ra(i)?YN(n,i.parameters,i.expression):jt(i)?ZN(e,i.$ref,c):XN()}function ow(e,n,i){return nw(e,"(anonymous)",n,i)}function eD(e,n,i){if(en(n)||qa(n)||to(Sn({},n,i)))return;let c={parameter:e,expect:i,actual:n};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:c})}function sw(e,n,i,c,p){let f=de(e,n,p);return eD(i,f,c),mn(e,{[i]:f})}function tD(e,n,i,c,p){let f=de(e,n,i.extends),g=de(e,n,i.equals);return It(p,(x,I)=>Qd(sw(e,n,i.name,f,x),n,c,I),()=>Qd(sw(e,n,i.name,f,g),n,c,[]))}function Qd(e,n,i,c){return It(i,(p,f)=>tD(e,n,p,f,c),()=>e)}function iw(e,n,i,c){return Qd(e,n,i,c)}var Xd=0,Yd=0;function rD(){if(Su(Yd,Vo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function nD(){rD(),Yd++,Xd++}function oD(){if(Xd--,_(Xd,0))Yd=0}function sD(e){return Bi(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function iD(e,n){return _(sD(e),n)}function aD(e,n,i,c,p,f){nD();try{let g=iw(e,n,c,f),x=de(g,dr([...n.callstack,i.$ref],n.visited),p);return de(g,dr([],[]),x)}finally{oD()}}function uD(e,n,i,c,p,f){return f.reduce((g,x)=>{let I=aD(e,n,i,c,p,x);return[...g,I]},[])}function cD(e,n,i,c,p,f){let g=rw(c,f,p),x=uD(e,n,i,c,p,g);return _(x.length,1)?x[0]:eo(x)}function cp(e,n,i,c){let p=lo(e,n,c),f=ow(e,i,c),g=f[0],x=f[1];return Ra(x)?iD(n,g)?Fu(on(g),p):cD(e,n,on(g),x.parameters,x.expression,p):Fu(i,p)}function Fu(e,n){return Ct({["~kind"]:"Call"},{type:"call",target:e,arguments:n},{})}function aw(e,n){return cp({},dr([],[]),e,n)}function qa(e){return Ae(e,"Call")}function mD(e){return Jo(e,["~immutable"])}function uw(e,n){return Et(mD(e),{},n)}function cw(e,n,i,c){let p=de(e,n,i);return uw(p,c)}function mw(e,n){return e(n)}function pw(e,n){return gt(n)?a(mw(e,n)):a(n)}function lw(e,n){let i=vn(n);return _s(e,i)}function dw(e,n){let i=n.map((c)=>_s(e,c));return m(i)}function _s(e,n){return yt(n)?pw(e,n.const):cr(n)?lw(e,n.pattern):be(n)?dw(e,n.anyOf):n}function Mm(e,n={}){return Ne("Capitalize",[e],n)}function fw(e,n={}){return Zd(e,n)}function vm(e,n={}){return Ne("Lowercase",[e],n)}function hw(e,n={}){return ef(e,n)}function Om(e,n={}){return Ne("Uncapitalize",[e],n)}function gw(e,n={}){return tf(e,n)}function _m(e,n={}){return Ne("Uppercase",[e],n)}function yw(e,n={}){return rf(e,n)}var pD=(e)=>e[0].toUpperCase()+e.slice(1),lD=(e)=>e.toLowerCase(),dD=(e)=>e[0].toLowerCase()+e.slice(1),fD=(e)=>e.toUpperCase();function Zd(e,n){return ct([e])?Et(_s(pD,e),{},n):Mm(e,n)}function ef(e,n){return ct([e])?Et(_s(lD,e),{},n):vm(e,n)}function tf(e,n){return ct([e])?Et(_s(dD,e),{},n):Om(e,n)}function rf(e,n){return ct([e])?Et(_s(fD,e),{},n):_m(e,n)}function xw(e,n,i,c){let p=de(e,n,i);return Zd(p,c)}function Iw(e,n,i,c){let p=de(e,n,i);return ef(p,c)}function bw(e,n,i,c){let p=de(e,n,i);return tf(p,c)}function Ew(e,n,i,c){let p=de(e,n,i);return rf(p,c)}function Lm(e,n,i,c,p={}){return Ne("Conditional",[e,n,i,c],p)}function Sw(e,n,i,c,p={}){return nf({},dr([],[]),e,n,i,c,p)}function hD(e,n,i,c,p,f){let g=Sn(e,i,c);return Fd(g)?m([de(g.inferred,n,p),de(e,n,f)]):jd(g)?de(g.inferred,n,p):de(e,n,f)}function nf(e,n,i,c,p,f,g){return ct([i,c])?Et(hD(e,n,i,c,p,f),{},g):Lm(i,c,p,f,g)}function ww(e,n,i,c,p,f,g){let x=de(e,n,i),I=de(e,n,c);return nf(e,n,x,I,p,f,g)}function Nm(e,n={}){return Ne("ConstructorParameters",[e],n)}function Tw(e,n={}){return of(e,n)}function gD(e){let n=Xr(e)?e.parameters:[],i=ai({},dr([],[]),n);return Dr(i)}function of(e,n){return ct([e])?Et(gD(e),{},n):Nm(e,n)}function Rw(e,n,i,c){let p=de(e,n,i);return of(p,c)}function Dm(e,n,i={}){return Ne("Exclude",[e,n],i)}function kw(e,n,i={}){return Zu(e,n,i)}function Zu(e,n,i){return ct([e,n])?Et(Tm(e,n),{},i):Dm(e,n,i)}function Aw(e,n,i,c,p){let f=de(e,n,i),g=de(e,n,c);return Zu(f,g,p)}function qm(e,n,i={}){return Ne("Extract",[e,n],i)}function Cw(e,n,i={}){return sf(e,n,i)}function yD(e,n){let i=Sn({},e,n);return to(i)?[e]:[]}function $w(e,n,i=[]){return It(e,(c,p)=>$w(p,n,[...i,...yD(c,n)]),()=>i)}function Pw(e,n){let i=So(e),c=be(i)?i.anyOf:[i],p=$w(c,n);return eo(p)}function sf(e,n,i){return ct([e,n])?Et(Pw(e,n),{},i):qm(e,n,i)}function Mw(e,n,i,c,p){let f=de(e,n,i),g=de(e,n,c);return sf(f,g,p)}function xD(e){return e.reduce((n,i)=>gm(i)?[...n,a(i)]:n,[])}function Fa(e){let n=xD(e);return m(n)}function ju(e,n,i={}){return Ne("Index",[e,n],i)}function vw(e,n,i={}){let c=Be(n)?Fa(n):n;return af(e,c,i)}function Ow(e,n){let i=Es(e,n);return fo(i)}function _w(e,n,i){let c=Xo(e,n,i);return fo(c)}function ID(e,n){let i=Ee(e).filter((E)=>!le(n,E)),c=Ee(n).filter((E)=>!le(e,E)),p=Ee(e).filter((E)=>le(n,E)),f=i.reduce((E,T)=>({...E,[T]:e[T]}),{}),g=c.reduce((E,T)=>({...E,[T]:n[T]}),{}),x=p.reduce((E,T)=>({...E,[T]:Rr([e[T],n[T]])}),{}),I=mn(f,g);return mn(I,x)}function Lw(e){return e.reduce((n,i)=>ID(n,fo(i)),{})}function Nw(e){return e}function Dw(e){let n=Rx(Dr(e));return fo(n)}function bD(e,n){return Ee(e).filter((p)=>(p in n)).reduce((p,f)=>({...p,[f]:eo([e[f],n[f]])}),{})}function qw(e,n){return It(e,(i,c)=>qw(c,bD(n,fo(i))),()=>n)}function Fw(e){return It(e,(n,i)=>qw(i,fo(n)),()=>Nr())}function fo(e){return Qt(e)?Ow(e.$defs,e.$ref):Lr(e)?_w(e.if,e.then,e.else):He(e)?Lw(e.allOf):be(e)?Fw(e.anyOf):lt(e)?Dw(e.items):Qe(e)?Nw(e.properties):{}}function ja(e){let n=fo(e);return s(n)}var ED=new RegExp("^(?:0|[1-9][0-9]*)$");function Ua(e){let n=`${e}`;return ED.test(n)?parseInt(n):e}function SD(e){return a(Ua(e))}function jw(e){return e.map((n)=>Uw(n))}function Uw(e){return He(e)?An(jw(e.allOf)):be(e)?m(jw(e.anyOf)):yt(e)?SD(e.const):e}function Bw(e,n){let i=Uw(n),c=Sn({},i,J());return to(c)?e:yt(n)&&_(n.const,"length")?J():zt()}function Gw(e,n){let i=Es(e,n);return uo(i)}function Kw(e,n,i){let c=Xo(e,n,i);return uo(c)}function Hw(e){let n=Jn(e);return uo(n)}function Ww(e){let n=Rr(e);return uo(n)}function zw(e){return[`${e}`]}function Vw(e){let n=vn(e);return uo(n)}function Jw(e){return e.reduce((n,i)=>[...n,...uo(i)],[])}function uo(e){return Qt(e)?Gw(e.$defs,e.$ref):Lr(e)?Kw(e.if,e.then,e.else):tn(e)?Hw(e.enum):He(e)?Ww(e.allOf):yt(e)?zw(e.const):cr(e)?Vw(e.pattern):be(e)?Jw(e.anyOf):[]}function Ba(e){return uo(e)}function ec(e,n){return n.map((i)=>tc(e,i))}function tc(e,n){return St(n)?W(tc(e,n.items)):Xr(n)?ds(ec(e,n.parameters),tc(e,n.instanceType)):Yr(n)?fs(ec(e,n.parameters),tc(e,n.returnType)):lt(n)?Dr(ec(e,n.items)):be(n)?m(ec(e,n.anyOf)):He(n)?An(ec(e,n.allOf)):Cm(n)?s(e):n}function Qw(e,n){return tc(e,n)}function wD(e,n){let i=n in e?e[n]:zt();return Qw(e,i)}function Xw(e,n){return n.reduce((i,c)=>[...i,wD(e,c)],[])}function TD(e,n){let i=Ba(n),c=Xw(e,i);return eo(c)}var RD=new RegExp(ti);function kD(e){return e.filter((i)=>RD.test(i))}function AD(e){let n=um(e),i=kD(n),c=Xw(e,i);return eo(c)}function Yw(e,n){return Tr(n)?AD(e):TD(e,n)}function CD(e){return a(Ua(e))}function Zw(e){return e.map((n)=>uf(n))}function uf(e){return He(e)?An(Zw(e.allOf)):be(e)?m(Zw(e.anyOf)):yt(e)?CD(e.const):e}function $D(e,n){return e.reduceRight((i,c,p)=>{let f=Sn({},a(p),n);return to(f)?[c,...i]:i},[])}function PD(e,n){let i=uf(n),c=$D(e,i);return Zs(c)}function MD(e){return Zs(e)}function eT(e,n){return yt(n)&&_(n.const,"length")?a(e.length):Tr(n)||pn(n)?MD(e):PD(e,n)}function tT(e,n){return St(e)?Bw(e.items,n):Qe(e)?Yw(e.properties,n):lt(e)?eT(e.items,n):zt()}function vD(e){return Qt(e)||Lr(e)||He(e)||be(e)?ja(e):e}function af(e,n,i){return ct([e,n])?Et(tT(vD(e),n),{},i):ju(e,n,i)}function rT(e,n,i,c,p){let f=de(e,n,i),g=de(e,n,c);return af(f,g,p)}function Fm(e,n={}){return Ne("InstanceType",[e],n)}function nT(e,n={}){return cf(e,n)}function OD(e){return Xr(e)?e.instanceType:zt()}function cf(e,n){return ct([e])?Et(OD(e),{},n):Fm(e,n)}function oT(e,n,i,c={}){let p=de(e,n,i);return cf(p,c)}function Uu(e,n={}){return Ne("KeyOf",[e],n)}function sT(e,n={}){return mf(e,n)}function iT(){return m([J(),l(),$a()])}function aT(e){return J()}function _D(e){return e.reduce((i,c)=>gm(c)?[...i,a(Ua(c))]:Nr(),[])}function uT(e){let n=Ee(e),i=_D(n);return Zs(i)}function cT(e){return ri(e)}function mT(e){let n=e.map((i,c)=>a(c));return Zs(n)}function pT(e){return Cr(e)?iT():St(e)?aT(e.items):Qe(e)?uT(e.properties):Kt(e)?cT(e):lt(e)?mT(e.items):zt()}function LD(e){return Qt(e)||Lr(e)||He(e)||be(e)?ja(e):e}function mf(e,n){return ct([e])?Et(pT(LD(e)),{},n):Uu(e,n)}function lT(e,n,i,c){let p=de(e,n,i);return mf(p,c)}function Du(e,n,i,c,p={}){return Ne("Mapped",[e,n,i,c],p)}function dT(e,n,i,c,p={}){return pf({},dr([],[]),e,n,i,c,p)}function ND(e){let n=vn(e);return mp(n)}function DD(e){return e.reduce((n,i)=>[...n,...mp(i)],[])}function qD(e){let n=Jn(e);return mp(n)}function FD(e){return Ot(e)?[a(`${e}`)]:[a(e)]}function mp(e){return tn(e)?qD(e.enum):yt(e)?FD(e.const):cr(e)?ND(e.pattern):be(e)?DD(e.anyOf):[e]}function fT(e){return mp(e)}function jD(e){return cr(e)?vn(e.pattern):e}function UD(e,n,i,c,p,f){let g=mn(e,{[i.name]:c}),x=de(g,n,p),I=jD(x),b=de(g,n,f);return ym(I)||xm(I)?{[I.const]:b}:{}}function BD(e,n,i,c,p,f){return c.reduce((g,x)=>[...g,UD(e,n,i,x,p,f)],[])}function GD(e){return e.reduce((n,i)=>[...n,s(i)],[])}function hT(e,n,i,c,p,f){let g=fT(c),x=BD(e,n,i,g,p,f),I=GD(x);return Rr(I)}function pf(e,n,i,c,p,f,g){return ct([c])?Et(hT(e,n,i,c,p,f),{},g):Du(i,c,p,f,g)}function gT(e,n,i,c,p,f,g){let x=de(e,n,c);return pf(e,n,i,x,p,f,g)}function KD(e,n,i){let c=mn(e,n);return Ee(n).filter((f)=>i.includes(f)).reduce((f,g)=>({...f,[g]:JS(c,g,n[g])}),{})}function HD(e,n,i){let c=mn(e,n);return Ee(n).filter((f)=>!i.includes(f)).reduce((f,g)=>({...f,[g]:de(c,dr([],[]),n[g])}),{})}function WD(e,n,i){let c=HS(n),p=KD(e,n,c),f=HD(e,n,c),g={...p,...f};return Et(g,{},i)}function pp(e,n,i,c){return WD(e,i,c)}function jm(e,n={}){return Ne("NonNullable",[e],n)}function yT(e,n={}){return lf(e,n)}function zD(e){let n=m([Pn(),va()]);return Zu(e,n,{})}function lf(e,n){return ct([e])?Et(zD(e),{},n):jm(e,n)}function xT(e,n,i,c){let p=de(e,n,i);return lf(p,c)}function Um(e,n,i={}){return Ne("Omit",[e,n],i)}function IT(e,n,i={}){let c=Be(n)?Fa(n):n;return df(e,c,i)}function lp(e){let n=ja(e);return Qe(n)?n.properties:Nr()}function VD(e,n){return Ee(e).reduce((c,p)=>n.includes(p)?c:{...c,[p]:e[p]},{})}function bT(e,n){let i=lp(e),c=Ba(n),p=VD(i,c);return s(p)}function df(e,n,i){return ct([e,n])?Et(bT(e,n),{},i):Um(e,n,i)}function ET(e,n,i,c,p){let f=de(e,n,i),g=de(e,n,c);return df(f,g,p)}function Bm(e,n={}){return Ne("Parameters",[e],n)}function ST(e,n={}){return ff(e,n)}function JD(e){let n=Yr(e)?e.parameters:[],i=ai({},dr([],[]),n);return Dr(i)}function ff(e,n){return ct([e])?Et(JD(e),{},n):Bm(e,n)}function wT(e,n,i,c){let p=de(e,n,i);return ff(p,c)}function Gm(e,n={}){return Ne("Partial",[e],n)}function TT(e,n={}){return hf(e,n)}function RT(e,n){let i=Es(e,n),c=Ss(i);return gs(mn(e,{[n]:c}),n)}function kT(e,n,i){let c=Xo(e,n,i);return Ss(c)}function AT(e){let n=Rr(e);return Ss(n)}function CT(e){let n=e.map((i)=>Ss(i));return m(n)}function $T(e){let n=Ee(e).reduce((c,p)=>({...c,[p]:Vi(e[p])}),{});return s(n)}function Ss(e){return Qt(e)?RT(e.$defs,e.$ref):Lr(e)?kT(e.if,e.then,e.else):He(e)?AT(e.allOf):be(e)?CT(e.anyOf):Qe(e)?$T(e.properties):s({})}function hf(e,n){return ct([e])?Et(Ss(e),{},n):Gm(e,n)}function PT(e,n,i,c){let p=de(e,n,i);return hf(p,c)}function Km(e,n,i={}){return Ne("Pick",[e,n],i)}function MT(e,n,i={}){let c=Be(n)?Fa(n):n;return gf(e,c,i)}function QD(e,n){return Ee(e).reduce((c,p)=>n.includes(p)?mn(c,{[p]:e[p]}):c,{})}function vT(e,n){let i=lp(e),c=Ba(n),p=QD(i,c);return s(p)}function gf(e,n,i){return ct([e,n])?Et(vT(e,n),{},i):Km(e,n,i)}function OT(e,n,i,c,p){let f=de(e,n,i),g=de(e,n,c);return gf(f,g,p)}function Hm(e,n={}){return Ne("ReadonlyObject",[e],n)}function yf(e,n={}){return xf(e,n)}var _T=yf;function LT(e){return Ca(W(e))}function NT(e,n){let i=Es(e,n),c=ws(i);return gs(mn(e,{[n]:c}),n)}function DT(e,n,i){let c=Xo(e,n,i);return ws(c)}function qT(e){let n=Rr(e);return ws(n)}function FT(e){let n=Ee(e).reduce((c,p)=>({...c,[p]:Yi(e[p])}),{});return s(n)}function jT(e){return Ca(Dr(e))}function UT(e){let n=e.map((i)=>ws(i));return m(n)}function ws(e){return St(e)?LT(e.items):Qt(e)?NT(e.$defs,e.$ref):Lr(e)?DT(e.if,e.then,e.else):He(e)?qT(e.allOf):Qe(e)?FT(e.properties):lt(e)?jT(e.items):be(e)?UT(e.anyOf):e}function xf(e,n){return ct([e])?Et(ws(e),{},n):Hm(e)}function BT(e,n,i,c){let p=de(e,n,i);return xf(p,c)}function GT(e,n,i,c){return n.visited.includes(c)?i:(c in e)?de(e,dr(n.callstack,[...n.visited,c]),e[c]):i}function KT(e,n){let i=Es(e,n),c=Ts(i);return gs(mn(e,{[n]:c}),n)}function HT(e,n,i){let c=Xo(e,n,i);return Ts(c)}function WT(e){let n=Rr(e);return Ts(n)}function zT(e){let n=e.map((i)=>Ts(i));return m(n)}function VT(e){let n=Ee(e).reduce((c,p)=>({...c,[p]:wm(e[p])}),{});return s(n)}function Ts(e){return Qt(e)?KT(e.$defs,e.$ref):Lr(e)?HT(e.if,e.then,e.else):He(e)?WT(e.allOf):be(e)?zT(e.anyOf):Qe(e)?VT(e.properties):s({})}function Wm(e,n={}){return Ne("Required",[e],n)}function JT(e,n={}){return If(e,n)}function If(e,n){return ct([e])?Et(Ts(e),{},n):Wm(e,n)}function QT(e,n,i,c){let p=de(e,n,i);return If(p,c)}function zm(e,n={}){return Ne("ReturnType",[e],n)}function XT(e,n={}){return bf(e,n)}function XD(e){return Yr(e)?e.returnType:zt()}function bf(e,n){return ct([e])?Et(XD(e),{},n):zm(e,n)}function YT(e,n,i,c={}){let p=de(e,n,i);return bf(p,c)}function Vm(e,n){return Ne("With",[e,n],{})}function dp(e,n){return Ef(e,n)}function Ef(e,n){return ct([e])?Et(e,{},n):Vm(e,n)}function ZT(e,n,i,c){let p=de(e,n,i);return Ef(p,c)}function YD(e){return ni(e)?lt(e.items)?Sf(e.items.items):en(e.items)?[e]:jt(e.items)?[e]:[zt()]:[e]}function Sf(e){return e.reduce((i,c)=>[...i,...YD(c)],[])}function dr(e,n){return{callstack:e,visited:n}}function ct(e){return It(e,(n,i)=>jt(n)?!1:ct(i),()=>!0)}function zu(e,n,i){return Ee(i).reduce((c,p)=>({...c,[p]:de(e,n,i[p])}),{})}function ai(e,n,i){let c=lo(e,n,i);return Sf(c)}function lo(e,n,i){return i.map((c)=>de(e,n,c))}function ZD(e,n){let i=sn(e)?Au(n,{}):n,c=Zi(e)?ku(i,{}):i;return Xi(e)?rc(c,{}):c}function eq(e,n,i,c,p){return _(i,"AddImmutable")?eR(e,n,c[0],p):_(i,"RemoveImmutable")?cw(e,n,c[0],p):_(i,"AddReadonly")?Ay(e,n,c[0],p):_(i,"RemoveReadonly")?bx(e,n,c[0],p):_(i,"AddOptional")?Cy(e,n,c[0],p):_(i,"RemoveOptional")?wx(e,n,c[0],p):_(i,"Capitalize")?xw(e,n,c[0],p):_(i,"Conditional")?ww(e,n,c[0],c[1],c[2],c[3],p):_(i,"ConstructorParameters")?Rw(e,n,c[0],p):_(i,"Evaluate")?YS(e,n,c[0],p):_(i,"Exclude")?Aw(e,n,c[0],c[1],p):_(i,"Extract")?Mw(e,n,c[0],c[1],p):_(i,"Index")?rT(e,n,c[0],c[1],p):_(i,"InstanceType")?oT(e,n,c[0],p):_(i,"Interface")?US(e,n,c[0],c[1],p):_(i,"KeyOf")?lT(e,n,c[0],p):_(i,"Lowercase")?Iw(e,n,c[0],p):_(i,"Mapped")?gT(e,n,c[0],c[1],c[2],c[3],p):_(i,"Module")?pp(e,n,c[0],p):_(i,"NonNullable")?xT(e,n,c[0],p):_(i,"Pick")?OT(e,n,c[0],c[1],p):_(i,"Parameters")?wT(e,n,c[0],p):_(i,"Partial")?PT(e,n,c[0],p):_(i,"Omit")?ET(e,n,c[0],c[1],p):_(i,"ReadonlyObject")?BT(e,n,c[0],p):_(i,"Record")?jx(e,n,c[0],c[1],p):_(i,"Required")?QT(e,n,c[0],p):_(i,"ReturnType")?YT(e,n,c[0],p):_(i,"TemplateLiteral")?aS(e,n,c[0],p):_(i,"Uncapitalize")?bw(e,n,c[0],p):_(i,"Uppercase")?Ew(e,n,c[0],p):_(i,"With")?ZT(e,n,c[0],c[1]):Ne(i,c,p)}function tq(e,n,i){let c=jt(i)?GT(e,n,i,i.$ref):St(i)?W(de(e,n,i.items),Ta(i)):qa(i)?cp(e,n,i.target,i.arguments):Xr(i)?ds(lo(e,n,i.parameters),de(e,n,i.instanceType),$y(i)):Yr(i)?fs(lo(e,n,i.parameters),de(e,n,i.returnType),Py(i)):Lr(i)?Ji(de(e,n,i.if),de(e,n,i.then),de(e,n,i.else),_y(i)):He(i)?An(lo(e,n,i.allOf),Fy(i)):Qe(i)?s(zu(e,n,i.properties),Oy(i)):Kt(i)?Ux(ln(i),de(e,n,lr(i))):ni(i)?ra(de(e,n,i.items)):lt(i)?Dr(ai(e,n,i.items),Ix(i)):be(i)?m(lo(e,n,i.anyOf),cx(i)):i;return ZD(i,c)}function de(e,n,i){return Qs(i)?eq(e,n,i.action,i.parameters,i.options):tq(e,n,i)}function wo(e,n){return de(e,dr([],[]),n)}function rq(e){return Et(e,{"~immutable":!0},{})}function rc(e,n){return Et(rq(e),{},n)}function eR(e,n,i,c){let p=de(e,n,i);return rc(p,c)}function nE(e,n={}){return Ne("AddImmutable",[e],n)}function Ca(e,n={}){return rc(e,n)}function oE(e,n={}){return Ne("Evaluate",[e],n)}function wn(e,n={}){return Jd(e,n)}function sE(e,n={}){return Ne("Module",[e],n)}function tR(e,n={}){return pp({},dr([],[]),e,n)}function nq(e,n){let i=Pa(e,n);return _(i,Lu)?1:_(i,Xu)?1:0}function rR(e,n,i=[]){return It(n,(c,p)=>_(nq(e,c),1)?rR(e,p,[...i,c]):[...i,e,...n],()=>[...i,e])}function nR(e,n=[]){return It(e,(i,c)=>nR(c,rR(i,n)),()=>n)}function oR(e){return nR(e)}function sR(...e){let[n,i,c]=En(e,{2:(g,x)=>gt(g)?[{},g,x]:[g,x,{}],3:(g,x,I)=>[g,x,I],1:(g)=>[{},g,{}]}),p=rS(i),f=Be(p)&&_(p.length,2)?de(n,dr([],[]),p[0]):zt();return Et(f,{},c)}function h(e,n){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let c=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:c}},resolve:async({ctx:i,credential:c,signal:p})=>{if(p.throwIfAborted(),c?.key)return{auth:{apiKey:c.key},env:c.env,source:"stored credential"};for(let f of n){let g=await i.env(f);if(p.throwIfAborted(),g)return{auth:{apiKey:g},source:f}}return}}}function ae(e){let n,i=()=>(n??=e.load(),n);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(c,p)=>(await i()).login(c,p),refresh:async(c,p)=>(await i()).refresh(c,p),toAuth:async(c)=>(await i()).toAuth(c)}}var cR="faux",mR="faux",pR="faux-1",oq="Faux Model",sq="http://localhost:0",iq=3,iR=5,gp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Cn(e){return{type:"text",text:e}}function Ro(e){return{type:"thinking",thinking:e}}function aq(e,n,i={}){return{type:"toolCall",id:i.id??Rf("tool"),name:e,arguments:n}}function uq(e){if(typeof e==="string")return[Cn(e)];return Array.isArray(e)?e:[e]}function Io(e,n={}){return{role:"assistant",content:uq(e),api:cR,provider:mR,model:pR,usage:gp,stopReason:n.stopReason??"stop",...n.deferred===void 0?{}:{deferred:n.deferred},...n.errorMessage===void 0?{}:{errorMessage:n.errorMessage},...n.responseId===void 0?{}:{responseId:n.responseId},timestamp:n.timestamp??Date.now()}}function lR(e){return Math.ceil(e.length/4)}function Rf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function dR(e){if(typeof e==="string")return e;return e.map((n)=>{if(n.type==="text")return n.text;return`[image:${n.mimeType}:${n.data.length}]`}).join(`
|
|
21
|
+
`)}function fR(e){return e.map((n)=>{if(n.type==="text")return n.text;if(n.type==="thinking")return n.thinking;return`${n.name}:${JSON.stringify(n.arguments)}`}).join(`
|
|
22
|
+
`)}function cq(e){return[e.toolName,...e.content.map((n)=>dR([n]))].join(`
|
|
23
|
+
`)}function mq(e){if(e.role==="system")return[N(e),...e.toolsRemoved?.map((n)=>`tool-:${JSON.stringify(n)}`)??[],...e.toolsAdded?.map((n)=>`tool+:${JSON.stringify(n)}`)??[]].filter((n)=>n.length>0).join(`
|
|
24
|
+
`);if(e.role==="user")return dR(e.content);if(e.role==="assistant")return fR(e.content);return cq(e)}function hR(e,n=e.length){let i=n>0?(n-1)*2:0;for(let c=0;c<n;c++)i+=e[c].length;return i}function pq(e,n){let i=0;while(i<e.length&&i<n.length&&e[i]===n[i])i++;let c=(p)=>i===p.length?"":(i>0?`
|
|
25
|
+
|
|
26
|
+
`:"")+p.slice(i).join(`
|
|
27
|
+
|
|
28
|
+
`);return hR(e,i)+lq(c(e),c(n))}function lq(e,n){let i=Math.min(e.length,n.length),c=0;while(c<i&&e[c]===n[c])c++;return c}function aR(e,n,i,c){let p=n.messages.map((k)=>`${k.role}:${mq(k)}`),f=hR(p),g=Math.ceil(f/4),x=lR(fR(e.content)),I=g,b=0,E=0,T=i?.sessionId;if(T&&i?.cacheRetention!=="none"){let k=c.get(T);if(k){let A=pq(k,p);b=Math.ceil(A/4),E=Math.ceil((f-A)/4),I=Math.max(0,g-b)}else E=g;c.set(T,p)}return{...e,usage:{input:I,output:x,cacheRead:b,cacheWrite:E,totalTokens:I+x+b+E,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function wf(e,n,i){let c=[],p=0;while(p<e.length){let f=n+Math.floor(Math.random()*(i-n+1)),g=Math.max(1,f*4);c.push(e.slice(p,p+g)),p+=g}return c.length>0?c:[""]}function dq(e,n,i,c){let p=structuredClone(e);return{...p,api:n,provider:i,model:c,timestamp:p.timestamp??Date.now(),usage:p.usage??gp}}function uR(e,n){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:gp,stopReason:"deferred",deferred:n,timestamp:Date.now()}}function fp(e,n,i,c){return{role:"assistant",content:[],api:n,provider:i,model:c,usage:gp,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 Tf(e,n){if(!n||n<=0)return new Promise((c)=>queueMicrotask(c));let i=lR(e)/n*1000;return new Promise((c)=>setTimeout(c,i))}async function hp(e,n,i,c,p,f){let g={...n,content:[],stopReason:"pending"};if(f?.aborted){let x=nc(g);e.push({type:"error",reason:"aborted",error:x}),e.end(x);return}e.push({type:"start",partial:{...g}});for(let x=0;x<n.content.length;x++){if(f?.aborted){let b=nc(g);e.push({type:"error",reason:"aborted",error:b}),e.end(b);return}let I=n.content[x];if(I.type==="thinking"){g.content=[...g.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:x,partial:{...g}});for(let b of wf(I.thinking,i,c)){if(await Tf(b,p),f?.aborted){let E=nc(g);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}g.content[x].thinking+=b,e.push({type:"thinking_delta",contentIndex:x,delta:b,partial:{...g}})}e.push({type:"thinking_end",contentIndex:x,content:I.thinking,partial:{...g}});continue}if(I.type==="text"){g.content=[...g.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:x,partial:{...g}});for(let b of wf(I.text,i,c)){if(await Tf(b,p),f?.aborted){let E=nc(g);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}g.content[x].text+=b,e.push({type:"text_delta",contentIndex:x,delta:b,partial:{...g}})}e.push({type:"text_end",contentIndex:x,content:I.text,partial:{...g}});continue}g.content=[...g.content,{type:"toolCall",id:I.id,name:I.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:x,partial:{...g}});for(let b of wf(JSON.stringify(I.arguments),i,c)){if(await Tf(b,p),f?.aborted){let E=nc(g);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}e.push({type:"toolcall_delta",contentIndex:x,delta:b,partial:{...g}})}g.content[x].arguments=I.arguments,e.push({type:"toolcall_end",contentIndex:x,toolCall:I,partial:{...g}})}if(n.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(n.stopReason==="error"||n.stopReason==="aborted"){e.push({type:"error",reason:n.stopReason,error:n}),e.end(n);return}e.push({type:"done",reason:n.stopReason,message:n}),e.end(n)}function gR(e){let n=e.api??Rf(cR),i=e.provider??mR,c=Math.max(1,Math.min(e.tokenSize?.min??iq,e.tokenSize?.max??iR)),p=Math.max(c,e.tokenSize?.max??iR),f=[],g=e.tokensPerSecond,x={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},I=new Map,b=new Map,T=((e.models?.length)?e.models:[{id:pR,name:oq,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:n,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,X,se,Z)=>{let z=typeof V==="function"?await V(X,se,x,Z):V;return aR(dq(z,n,i,Z.id),X,se,I)},A=(V,X,se)=>{let Z=Kn(),z=f.shift();return x.callCount++,queueMicrotask(async()=>{try{if(await se?.onResponse?.({status:200,headers:{}},V),!z){let he=fp(Error("No more faux responses queued"),n,i,V.id);he=aR(he,X,se,I),Z.push({type:"error",reason:"error",error:he}),Z.end(he);return}if(se?.deferred){let he={provider:V.provider,modelId:V.id,api:V.api,id:Rf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};b.set(he.id,{handle:he,step:z,context:X,options:se,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await hp(Z,uR(V,he),c,p,g,se.signal);return}let ce=await k(z,X,se,V);await hp(Z,ce,c,p,g,se?.signal)}catch(ce){let he=fp(ce,n,i,V.id);Z.push({type:"error",reason:"error",error:he}),Z.end(he)}}),Z},L=(V,X,se)=>A(V,X,se),q=(V,X,se)=>{let Z=Kn();return x.deferredFetchCount++,queueMicrotask(async()=>{try{await se?.onResponse?.({status:200,headers:{}},V);let z=b.get(X.id);if(!z||z.handle.provider!==X.provider||z.handle.modelId!==X.modelId||z.handle.api!==X.api)throw Error(`Unknown faux deferred response: ${X.id}`);if(z.cancelled)throw Error(`Faux deferred response was cancelled: ${X.id}`);if(z.pendingFetches>0){z.pendingFetches--,await hp(Z,uR(V,z.handle),c,p,g,se?.signal);return}if(!z.final){let{deferred:ce,signal:he,onResponse:ve,...fe}=z.options??{};try{z.final=await k(z.step,z.context,fe,z.model)}catch(ie){z.final=fp(ie,n,i,z.model.id)}}await hp(Z,z.final,c,p,g,se?.signal)}catch(z){let ce=fp(z,n,i,V.id);Z.push({type:"error",reason:"error",error:ce}),Z.end(ce)}}),Z},Y=async(V,X,se)=>{x.cancelledDeferred.push(structuredClone(X));let Z=b.get(X.id);if(Z)Z.cancelled=!0;await se?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return T[0];return T.find((X)=>X.id===V)}return{api:n,provider:i,models:T,stream:A,streamSimple:L,fetchDeferred:q,cancelDeferred:Y,getModel:j,state:x,setResponses(V){f=[...V]},appendResponses(V){f.push(...V)},getPendingResponseCount(){return f.length}}}function Co(e={}){let n=gR(e);return{provider:d({id:n.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:n.models,api:{stream:n.stream,streamSimple:n.streamSimple,fetchDeferred:n.fetchDeferred,cancelDeferred:n.cancelDeferred}}),api:n.api,models:n.models,getModel:n.getModel,state:n.state,setResponses:n.setResponses,appendResponses:n.appendResponses,getPendingResponseCount:n.getPendingResponseCount}}function fq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function hq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function gq(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 yq(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 Ga(e){oc(e.contentIndex);let n=e.partial.content[e.contentIndex];if(!n)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return n}function Af(e){let n=JSON.stringify(e);if(n===void 0)throw Error("Tool-call arguments are not JSON-serializable");return n}var xq=Af(F(""));function Cf(e,n){if(typeof e==="string")return typeof n==="string"&&n.startsWith(e);if(Array.isArray(e))return Array.isArray(n)&&e.length<=n.length&&e.every((c,p)=>Cf(c,n[p]));if(typeof e!=="object"||e===null)return Object.is(e,n);if(typeof n!=="object"||n===null||Array.isArray(n))return!1;let i=n;return Object.entries(e).every(([c,p])=>Object.hasOwn(i,c)&&Cf(p,i[c]))}class yR{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:yq(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 n=Ga(e);if(n.type!=="text")throw Error(`text_start event points to ${n.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:n.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:fq(n)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let n=Ga(e);if(n.type!=="text")throw Error(`text_end event points to ${n.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...n.textSignature===void 0?{}:{textSignature:n.textSignature}}}case"thinking_start":{let n=Ga(e);if(n.type!=="thinking")throw Error(`thinking_start event points to ${n.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:n.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:hq(n)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let n=Ga(e);if(n.type!=="thinking")throw Error(`thinking_end event points to ${n.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...n.thinkingSignature===void 0?{}:{thinkingSignature:n.thinkingSignature},...n.redacted===void 0?{}:{redacted:n.redacted}}}case"toolcall_start":{let n=Ga(e);if(n.type!=="toolCall")throw Error(`toolcall_start event points to ${n.type} block at index ${e.contentIndex}`);let i=Af(n.arguments),c=i===xq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:c,catchupJson:"",snapshotArguments:c?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:gq(n)}}case"toolcall_delta":{let n=this.block(e.contentIndex,"toolCall");if(n.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(n.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};n.catchupJson+=e.delta;let i=F(n.catchupJson);if(Af(i)!==n.snapshotArguments){let p=F(n.snapshotArguments);if(!Cf(p,i))return}n.caughtUp=!0,n.snapshotArguments="";let c=n.catchupJson;return n.catchupJson="",c.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:c}}case"toolcall_end":{let n=Ga(e);if(n.type!=="toolCall")throw Error(`toolcall_end event points to ${n.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,n){if(oc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,n)}block(e,n){oc(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${n} block ${e} has not started`);if(i.kind!==n)throw Error(`Assistant message block ${e} is ${i.kind}, not ${n}`);return i}endBlock(e,n){this.block(e,n),this.blocks.delete(e)}encodeTextDelta(e,n,i){let c=this.block(e,i);if(c.kind==="toolCall")throw Error("Unreachable text encoder state");let p=c.deltaChars;c.deltaChars+=n.length;let f=Math.max(0,c.coveredChars-p);if(f>=n.length)return;let g=f===0?n:n.slice(f);return i==="text"?{type:"text_delta",contentIndex:e,delta:g}:{type:"thinking_delta",contentIndex:e,delta:g}}}function kf(e,n,i,c,p){if(oc(i),i!==e.content.length){let f=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${f}`)}e.content.push(structuredClone(c)),n.set(i,p)}function ia(e,n,i,c,p){oc(i);let f=n.get(i),g=e.content[i];if(!f||!g)throw Error(`${p} frame has no started block at index ${i}`);if(f.kind!==c||g.type!==c)throw Error(`${p} frame expected ${c} block at index ${i}, found ${g.type}`);if(f.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:g,state:f}}function Iq(e){let n,i,c=new Map;for(let p of e){if(p.type==="start"){if(n)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`);n=structuredClone(p.partial);continue}if(!n){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`);kf(n,c,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:f}=ia(n,c,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");f.text+=p.delta;break}case"text_end":{let{block:f,state:g}=ia(n,c,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");if(f.text=p.content,delete f.textSignature,p.textSignature!==void 0)f.textSignature=p.textSignature;g.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);kf(n,c,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:f}=ia(n,c,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");f.thinking+=p.delta;break}case"thinking_end":{let{block:f,state:g}=ia(n,c,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");if(f.thinking=p.content,delete f.thinkingSignature,delete f.redacted,p.thinkingSignature!==void 0)f.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)f.redacted=p.redacted;g.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);kf(n,c,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:f,state:g}=ia(n,c,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||g.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");g.json=p.json,f.arguments=F(p.json);break}case"toolcall_delta":{let{block:f,state:g}=ia(n,c,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||g.kind!=="toolCall")throw Error("Unreachable tool-call frame state");g.json+=p.delta;break}case"toolcall_end":{let{block:f,state:g}=ia(n,c,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(f.id=p.id,f.name=p.name,f.arguments=structuredClone(p.arguments),delete f.thoughtSignature,delete f.namespace,p.thoughtSignature!==void 0)f.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)f.namespace=p.namespace;g.ended=!0;break}}}if(!n)return;for(let[p,f]of c){if(f.kind!=="toolCall"||f.ended||f.json.length===0)continue;let g=n.content[p];if(g?.type!=="toolCall")throw Error("Unreachable tool-call frame state");g.arguments=F(f.json)}return n}var xR=[/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],bq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Eq=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function li(e,n){if(e.stopReason==="error"&&e.errorMessage){if(!Eq.some((c)=>c.test(e.errorMessage))){if(xR.some((c)=>c.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&bq.test(e.errorMessage))return!0}}if(n&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>n)return!0}if(n&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=n*0.99)return!0}return!1}function Sq(e,n){return e.stopReason==="length"&&n>0&&e.usage.output<n}function wq(){return[...xR]}function IR(e){return new RegExp(e.join("|"),"i")}var Tq=IR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),Rq=IR(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),bR=60000;function ER(e,n){let i=e.baseDelayMs*2**Math.max(0,n-1),c=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(c,e.maxAgentDelayMs??bR)}class yp extends Error{constructor(){super("Aborted")}}function kq(e,n){return new Promise((i,c)=>{if(n?.aborted){c(new yp);return}let p=setTimeout(i,e);n?.addEventListener("abort",()=>{clearTimeout(p),c(new yp)},{once:!0})})}async function Aq(e,n,i,c){let p=n?.enabled?n.maxRetries:0,f=0,g;for(;;){let x=await e();if(x.stopReason==="aborted"){if(g)await c?.onRetryFinished?.(!1,g.attempt);return x}if(x.stopReason!=="error"){if(g)await c?.onRetryFinished?.(!0,g.attempt);return x}if(f>=p||!SR(x)){if(g)await c?.onRetryFinished?.(!1,g.attempt,x.errorMessage);return x}f++,g={attempt:f,errorMessage:x.errorMessage||"Unknown error"};let I=ER(n,f);await c?.onRetryScheduled?.(f,p,I,g.errorMessage);try{await kq(I,i)}catch(b){if(await c?.onRetryFinished?.(!1,f,g.errorMessage),b instanceof yp){let{errorMessage:E,...T}=x;return{...T,stopReason:"aborted"}}throw b}await c?.onRetryAttemptStart?.()}}function SR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let n=e.errorMessage;if(Tq.test(n))return!1;return Rq.test(n)}function Cq(e,n){return Br({type:"string",enum:e,...n?.description&&{description:n.description},...n?.default&&{default:n.default}})}function sc(e){return le(e,"~refine")&&Be(e["~refine"])&&nn(e["~refine"],0,(n)=>at(n)&&le(n,"check")&&le(n,"error")&&ms(n.check)&&ms(n.error))}function dn(e){return at(e)&&!Be(e)}function Ls(e){return un(e)}function Xe(e){return dn(e)||Ls(e)}function Ka(e){return le(e,"additionalItems")&&Xe(e.additionalItems)}function Ao(e){return le(e,"additionalProperties")&&Xe(e.additionalProperties)}function ic(e){return le(e,"allOf")&&Be(e.allOf)&&e.allOf.every((n)=>Xe(n))}function ac(e){return le(e,"$anchor")&>(e.$anchor)}function uc(e){return le(e,"anyOf")&&Be(e.anyOf)&&e.anyOf.every((n)=>Xe(n))}function xp(e){return le(e,"const")}function Rs(e){return le(e,"contains")&&Xe(e.contains)}function ho(e){return le(e,"default")}function cc(e){return le(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((n)=>Xe(n)||Be(n)&&n.every((i)=>gt(i)))}function mc(e){return le(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((n)=>Be(n)&&n.every((i)=>gt(i)))}function Ha(e){return le(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((n)=>Xe(n))}function Ns(e){return le(e,"$dynamicAnchor")&>(e.$dynamicAnchor)}function pc(e){return le(e,"$dynamicRef")&>(e.$dynamicRef)}function lc(e){return le(e,"else")&&Xe(e.else)}function Ip(e){return le(e,"enum")&&Be(e.enum)}function dc(e){return le(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||_r(e.exclusiveMaximum))}function Zo(e){return le(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||_r(e.exclusiveMinimum))}function aa(e){return le(e,"format")&>(e.format)}function go(e){return le(e,"$id")&>(e.$id)}function fc(e){return le(e,"if")&&Xe(e.if)}function Ds(e){return le(e,"items")&&(Xe(e.items)||Be(e.items)&&e.items.every((n)=>Xe(n)))}function hc(e){return Ds(e)&&Be(e.items)}function gc(e){return le(e,"maximum")&&(Ot(e.maximum)||_r(e.maximum))}function yc(e){return le(e,"maxContains")&&Ot(e.maxContains)}function Wa(e){return le(e,"maxItems")&&Ot(e.maxItems)}function xc(e){return le(e,"maxLength")&&Ot(e.maxLength)}function Ic(e){return le(e,"maxProperties")&&Ot(e.maxProperties)}function es(e){return le(e,"minimum")&&(Ot(e.minimum)||_r(e.minimum))}function qs(e){return le(e,"minContains")&&Ot(e.minContains)}function Ii(e){return le(e,"minItems")&&Ot(e.minItems)}function ua(e){return le(e,"minLength")&&Ot(e.minLength)}function ca(e){return le(e,"minProperties")&&Ot(e.minProperties)}function bc(e){return le(e,"multipleOf")&&(Ot(e.multipleOf)||_r(e.multipleOf))}function Ec(e){return le(e,"not")&&Xe(e.not)}function Sc(e){return le(e,"oneOf")&&Be(e.oneOf)&&e.oneOf.every((n)=>Xe(n))}function ma(e){return le(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function Fs(e){return le(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((n)=>Xe(n))}function ts(e){return le(e,"prefixItems")&&Be(e.prefixItems)&&e.prefixItems.every((n)=>Xe(n))}function js(e){return le(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((n)=>Xe(n))}function za(e){return le(e,"propertyNames")&&(at(e.propertyNames)||Xe(e.propertyNames))}function $q(e){return le(e,"$recursiveAnchor")&&un(e.$recursiveAnchor)}function wc(e){return $q(e)&&_(e.$recursiveAnchor,!0)}function Tc(e){return le(e,"$recursiveRef")&>(e.$recursiveRef)}function Rc(e){return le(e,"$ref")&>(e.$ref)}function rs(e){return le(e,"required")&&Be(e.required)&&e.required.every((n)=>gt(n))}function kc(e){return le(e,"then")&&Xe(e.then)}function Ac(e){return le(e,"type")&&(gt(e.type)||Be(e.type)&&e.type.every((n)=>gt(n)))}function Ri(e){return le(e,"uniqueItems")&&un(e.uniqueItems)}function Ci(e){return le(e,"unevaluatedItems")&&Xe(e.unevaluatedItems)}function $i(e){return le(e,"unevaluatedProperties")&&Xe(e.unevaluatedProperties)}function Pq(e){return Ci(e)||$i(e)||Ea(Ee(e),(n)=>bp(e[n]))}function Mq(e){return Ea(e,(n)=>bp(n))}function bp(e){return Be(e)?Mq(e):at(e)?Pq(e):!1}function wR(e,n){return bp(n)||Ea(Ee(e),(i)=>bp(e[i]))}class $f{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return yr(bt("context","Push"),[])}Pop(){return yr(bt("context","Pop"),[])}AddIndex(e){return yr(bt("context","AddIndex"),[e])}AddKey(e){return yr(bt("context","AddKey"),[e])}Merge(e){return yr(bt("context","Merge"),[e])}}class _n{constructor(){let e=new Set,n=new Set;this.stack=[{indices:e,keys:n}]}Push(){let e=new Set,n=new Set;return this.stack.push({indices:e,keys:n}),!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 n of e)n.GetIndices().forEach((i)=>this.GetIndices().add(i)),n.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class Nn extends _n{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Vo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var Ep={identifier:"External",variables:[]};function vo(e){let n=`External[${Ep.variables.length}]`;return Ep.variables.push(e),n}function TR(){Ep.variables=[]}function RR(){return{...Ep}}function kR(e,n,i,c){let p=vo(i["~refine"].map((f)=>f));return ls(p,De(0),["refinement","_"],yr(bt("refinement","check"),[c]))}function AR(e,n,i,c){return nn(i["~refine"],0,(p,f)=>p.check(c))}function CR(e,n,i,c,p,f){return Rn(p["~refine"],0,(g,x)=>g.check(f)||n.AddError({keyword:"~refine",schemaPath:i,instancePath:c,params:{index:x,message:g.error(f)}}))}var vq=0;function Vt(){return`var_${vq++}`}function Pf(e){return Ds(e)&&Be(e.items)}function Oq(e,n,i,c){let[p,f]=[Vt(),Vt()],g=Xn(e,n,i.additionalItems,p),x=pd(f,De(i.items.length)),I=n.AddIndex(f);return ls(c,De(0),[p,f],gr(x,bn(g,I)))}function _q(e,n,i,c){let[p,f]=[Vt(),Vt()],g=Xn(e,n,i.additionalItems,p),x=pd(f,De(i.items.length));return ls(c,De(0),[p,f],gr(x,g))}function $R(e,n,i,c){if(!Pf(i))return De(!0);return n.UseUnevaluated()?Oq(e,n,i,c):_q(e,n,i,c)}function PR(e,n,i,c){if(!Pf(i))return!0;return nn(c,0,(f,g)=>Su(g,i.items.length)||yo(e,n,i.additionalItems,f)&&n.AddIndex(g))}function MR(e,n,i,c,p,f){if(!Pf(p))return!0;return nn(f,0,(x,I)=>{let b=`${i}/additionalItems`,E=`${c}/${I}`;return Su(I,p.items.length)||xo(e,n,b,E,p.additionalItems,x)&&n.AddIndex(I)})}function ns(e){return new RegExp(e,"u")}function Lq(e,n){return!e.UseUnevaluated()&&(_(n,!0)||at(n)&&_(Ee(n).length,0))}function Nq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Mf(e){let n=[];if(Fs(e))n.push(...Ee(e.patternProperties));if(js(e))n.push(...Ee(e.properties).map(Nq));return _(n.length,0)?"(?!)":`(${n.join("|")})`}function Dq(e,n,i){return rs(n)&&js(n)&&!Fs(n)&&_(n.additionalProperties,!1)&&_(Ee(n.properties).length,n.required.length)}function qq(e,n,i){return oo(bt(yr(bt("Object","getOwnPropertyNames"),[i]),"length"),De(n.required.length))}function Fq(e,n,i,c){let[p,f]=[Vt(),Vt()],g=vo(ns(Mf(i))),x=Xn(e,n,i.additionalProperties,`${c}[${p}]`),I=yr(bt(g,"test"),[p]),b=n.AddKey(p),E=n.UseUnevaluated()?gr(I,bn(x,b)):gr(I,x);return ls(Hi(c),De(0),[p,f],E)}function vR(e,n,i,c){if(Lq(n,i.additionalProperties))return De(!0);return Dq(n,i,c)?qq(n,i,c):Fq(e,n,i,c)}function OR(e,n,i,c){let p=ns(Mf(i));return nn(Ee(c),0,(g,x)=>p.test(g)||yo(e,n,i.additionalProperties,c[g])&&n.AddKey(g))}function _R(e,n,i,c,p,f){let g=ns(Mf(p)),x=[];return Rn(Ee(f),0,(b,E)=>{let T=`${i}/additionalProperties`,k=`${c}/${b}`,A=g.test(b)||xo(e,n,T,k,p.additionalProperties,f[b])&&n.AddKey(b);if(!A)x.push(b);return A})||n.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:c,params:{additionalProperties:x}})}function Mi(e,n,i,c,p){let f=vs("results","[]"),g=i.map((E,T)=>vs(`context_${T}`,ld("CheckContext",[]))),x=i.map((E,T)=>vs(`condition_${T}`,yr(Vs(["context"],Nt(e,n,E,c)),[`context_${T}`]))),I=i.map((E,T)=>wy(`condition_${T}`,yr(bt("results","push"),[`context_${T}`]))),b=am(bn(p,n.Merge("results")));return yr(Vs([],im([f,...g,...x,...I,b])),[])}function jq(e,n,i,c){return Mi(e,n,i.allOf,c,oo(bt("results","length"),De(i.allOf.length)))}function Uq(e,n,i,c){return kn(i.allOf.map((p)=>Nt(e,n,p,c)))}function LR(e,n,i,c){return n.UseUnevaluated()?jq(e,n,i,c):Uq(e,n,i,c)}function NR(e,n,i,c){let p=i.allOf.reduce((f,g)=>{let x=new _n;return kt(e,x,g,c)?[...f,x]:f},[]);return _(p.length,i.allOf.length)&&n.Merge(p)}function DR(e,n,i,c,p,f){let g=[],x=p.allOf.reduce((b,E,T)=>{let k=`${i}/allOf/${T}`,A=new Nn,L=mr(e,A,k,c,E,f);if(!L)g.push(A);return L?[...b,A]:b},[]),I=_(x.length,p.allOf.length)&&n.Merge(x);if(!I)g.forEach((b)=>b.GetErrors().forEach((E)=>n.AddError(E)));return I}function Bq(e,n,i,c){return Mi(e,n,i.anyOf,c,by(bt("results","length"),De(0)))}function Gq(e,n,i,c){return dd(i.anyOf.map((p)=>Nt(e,n,p,c)))}function qR(e,n,i,c){return n.UseUnevaluated()?Bq(e,n,i,c):Gq(e,n,i,c)}function FR(e,n,i,c){let p=i.anyOf.reduce((f,g)=>{let x=new _n;return kt(e,x,g,c)?[...f,x]:f},[]);return Bi(p.length,0)&&n.Merge(p)}function jR(e,n,i,c,p,f){let g=[],x=p.anyOf.reduce((b,E,T)=>{let k=new Nn,A=`${i}/anyOf/${T}`,L=mr(e,k,A,c,E,f);if(!L)g.push(k);return L?[...b,k]:b},[]),I=Bi(x.length,0)&&n.Merge(x);if(!I)g.forEach((b)=>b.GetErrors().forEach((E)=>n.AddError(E)));return I||n.AddError({keyword:"anyOf",schemaPath:i,instancePath:c,params:{}})}function UR(e,n,i,c){return i?De(!0):De(!1)}function vf(e,n,i,c){return i}function BR(e,n,i,c,p,f){return vf(e,n,p,f)||n.AddError({keyword:"boolean",schemaPath:i,instancePath:c,params:{}})}function GR(e,n,i,c){return Gi(i.const)?oo(c,De(i.const)):Sy(c,vo(i.const))}function Of(e,n,i,c){return Gi(i.const)?_(c,i.const):Sa(c,i.const)}function KR(e,n,i,c,p,f){return Of(e,n,p,f)||n.AddError({keyword:"const",schemaPath:i,instancePath:c,params:{allowedValue:p.const}})}function HR(e){return!(qs(e)&&_(e.minContains,0))}function Kq(e,n,i,c){let[p,f]=[Vt(),Vt()],g=Fn(oo(bt(c,"length"),De(0))),x=Tv(c,[p,f],bn(Nt(e,n,i.contains,p),n.AddIndex(f)));return bn(g,x)}function Hq(e,n,i,c){let[p]=[Vt()],f=Fn(oo(bt(c,"length"),De(0))),g=wv(c,[p,"_"],Nt(e,n,i.contains,p));return bn(f,g)}function WR(e,n,i,c){if(!HR(i))return De(!0);return n.UseUnevaluated()?Kq(e,n,i,c):Hq(e,n,i,c)}function _f(e,n,i,c){if(!HR(i))return!0;return!_(c.length,0)&&dy(c,(p,f)=>kt(e,n,i.contains,p)&&n.AddIndex(f))}function zR(e,n,i,c,p,f){return _f(e,n,p,f)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:1}})}function VR(e,n,i,c){let p=oo(bt(Hi(c),"length"),De(0)),f=kn(cn(i.dependencies).map(([g,x])=>{let I=Fn(Wi(c,De(g))),b=Nt(e,n,x,c),E=(T)=>kn(T.map((k)=>Wi(c,De(k))));return gr(I,Be(x)?E(x):b)}));return gr(p,f)}function JR(e,n,i,c){let p=_(Ee(c).length,0),f=nn(cn(i.dependencies),0,([g,x])=>!le(c,g)||(Be(x)?x.every((I)=>le(c,I)):kt(e,n,x,c)));return p||f}function QR(e,n,i,c,p,f){let g=_(Ee(f).length,0),x=Rn(cn(p.dependencies),0,([I,b])=>{let E=`${i}/dependencies/${I}`;return!le(f,I)||(Be(b)?b.every((T)=>le(f,T)||n.AddError({keyword:"dependencies",schemaPath:i,instancePath:c,params:{property:I,dependencies:b}})):mr(e,n,E,c,b,f))});return g||x}function XR(e,n,i,c){let p=oo(bt(Hi(c),"length"),De(0)),f=kn(cn(i.dependentRequired).map(([g,x])=>{let I=Fn(Wi(c,De(g))),b=kn(x.map((E)=>Wi(c,De(E))));return gr(I,b)}));return gr(p,f)}function YR(e,n,i,c){let p=_(Ee(c).length,0),f=nn(cn(i.dependentRequired),0,([g,x])=>!le(c,g)||x.every((I)=>le(c,I)));return p||f}function ZR(e,n,i,c,p,f){let g=_(Ee(f).length,0),x=Rn(cn(p.dependentRequired),0,([I,b])=>!le(f,I)||Rn(b,0,(E)=>le(f,E)||n.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:c,params:{property:I,dependencies:b}})));return g||x}function ek(e,n,i,c){let p=oo(bt(Hi(c),"length"),De(0)),f=kn(cn(i.dependentSchemas).map(([g,x])=>{let I=Fn(Wi(c,De(g))),b=Nt(e,n,x,c);return gr(I,b)}));return gr(p,f)}function tk(e,n,i,c){let p=_(Ee(c).length,0),f=nn(cn(i.dependentSchemas),0,([g,x])=>!le(c,g)||kt(e,n,x,c));return p||f}function rk(e,n,i,c,p,f){let g=_(Ee(f).length,0),x=Rn(cn(p.dependentSchemas),0,([I,b])=>{let E=`${i}/dependentSchemas/${I}`;return!le(f,I)||mr(e,n,E,c,b,f)});return g||x}function nk(e,n,i,c){let p=e.DynamicRef(i)??!1;return Us(e,n,p,c)}function ok(e,n,i,c){let p=e.DynamicRef(i)??!1;return Xe(p)&&kt(e,n,p,c)}function sk(e,n,i,c,p,f){let g=e.DynamicRef(p)??!1;return Xe(g)&&mr(e,n,"#",c,g,f)}function ik(e,n,i,c){return dd(i.enum.map((p)=>{if(Gi(p))return oo(c,De(p));let f=vo(p);return Sy(c,f)}))}function Nf(e,n,i,c){return Ea(i.enum,(p)=>Gi(p)?_(c,p):Sa(c,p))}function ak(e,n,i,c,p,f){return Nf(e,n,p,f)||n.AddError({keyword:"enum",schemaPath:i,instancePath:c,params:{allowedValues:p.enum}})}function uk(e,n,i,c){return pd(c,De(i.exclusiveMaximum))}function Df(e,n,i,c){return Su(c,i.exclusiveMaximum)}function ck(e,n,i,c,p,f){return Df(e,n,p,f)||n.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:c,params:{comparison:"<",limit:p.exclusiveMaximum}})}function mk(e,n,i,c){return by(c,De(i.exclusiveMinimum))}function qf(e,n,i,c){return Bi(c,i.exclusiveMinimum)}function pk(e,n,i,c,p,f){return qf(e,n,p,f)||n.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:c,params:{comparison:">",limit:p.exclusiveMinimum}})}var Wq=[0,31,28,31,30,31,30,31,31,30,31,30,31],zq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function Vq(e){return e%4===0&&(e%100!==0||e%400===0)}function Ja(e){let n=zq.exec(e);if(!n)return!1;let i=+n[1],c=+n[2],p=+n[3];return c>=1&&c<=12&&p>=1&&p<=(c===2&&Vq(i)?29:Wq[c])}var Jq=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Qa(e,n=!0){let i=Jq.exec(e);if(!i)return!1;if(n&&!i[4]&&!i[5])return!1;let c=+i[1],p=+i[2],f=+i[3];if(c>23||p>59||f>60)return!1;if(i[5]){let E=+i[6],T=+i[7];if(E>23||T>59)return!1}if(f<60)return!0;let g=i[5]==="-"?-1:1,x=+(i[6]||0),I=+(i[7]||0);return((c*60+p-g*(x*60+I))%1440+1440)%1440===1439}function Sp(e){let n=e.split(/T/i);return n.length===2&&Ja(n[0])&&Qa(n[1])}var Qq=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function wp(e){return Qq.test(e)}var Xq=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function Tp(e){return Xq.test(e)}var lk=/^(?!-).*(?<!-)$/,dk=/^(?!..--)/,fk=/^[a-zA-Z0-9-]*$/;var Xa=/[^\p{ASCII}]/u;var Yq=/[0-9]/,hk=/[\u{0660}-\u{0669}]/u,Zq=/[\u{06f0}-\u{06f9}]/u,eF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,tF=/[\u{002d}\u{002b}]/u,Ff=/\p{Mn}/u,rF=/\p{Mc}/u;var gk=/[\p{Mn}\p{Mc}\p{Me}]/u,jf=/\p{L}/u,nF=/\p{Nd}/u,yk=/\p{Script=Greek}/u,Rp=/\p{Script=Hebrew}/u,xk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Ik=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Uf=/[\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,bk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,oF=/[\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,Ek=new RegExp([Yq,Zq].map((e)=>e.source).join("|"),"u"),Sk=new RegExp([jf,tF,eF,nF,Ff,rF,oF,sF].map((e)=>e.source).join("|"),"u");function wk(e){return lk.test(e)&&dk.test(e)&&fk.test(e)}var os=36,$c=1,Pc=26,aF=38,uF=700,Rk=72,kk=128;function Bf(){throw null}function kp(e){return e.toLowerCase().startsWith("xn--")}function Ak(e,n,i){e=i?Math.floor(e/uF):e>>1,e+=Math.floor(e/n);let c=0;while(e>(os-$c)*Pc>>1)e=Math.floor(e/(os-$c)),c+=os;return c+Math.floor((os-$c+1)*e/(e+aF))}function Ap(e){let n=[],i=kk,c=0,p=Rk,f=e.lastIndexOf("-");if(f>0)for(let x=0;x<f;x++){let I=e.charCodeAt(x);if(I>=128)Bf();n.push(I)}let g=f<0?0:f+1;while(g<e.length){let x=c,I=1,b=os;while(!0){if(g>=e.length)Bf();let T=e.charCodeAt(g++),k;if(T>=97&&T<=122)k=T-97;else if(T>=48&&T<=57)k=T-48+26;else Bf();c+=k*I;let A=b<=p?$c:b>=p+Pc?Pc:b-p;if(k<A)break;I*=os-A,b+=os}let E=n.length+1;p=Ak(c-x,E,x===0),i+=Math.floor(c/E),c%=E,n.splice(c,0,i),c++}return String.fromCodePoint(...n)}function Tk(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var cF=new RegExp(Xa.source,"gu");function Ck(e){let n=e.replace(cF,""),i=n.length,c=i>0?[n,"-"]:[],p=Array.from(e,(b)=>b.codePointAt(0)),f=kk,g=0,x=Rk,I=i;while(I<p.length){let b=1/0;for(let E of p)if(E>=f&&E<b)b=E;g+=(b-f)*(I+1),f=b;for(let E of p){if(E<f)g++;if(E===f){let T=g;for(let k=os;;k+=os){let A=k<=x?$c:k>=x+Pc?Pc:k-x;if(T<A)break;let L=A+(T-A)%(os-A);c.push(Tk(L)),T=Math.floor((T-A)/(os-A))}c.push(Tk(T)),x=Ak(g,I+1,I===i),g=0,I++}}g++,f++}return c.join("")}var mF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,$k=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,pF=/^(?:R|AL|AN)$/;function Pk(e){if(kp(e))try{return Cp(Ap(e.slice(4).toLowerCase()))}catch{return!1}return Cp(e)}function Mk(e){let n=String.fromCodePoint(e);return Ek.test(n)?"EN":hk.test(n)?"AN":Ff.test(n)?"NSM":Rp.test(n)?"R":Ik.test(n)?"AL":jf.test(n)?"L":"ON"}function Cp(e){for(let n of e)if(pF.test(Mk(n.codePointAt(0))))return!0;return!1}function $p(e){let n=!1,i=$k,c=!1,p=!1,f=!0;for(let g of e){let x=Mk(g.codePointAt(0));if(f){if(x!=="L"&&x!=="R"&&x!=="AL")return!1;n=x==="R"||x==="AL",i=n?mF:$k,f=!1}if(!i.test(x))return!1;if(x==="EN")c=!0;else if(x==="AN")p=!0}if(n&&c&&p)return!1;return!0}function lF(e){return Xa.test(e)&&Ck(e).length+4>63}function dF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Pp(e){if(lF(e))return!1;if(Cp(e)&&!$p(e))return!1;let n=[...e],i=n.map((f)=>f.codePointAt(0)),c=i.length;if(dF(n))return!1;if(gk.test(n[0]))return!1;let p=!1;for(let f=0;f<c;f++){let g=i[f],x=n[f];if(bk.test(x))return!1;if(!Sk.test(x))return!1;if(xk.test(x))p=!0;let I=i[f-1],b=i[f+1];switch(g){case 183:if(I!==108||b!==108)return!1;break;case 885:if(!b||!yk.test(n[f+1]))return!1;break;case 1523:case 1524:if(!I||!Rp.test(n[f-1]))return!1;break;case 8204:if(!I||I<128&&!Uf.test(n[f-1]))return!1;break;case 8205:if(!I||!Uf.test(n[f-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function Mp(e){if(!kp(e))return!1;try{let n=e.slice(4).toLowerCase();if(n.lastIndexOf("-")===0)return!1;let i=Ap(n);if(!Xa.test(i))return!1;return Pp(i)}catch{return!1}}function fF(e){return e.length>0&&e.length<=63}function hF(e){return fF(e)&&(Mp(e)||wk(e))}function Lk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((n)=>hF(n))}function gF(e){return e.length>0&&e.length<=63}function yF(e){return gF(e)&&(Mp(e)||Pp(e))}function xF(e){return e.replace(/[\uff01-\uff5e]/g,(n)=>String.fromCharCode(n.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 Nk(e){if(e.length===0||e.includes(" "))return!1;let n=xF(e);if(n.length>253)return!1;let i=n.split("."),c=i.some((p)=>Pk(p));return i.every((p)=>yF(p)&&(!c||$p(p)))}function vp(e){return Lk(e)}var IF=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Op(e){return IF.test(e.normalize("NFC"))}function _p(e){return Nk(e)}var bF=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Lp(e){return bF.test(e)}var EF=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function Np(e){return EF.test(e)}var SF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,wF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Dp(e){return!SF.test(e)&&!wF.test(e)&&URL.canParse(e,"http://example.com")}var TF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,RF=/[\x00-\x20<>\^`{|}\\]/,kF=/%(?![0-9a-fA-F]{2})/;function AF(e){return e.length<2048?e.replace(TF,"[::1]"):e}function qp(e){if(RF.test(e))return!1;if(kF.test(e))return!1;return URL.canParse(AF(e))}var CF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Fp(e){return CF.test(e)}var $F=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function jp(e){return $F.test(e)}function Up(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var PF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Bp(e){return PF.test(e)}var MF=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Gp(e){return MF.test(e)}var vF=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Kp(e){return vF.test(e)}var OF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Hp(e){return OF.test(e)}function Wp(e){return URL.canParse(e)}var _F=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function zp(e){return _F.test(e)}var Ir=new Map;function qk(){Ir.clear()}function LF(){return[...Ir.entries()]}function NF(e,n){Ir.set(e,n)}function DF(e){return Ir.has(e)}function qF(e){return Ir.get(e)}function Fk(e,n){return Ir.get(e)?.(n)??!0}function jk(){qk(),Ir.set("date-time",Sp),Ir.set("date",Ja),Ir.set("duration",wp),Ir.set("email",Tp),Ir.set("hostname",vp),Ir.set("idn-email",Op),Ir.set("idn-hostname",_p),Ir.set("ipv4",Lp),Ir.set("ipv6",Np),Ir.set("iri-reference",Dp),Ir.set("iri",qp),Ir.set("json-pointer-uri-fragment",Fp),Ir.set("json-pointer",jp),Ir.set("regex",Up),Ir.set("relative-json-pointer",Bp),Ir.set("time",Qa),Ir.set("uri-reference",Gp),Ir.set("uri-template",Kp),Ir.set("uri",Hp),Ir.set("url",Wp),Ir.set("uuid",zp)}jk();function Uk(e,n,i,c){return yr(bt("Format","Test"),[De(i.format),c])}function Kf(e,n,i,c){return Fk(i.format,c)}function Bk(e,n,i,c,p,f){return Kf(e,n,p,f)||n.AddError({keyword:"format",schemaPath:i,instancePath:c,params:{format:p.format}})}function Gk(e,n,i,c){let p=kc(i)?i.then:!0,f=lc(i)?i.else:!0;return kv(Nt(e,n,i.if,c),Nt(e,n,p,c),Nt(e,n,f,c))}function Kk(e,n,i,c){let p=kc(i)?i.then:!0,f=lc(i)?i.else:!0;return kt(e,n,i.if,c)?kt(e,n,p,c):kt(e,n,f,c)}function Hk(e,n,i,c,p,f){let g=kc(p)?p.then:!0,x=lc(p)?p.else:!0,I=new Nn,b=mr(e,I,`${i}/if`,c,p.if,f)?mr(e,I,`${i}/then`,c,g,f)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"then"}}):mr(e,n,`${i}/else`,c,x,f)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"else"}});if(b)n.Merge([I]);return b}function FF(e,n,i,c){return kn(i.items.map((p,f)=>{let g=Ki(bt(c,"length"),De(f)),x=Xn(e,n,p,`${c}[${f}]`),I=n.AddIndex(De(f));return gr(g,bn(x,I))}))}function jF(e,n,i,c){return kn(i.items.map((p,f)=>{let g=Ki(bt(c,"length"),De(f)),x=Xn(e,n,p,`${c}[${f}]`);return gr(g,x)}))}function UF(e,n,i,c){return n.UseUnevaluated()?FF(e,n,i,c):jF(e,n,i,c)}function BF(e,n,i,c){return nn(i.items,0,(p,f)=>ps(c.length,f)||yo(e,n,p,c[f])&&n.AddIndex(f))}function GF(e,n,i,c,p,f){return Rn(p.items,0,(g,x)=>{let I=`${i}/items/${x}`,b=`${c}/${x}`;return ps(f.length,x)||xo(e,n,I,b,g,f[x])&&n.AddIndex(x)})}function KF(e,n,i,c){let p=ts(i)?i.prefixItems.length:0,f=Xn(e,n,i.items,"element"),g=n.AddIndex("index");return ls(c,De(p),["element","index"],bn(f,g))}function HF(e,n,i,c){let p=ts(i)?i.prefixItems.length:0,f=Xn(e,n,i.items,"element");return ls(c,De(p),["element","index"],f)}function WF(e,n,i,c){return n.UseUnevaluated()?KF(e,n,i,c):HF(e,n,i,c)}function zF(e,n,i,c){let p=ts(i)?i.prefixItems.length:0;return nn(c,p,(f,g)=>yo(e,n,i.items,f)&&n.AddIndex(g))}function VF(e,n,i,c,p,f){let g=ts(p)?p.prefixItems.length:0;return Rn(f,g,(x,I)=>{let b=`${i}/items`,E=`${c}/${I}`;return xo(e,n,b,E,p.items,x)&&n.AddIndex(I)})}function Wk(e,n,i,c){return hc(i)?UF(e,n,i,c):WF(e,n,i,c)}function zk(e,n,i,c){return hc(i)?BF(e,n,i,c):zF(e,n,i,c)}function Vk(e,n,i,c,p,f){return hc(p)?GF(e,n,i,c,p,f):VF(e,n,i,c,p,f)}function Jk(e){return Rs(e)}function Qk(e,n,i,c){if(!Jk(i))return De(!0);let[p]=[Vt()],f=sm(c,[p,"_"],Nt(e,n,i.contains,p));return Ki(f,De(i.maxContains))}function Hf(e,n,i,c){if(!Jk(i))return!0;let p=ad(c,(f)=>kt(e,n,i.contains,f));return ps(p,i.maxContains)}function Xk(e,n,i,c,p,f){let g=qs(p)?p.minContains:1;return Hf(e,n,p,f)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:g,maxContains:p.maxContains}})}function Yk(e,n,i,c){return Ki(c,De(i.maximum))}function Wf(e,n,i,c){return ps(c,i.maximum)}function Zk(e,n,i,c,p,f){return Wf(e,n,p,f)||n.AddError({keyword:"maximum",schemaPath:i,instancePath:c,params:{comparison:"<=",limit:p.maximum}})}function eA(e,n,i,c){return Ki(bt(c,"length"),De(i.maxItems))}function zf(e,n,i,c){return ps(c.length,i.maxItems)}function tA(e,n,i,c,p,f){return zf(e,n,p,f)||n.AddError({keyword:"maxItems",schemaPath:i,instancePath:c,params:{limit:p.maxItems}})}function rA(e,n,i,c){return Sv(c,De(i.maxLength))}function Vf(e,n,i,c){return py(c,i.maxLength)}function nA(e,n,i,c,p,f){return Vf(e,n,p,f)||n.AddError({keyword:"maxLength",schemaPath:i,instancePath:c,params:{limit:p.maxLength}})}function oA(e,n,i,c){return Ki(bt(Hi(c),"length"),De(i.maxProperties))}function Jf(e,n,i,c){return ps(Ee(c).length,i.maxProperties)}function sA(e,n,i,c,p,f){return Jf(e,n,p,f)||n.AddError({keyword:"maxProperties",schemaPath:i,instancePath:c,params:{limit:p.maxProperties}})}function iA(e){return Rs(e)}function JF(e,n,i,c){let[p,f]=[Vt(),Vt()],g=sm(c,[p,f],bn(Nt(e,n,i.contains,p),n.AddIndex(f)));return Tu(g,De(i.minContains))}function QF(e,n,i,c){let[p]=[Vt()],f=sm(c,[p,"_"],Nt(e,n,i.contains,p));return Tu(f,De(i.minContains))}function aA(e,n,i,c){if(!iA(i))return De(!0);return n.UseUnevaluated()?JF(e,n,i,c):QF(e,n,i,c)}function Qf(e,n,i,c){if(!iA(i))return!0;let p=ad(c,(f,g)=>kt(e,n,i.contains,f)&&n.AddIndex(g));return ba(p,i.minContains)}function uA(e,n,i,c,p,f){return Qf(e,n,p,f)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:p.minContains}})}function cA(e,n,i,c){return Tu(c,De(i.minimum))}function Xf(e,n,i,c){return ba(c,i.minimum)}function mA(e,n,i,c,p,f){return Xf(e,n,p,f)||n.AddError({keyword:"minimum",schemaPath:i,instancePath:c,params:{comparison:">=",limit:p.minimum}})}function pA(e,n,i,c){return Tu(bt(c,"length"),De(i.minItems))}function Yf(e,n,i,c){return ba(c.length,i.minItems)}function lA(e,n,i,c,p,f){return Yf(e,n,p,f)||n.AddError({keyword:"minItems",schemaPath:i,instancePath:c,params:{limit:p.minItems}})}function dA(e,n,i,c){return Ev(c,De(i.minLength))}function Zf(e,n,i,c){return ly(c,i.minLength)}function fA(e,n,i,c,p,f){return Zf(e,n,p,f)||n.AddError({keyword:"minLength",schemaPath:i,instancePath:c,params:{limit:p.minLength}})}function hA(e,n,i,c){return Tu(bt(Hi(c),"length"),De(i.minProperties))}function eh(e,n,i,c){return ba(Ee(c).length,i.minProperties)}function gA(e,n,i,c,p,f){return eh(e,n,p,f)||n.AddError({keyword:"minProperties",schemaPath:i,instancePath:c,params:{limit:p.minProperties}})}function yA(e,n,i,c){return Av(c,De(i.multipleOf))}function th(e,n,i,c){return cy(c,i.multipleOf)}function xA(e,n,i,c,p,f){return th(e,n,p,f)||n.AddError({keyword:"multipleOf",schemaPath:i,instancePath:c,params:{multipleOf:p.multipleOf}})}function XF(e,n,i,c){return Mi(e,n,[i.not],c,Fn(oo(bt("results","length"),De(1))))}function YF(e,n,i,c){return Fn(Nt(e,n,i.not,c))}function IA(e,n,i,c){return n.UseUnevaluated()?XF(e,n,i,c):YF(e,n,i,c)}function rh(e,n,i,c){let p=new _n;return!kt(e,p,i.not,c)&&n.Merge([p])}function bA(e,n,i,c,p,f){return rh(e,n,p,f)||n.AddError({keyword:"not",schemaPath:i,instancePath:c,params:{}})}function ZF(e,n,i,c){return Mi(e,n,i.oneOf,c,oo(bt("results","length"),De(1)))}function e1(e,n,i,c){let[p]=[Vt()],f=Rv(i.oneOf.map((x)=>Nt(e,n,x,c))),g=sm(f,[p,"_"],oo(p,De(!0)));return oo(g,De(1))}function EA(e,n,i,c){return n.UseUnevaluated()?ZF(e,n,i,c):e1(e,n,i,c)}function SA(e,n,i,c){let p=i.oneOf.reduce((f,g)=>{let x=new _n;return kt(e,x,g,c)?[...f,x]:f},[]);return _(p.length,1)&&n.Merge(p)}function wA(e,n,i,c,p,f){let g=[],x=[],I=p.oneOf.reduce((E,T,k)=>{let A=new Nn,L=`${i}/oneOf/${k}`,q=mr(e,A,L,c,T,f);if(q)x.push(k);if(!q)g.push(A);return q?[...E,A]:E},[]),b=_(I.length,1)&&n.Merge(I);if(!b&&_(x.length,0))g.forEach((E)=>E.GetErrors().forEach((T)=>n.AddError(T)));return b||n.AddError({keyword:"oneOf",schemaPath:i,instancePath:c,params:{passingSchemas:x}})}function TA(e,n,i,c){let p=vo(gt(i.pattern)?ns(i.pattern):i.pattern);return yr(bt(p,"test"),[c])}function nh(e,n,i,c){return(gt(i.pattern)?ns(i.pattern):i.pattern).test(c)}function RA(e,n,i,c,p,f){return nh(e,n,p,f)||n.AddError({keyword:"pattern",schemaPath:i,instancePath:c,params:{pattern:p.pattern}})}function kA(e,n,i,c){return kn(cn(i.patternProperties).map(([p,f])=>{let[g,x]=[Vt(),Vt()],I=vo(ns(p)),b=Fn(yr(bt(I,"test"),[g])),E=Xn(e,n,f,x),T=n.AddKey(g),k=n.UseUnevaluated()?gr(b,bn(E,T)):gr(b,E);return ls(Ey(c),De(0),[`[${g}, ${x}]`,"_"],k)}))}function AA(e,n,i,c){return nn(cn(i.patternProperties),0,([p,f])=>{let g=ns(p);return nn(cn(c),0,([x,I])=>!g.test(x)||yo(e,n,f,I)&&n.AddKey(x))})}function CA(e,n,i,c,p,f){return Rn(cn(p.patternProperties),0,([g,x])=>{let I=`${i}/patternProperties/${g}`,b=ns(g);return Rn(cn(f),0,([E,T])=>{let k=`${c}/${E}`;return!b.test(E)||xo(e,n,I,k,x,T)&&n.AddKey(E)})})}function $A(e,n,i,c){return kn(i.prefixItems.map((p,f)=>{let g=Ki(bt(c,"length"),De(f)),x=Xn(e,n,p,`${c}[${f}]`),I=n.AddIndex(De(f)),b=n.UseUnevaluated()?bn(x,I):x;return gr(g,b)}))}function PA(e,n,i,c){return _(c.length,0)||nn(i.prefixItems,0,(p,f)=>ps(c.length,f)||yo(e,n,p,c[f])&&n.AddIndex(f))}function MA(e,n,i,c,p,f){return _(f.length,0)||Rn(p.prefixItems,0,(g,x)=>{let I=`${i}/prefixItems/${x}`,b=`${c}/${x}`;return ps(f.length,x)||xo(e,n,I,b,g,f[x])&&n.AddIndex(x)})}function Vp(e,n){return e.includes(n)||Vo().exactOptionalPropertyTypes}function vA(e,n){return md(bt(e,n))}function oh(e,n){return Gt(e[n])}function OA(e,n,i,c){let p=rs(i)?i.required:[],f=cn(i.properties).map(([g,x])=>{let I=Fn(Wi(c,De(g))),b=Xn(e,n,x,bt(c,g)),E=n.AddKey(De(g)),T=n.UseUnevaluated()?bn(b,E):b,k=p.includes(g)?T:gr(I,T);return Vp(p,g)?k:gr(vA(c,g),k)});return kn(f)}function _A(e,n,i,c){let p=rs(i)?i.required:[];return nn(cn(i.properties),0,([g,x])=>{let I=!le(c,g)||yo(e,n,x,c[g])&&n.AddKey(g);return Vp(p,g)?I:oh(c,g)||I})}function LA(e,n,i,c,p,f){let g=rs(p)?p.required:[];return Rn(cn(p.properties),0,([I,b])=>{let E=`${i}/properties/${I}`,T=`${c}/${I}`,k=()=>!le(f,I)||xo(e,n,E,T,b,f[I])&&n.AddKey(I);return Vp(g,I)?k():oh(f,I)||k()})}function NA(e,n,i,c){let[p,f]=[Vt(),Vt()];return ls(Hi(c),De(0),[p,f],Nt(e,n,i.propertyNames,p))}function DA(e,n,i,c){return nn(Ee(c),0,(p,f)=>kt(e,n,i.propertyNames,p))}function qA(e,n,i,c,p,f){let g=[];return Rn(Ee(f),0,(I,b)=>{let E=`${c}/${I}`,T=`${i}/propertyNames`,k=mr(e,n,T,E,p.propertyNames,I);if(!k)g.push(I);return k})||n.AddError({keyword:"propertyNames",schemaPath:i,instancePath:c,params:{propertyNames:g}})}function FA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Us(e,n,p,c)}function jA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Xe(p)&&kt(e,n,p,c)}function UA(e,n,i,c,p,f){let g=e.RecursiveRef(p)??!1;return Xe(g)&&mr(e,n,"#",c,g,f)}function t1(e,n,i,c){let p=Vs(["context","value"],Us(e,n,i,"value")),f=Vs(["context","value"],im([vs("nextContext",ld("CheckContext",[])),vs("result",yr(p,["nextContext","value"])),wy("result",n.Merge("[nextContext]")),am("result")]));return yr(f,["context",c])}function r1(e,n,i,c){return Us(e,n,i,c)}function BA(e,n,i,c){let p=e.Ref(i)??!1;return n.UseUnevaluated()?t1(e,n,p,c):r1(e,n,p,c)}function GA(e,n,i,c){let p=e.Ref(i)??!1,f=new _n,g=Xe(p)&&kt(e,f,p,c);if(g)n.Merge([f]);return g}function KA(e,n,i,c,p,f){let g=e.Ref(p)??!1,x=new Nn,I=Xe(g)&&mr(e,x,"#",c,g,f);if(I)n.Merge([x]);if(!I)x.GetErrors().forEach((b)=>n.AddError(b));return I}function HA(e,n,i,c){return kn(i.required.map((p)=>Wi(c,De(p))))}function WA(e,n,i,c){return nn(i.required,0,(p)=>le(c,p))}function zA(e,n,i,c,p,f){let g=[];return Rn(p.required,0,(I)=>{let b=le(f,I);if(!b)g.push(I);return b})||n.AddError({keyword:"required",schemaPath:i,instancePath:c,params:{requiredProperties:g}})}function VA(e,n,i,c){return _(i,"object")?yy(c):_(i,"array")?om(c):_(i,"boolean")?hv(c):_(i,"integer")?gv(c):_(i,"number")?gy(c):_(i,"null")?yv(c):_(i,"string")?Iy(c):_(i,"bigint")?hy(c):_(i,"constructor")?bv(c):_(i,"function")?Iv(c):_(i,"symbol")?xv(c):_(i,"undefined")?md(c):_(i,"void")?md(c):De(!0)}function sh(e,n,i,c,p){return _(i,"object")?zo(p):_(i,"array")?Be(p):_(i,"boolean")?un(p):_(i,"integer")?nm(p):_(i,"number")?Ot(p):_(i,"null")?mo(p):_(i,"string")?gt(p):_(i,"bigint")?_r(p):_(i,"constructor")?sd(p):_(i,"function")?ms(p):_(i,"symbol")?id(p):_(i,"undefined")?Gt(p):_(i,"void")?Gt(p):!0}function n1(e,n,i,c){return dd(i.map((p)=>VA(e,n,p,c)))}function JA(e,n,i,c,p){return Ea(i,(f)=>sh(e,n,f,c,p))}function QA(e,n,i,c){return Be(i.type)?n1(e,n,i.type,c):VA(e,n,i.type,c)}function XA(e,n,i,c){return Be(i.type)?JA(e,n,i.type,i,c):sh(e,n,i.type,i,c)}function YA(e,n,i,c,p,f){return(Be(p.type)?JA(e,n,p.type,p,f):sh(e,n,p.type,p,f))||n.AddError({keyword:"type",schemaPath:i,instancePath:c,params:{type:p.type}})}function ZA(e,n,i,c){let[p,f]=[Vt(),Vt()],g=yr(bt("context","GetIndices"),[]),x=yr(bt("indices","has"),[p]),I=Nt(e,n,i.unevaluatedItems,f),b=yr(bt("context","AddIndex"),[p]),E=ls(c,De(0),[f,p],bn(gr(x,I),b));return yr(Vs(["context"],im([vs("indices",g),am(E)])),["context"])}function e0(e,n,i,c){let p=n.GetIndices();return nn(c,0,(f,g)=>(p.has(g)||kt(e,n,i.unevaluatedItems,f))&&n.AddIndex(g))}function t0(e,n,i,c,p,f){let g=n.GetIndices(),x=[];return Rn(f,0,(b,E)=>{let T=new Nn,k=(g.has(E)||mr(e,T,i,c,p.unevaluatedItems,b))&&n.AddIndex(E);if(!k)x.push(E);return k})||n.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:c,params:{unevaluatedItems:x}})}function r0(e,n,i,c){let[p,f]=[Vt(),Vt()],g=yr(bt("context","GetKeys"),[]),x=yr(bt("keys","has"),[p]),I=yr(bt("context","AddKey"),[p]),b=Nt(e,n,i.unevaluatedProperties,f),E=ls(Ey(c),De(0),[`[${p}, ${f}]`,"_"],gr(x,bn(b,I)));return yr(Vs(["context"],im([vs("keys",g),am(E)])),["context"])}function n0(e,n,i,c){let p=n.GetKeys();return nn(cn(c),0,([f,g])=>p.has(f)||kt(e,n,i.unevaluatedProperties,g)&&n.AddKey(f))}function o0(e,n,i,c,p,f){let g=n.GetKeys(),x=[];return Rn(cn(f),0,([b,E])=>{let T=new Nn,k=g.has(b)||mr(e,T,i,c,p.unevaluatedProperties,E)&&n.AddKey(b);if(!k)x.push(b);return k})||n.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:c,params:{unevaluatedProperties:x}})}function ih(e){return!_(e.uniqueItems,!1)}function s0(e,n,i,c){if(!ih(i))return De(!0);let p=bt(ld("Set",[yr(bt(c,"map"),[bt("Hashing","Hash")])]),"size"),f=bt(c,"length");return oo(p,f)}function i0(e,n,i,c){if(!ih(i))return!0;let p=new Set(c.map(gd)).size,f=c.length;return _(p,f)}function a0(e,n,i,c,p,f){if(!ih(p))return!0;let g=new Set,x=f.reduce((b,E,T)=>{let k=gd(E);if(g.has(k))return[...b,T];return g.add(k),b},[]);return _(x.length,0)||n.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:c,params:{duplicateItems:x}})}function Mc(e,n){return Ac(e)&&(Be(e.type)&&Bi(e.type.length,0)&&nn(e.type,0,(i)=>_(i,n))||_(e.type,n))}function o1(e){return Mc(e,"object")}function s1(e){return dn(e)&&(Ao(e)||cc(e)||mc(e)||Ha(e)||js(e)||Fs(e)||za(e)||ca(e)||Ic(e)||rs(e)||$i(e))}function i1(e){return Mc(e,"array")}function a1(e){return dn(e)&&(Ka(e)||Ds(e)||Rs(e)||yc(e)||Wa(e)||qs(e)||Ii(e)||ts(e)||Ci(e)||Ri(e))}function u1(e){return Mc(e,"string")}function c1(e){return dn(e)&&(ua(e)||xc(e)||aa(e)||ma(e))}function m1(e){return Mc(e,"number")||Mc(e,"bigint")}function p1(e){return dn(e)&&(es(e)||gc(e)||dc(e)||Zo(e)||bc(e))}function Xn(e,n,i,c){return n.UseUnevaluated()?bn(bn(n.Push(),Nt(e,n,i,c)),n.Pop()):Nt(e,n,i,c)}function Nt(e,n,i,c){e.Push(i);let p=[];if(Ls(i))return UR(e,n,i,c);if(Ac(i))p.push(QA(e,n,i,c));if(s1(i)){let g=[];if(rs(i))g.push(HA(e,n,i,c));if(Ao(i))g.push(vR(e,n,i,c));if(cc(i))g.push(VR(e,n,i,c));if(mc(i))g.push(XR(e,n,i,c));if(Ha(i))g.push(ek(e,n,i,c));if(Fs(i))g.push(kA(e,n,i,c));if(js(i))g.push(OA(e,n,i,c));if(za(i))g.push(NA(e,n,i,c));if(ca(i))g.push(hA(e,n,i,c));if(Ic(i))g.push(oA(e,n,i,c));let x=kn(g),I=gr(Fn(yy(c)),x);p.push(o1(i)?x:I)}if(a1(i)){let g=[];if(Ka(i))g.push($R(e,n,i,c));if(Rs(i))g.push(WR(e,n,i,c));if(Ds(i))g.push(Wk(e,n,i,c));if(yc(i))g.push(Qk(e,n,i,c));if(Wa(i))g.push(eA(e,n,i,c));if(qs(i))g.push(aA(e,n,i,c));if(Ii(i))g.push(pA(e,n,i,c));if(ts(i))g.push($A(e,n,i,c));if(Ri(i))g.push(s0(e,n,i,c));let x=kn(g),I=gr(Fn(om(c)),x);p.push(i1(i)?x:I)}if(c1(i)){let g=[];if(xc(i))g.push(rA(e,n,i,c));if(ua(i))g.push(dA(e,n,i,c));if(aa(i))g.push(Uk(e,n,i,c));if(ma(i))g.push(TA(e,n,i,c));let x=kn(g),I=gr(Fn(Iy(c)),x);p.push(u1(i)?x:I)}if(p1(i)){let g=[];if(dc(i))g.push(uk(e,n,i,c));if(Zo(i))g.push(mk(e,n,i,c));if(gc(i))g.push(Yk(e,n,i,c));if(es(i))g.push(cA(e,n,i,c));if(bc(i))g.push(yA(e,n,i,c));let x=kn(g),I=gr(Fn(gr(gy(c),hy(c))),x);p.push(m1(i)?x:I)}if(Rc(i))p.push(BA(e,n,i,c));if(Tc(i))p.push(FA(e,n,i,c));if(pc(i))p.push(nk(e,n,i,c));if(xp(i))p.push(GR(e,n,i,c));if(Ip(i))p.push(ik(e,n,i,c));if(fc(i))p.push(Gk(e,n,i,c));if(Ec(i))p.push(IA(e,n,i,c));if(ic(i))p.push(LR(e,n,i,c));if(uc(i))p.push(qR(e,n,i,c));if(Sc(i))p.push(EA(e,n,i,c));if(Ci(i))p.push(gr(Fn(om(c)),ZA(e,n,i,c)));if($i(i))p.push(gr(Fn(xy(c)),r0(e,n,i,c)));if(sc(i))p.push(kR(e,n,i,c));let f=kn(p);return e.Pop(i),f}function yo(e,n,i,c){return n.Push()&&kt(e,n,i,c)&&n.Pop()}function kt(e,n,i,c){e.Push(i);let p=Ls(i)?vf(e,n,i,c):(!Ac(i)||XA(e,n,i,c))&&(!(at(c)&&!Be(c))||(!rs(i)||WA(e,n,i,c))&&(!Ao(i)||OR(e,n,i,c))&&(!cc(i)||JR(e,n,i,c))&&(!mc(i)||YR(e,n,i,c))&&(!Ha(i)||tk(e,n,i,c))&&(!Fs(i)||AA(e,n,i,c))&&(!js(i)||_A(e,n,i,c))&&(!za(i)||DA(e,n,i,c))&&(!ca(i)||eh(e,n,i,c))&&(!Ic(i)||Jf(e,n,i,c)))&&(!Be(c)||(!Ka(i)||PR(e,n,i,c))&&(!Rs(i)||_f(e,n,i,c))&&(!Ds(i)||zk(e,n,i,c))&&(!yc(i)||Hf(e,n,i,c))&&(!Wa(i)||zf(e,n,i,c))&&(!qs(i)||Qf(e,n,i,c))&&(!Ii(i)||Yf(e,n,i,c))&&(!ts(i)||PA(e,n,i,c))&&(!Ri(i)||i0(e,n,i,c)))&&(!gt(c)||(!xc(i)||Vf(e,n,i,c))&&(!ua(i)||Zf(e,n,i,c))&&(!aa(i)||Kf(e,n,i,c))&&(!ma(i)||nh(e,n,i,c)))&&(!(Ot(c)||_r(c))||(!dc(i)||Df(e,n,i,c))&&(!Zo(i)||qf(e,n,i,c))&&(!gc(i)||Wf(e,n,i,c))&&(!es(i)||Xf(e,n,i,c))&&(!bc(i)||th(e,n,i,c)))&&(!Rc(i)||GA(e,n,i,c))&&(!Tc(i)||jA(e,n,i,c))&&(!pc(i)||ok(e,n,i,c))&&(!xp(i)||Of(e,n,i,c))&&(!Ip(i)||Nf(e,n,i,c))&&(!fc(i)||Kk(e,n,i,c))&&(!Ec(i)||rh(e,n,i,c))&&(!ic(i)||NR(e,n,i,c))&&(!uc(i)||FR(e,n,i,c))&&(!Sc(i)||SA(e,n,i,c))&&(!Ci(i)||(!Be(c)||e0(e,n,i,c)))&&(!$i(i)||(!at(c)||n0(e,n,i,c)))&&(!sc(i)||AR(e,n,i,c));return e.Pop(i),p}function xo(e,n,i,c,p,f){return n.Push()&&mr(e,n,i,c,p,f)&&n.Pop()}function mr(e,n,i,c,p,f){if(n.AtCapacity())return!1;e.Push(p);let g=Ls(p)?BR(e,n,i,c,p,f):!!(+(!Ac(p)||YA(e,n,i,c,p,f))&+(!(at(f)&&!Be(f))||!!(+(!rs(p)||zA(e,n,i,c,p,f))&+(!Ao(p)||_R(e,n,i,c,p,f))&+(!cc(p)||QR(e,n,i,c,p,f))&+(!mc(p)||ZR(e,n,i,c,p,f))&+(!Ha(p)||rk(e,n,i,c,p,f))&+(!Fs(p)||CA(e,n,i,c,p,f))&+(!js(p)||LA(e,n,i,c,p,f))&+(!za(p)||qA(e,n,i,c,p,f))&+(!ca(p)||gA(e,n,i,c,p,f))&+(!Ic(p)||sA(e,n,i,c,p,f))))&+(!Be(f)||!!(+(!Ka(p)||MR(e,n,i,c,p,f))&+(!Rs(p)||zR(e,n,i,c,p,f))&+(!Ds(p)||Vk(e,n,i,c,p,f))&+(!yc(p)||Xk(e,n,i,c,p,f))&+(!Wa(p)||tA(e,n,i,c,p,f))&+(!qs(p)||uA(e,n,i,c,p,f))&+(!Ii(p)||lA(e,n,i,c,p,f))&+(!ts(p)||MA(e,n,i,c,p,f))&+(!Ri(p)||a0(e,n,i,c,p,f))))&+(!gt(f)||!!(+(!xc(p)||nA(e,n,i,c,p,f))&+(!ua(p)||fA(e,n,i,c,p,f))&+(!aa(p)||Bk(e,n,i,c,p,f))&+(!ma(p)||RA(e,n,i,c,p,f))))&+(!(Ot(f)||_r(f))||!!(+(!dc(p)||ck(e,n,i,c,p,f))&+(!Zo(p)||pk(e,n,i,c,p,f))&+(!gc(p)||Zk(e,n,i,c,p,f))&+(!es(p)||mA(e,n,i,c,p,f))&+(!bc(p)||xA(e,n,i,c,p,f))))&+(!Rc(p)||KA(e,n,i,c,p,f))&+(!Tc(p)||UA(e,n,i,c,p,f))&+(!pc(p)||sk(e,n,i,c,p,f))&+(!xp(p)||KR(e,n,i,c,p,f))&+(!Ip(p)||ak(e,n,i,c,p,f))&+(!fc(p)||Hk(e,n,i,c,p,f))&+(!Ec(p)||bA(e,n,i,c,p,f))&+(!ic(p)||DR(e,n,i,c,p,f))&+(!uc(p)||jR(e,n,i,c,p,f))&+(!Sc(p)||wA(e,n,i,c,p,f))&+(!Ci(p)||(!Be(f)||t0(e,n,i,c,p,f)))&+(!$i(p)||(!at(f)||o0(e,n,i,c,p,f))))&&(!sc(p)||CR(e,n,i,c,p,f));return e.Pop(p),g}var u0=[0],Jp=new Map,vc=new Map;function l1(){return`${u0[0]++}`}function d1(e,n){if(!Jp.has(e))Jp.set(e,new Map);let i=Jp.get(e);if(i.has(n))return i.get(n);let c=l1();return i.set(n,c),c}function f1(e,n,i,c){return e.UseUnevaluated()?yr(`check_${i}`,["context",c]):yr(`check_${i}`,[c])}function h1(e,n,i,c){let p=Nt(e,n,i,"value");return n.UseUnevaluated()?vs(`check_${c}`,Vs(["context","value"],p)):vs(`check_${c}`,Vs(["value"],p))}function c0(){u0[0]=0,Jp.clear(),vc.clear()}function m0(){return[...vc.values()]}function Us(e,n,i,c){let p=d1(i,e.LexicalBaseURL()),f=f1(n,i,p,c);if(vc.has(p))return f;return vc.set(p,""),vc.set(p,h1(e,n,i,p)),f}function g1(e,n){return at(n)&&!wu(e)?n[e]:void 0}function y1(e,n){return e.reduce((i,c)=>g1(c,i),n)}function x1(e){if(_(e.length,0))return[];let n=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return n.length>0&&n[0]===""?n.slice(1):n}function I1(e,n){let i=x1(n);return y1(i,e)}var Xp="https://json-schema.org";function l0(e,n){if(at(e)&&Ns(e)&&_(e.$dynamicAnchor,n))return e;if(at(e))for(let i of Ee(e)){let c=l0(e[i],n);if(c)return c}return}function ah(e,n,i){if(_(e,i))return n.href;let c=dn(e)&&go(e)?new URL(e.$id,n.href):n;if(Be(e))for(let p of e){let f=ah(p,c,i);if(!Gt(f))return f}else if(at(e))for(let p of Ee(e)){let f=ah(e[p],c,i);if(!Gt(f))return f}return}function b1(e,n,i){if(_(e.$id,i.hash))return e;let c=new URL(i.href,n.href);if(_(n.pathname,c.pathname))return i.hash.startsWith("#")?d0(e,i):e;return}function E1(e,n,i){let c=new URL(`#${e.$anchor}`,n.href),p=new URL(i.href,n.href);return _(c.href,p.href)?e:void 0}function S1(e,n,i){let c=new URL(`#${e.$dynamicAnchor}`,n.href),p=new URL(i.href,n.href);return _(c.href,p.href)?e:void 0}function d0(e,n){if(n.href.endsWith("#"))return e;if(!n.hash.startsWith("#"))return;let i=decodeURIComponent(n.hash.slice(1));if(!i.startsWith("/"))return;return I1(e,i)}function w1(e,n,i){if(go(e)){let c=b1(e,n,i);if(!Gt(c))return c}if(ac(e)){let c=E1(e,n,i);if(!Gt(c))return c}if(Ns(e)){let c=S1(e,n,i);if(!Gt(c))return c}return d0(e,i)}function T1(e,n,i){return e.reduce((c,p)=>{let f=Yp(p,n,i);return!Gt(f)?f:c},void 0)}function R1(e){return _(e,"const")||_(e,"enum")}function k1(e,n,i){return Ee(e).reduce((c,p)=>{if(R1(p))return c;let f=Yp(e[p],n,i);return!Gt(f)?f:c},void 0)}function Yp(e,n,i){let c=dn(e)&&go(e)?new URL(e.$id,n.href):n;if(dn(e)){let p=w1(e,c,i);if(!Gt(p))return p}if(Be(e))return T1(e,c,i);if(at(e))return k1(e,c,i);return}function A1(e,n,i){return ah(e,new URL(n||".",Xp),i)}function C1(e,n,i,c){let p=Zp(e,n,i,c,!1);return dn(p)&&go(p)?p:void 0}function p0(e){return e.href.split("#")[0]}function $1(e,n){return le(e,n)?e[n]:void 0}function P1(e,n,i){return Yp(e,n,i)}function M1(e,n,i){let c=p0(i);if(_(c,p0(n)))return;if(!le(e,c))return;let p=e[c],f=dn(p)&&go(p)?new URL(p.$id,c):new URL(c);return _(i.hash,"")?p:Yp(p,f,i)}function v1(e,n,i,c,p){if(!c.$ref.startsWith("#"))return;if(le(e,"$schema"))return;let f=A1(n,i,p);if(Gt(f)||_(f,i))return;return{target:p,base:f,root:n}}function O1(e,n,i){let c=e[n];if(!dn(c))return;return{target:i,base:n,root:c}}function _1(e,n,i,c,p){let f=p?O1(e.context,c,i):void 0;if(!Gt(f))return f;return v1(e.root,e.lexicalSchema,e.referenceBase,n,i)}function L1(e,n,i,c,p,f){if(go(p))return;let g=C1(e,n,i,c);if(!g||f.includes(g))return;return{target:p,resource:g}}function Zp(e,n,i,c,p=!0){let f=new URL(i||".",Xp),g=p&&go(n)?new URL(n.$id,f):f,x=new URL(c,g.href);return $1(e,c)??P1(n,g,x)??M1(e,g,x)}function N1(e,n,i,c,p,f){let g=new URL(i||".",Xp),x=p.$dynamicRef.startsWith("#")?c:n,I=Zp(e,x,i,p.$dynamicRef,!1);if(Gt(I)){let T=new URL(p.$dynamicRef,g).hash;if(!T.startsWith("#/")&&T.startsWith("#")){let k=decodeURIComponent(T.slice(1));return f.find((L)=>_(L.$dynamicAnchor,k))??l0(n,k)}return}if(!dn(I)||!Ns(I))return I;if(new URL(p.$dynamicRef,g).hash.startsWith("#/"))return I;return f.find((T)=>_(T.$dynamicAnchor,I.$dynamicAnchor))??I}function D1(e,n){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,c=n.$ref.startsWith("#")?e.lexicalSchema:i,p=Zp(e.context,c,e.referenceBase,n.$ref,!1);if(!p||!dn(p))return{schema:p};let f=new URL(n.$ref,e.referenceBase).href.split("#")[0],g=!_(f,e.resourceBase),x=_1(e,n,p,f,g),I=g?L1(e.context,e.root,e.referenceBase,f,p,e.ids):void 0;return{schema:p,retrievedResource:x,resolvedResource:I}}function q1(e,n){let i=wc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Zp(e.context,i,e.lexicalBase,n.$recursiveRef,!1)}function F1(e,n){return N1(e.context,e.root,e.lexicalBase,e.lexicalSchema,n,e.dynamicAnchors)}var vr=function(e,n,i,c){if(i==="a"&&!c)throw TypeError("Private accessor was defined without a getter");if(typeof n==="function"?e!==n||!c:!n.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?c:i==="a"?c.call(e):c?c.value:n.get(e)},br,tl,I0,ph,el,f0,h0,g0,y0,ch,mh,lh,dh,x0,b0;class vi{constructor(e,n){br.add(this),this.context=e,this.schema=n,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 vr(this,br,"m",ph).call(this,this.ids)}Push(e){if(!dn(e))return;if(go(e))vr(this,br,"m",lh).call(this,e);if(ac(e))this.anchors.push(e);if(wc(e))this.recursiveAnchors.push(e);if(Ns(e))this.dynamicAnchors.push(e);let n=this.retrievedResources.get(e);if(n)this.retrievedFrames.push({schema:n.root,base:n.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!dn(e))return;if(go(e))vr(this,br,"m",dh).call(this,e);if(ac(e))this.anchors.pop();if(wc(e))this.recursiveAnchors.pop();if(Ns(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();vr(this,br,"m",b0).call(this,e)}Ref(e){let n=D1(vr(this,br,"m",tl).call(this),e);return vr(this,br,"m",I0).call(this,n),n.schema}RecursiveRef(e){let n=q1(vr(this,br,"m",tl).call(this),e);if(n)this.pendingResource=!0;return n}DynamicRef(e){let n=F1(vr(this,br,"m",tl).call(this),e);if(n)this.pendingResource=!0;return n}}br=new WeakSet,tl=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:vr(this,br,"m",h0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:vr(this,br,"m",f0).call(this),resourceBase:vr(this,br,"m",el).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},I0=function(n){if(!Gt(n.schema))this.pendingResource=!0;if(!Gt(n.resolvedResource))vr(this,br,"m",x0).call(this,n.resolvedResource.target,n.resolvedResource.resource);if(!Gt(n.retrievedResource))this.retrievedResources.set(n.retrievedResource.target,{base:n.retrievedResource.base,root:n.retrievedResource.root})},ph=function(n){let i=this.retrievedFrames[this.retrievedFrames.length-1],c=i?new URL(i.base):new URL(Xp);return(i?n.slice(i.idDepth):n).reduce((f,g)=>new URL(g.$id,f),c).href},el=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(!n)return vr(this,br,"m",ph).call(this,this.resourceIds);return this.resourceIds.slice(n.resourceDepth).reduce((i,c)=>new URL(c.$id,i),new URL(n.base)).href},f0=function(){if(this.retrievedFrames.length>0)return vr(this,br,"m",el).call(this);let n=this.ids[this.ids.length-1];if(n&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(n.$id))return this.LexicalBaseURL();return vr(this,br,"m",el).call(this)},h0=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(n)return this.ids.length>n.idDepth?this.ids[this.ids.length-1]:n.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},g0=function(n){n.forEach((i)=>vr(this,br,"m",ch).call(this,i,!1))},y0=function(n){n.forEach((i)=>vr(this,br,"m",mh).call(this,i,!1))},ch=function e(n,i=!0){if(Ls(n))return;if(Be(n))return vr(this,br,"m",g0).call(this,n);if(!dn(n))return;let c=n;if(!i&&go(c))return;if(!i&&Ns(c))this.dynamicAnchors.push(c);for(let p of Ee(c))vr(this,br,"m",e).call(this,c[p],!1)},mh=function e(n,i=!0){if(Ls(n))return;if(Be(n))return vr(this,br,"m",y0).call(this,n);if(!dn(n))return;let c=n;if(!i&&go(c))return;if(!i&&Ns(c))this.dynamicAnchors.pop();for(let p of Ee(c))vr(this,br,"m",e).call(this,c[p],!1)},lh=function(n){this.ids.push(n);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(n);vr(this,br,"m",ch).call(this,n,!0)},dh=function(n){if(this.ids.pop(),this.resourceIds.length>0&&_(this.resourceIds[this.resourceIds.length-1],n))this.resourceIds.pop();vr(this,br,"m",mh).call(this,n,!0)},x0=function(n,i){vr(this,br,"m",lh).call(this,i),this.resolvedResources.set(n,i)},b0=function(n){if(!this.resolvedResources.has(n))return;let i=this.resolvedResources.get(n);vr(this,br,"m",dh).call(this,i),this.resolvedResources.delete(n)};function j1(e){let n=e.Functions().join(`;
|
|
29
|
+
`),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${n}; return (value) => { ${i.join("; ")} }`}function U1(e,n){return Uy("CheckContext","Guard","Format","Hashing",e.External().identifier,n)(_n,B,Ya,Qi,e.External().variables)}function B1(e){let n=new vi(e.Context(),e.Schema()),i=new _n;return(c)=>kt(n,i,e.Schema(),c)}function G1(e,n){return jy()?U1(e,n):B1(e)}class E0{constructor(e,n,i){this.isAccelerated=e,this.code=n,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class S0{constructor(e,n,i,c,p,f){this.context=e,this.schema=n,this.external=i,this.functions=c,this.entry=p,this.useUnevaluated=f}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=j1(this),n=G1(this,e);return new E0(jy(),e,n)}}function rl(...e){let[n,i]=En(e,{2:(I,b)=>[I,b],1:(I)=>[{},I]});TR(),c0();let c=new vi(n,i),p=new $f(wR(n,i)),f=Us(c,p,i,"value"),g=m0(),x=RR();return new S0(n,i,x,g,f,p.UseUnevaluated())}function nl(...e){let[n,i,c]=En(e,{3:(E,T,k)=>[E,T,k],2:(E,T)=>[{},E,T]}),p=new vi(n,i),f=new Nn,g=mr(p,f,"#","",i,c),x=f.GetErrors(),I=Qy(),b=x.map((E)=>({...E,message:I(E)}));return[g,b]}function hh(...e){let[n,i,c]=En(e,{3:(g,x,I)=>[g,x,I],2:(g,x)=>[{},g,x]}),p=new vi(n,i),f=new _n;return kt(p,f,i,c)}function Xt(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return hh(n,i,c)}function ks(...e){let[n,i,c]=En(e,{3:(g,x,I)=>[g,x,I],2:(g,x)=>[{},g,x]}),[p,f]=nl(n,i,c);return f}class pa extends Error{constructor(e,n,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:n},writable:!1,configurable:!1,enumerable:!1})}}function w0(e,n,i){if(!Be(i))return i;return i.map((c)=>fn(e,n.items,c))}function T0(e,n,i){return fn({...e,...n.$defs},on(n.$ref),i)}function W1(e,n){let i=le(n,"unevaluatedProperties")?{additionalProperties:n.unevaluatedProperties}:{},c=wo(e,n),p=wn(c);return Qe(p)?dp(p,i):p}function R0(e,n,i){let c=W1(e,n);return fn(e,c,i)}function ol(e){return le(e,"additionalProperties")?e.additionalProperties:void 0}function k0(e,n,i){if(!at(i)||Be(i))return i;let c=ol(n);for(let p of Ee(i)){if(le(n.properties,p)){i[p]=fn(e,n.properties[p],i[p]);continue}if(un(c)&&_(c,!0)||Ar(c)&&Xt(e,c,i[p])){i[p]=fn(e,c,i[p]);continue}delete i[p]}return i}function A0(e,n,i){if(!at(i))return i;let c=ol(n),[p,f]=[new RegExp(ln(n)),lr(n)];for(let g of Ee(i)){if(p.test(g)){i[g]=fn(e,f,i[g]);continue}if(un(c)&&_(c,!0)||Ar(c)&&Xt(e,c,i[g])){i[g]=fn(e,c,i[g]);continue}delete i[g]}return i}function C0(e,n,i){return le(e,n.$ref)?fn(e,e[n.$ref],i):i}function $0(e,n,i){if(!Be(i))return i;let c=Math.min(i.length,n.items.length);for(let p=0;p<c;p++)i[p]=fn(e,n.items[p],i[p]);return Bi(i.length,c)?i.slice(0,c):i}function Kr(e){return wa(e)}function P0(e,n,i){for(let c of n.anyOf){let p=fn(e,c,Kr(i));if(Xt(e,c,p))return p}return i}function fn(e,n,i){return St(n)?w0(e,n,i):Qt(n)?T0(e,n,i):He(n)?R0(e,n,i):Qe(n)?k0(e,n,i):Kt(n)?A0(e,n,i):jt(n)?C0(e,n,i):lt(n)?$0(e,n,i):be(n)?P0(e,n,i):i}function z1(e,n){for(let i of Ee(e)){if(le(n,i))continue;n[i]=e[i]}return n}function V1(e){let n={};for(let i of Ee(e))n[i]=Oc(e[i]);return n}function J1(e){return gh(oR(e))}function gh(e){return e.map((n)=>Oc(n))}function Oc(e){let n=St(e)?W(Oc(e.items),Ta(e)):He(e)?An(gh(e.allOf)):be(e)?m(J1(e.anyOf)):Qe(e)?s(V1(e.properties)):Kt(e)?bs(ri(e),Oc(lr(e))):lt(e)?Dr(gh(e.items)):e;return z1(e,n)}function Za(e){return Oc(e)}function _o(...e){let[n,i,c]=En(e,{3:(f,g,x)=>[f,g,x],2:(f,g)=>[{},f,g]}),p=Vo().unionPrioritySort?Za(i):i;return fn(n,p,c)}function co(e){return at(e)&&le(e,"value")}function Ge(e){return{value:e}}function Er(){return}function Q1(e){return Be(e)?Ge(e):Ge([e])}function X1(e){return _(e,!0)?Ge(BigInt(1)):Ge(BigInt(0))}var Y1=/^-?(0|[1-9]\d*)n$/,Z1=/^-?(0|[1-9]\d*)\.\d+$/,ej=/^-?(0|[1-9]\d*)$/;function tj(e){return Y1.test(e)}function rj(e){return Z1.test(e)}function nj(e){return ej.test(e)}function oj(e){let n=e.toLowerCase();return tj(e)?Ge(BigInt(e.slice(0,e.length-1))):rj(e)?Ge(BigInt(e.split(".")[0])):nj(e)?Ge(BigInt(e)):_(n,"false")?Ge(BigInt(0)):_(n,"true")?Ge(BigInt(1)):Er()}function sl(e){return _r(e)?Ge(e):un(e)?X1(e):Ot(e)?Ge(BigInt(Math.trunc(e))):mo(e)?Ge(BigInt(0)):gt(e)?oj(e):Gt(e)?Ge(BigInt(0)):Er()}function sj(e){return _(e,BigInt(0))?Ge(!1):_(e,BigInt(1))?Ge(!0):Er()}function ij(e){return _(e,0)?Ge(!1):_(e,1)?Ge(!0):Er()}function aj(e){return _(e.toLowerCase(),"false")?Ge(!1):_(e.toLowerCase(),"true")?Ge(!0):_(e,"0")?Ge(!1):_(e,"1")?Ge(!0):Er()}function M0(e){return _r(e)?sj(e):un(e)?Ge(e):Ot(e)?ij(e):mo(e)?Ge(!1):gt(e)?aj(e):Gt(e)?Ge(!1):Er()}function uj(e){return _(e,BigInt(0))?Ge(null):Er()}function cj(e){return _(e,!1)?Ge(null):Er()}function mj(e){return _(e,0)?Ge(null):Er()}function pj(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(null):Er()}function lj(e){return _r(e)?uj(e):un(e)?cj(e):Ot(e)?mj(e):mo(e)?Ge(null):gt(e)?pj(e):Gt(e)?Ge(null):Er()}var v0=BigInt(Number.MAX_SAFE_INTEGER),O0=BigInt(Number.MIN_SAFE_INTEGER);function dj(e){return e<=v0&&e>=O0?Ge(Number(e)):Er()}function fj(e){return Ge(e?1:0)}function hj(e){let n=+e;if(Ot(n))return Ge(n);let i=e.toLowerCase();if(_(i,"false"))return Ge(0);if(_(i,"true"))return Ge(1);let c=sl(e);if(co(c))return c.value<=v0&&c.value>=O0?Ge(Number(c.value)):Er();return Er()}function yh(e){return _r(e)?dj(e):un(e)?fj(e):Ot(e)?Ge(e):mo(e)?Ge(0):gt(e)?hj(e):Gt(e)?Ge(0):Er()}function _0(e){return _r(e)?Ge(e.toString()):un(e)?Ge(e.toString()):Ot(e)?Ge(e.toString()):mo(e)?Ge("null"):gt(e)?Ge(e):Gt(e)?Ge(""):Er()}function gj(e){return _(e,BigInt(0))?Ge(void 0):Er()}function yj(e){return _(e,!1)?Ge(void 0):Er()}function xj(e){return _(e,0)?Ge(void 0):Er()}function Ij(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(void 0):Er()}function L0(e){return _r(e)?gj(e):un(e)?yj(e):Ot(e)?xj(e):mo(e)?Ge(void 0):gt(e)?Ij(e):Gt(e)?Ge(e):Er()}function N0(e,n,i){return Q1(i).value.map((p)=>Hr(e,n.items,p))}function D0(e,n,i){let c=sl(i);return co(c)?c.value:i}function q0(e,n,i){let c=M0(i);return co(c)?c.value:i}function F0(e,n,i){return Hr({...e,...n.$defs},on(n.$ref),i)}function j0(e,n,i){return Hr(e,wn(n),i)}function U0(e,n,i){let c=yh(i);return co(c)?Math.trunc(c.value):i}function B0(e,n,i){let c=wo(e,n),p=wn(c);return Hr(e,p,i)}function bj(e,n,i){let c=sl(i);return co(c)&&_(n.const,c.value)?c.value:i}function Ej(e,n,i){let c=M0(i);return co(c)&&_(n.const,c.value)?c.value:i}function Sj(e,n,i){let c=yh(i);return co(c)&&_(n.const,c.value)?c.value:i}function wj(e,n,i){let c=_0(i);return co(c)&&_(n.const,c.value)?c.value:i}function G0(e,n,i){if(_(n.const,i))return i;return ix(n)?bj(e,n,i):ax(n)?Ej(e,n,i):ym(n)?Sj(e,n,i):xm(n)?wj(e,n,i):Nr()}function K0(e,n,i){let c=lj(i);return co(c)?c.value:i}function H0(e,n,i){let c=yh(i);return co(c)?c.value:i}function il(e,n,i,c){let p=Ee(c);for(let[f,g]of n)for(let x of p)if(!f.test(x))c[x]=Hr(e,i,c[x]);return c}function _c(e,n,i){return sn(e)&&Gt(i[n])}function Tj(e,n,i){let c=ud(n.properties),p=Ee(i);for(let[f,g]of c)for(let x of p){if(!f.test(x)||_c(g,x,i))continue;i[x]=Hr(e,g,i[x])}return le(n,"additionalProperties")&&at(n.additionalProperties)?il(e,c,n.additionalProperties,i):i}function W0(e,n,i){return zo(i)?Tj(e,n,i):i}function Rj(e,n,i){let c=ud(n.patternProperties),p=Ee(i);for(let[f,g]of c)for(let x of p)if(f.test(x))i[x]=Hr(e,g,i[x]);return le(n,"additionalProperties")&&at(n.additionalProperties)?il(e,c,n.additionalProperties,i):i}function z0(e,n,i){return zo(i)?Rj(e,n,i):i}function V0(e,n,i){return le(e,n.$ref)?Hr(e,e[n.$ref],i):i}function J0(e,n,i){let c=_0(i);return co(c)?c.value:i}function Q0(e,n,i){return Hr(e,wn(n),i)}function X0(e,n,i){if(!Be(i))return i;for(let c=0;c<Math.min(n.items.length,i.length);c++)i[c]=Hr(e,n.items[c],i[c]);return i}function Y0(e,n,i){let c=L0(i);return co(c)?c.value:i}function Z0(e,n,i){if(n.anyOf.some((g)=>Xt(e,g,i)))return i;let f=n.anyOf.map((g)=>Hr(e,g,Kr(i))).find((g)=>Xt(e,n,g));return Gt(f)?i:f}function eC(e,n,i){let c=L0(i);return co(c)?void 0:i}function Hr(e,n,i){return St(n)?N0(e,n,i):io(n)?D0(e,n,i):Wn(n)?q0(e,n,i):Qt(n)?F0(e,n,i):tn(n)?j0(e,n,i):pn(n)?U0(e,n,i):He(n)?B0(e,n,i):yt(n)?G0(e,n,i):xs(n)?K0(e,n,i):Tr(n)?H0(e,n,i):Qe(n)?W0(e,n,i):Kt(n)?z0(e,n,i):jt(n)?V0(e,n,i):rn(n)?J0(e,n,i):cr(n)?Q0(e,n,i):lt(n)?X0(e,n,i):Yo(n)?Y0(e,n,i):be(n)?Z0(e,n,i):ao(n)?eC(e,n,i):i}function is(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return Hr(n,i,c)}function tC(e,n,i){if(!Be(i))return i;for(let c=0;c<i.length;c++)i[c]=hn(e,n.items,i[c]);return i}function rC(e,n,i){return hn({...e,...n.$defs},on(n.$ref),i)}function nC(e,n){if(!Gt(n))return n;return ms(e.default)?e.default():Kr(e.default)}function oC(e,n,i){let c=wo(e,n),p=wn(c);return hn(e,p,i)}function sC(e,n,i){if(!at(i))return i;let c=Ee(n.properties);for(let p of c){let f=hn(e,n.properties[p],i[p]);if(Gt(f)&&(sn(n.properties[p])||!le(n.properties[p],"default")))continue;i[p]=f}if(!Ao(n)||un(n.additionalProperties))return i;for(let p of Ee(i)){if(c.includes(p))continue;i[p]=hn(e,n.additionalProperties,i[p])}return i}function iC(e,n,i){if(!at(i))return i;let[c,p]=[new RegExp(ln(n)),lr(n)];for(let f of Ee(i)){if(!(c.test(f)&&ho(p)))continue;i[f]=hn(e,p,i[f])}if(!Ao(n))return i;for(let f of Ee(i)){if(c.test(f))continue;i[f]=hn(e,n.additionalProperties,i[f])}return i}function aC(e,n,i){return le(e,n.$ref)?hn(e,e[n.$ref],i):i}function uC(e,n,i){if(!Be(i))return i;let[c,p]=[n.items,Math.max(n.items.length,i.length)];for(let f=0;f<p;f++)if(f<c.length)i[f]=hn(e,c[f],i[f]);return i}function cC(e,n,i){for(let c of n.anyOf){let p=hn(e,c,Kr(i));if(Xt(e,c,p))return p}return i}function hn(e,n,i){let c=ho(n)?nC(n,i):i;return St(n)?tC(e,n,c):Qt(n)?rC(e,n,c):He(n)?oC(e,n,c):Qe(n)?sC(e,n,c):Kt(n)?iC(e,n,c):jt(n)?aC(e,n,c):lt(n)?uC(e,n,c):be(n)?cC(e,n,c):c}function Bs(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return hn(n,i,c)}function eu(e){return(...n)=>{let[i,c,p]=En(n,{3:(f,g,x)=>[f,g,x],2:(f,g)=>[{},f,g]});return e.reduce((f,g)=>g(i,c,f),p)}}function kj(e,n,i){return n["~codec"].decode(i)}function Aj(e,n,i){return n["~codec"].encode(i)}function Sr(e,n,i,c){if(!Bn(i))return c;return _(e,"Decode")?kj(n,i,c):Aj(n,i,c)}function Cj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<c.length;p++)c[p]=kr(e,n,i.items,c[p]);return Sr(e,n,i,c)}function $j(e,n,i,c){let p=Sr(e,n,i,c);if(!Be(p))return p;for(let f=0;f<p.length;f++)p[f]=kr(e,n,i.items,p[f]);return p}function mC(e,n,i,c){return _(e,"Decode")?Cj(e,n,i,c):$j(e,n,i,c)}function pC(e,n,i,c){return c=kr(e,{...n,...i.$defs},on(i.$ref),c),Sr(e,n,i,c)}function lC(e){return e.reduce((n,i)=>({...n,...i}),{})}function dC(e,n){for(let i of n)if(!Sa(e,i))return i;return e}function Pj(e,n,i,c){if(_(i.allOf.length,0))return Sr(e,n,i,c);let p=i.allOf.map((x)=>kr(e,n,x,_o(x,Kr(c)))),g=p.every((x)=>at(x))?lC(p):dC(c,p);return Sr(e,n,i,g)}function Mj(e,n,i,c){if(_(i.allOf.length,0))return Sr(e,n,i,c);let p=Sr(e,n,i,c),f=i.allOf.map((x)=>kr(e,n,x,_o(x,Kr(p))));if(f.every((x)=>at(x)))return lC(f);return dC(p,f)}function fC(e,n,i,c){return _(e,"Decode")?Pj(e,n,i,c):Mj(e,n,i,c)}function vj(e,n,i,c){if(!zo(c))return c;for(let p of Ee(i.properties)){if(!le(c,p)||_c(i.properties[p],p,c))continue;c[p]=kr(e,n,i.properties[p],c[p])}return Sr(e,n,i,c)}function Oj(e,n,i,c){let p=Sr(e,n,i,c);if(!zo(p))return p;for(let f of Ee(i.properties)){if(!le(p,f)||_c(i.properties[f],f,p))continue;p[f]=kr(e,n,i.properties[f],p[f])}return p}function hC(e,n,i,c){return _(e,"Decode")?vj(e,n,i,c):Oj(e,n,i,c)}function _j(e,n,i,c){if(!zo(c))return c;let p=new RegExp(ln(i));for(let f of Ee(c)){if(!p.test(f))continue;c[f]=kr(e,n,lr(i),c[f])}return Sr(e,n,i,c)}function Lj(e,n,i,c){let p=Sr(e,n,i,c);if(!zo(p))return p;let f=new RegExp(ln(i));for(let g of Ee(p)){if(!f.test(g))continue;p[g]=kr(e,n,lr(i),p[g])}return p}function gC(e,n,i,c){return _(e,"Decode")?_j(e,n,i,c):Lj(e,n,i,c)}function yC(e,n,i,c){return le(n,i.$ref)?kr(e,n,n[i.$ref],c):c}function xC(e,n,i,c){return _(e,"Decode")?Sr(e,n,i,yC(e,n,i,c)):yC(e,n,i,Sr(e,n,i,c))}function Nj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<Math.min(i.items.length,c.length);p++)c[p]=kr(e,n,i.items[p],c[p]);return Sr(e,n,i,c)}function Dj(e,n,i,c){let p=Sr(e,n,i,c);if(!Be(p))return c;for(let f=0;f<Math.min(i.items.length,p.length);f++)p[f]=kr(e,n,i.items[f],p[f]);return p}function IC(e,n,i,c){return _(e,"Decode")?Nj(e,n,i,c):Dj(e,n,i,c)}function qj(e,n,i,c){for(let p of i.anyOf){if(!Xt(n,p,c))continue;let f=kr(e,n,p,c);return Sr(e,n,i,f)}return c}function Fj(e,n,i,c){let p=Sr(e,n,i,c);for(let f of i.anyOf){let g=kr(e,n,f,Kr(p));if(!Xt(n,f,g))continue;return g}return p}function bC(e,n,i,c){return _(e,"Decode")?qj(e,n,i,c):Fj(e,n,i,c)}function kr(e,n,i,c){return St(i)?mC(e,n,i,c):Qt(i)?pC(e,n,i,c):He(i)?fC(e,n,i,c):Qe(i)?hC(e,n,i,c):Kt(i)?gC(e,n,i,c):jt(i)?xC(e,n,i,c):lt(i)?IC(e,n,i,c):be(i)?bC(e,n,i,c):Sr(e,n,i,c)}class EC extends pa{constructor(e,n){super("Decode",e,n)}}function jj(e,n,i){if(!Xt(e,n,i))throw new EC(i,ks(e,n,i));return i}function Uj(e,n,i){let c=Vo().unionPrioritySort?Za(n):n;return kr("Decode",e,c,i)}var Bj=eu([(e,n,i)=>Kr(i),(e,n,i)=>Bs(e,n,i),(e,n,i)=>is(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>jj(e,n,i),(e,n,i)=>Uj(e,n,i)]);function xh(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return Bj(n,i,c)}class SC extends pa{constructor(e,n){super("Encode",e,n)}}function Gj(e,n,i){if(!Xt(e,n,i))throw new SC(i,ks(e,n,i));return i}function Kj(e,n,i){let c=Vo().unionPrioritySort?Za(n):n;return kr("Encode",e,c,i)}var Hj=eu([(e,n,i)=>Kr(i),(e,n,i)=>Kj(e,n,i),(e,n,i)=>Bs(e,n,i),(e,n,i)=>is(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>Gj(e,n,i)]);function Ih(...e){let[n,i,c]=En(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return Hj(n,i,c)}function Wj(e,n){return Bn(n)||Oi(e,n.items)}function zj(e,n){return Bn(n)||wC({...e,...n.$defs},on(n.$ref))}function Vj(e,n){return Bn(n)||n.allOf.some((i)=>Oi(e,i))}function Jj(e,n){return Bn(n)||Ee(n.properties).some((i)=>Oi(e,n.properties[i]))}function Qj(e,n){return Bn(n)||Oi(e,lr(n))}function wC(e,n){if(bh.has(n.$ref))return!1;return bh.add(n.$ref),Bn(n)||le(e,n.$ref)&&Oi(e,e[n.$ref])}function Xj(e,n){return Bn(n)||n.items.some((i)=>Oi(e,i))}function Yj(e,n){return Bn(n)||n.anyOf.some((i)=>Oi(e,i))}function Oi(e,n){return St(n)?Wj(e,n):Qt(n)?zj(e,n):He(n)?Vj(e,n):Qe(n)?Jj(e,n):Kt(n)?Qj(e,n):jt(n)?wC(e,n):lt(n)?Xj(e,n):be(n)?Yj(e,n):Bn(n)}var bh=new Set;function Eh(...e){let[n,i]=En(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return bh.clear(),Oi(n,i)}class as extends Error{constructor(e,n){super(n);this.type=e}}function TC(e,n){return ms(n.default)?n.default(n):at(n.default)?Kr(n.default):n.default}function RC(e,n){if(Ri(n)&&!ho(n))throw new as(n,"Arrays with uniqueItems constraints must specify a default annotation");let i=Ii(n)?n.minItems:0;return Array.from({length:i},()=>Jr(e,n.items))}function kC(e,n){return Zo(n)?BigInt(n.exclusiveMinimum)+BigInt(1):es(n)?BigInt(n.minimum):BigInt(0)}function AC(e,n){return!1}function CC(e,n){let i=Jr(e,n.instanceType);return class{constructor(){Object.assign(this,i)}}}function $C(e,n){return Jr({...e,...n.$defs},on(n.$ref))}function PC(e,n){return Jr(e,wn(n))}function MC(e,n){let i=Jr(e,n.returnType);return()=>i}function vC(e,n){return Zo(n)&&Ot(n.exclusiveMinimum)?n.exclusiveMinimum+1:es(n)?n.minimum:0}function OC(e,n){let i=wo(e,n),c=wn(i);return Jr(e,c)}function _C(e,n){return n.const}function LC(e,n){throw new as(n,"Cannot create TNever types")}function NC(e,n){return null}function DC(e,n){return Zo(n)&&Ot(n.exclusiveMinimum)?n.exclusiveMinimum+1:es(n)?n.minimum:0}function qC(e,n){return(Gt(n.required)?[]:n.required).reduce((c,p)=>({...c,[p]:Jr(e,n.properties[p])}),{})}function FC(e,n){if(ca(n)&&!ho(n))throw new as(n,"Record with the minProperties constraint must have a default annotation");return{}}function jC(e,n){return le(e,n.$ref)?Jr(e,e[n.$ref]):(()=>{throw new as(n,"Unable to deref Ref")})()}function UC(e,n){if((ma(n)||aa(n))&&!ho(n))throw Error("Strings with format or pattern constraints must specify default");let c=ua(n)?n.minLength:0;return"".padEnd(c)}function BC(e,n){return Symbol()}function GC(e,n){let i=vu(n.pattern);if(rn(i))throw new as(n,"Unable to create TemplateLiteral due to infinite type expansion");return Jr(e,i)}function KC(e,n){return Array.from({length:n.minItems},(i,c)=>Jr(e,n.items[c]))}function HC(e,n){return}function WC(e,n){if(_(n.anyOf.length,0))throw Error("Unable to create Union with no variants");return Jr(e,n.anyOf[0])}function zC(e,n){return}function Jr(e,n){return ho(n)?TC(e,n):St(n)?RC(e,n):io(n)?kC(e,n):Wn(n)?AC(e,n):Xr(n)?CC(e,n):Qt(n)?$C(e,n):tn(n)?PC(e,n):Yr(n)?MC(e,n):pn(n)?vC(e,n):He(n)?OC(e,n):yt(n)?_C(e,n):so(n)?LC(e,n):xs(n)?NC(e,n):Tr(n)?DC(e,n):Qe(n)?qC(e,n):Kt(n)?FC(e,n):jt(n)?jC(e,n):rn(n)?UC(e,n):Is(n)?BC(e,n):cr(n)?GC(e,n):lt(n)?KC(e,n):Yo(n)?HC(e,n):be(n)?WC(e,n):ao(n)?zC(e,n):void 0}function As(...e){let[n,i]=En(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return Jr(n,i)}class al extends pa{constructor(e,n){super("Parse",e,n)}}function Zj(e,n,i){if(!Xt(e,n,i))throw new al(i,ks(e,n,i));return i}var VC=eu([(e,n,i)=>Kr(i),(e,n,i)=>Bs(e,n,i),(e,n,i)=>is(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>Zj(e,n,i)]);var tU=s({type:a("insert"),path:l(),value:wr()}),rU=Object({type:a("update"),path:l(),value:wr()}),nU=s({type:a("delete"),path:l()}),fOe=m([tU,rU,nU]);class ul{constructor(e,n){this.hasCodec=Eh(e,n),this.buildResult=rl(e,n),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(Vo().correctiveParse)return VC(this.Context(),this.Type(),e);throw new al(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 is(this.Context(),this.Type(),e)}Create(){return As(this.Context(),this.Type())}Default(e){return Bs(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?xh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Ih(this.Context(),this.Type(),e):this.Parse(e)}}function wh(...e){let[n,i]=En(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return new ul(n,i)}var QC=new WeakMap,iU=Symbol.for("TypeBox.Kind");function aU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((n)=>typeof n==="string");return[]}function uU(e,n){switch(n){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 Th(e){try{return YC(e)}catch{return}}function cU(e,n){switch(n){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 mU(e,n){let i=n.properties,c=new Set(i?Object.keys(i):[]);if(i)for(let[p,f]of Object.entries(i)){if(!(p in e))continue;e[p]=da(e[p],f)}if(n.additionalProperties&&typeof n.additionalProperties==="object")for(let[p,f]of Object.entries(e)){if(c.has(p))continue;e[p]=da(f,n.additionalProperties)}}function pU(e,n){if(Array.isArray(n.items)){for(let i=0;i<e.length;i++){let c=n.items[i];if(!c)continue;e[i]=da(e[i],c)}return}if(n.items&&typeof n.items==="object")for(let i=0;i<e.length;i++)e[i]=da(e[i],n.items)}function XC(e,n){for(let i of n)if(Th(i)?.Check(e))return e;for(let i of n){let c=structuredClone(e),p=da(c,i);if(Th(i)?.Check(p))return p}return e}function da(e,n){let i=e;if(Array.isArray(n.allOf))for(let f of n.allOf)i=da(i,f);if(Array.isArray(n.anyOf))i=XC(i,n.anyOf);if(Array.isArray(n.oneOf))i=XC(i,n.oneOf);let c=aU(n),p=c.length>1&&c.some((f)=>uU(i,f));if(c.length>0&&!p)for(let f of c){let g=cU(i,f);if(g!==i){i=g;break}}if(c.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))mU(i,n);if(c.includes("array")&&Array.isArray(i))pU(i,n);return i}function cl(e,n){if(Array.isArray(e)){if(Array.isArray(n.items))for(let p=0;p<e.length;p++){let f=n.items[p];if(f)cl(e[p],f)}else if(n.items)for(let p of e)cl(p,n.items);return}if(typeof e!=="object"||e===null||!n.properties)return;let i=e,c=new Set(n.required??[]);for(let[p,f]of Object.entries(n.properties)){if(!(p in i))continue;if(i[p]===null&&!c.has(p)&&typeof f.$ref!=="string"&&Th(f)?.Check(null)===!1)delete i[p];else cl(i[p],f)}}function YC(e){let n=e,i=QC.get(n);if(i)return i;let c=wh(e);return QC.set(n,c),c}function lU(e){if(e.keyword==="required"){let c=e.params.requiredProperties?.[0];if(c){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${c}`:c}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function dU(e,n){let i=e.find((c)=>c.name===n.name);if(!i)throw Error(`Tool "${n.name}" not found`);return tu(i,n)}function tu(e,n){let i=structuredClone(n.arguments);cl(i,e.parameters),is(e.parameters,i);let c=YC(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(iU)){let g=da(i,e.parameters);if(g!==i)if(typeof i==="object"&&i!==null&&typeof g==="object"&&g!==null){for(let x of Object.keys(i))delete i[x];Object.assign(i,g)}else return c.Check(g)?g:i}if(c.Check(i))return i;let p=c.Errors(i).map((g)=>` - ${lU(g)}: ${g.message}`).join(`
|
|
30
|
+
`)||"Unknown validation error",f=`Validation failed for tool "${n.name}":
|
|
31
|
+
${p}
|
|
32
|
+
|
|
33
|
+
Received arguments:
|
|
34
|
+
${JSON.stringify(n.arguments,null,2)}`;throw Error(f)}var ZC;function Lc(){if(!ZC)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return ZC}async function e$(e,n,i,c,p,f){let g=n$(n,e),x=[...g],I={...n,messages:[...n.messages,...g]};await c({type:"agent_start"}),await c({type:"turn_start"});for(let b of g)await c({type:"message_start",message:b}),await c({type:"message_end",message:b});return await r$(I,x,i,p,c,f??Lc()),x}async function t$(e,n,i,c,p){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let f=[],g={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await r$(g,f,n,c,i,p??Lc()),f}async function r$(e,n,i,c,p,f){let g=e,x=i,I,b=!1,E=await x.getSteeringMessages?.()||[];while(!0){let T=!0;while(T||E.length>0){let A=[];if(I){let X=await x.prepareNextTurn?.(I);if(X)g=X.context??g,A=X.messages??[],x={...x,model:X.model??x.model,reasoning:X.thinkingLevel===void 0?x.reasoning:X.thinkingLevel==="off"?void 0:X.thinkingLevel};if(E.length===0)E=await x.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let X of n$(g,[...A,...E]))await p({type:"message_start",message:X}),await p({type:"message_end",message:X}),g.messages.push(X),n.push(X);E=[];let L=await x.prepareRequest?.({context:g,model:x.model,thinkingLevel:x.reasoning??"off"},c);if(L)g=L.context??g,x={...x,model:L.model??x.model,reasoning:L.thinkingLevel===void 0?x.reasoning:L.thinkingLevel==="off"?void 0:L.thinkingLevel};let q=await hU(g,x,c,p,f);if(n.push(q),q.stopReason==="error"||q.stopReason==="aborted"){I={message:q,toolResults:[],context:g,newMessages:n},await x.finishTurn?.(I,c),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:n});return}let Y=q.content.filter((X)=>X.type==="toolCall"),j=[];if(T=!1,Y.length>0){let X=q.stopReason==="length"?await gU(Y,p):await yU(g,q,x,c,p);j.push(...X.messages),T=!X.terminate;for(let se of j)g.messages.push(se),n.push(se)}I={message:q,toolResults:j,context:g,newMessages:n};let V=await x.finishTurn?.(I,c);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:n});return}if(b=V?.action==="continue",E=await x.getSteeringMessages?.()||[],T||E.length>0)b=!1}let k=await x.getFollowUpMessages?.()||[];if(k.length>0){b=!1,E=k;continue}if(b){b=!1;continue}break}await p({type:"agent_end",messages:n})}function n$(e,n){let i=-1;for(let E=n.length-1;E>=0;E--)if(n[E].role==="system"){i=E;break}let c=n[i],p=c?n.map((E,T)=>T===i?Rh(c,fU):E):n,f=Bo(ne([...e.messages,...p]),(e.tools??[]).map(nt)),g=f.toolsAdded.length===0&&f.toolsRemoved.length===0;if(c){if(g&&!c.toolsAdded?.length&&!c.toolsRemoved?.length)return n;return p.map((E,T)=>T===i?Rh(c,f):E)}if(g)return n;let x=Rh({role:"system",content:"",timestamp:Date.now()},f),I=n.findIndex((E)=>E.role!=="system"),b=I===-1?n.length:I;return[...n.slice(0,b),x,...n.slice(b)]}var fU={toolsAdded:[],toolsRemoved:[]};function Rh(e,{toolsAdded:n,toolsRemoved:i}){let{toolsAdded:c,toolsRemoved:p,...f}=e;return{...f,...n.length>0?{toolsAdded:n}:{},...i.length>0?{toolsRemoved:i}:{}}}async function hU(e,n,i,c,p){let f=e.messages;if(n.transformContext)f=await n.transformContext(f,i);let g=await n.convertToLlm(f),x=ht({messages:g}),I=(n.getApiKey?await n.getApiKey(n.model.provider):void 0)||n.apiKey,b=await p(n.model,x,{...n,apiKey:I,signal:i}),E=async()=>Object.assign(await b.result(),{thinkingLevel:n.reasoning??"off"}),T=null,k=!1;for await(let L of b)switch(L.type){case"start":T=L.partial,e.messages.push(T),k=!0,await c({type:"message_start",message:{...T}});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(T)T=L.partial,e.messages[e.messages.length-1]=T,await c({type:"message_update",assistantMessageEvent:L,message:{...T}});break;case"done":case"error":{let q=await E();if(k)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!k)await c({type:"message_start",message:{...q}});return await c({type:"message_end",message:q}),q}}let A=await E();if(k)e.messages[e.messages.length-1]=A;else e.messages.push(A),await c({type:"message_start",message:{...A}});return await c({type:"message_end",message:A}),A}async function gU(e,n){let i=[];for(let c of e){await n({type:"tool_execution_start",toolCallId:c.id,toolName:c.name,args:c.arguments});let p={toolCall:c,result:Ks(`Tool call "${c.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,n);let f=kh(p);await Ah(f,n),i.push(f)}return{messages:i,terminate:!1}}async function yU(e,n,i,c,p){let f=n.content.filter((x)=>x.type==="toolCall"),g=f.some((x)=>e.tools?.find((I)=>I.name===x.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||g)return xU(e,n,f,i,c,p);return IU(e,n,f,i,c,p)}async function xU(e,n,i,c,p,f){let g=[],x=[];for(let I of i){await f({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let b=await s$(e,n,I,c,p),E;if(b.kind==="immediate")E={toolCall:I,result:b.result,isError:b.isError};else{let k=await a$(b,p,i$(I,f));E=await u$(e,n,b,k,c,p)}await Nc(E,f);let T=kh(E);if(await Ah(T,f),g.push(E),x.push(T),p?.aborted)break}return{messages:x,terminate:o$(g)}}async function IU(e,n,i,c,p,f){let g=[];for(let b of i){await f({type:"tool_execution_start",toolCallId:b.id,toolName:b.name,args:b.arguments});let E=await s$(e,n,b,c,p);if(E.kind==="immediate"){let T={toolCall:b,result:E.result,isError:E.isError};if(await Nc(T,f),g.push(T),p?.aborted)break;continue}if(g.push(async()=>{if(p?.aborted){let A={toolCall:b,result:Ks("Operation aborted"),isError:!0};return await Nc(A,f),A}let T=await a$(E,p,i$(b,f)),k=await u$(e,n,E,T,c,p);return await Nc(k,f),k}),p?.aborted)break}let x=await Promise.all(g.map((b)=>typeof b==="function"?b():Promise.resolve(b))),I=[];for(let b of x){let E=kh(b);await Ah(E,f),I.push(E)}return{messages:I,terminate:o$(x)}}function o$(e){return e.length>0&&e.every((n)=>n.result.terminate===!0)}function bU(e,n){if(!e.prepareArguments)return n;let i=e.prepareArguments(n.arguments);if(i===n.arguments)return n;return{...n,arguments:i}}async function s$(e,n,i,c,p,f=e.tools??[]){let g=f.find((x)=>x.name===i.name);if(!g)return{kind:"immediate",result:Ks(`Tool ${i.name} not found`),isError:!0};try{let x=bU(g,i),I=tu(g,x);if(c.beforeToolCall){let b=await c.beforeToolCall({assistantMessage:n,toolCall:i,args:I,context:e},p);if(p?.aborted)return{kind:"immediate",result:Ks("Operation aborted"),isError:!0};if(b?.block){let E=Ks(b.reason||"Tool execution was blocked");if(b.terminate===!0)E.terminate=!0;return{kind:"immediate",result:E,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Ks("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:g,args:I}}catch(x){return{kind:"immediate",result:Ks(x instanceof Error?x.message:String(x)),isError:!0}}}function i$(e,n){return(i)=>n({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function a$(e,n,i){let c=[],p=!0,f=performance.now(),g=()=>Math.round(performance.now()-f);try{let x=await e.tool.execute(e.toolCall.id,e.args,n,(b)=>{if(!p)return;c.push(Promise.resolve(i(b)))}),I=g();return p=!1,await Promise.all(c),{result:x,isError:x.isError===!0,durationMs:I}}catch(x){let I=g();return p=!1,await Promise.all(c),{result:Ks(x instanceof Error?x.message:String(x)),isError:!0,durationMs:I}}finally{p=!1}}async function u$(e,n,i,c,p,f){let{result:g,isError:x}=c;if(p.afterToolCall)try{let I=await p.afterToolCall({assistantMessage:n,toolCall:i.toolCall,args:i.args,result:g,isError:x,context:e},f);if(I){let b=I.structuredContent??(I.content?void 0:g.structuredContent);if(g={...g,content:I.content??g.content,details:I.details??g.details,usage:I.usage??g.usage,terminate:I.terminate??g.terminate},b===void 0)delete g.structuredContent;else g.structuredContent=b;x=I.isError??x}}catch(I){g=Ks(I instanceof Error?I.message:String(I)),x=!0}return{toolCall:i.toolCall,result:g,isError:x,durationMs:c.durationMs}}function Ks(e){return{content:[{type:"text",text:e}],details:{}}}async function Nc(e,n){await n({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 kh(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 Ah(e,n){await n({type:"message_start",message:e}),await n({type:"message_end",message:e})}function EU(e){return e.filter((n)=>n.role==="system"||n.role==="user"||n.role==="assistant"||n.role==="toolResult")}var SU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},wU={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 TU(e){let n=e?.tools?.slice()??[],i=e?.messages?.slice()??[],c=Gn(e?.systemPrompt,n.map(nt));if(i[0]?.role!=="system"&&c)i.unshift(c);return{get systemPrompt(){return Fo(i)},model:e?.model??wU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return n},set tools(p){n=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Ch{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 $h{_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 n=e??{};this._state=TU(n.initialState),this.convertToLlm=n.convertToLlm??EU,this.transformContext=n.transformContext,this.streamFunction=n.streamFn??Lc(),this.getApiKey=n.getApiKey,this.onPayload=n.onPayload,this.onResponse=n.onResponse,this.onProviderStreamEvent=n.onProviderStreamEvent,this.beforeToolCall=n.beforeToolCall,this.afterToolCall=n.afterToolCall,this.finishTurn=n.finishTurn,this.prepareRequest=n.prepareRequest,this.prepareNextTurn=n.prepareNextTurn,this.prepareNextTurnWithContext=n.prepareNextTurnWithContext,this.steeringQueue=new Ch(n.steeringMode??"one-at-a-time"),this.followUpQueue=new Ch(n.followUpMode??"one-at-a-time"),this.sessionId=n.sessionId,this.thinkingBudgets=n.thinkingBudgets,this.transport=n.transport??"auto",this.maxRetryDelayMs=n.maxRetryDelayMs,this.toolExecution=n.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=jr(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,n){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,n);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((n)=>n.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let n=this.steeringQueue.drain();if(n.length>0){await this.runPromptMessages(n,{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,n){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(n&&n.length>0)i.push(...n);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,n={}){await this.runWithLifecycle(async(i)=>{await e$(e,this.createContextSnapshot(),this.createLoopConfig(n),(c)=>this.processEvents(c),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await t$(this.createContextSnapshot(),this.createLoopConfig(),(n)=>this.processEvents(n),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let n=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(n)return n=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let n=new AbortController,i=()=>{},c=new Promise((p)=>{i=p});this.activeRun={promise:c,resolve:i,abortController:n},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(n.signal)}catch(p){await this.handleRunFailure(p,n.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,n){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:SU,stopReason:n?"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 n=this.activeRun?.abortController.signal;if(!n)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,n)}}function we(e,...n){return Object.assign(e,{aliases:n})}function fa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function RU(e){let n=[],i="";for(let c of e){if(!/[a-zA-Z0-9]/.test(c)){if(i)n.push(i);i="";continue}if(c>="A"&&c<="Z"&&i&&!/[A-Z]$/.test(i))n.push(i),i="";i+=c}if(i)n.push(i);return n}function c$(e,n){if(e.some((L)=>L.name===n))return n;let i=e.map((L)=>L.name),c=(L)=>i.filter((q)=>fa(q)===L),p=c(fa(n));if(p.length===1&&p[0])return p[0];if(p.length>1)return n;let f=n.split(/[.:/]/).pop()??n,g=f===n?[]:c(fa(f));if(g.length===1&&g[0])return g[0];let x=new Map;for(let L of e)for(let q of L.aliases??[]){let Y=fa(q);x.set(Y,(x.get(Y)??new Set).add(L.name))}let I=(L)=>[...new Set([...c(L),...x.get(L)??[]])],b=I(fa(f));if(b.length===1&&b[0])return b[0];if(b.length>1)return n;let E=RU(f),T=new Set;E.forEach((L,q)=>{T.add(fa(L));let Y=E[q+1];if(Y)T.add(fa(L+Y))});let k=new Set;for(let L of T)for(let q of I(L))k.add(q);let A=[...k];return A.length===1&&A[0]?A[0]:n}function v(e){return e}function xn(e,n){let i=n.indexOf("/");if(i<=0)return;return e.getModel(n.slice(0,i),n.slice(i+1))}function tt(e){return`${e.provider}/${e.id}`}function kU(e,n,i){let c=async(f,g)=>{try{if(n){let I=f instanceof Request?f:void 0;n({at:Date.now(),method:g?.method??I?.method??"GET",url:typeof f==="string"?f:f instanceof URL?f.toString():f.url,headers:m$(g?.headers??I?.headers),body:AU(g?.body!==void 0?g.body:I?.body??void 0)})}}catch{}let x=await e(f,g);if(i)try{let I=Date.now(),{status:b,statusText:E}=x,T=m$(x.headers);if(!x.body)return i({at:I,status:b,statusText:E,headers:T,body:""}),x;let k="",A=new TextDecoder,L=new TransformStream({transform(j,V){V.enqueue(j),k+=A.decode(j,{stream:!0}),i({at:I,status:b,statusText:E,headers:T,body:k})},flush(){k+=A.decode(),i({at:I,status:b,statusText:E,headers:T,body:k})}}),q=x.body.pipeThrough(L),Y=new Response(q,x);try{Object.defineProperty(Y,"url",{value:x.url})}catch{}return Y}catch{}return x},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(c,{preconnect:p})}function m$(e){if(!e||typeof e!=="object")return{};let n={};if(e instanceof Headers)return e.forEach((c,p)=>{n[p]=c}),n;let i=Array.isArray(e)?e:Object.entries(e);for(let c of i)if(Array.isArray(c)&&typeof c[0]==="string"&&typeof c[1]==="string")n[c[0]]=c[1];return n}function AU(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 CU(e,n){return c$(e,n)}function $U(e,n,i){let c=Date.now(),p=new WeakSet,f=(I)=>{if(!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;let b=Date.now(),E=Math.max(10,b-c);I.generationMs=E},g=async(I)=>{if(!i||!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;if(f(I),p.has(I))return;p.add(I),Object.assign(I,await i(I))},x=(I)=>{let b=I?.content;if(!Array.isArray(b))return;for(let E of b)if(E&&E.type==="toolCall"&&typeof E.name==="string")E.name=CU(n(),E.name)};return{async*[Symbol.asyncIterator](){for await(let I of e){let{partial:b,message:E}=I;x(b),await g(E),x(E),yield I}},result:async()=>{let I=await e.result();return f(I),await g(I),x(I),I}}}function Dc(e,n){let i=(n??[]).filter((g)=>g.kind==="path").map((g)=>`<file path=${JSON.stringify(g.data)} />`),c=(n??[]).filter((g)=>g.kind==="text").map((g)=>`<file name=${JSON.stringify(g.name)}>
|
|
35
|
+
${g.data}
|
|
36
|
+
</file>`),p=(n??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType}));return{merged:[...i,...c,...e.trim()?[e]:[]].join(`
|
|
37
|
+
|
|
38
|
+
`),images:p}}function Ph(e,n){let{merged:i,images:c}=Dc(e,n);return{role:"user",content:c.length>0?[{type:"text",text:i},...c]:i,timestamp:Date.now()}}function p$(e){let n=new Set;for(let x of e.tools){let I=x.name.toLowerCase();if(n.has(I))throw Error(`Tool names collide ignoring case: ${x.name}`);n.add(I)}let i=new $h({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(x,I,b)=>{let{captureRequest:E,captureResponse:T}=e,k=E||T?{...b,fetch:kU(b?.fetch??globalThis.fetch,E?(L)=>E({...L,model:tt(x)}):void 0,T?(L)=>T({...L,model:tt(x)}):void 0)}:b,A=x.api==="openai-completions"||x.api==="openai-responses"?{...x,compat:{...x.compat,supportsDeveloperRole:!1}}:x;return $U(e.models.streamSimple(A,I,k),()=>i.state.tools,e.hooks.response)},convertToLlm:(x)=>x,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:x,model:I})=>{let b=x.messages.findIndex((A)=>A.role!=="system"),E=x.messages.slice(0,b===-1?x.messages.length:b),T=e.hooks.prepare,k=e.hooks.tools?.()??x.tools;if(k){i.state.tools=k;let A=E[0];if(A?.role==="system")E[0]={...A,toolsAdded:k.map(nt),toolsRemoved:void 0}}return{context:{...x,tools:k,messages:await T(E,k,I)}}}:void 0}),c=new Map,p=new Map,f=new WeakSet,g;return i.subscribe((x)=>{if(x.type==="message_update"&&x.message.role==="assistant"){p.clear(),e.hooks.draft(d$(x.message));return}if(x.type==="tool_execution_update"){let b=c.get(x.toolCallId)??_e(x.toolName,x.args),E=Array.isArray(x.partialResult?.content)?x.partialResult.content.map((T)=>T.type==="text"&&typeof T.text==="string"?T.text:"").join(""):"";p.set(x.toolCallId,{type:"tool_call",id:x.toolCallId,name:b.name,input:b.input,...b.source?{source:b.source}:{},output:E}),e.hooks.draft([...p.values()]);return}if(x.type==="tool_execution_end"){if(p.delete(x.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(x.type!=="message_end")return;if(f.has(x.message)){e.steerConsumed?.(x.message);return}let I=x.message.role==="user"&&g?{type:"user",text:g.text,...g.attachments?.length?{attachments:g.attachments}:{}}:PU(x.message);if(x.message.role==="user")g=void 0;if(I?.type==="assistant"){for(let b of I.parts)if(b.type==="tool_call")c.set(b.id,b)}if(I?.type==="tool_result"){let b=c.get(I.callID);if(b?.source)Object.assign(I,{name:b.name,source:b.source})}if(I)e.hooks.message(I,x.message);if(x.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(x,I)=>{g={text:x,attachments:I};let{merged:b,images:E}=Dc(x,I);return i.prompt(b,E.length>0?E:void 0)},retry:async()=>{let x=i.state.messages;if(x.at(-1)?.role==="assistant")i.state.messages=x.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(x)=>{f.add(x),i.steer(x)},unsteer:(x)=>{let b=i.steeringQueue?.messages;if(!b)return!1;let E=b.indexOf(x);if(E<0){let k=JSON.stringify(x);E=b.findIndex((A)=>JSON.stringify(A)===k)}if(E<0)return!1;let[T]=b.splice(E,1);if(T)f.delete(T);return!0},abort:()=>i.abort()}}function Mh(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 l$(e){let{name:i,source:c}=_e(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:i,...c?{source:c}:{},output:"\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",isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:"\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"}],isError:!0,timestamp:Date.now()}}}function d$(e){return e.content.map((n)=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="thinking")return{type:"thinking",text:n.thinking};return{type:"tool_call",id:n.id,..._e(n.name,n.arguments)}})}function PU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((n)=>n.type==="text"?n.text:"").join("")};case"assistant":return{type:"assistant",parts:d$(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let n=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(""),...n.length>0?{images:n}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class ut extends Error{errors;constructor(e){super(e.map((n)=>n.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function R(e){return e}import{createHash as f$}from"crypto";import{existsSync as MU}from"fs";import{readFile as h$,realpath as ml}from"fs/promises";import{dirname as vU,isAbsolute as g$,relative as y$,resolve as x$,sep as I$}from"path";var b$=[..._g];class pl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((n)=>n.message).join("; ")}`);this.errors=e}}class ll{cache=new Map;pending=new Map;async entry(e,n){if(!e){if(n)throw Error("Plugin web entry requires a plugin source path");return}let i=vU(x$(e)),c=x$(i,n??"web.tsx");if(!n&&!MU(c))return;let p=y$(await ml(i),await ml(c));if(g$(p)||p===".."||p.startsWith(`..${I$}`))throw Error("Plugin web entry must stay inside its plugin directory");return c}async build(e,n){let i=this.pending.get(e);if(i)return i;let c=this.compile(e,n);this.pending.set(e,c);try{return await c}finally{this.pending.delete(e)}}async compile(e,n){let i=this.cache.get(e);if(i){let b=!0;for(let[E,T]of i.inputs){let k=await h$(E).catch(()=>{return});if(!k||f$("sha256").update(k).digest("hex")!==T){b=!1;break}}if(b)return i.source;this.cache.delete(e)}let c=await ml(n),p=new Map,f=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:b$,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(b){b.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(E)=>{if(!b$.includes(E.path))throw Error(`Unsupported shared web import: ${E.path}`);return{path:E.path,external:!0}}),b.onLoad({filter:/.*/},async(E)=>{let T=y$(c,await ml(E.path));if(g$(T)||T===".."||T.startsWith(`..${I$}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await h$(E.path);p.set(E.path,f$("sha256").update(k).digest("hex"));return})}}]}).catch((b)=>{let T=(b instanceof AggregateError?b.errors:[b]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${T.join("; ")}`,{cause:b})});if(!f.success)throw new pl(f.logs.filter((b)=>b.level==="error").map((b)=>({file:b.position?.file??null,line:b.position?.line??null,message:b.message})));let g=f.outputs.find((b)=>b.kind==="entry-point"&&b.path.endsWith(".js")),x=f.outputs.find((b)=>b.path.endsWith(".css"));if(!g||f.outputs.some((b)=>b!==g&&b!==x))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let I=await g.text();return this.cache.set(e,{source:I,css:await x?.text(),inputs:p}),I}}function jo(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Cs(e){let n=e;if(typeof n.content==="string")return n.content;return n.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(`
|
|
39
|
+
|
|
40
|
+
`)}function ru(e){return e.content.map((n)=>n.type==="text"?n.text:"[image]").join("")}function nu(e){return e.role==="assistant"&&e.content.length>0}function us(e){let n=[],i=new Map,c=0;for(let p of e){let f=p.raw;if(f.role==="assistant"){if(nu(f))c++;for(let g of f.content){if(g.type!=="toolCall")continue;let x={call:g,step:c,message:f};n.push(x),i.set(g.id,x)}}else if(f.role==="toolResult"){let g=i.get(f.toolCallId);if(g)g.result=f}}return n}var fl=new Set(["edit","write"]),E$=new Set(["grep","glob"]);function no(e,n){let i=_e(e.name,e.arguments).input?.[n];return typeof i==="string"?i:void 0}function S$(e){return[...new Set(us(e).flatMap((n)=>fl.has(_e(n.call.name,n.call.arguments).name)&&n.result&&!n.result.isError&&no(n.call,"path")?[no(n.call,"path")]:[]))]}function vh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function hl(e){let n=[{source:"ASSISTANT_TOOL",text:`${_e(e.call.name,e.call.arguments).name}(${jo(_e(e.call.name,e.call.arguments).input)}) [${vh(e)}, call=${e.call.id}]`}];if(e.result)n.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:ru(e.result)});return n}function O(e){let n=0,i=0,c=0;for(let p of e){let f=p.codePointAt(0);if(f<=127)n++;else if(f>=19968&&f<=40959||f>=12288&&f<=12351||f>=65280&&f<=65519||f>=131072&&f<=173791)i++;else c++}return Math.max(0,Math.ceil(n/4+i+c/2))}var Oh=8192;function U(e){let n=e,i=0,c="";if(n.role==="system")c=typeof n.content==="string"?n.content:JSON.stringify(n.content);else if(n.role==="user")if(typeof n.content==="string")c=n.content;else for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else if(n.role==="assistant")for(let p of n.content)if(p.type==="text")c+=p.text;else if(p.type==="thinking")c+=p.thinking;else c+=`${p.name}${jo(p.arguments)}`;else if(n.role==="toolResult")for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else c=jo(e);return O(c)+16+i*Oh}function Li(e=[]){return e.reduce((n,i)=>n+O(i.name+i.description+jo(i.parameters))+16,0)}function Dn(e,n){let i=e.replace(/\s+/g," ").trim();if(O(i)<=n)return i;let c=Math.min(i.length,n*4);while(c>0&&O(i.slice(0,c))>n-1)c=Math.floor(c*0.8);return`${i.slice(0,c).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function bo(e,n,i=Number.POSITIVE_INFINITY){if(O(e)<=n&&e.length<=i)return e;let c=`
|
|
41
|
+
[... omitted; use history tools for the full text ...]
|
|
42
|
+
`,p=Math.floor((n-O(c))/2);if(p<=0)return"";let f=(g)=>{let x=0,I=Math.max(0,Math.min(e.length,p*4,Math.floor((i-c.length)/2)));while(x<I){let b=Math.ceil((x+I)/2),E=g?e.slice(-b):e.slice(0,b);if(O(E)<=p)x=b;else I=b-1}if(!x)return"";return g?e.slice(-x).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,x).replace(/[\uD800-\uDBFF]$/,"")};return`${f(!1)}${c}${f(!0)}`}function gl(e,n){if(O(e.join(`
|
|
43
|
+
`))<=n)return e;let i=(E)=>`- [... ${E} steps omitted; use history tools for the full text ...]`,c=n-O(i(e.length)),p=[],f=[],g=0,x=0,I=e.length-1;while(x<=I){let E=p.length<=f.length,T=E?e[x]:e[I],k=O(`${T}
|
|
44
|
+
`);if(g+k>c)break;if(g+=k,E)p.push(e[x++]);else f.unshift(e[I--])}let b=I-x+1;return[...p,...b>0?[i(b)]:[],...f]}function $s(e){let n=[],i;for(let c of e){let p=c.entry;if(p.type==="run"&&p.state==="start"){i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},n.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=OU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!c.raw)continue;if(!i&&p.type==="user"&&p.notices&&n.length){n.at(-1)?.records.push(c);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},n.push(i);i.records.push(c)}for(let c of n)c.records=_h(c.records);return n}function _h(e){if(e.length<=1)return[...e];let n=[],i=[],c=new Set;for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;let g=f.raw?.role;if(g==="assistant"){let I=f.raw.content?.filter((b)=>b.type==="toolCall")??[];if(I.length>0)for(let b of I)c.add(b.id);if(n.push(f),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(g==="toolResult"){let x=f.raw;if(x.toolCallId)c.delete(x.toolCallId);if(n.push(f),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(g==="user"){if(n.length===0){n.push(f);continue}let x=e.slice(p+1).some((I)=>I.raw?.role==="assistant");if(c.size>0||x){i.push(f);continue}n.push(f);continue}n.push(f)}if(i.length>0)n.push(...i);return n}function OU(e,n){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=n.findLast((c)=>c.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&li(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return li(i)?"interrupted":"failed";default:return"interrupted"}}function ha(e){for(let n=e.length-1;n>=0;n--){let i=e[n]?.entry;if(i?.type==="compaction")return i.through}return 0}function yl(e,n){return e.end!==void 0&&e.end<=n&&e.records.every((i)=>i.entry.seq<=n)}function Lh(e,n){return e.find((i)=>i.start<n&&!yl(i,n)&&i.records.some((c)=>c.entry.seq<=n))}function ou(e){let n=ha(e),c=$s(e).findLast((p)=>p.end!==void 0);if(!c?.end||c.end<=n)return;return c.end}function xl(e){let n=ha(e);return Lh($s(e),n)?.end}function qc(e,n){let i=ha(e),c=$s(e).at(-1);if(!c||c.end!==void 0)return;let p=c.records.filter((E)=>E.entry.seq>i),f=[],g=new Set;for(let E of p){let T=E.raw,k=U(E.raw);if(T.role==="assistant"){for(let A of T.content)if(A.type==="toolCall")g.add(A.id)}else if(T.role==="toolResult")g.delete(T.toolCallId);if(nu(T)||!f.length||T.role==="user"&&f.at(-1)?.assistant)f.push({end:E.entry.seq,tokens:k,assistant:nu(T),pending:g.size});else{let A=f.at(-1);A.end=E.entry.seq,A.tokens+=k,A.pending=g.size}}let x=f.findLastIndex((E)=>E.assistant),I=0,b;for(let E=f.length-1;E>=0;E--){let T=f[E];if(E<x&&T.assistant&&T.pending===0&&(I<=n||b===void 0))b=T.end;if(I+=T.tokens,I>n&&b!==void 0)break}if(I<=n)return;return b}var w$=2000;function Ni(e,n){let i=O(n);if(i<=w$)return n;let c=new TextEncoder().encode(n).length,p=n.split(`
|
|
45
|
+
`).length,f=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${c} 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(`
|
|
46
|
+
`),g="</user-text-reference>",x=w$-O(`${f}
|
|
47
|
+
|
|
48
|
+
${g}`);if(x<=0)return n;let I=`${f}
|
|
49
|
+
${bo(n,x,n.length-f.length-g.length-3)}
|
|
50
|
+
${g}`;return I.length<n.length&&O(I)<i?I:n}function T$(e){let n=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return n;if(typeof n.content==="string"){let p=Ni(e.entry.seq,n.content);return p===n.content?n:{...n,content:p}}let i=!1,c=n.content.map((p)=>{if(p.type!=="text")return p;let f=Ni(e.entry.seq,p.text);if(f!==p.text)i=!0;return f===p.text?p:{...p,text:f}});return i?{...n,content:c}:n}function Nh(e,n=!1){let i=e.records.filter((A)=>A.entry.type==="user"&&!A.entry.notices&&A.raw.role==="user"),c=i.flatMap((A)=>{let L=A.raw.content;return typeof L==="string"?[]:L.filter((q)=>q.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,f=e.status==="open"?"interrupted":e.status,g="";if(i.length){let A=n?bo(i.map((L)=>Cs(L.raw)).join(`
|
|
51
|
+
|
|
52
|
+
`),600):i.map((L,q)=>`<user-message sequence="${q+1}">
|
|
53
|
+
${Ni(L.entry.seq,Cs(L.raw))}
|
|
54
|
+
</user-message>`).join(`
|
|
55
|
+
|
|
56
|
+
`);g=[`<chunk-input id="${e.id}" status="${f}"${n?' excerpt="true"':""}>`,A,...n?[p]:[],"</chunk-input>"].join(`
|
|
57
|
+
`)}let I=e.records.filter((A)=>A.raw.role==="assistant").at(-1)?.raw,b=I?dl(I):"",E=[];if(f!=="completed"){let A=us(e.records),L=new Map(A.map((X)=>[X.call,X])),q=A.slice(-3),Y=new Set(q.map((X)=>X.message)),j=[],V=[];for(let X of e.records){let se=X.raw;if(se.role!=="assistant")continue;let Z=Y.has(se);for(let z of se.content)if(z.type==="text"&&se!==I&&z.text.trim())if(Z)V.push(`ASSISTANT: ${Dn(z.text,50)}`);else j.push(`- ASSISTANT: ${Dn(z.text,50)}`);else if(z.type==="toolCall"){let ce=L.get(z);if(!ce)continue;if(Z){if(q.includes(ce))for(let he of hl(ce))V.push(`${he.source}: ${bo(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${z.name}(${Dn(jo(z.arguments),40)}) [${vh(ce)}]`)}}E.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...j.length?[`Earlier steps, oldest first:
|
|
58
|
+
${gl(j,n?300:800).join(`
|
|
59
|
+
`)}`]:[],...V)}let T=S$(e.records),k=[`<chunk-summary id="${e.id}" status="${f}" folded-messages="${e.records.length}"${n?' excerpt="true"':""}>`,b?n?bo(b,600):b:"No final assistant response was recorded.",...E,...T.length?[`Recorded file changes:
|
|
60
|
+
${bo(T.join(`
|
|
61
|
+
`),250)}`]:[],...n&&f==="completed"?[p]:[],"</chunk-summary>"].join(`
|
|
62
|
+
`);return{input:g,images:c,summary:k,tokens:_U(g,k,c.length)}}function _U(e,n,i){return(e?O(e)+16:0)+O(n)+16+i*Oh}var LU=["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."],NU="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.",DU=1500,qU=80,FU=240;function R$(e,n,i){let c=[],p=0,f=Math.min(n.target,n.hard);for(let x=e.length-1;x>=0;x--){let I=e[x],b=Nh(I),E=p+b.tokens>f?Nh(I,!0):void 0,T=E&&E.tokens<b.tokens?E:b;if(!(!i&&x===e.length-1&&I.status!=="completed")&&p+T.tokens>n.hard)break;p+=T.tokens,c.push({run:I,content:T})}c.reverse();let g=e.slice(0,e.length-c.length);return{visible:c,archived:g,tokens:p}}function k$(e){let{runs:n,visible:i,archived:c,partial:p}=e,f=c.flatMap((I)=>{let b=I.records.filter((T)=>T.raw.role==="user"&&!(T.entry.type==="user"&&T.entry.notices)).map((T)=>Cs(T.raw));if(!b.length)return[];let E=I===n[0]?FU:qU;return[`- ${I.id} [${I.status}]: ${Dn(b.join(" / "),E)}`]}),g=new Map(n.map((I,b)=>[I,b+1])),x=[...i.map((I)=>g.get(I)??0),...p?[n.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...LU,...p?[NU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${c.length}`,`archived chunk IDs: ${c.length?c.map((I)=>I.id).join(", "):"none"}`,`visible sequences: ${x.length?`${x[0]}..${x.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...f.length?["archived requests, oldest first:",bo(f.join(`
|
|
63
|
+
`),DU)]:[],"</conversation-checkpoint>"].join(`
|
|
64
|
+
`)}function A$(e,n){let i=e.split(`
|
|
65
|
+
`),c=n.split(`
|
|
66
|
+
`),p=new Set(i),f=new Set(c),g=[...i.filter((I)=>I.trim()&&!f.has(I)).map((I)=>`- ${Dn(I,40)}`),...c.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`+ ${Dn(I,40)}`)],x=i.find((I)=>I.trim()&&f.has(I));return[...g.slice(0,6),...g.length>6?[`\u2026 ${g.length-6} more changed lines`]:[],...x&&g.every((I)=>I.startsWith("+"))?[`@ ${Dn(x,40)}`]:[]]}function Il(e,n){if(!n)return e;let i=n.endsWith("/")?n:`${n}/`;return e.startsWith(i)?e.slice(i.length):e}function jU(e){let n=e.arguments?.paths;if(!Array.isArray(n))return[];return n.flatMap((i)=>{let c=i&&typeof i==="object"?i.path:void 0;return typeof c==="string"?[c]:[]})}function UU(e,n){let i=no(e,"path");if(fl.has(e.name)&&i)return`file:${Il(i,n)}`;let c=no(e,"command");if(c)return`command:${c}`;return`${e.name}:${jo(e.arguments)}`}function BU(e,n){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},c=new Map;for(let f of us(e)){let g=c.get(f.step)??[];g.push(f),c.set(f.step,g)}let p=new Map;for(let f of e){let g=f.raw;if(!nu(g))continue;let x=++i.steps,I=dl(g);if(I)i.narration.push({step:x,text:Dn(I,60)});for(let{call:b,result:E}of c.get(x)??[]){if(!E)continue;let T=_e(b.name,b.arguments),k={...b,name:T.name,arguments:T.input},A=UU(k,n),L=ru(E);if(E.isError){let se=no(k,"command"),Z=se?`${k.name} \`${Dn(se,40)}\``:`${k.name} ${A.startsWith("file:")?A.slice(5):Dn(jo(k.arguments),40)}`,z={step:x,key:A,what:Z,detail:bo(L.trim().split(`
|
|
67
|
+
`).slice(0,8).join(`
|
|
68
|
+
`),200)};i.errors.push(z);let ce=p.get(A)??[];ce.push(z),p.set(A,ce);continue}for(let se of p.get(A)??[])se.resolved=x;p.delete(A);let q=no(k,"path");if(fl.has(k.name)&&q){let se=Il(q,n),Z=i.files.get(se)??{count:0,first:x,last:x,diffs:[]};if(Z.count++,Z.last=x,Z.diffs.push({step:x,lines:k.name==="edit"?no(k,"old_string")!==void 0?A$(no(k,"old_string")??"",no(k,"new_string")??""):[]:A$("",no(k,"content")??"")}),Z.diffs.length>3)Z.diffs.shift();i.files.set(se,Z);continue}let Y=k.name==="read"?[...q?[q]:[],...jU(k)]:[];if(Y.length){for(let se of Y){let Z=Il(se,n),z=i.reads.get(Z)??[];z.push(x),i.reads.set(Z,z)}continue}if(E$.has(k.name)){let se=q?` in ${Il(q,n)}`:"",Z=k.name==="grep"&&no(k,"glob")?` (${no(k,"glob")})`:"",z=`${k.name} ${no(k,"pattern")??""}${se}${Z}`.replace(/\s+/g," "),ce=i.searches.get(z)??{steps:[],head:""};ce.steps.push(x),ce.head=Dn(L.trim().split(`
|
|
69
|
+
`)[0]??"",25),i.searches.set(z,ce);continue}let j=no(k,"command");if(j){let se=L.trim().split(`
|
|
70
|
+
`);i.commands.push({step:x,command:Dn(j,40),exit:"0",lines:se.length,tail:se.slice(-3).map((Z)=>Dn(Z,40))});continue}let V=`${k.name} ${Dn(jo(k.arguments),40)}`,X=i.other.get(V)??[];X.push(x),i.other.set(V,X)}}return i}function C$(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Fc(e,n,i){let c=(b,E)=>E===void 0||!b.length?b:gl(b,E),p=[`<work-state chunk="${n.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="${n.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],f=[...e.files];p.push("",`## Modified files (${f.length})`),f.forEach(([b,E],T)=>{if(p.push(`- ${b}: ${E.count} change${E.count>1?"s":""} (step ${E.first}${E.last!==E.first?`-${E.last}`:""})`),T<f.length-i.diffFiles)return;for(let k of E.diffs)p.push(` step ${k.step}:`,...k.lines.map((A)=>` ${A}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((b)=>b.resolved?`- step ${b.step} ${b.what} (resolved at step ${b.resolved})${i.lists===void 0?`: ${b.detail.replace(/\n/g,`
|
|
71
|
+
`)}`:""}`:`- step ${b.step} ${b.what} (UNRESOLVED): ${b.detail.replace(/\n/g,`
|
|
72
|
+
`)}`)),p.push("","## Steps",...c(e.narration.map((b)=>`- ${b.step}. ${b.text}`),i.narration));let g=[...e.reads].map(([b,E])=>`- ${b} @ ${E.join(",")}`);p.push("",`## Files read (${g.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...c(g,i.lists));let x=[...e.searches].map(([b,E])=>`- ${b} \u2192 ${E.head||"(no output)"} (${C$(E.steps)})`);p.push("",`## Searches (${x.length})`,...c(x,i.lists));let I=e.commands.map((b)=>[`- ${b.step}. \`${b.command}\` exit=${b.exit}, ${b.lines} output lines, last ${b.tail.length}:`,...b.tail.map((E)=>` ${E}`)].join(`
|
|
73
|
+
`));if(p.push("",`## Commands (${I.length})`,...c(I,i.lists)),e.other.size){let b=[...e.other].map(([E,T])=>`- ${E} (${C$(T)})`);p.push("",`## Other tool calls (${b.length})`,...c(b,i.lists))}return p.push("</work-state>"),p.join(`
|
|
74
|
+
`)}function bl(e,n,i,c){let p=BU(e,c),f=Fc(p,n,{diffFiles:Number.POSITIVE_INFINITY});if(O(f)<=i)return f;let g={...p,narration:[]};for(let b of[Number.POSITIVE_INFINITY,20,10,5]){let E=O(Fc(g,n,{diffFiles:b}));if(E>i*0.7)continue;return Fc(p,n,{narration:Math.max(500,i-E),diffFiles:b})}let x=Math.max(300,Math.floor(i*0.1)),I=O(Fc(g,n,{diffFiles:0,lists:x}));return Fc(p,n,{narration:Math.max(500,i-I),diffFiles:0,lists:x})}function El(e){return{role:"user",content:e,timestamp:0}}function Dh(e,n){return{role:"assistant",content:[{type:"text",text:e}],api:n.api,provider:n.provider,model:n.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 $$(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:El(e.input)}function su(e){let n=[];for(let i of e){let c=n.at(-1),p=i;if(c?.role==="user"&&p.role==="user"){let f=(g)=>typeof g.content==="string"?[{type:"text",text:g.content}]:g.content;n[n.length-1]={...p,content:[...f(c),{type:"text",text:`
|
|
75
|
+
|
|
76
|
+
`},...f(p)]};continue}n.push(i)}return n}function GU(e,n){if(typeof n!=="string")return n;if(e==="data"&&n.length>160)return`${n.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(n.length-96).toLocaleString()} \u5B57\u7B26]`;if(n.length>2400)return`${n.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(n.length-1600).toLocaleString()} \u5B57\u7B26]`;return n}function ke(e,n,i,c={}){let p=ha(e),f=$s(e),g=f.filter((fe)=>yl(fe,p)),x=Lh(f,p),I=[],b=c.inspect?e.flatMap(({entry:fe})=>{if(fe.type!=="extension")return[];return[{id:`extension-${fe.seq}`,label:fe.display?.title??`${fe.namespace}/${fe.kind}`,detail:fe.display?.text??`Extension ${fe.namespace}/${fe.kind} (schema ${fe.schemaVersion})`,tokens:0}]}):[],E=0;for(let fe of f){if(yl(fe,p))continue;let ie=[];for(let me of fe.records){if(fe===x&&me.entry.seq<=p)continue;let qe=me.raw.role==="user"?T$(me):me.raw;E+=U(qe),I.push(qe),ie.push(qe)}if(c.inspect&&ie.length)b.push({id:`recent-${fe.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${fe.id}`,tokens:ie.reduce((me,qe)=>me+U(qe),0),detail:JSON.stringify(ie,GU,2)})}if(!g.length&&!x)return{items:b,messages:su(I),visible:0,archived:0,open:E,tokens:E,untrimmed:E};let T=R$(g,i,!!x),{visible:k,archived:A}=T,L=T.tokens,q=[],Y="",j="";if(x){let fe=x.records.filter((me)=>me.entry.seq<=p),ie=fe.filter((me)=>me.entry.type==="user"&&!me.entry.notices&&me.raw.role==="user");if(ie.length){Y=[`<chunk-input id="${x.id}" status="partial">`,...ie.map((qe,xt)=>`<user-message sequence="${xt+1}">
|
|
77
|
+
${Ni(qe.entry.seq,Cs(qe.raw))}
|
|
78
|
+
</user-message>`),"</chunk-input>"].join(`
|
|
79
|
+
`);let me=ie.flatMap((qe)=>{let xt=qe.raw.content;return typeof xt==="string"?[]:xt.filter((Je)=>Je.type==="image")});q.push(me.length?{role:"user",content:[{type:"text",text:Y},...me],timestamp:0}:El(Y))}j=bl(fe,x,i.index,c.cwd),q.push(Dh(j,n))}let V=e.flatMap((fe)=>{let ie=fe.raw;if(fe.entry.seq>p||ie?.role!=="toolResult"||ie.toolName!=="skill")return[];return[El(ie.content.filter((me)=>me.type==="text").map((me)=>me.text).join(`
|
|
80
|
+
`))]}),X="",se=()=>{X=k$({runs:g,visible:k.map((ie)=>ie.run),archived:A,partial:!!x,tokens:L,budget:i});let fe=[El(X)];for(let{content:ie}of k){if(ie.input)fe.push($$(ie));fe.push(Dh(ie.summary,n))}return[...fe,...V,...q]},Z=(fe)=>fe.reduce((ie,me)=>ie+U(me),0),z=se(),ce=Z(z)+E,he=ce,{trim:ve}=c;while(ve&&ve.fixed+ce>ve.limit){let fe=x||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!fe.length)break;let ie=0,me=0;for(let qe of fe)if(me++,ie+=qe.content.tokens,ie>=ve.fixed+ce-ve.limit)break;A=[...A,...k.slice(0,me).map((qe)=>qe.run)],k=k.slice(me),L-=ie,z=se(),ce=Z(z)+E}return{items:c.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:U(z[0]),detail:X},...k.map(({run:fe,content:ie})=>({id:fe.id,label:`Chunk ${fe.id}`,state:"sealed",tokens:(ie.input?U($$(ie)):0)+U(Dh(ie.summary,n)),detail:[ie.input,ie.summary].filter(Boolean).join(`
|
|
81
|
+
|
|
82
|
+
`)})),...A.map((fe)=>({id:fe.id,label:`Chunk ${fe.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...x?[{id:x.id,label:`Chunk ${x.id}`,state:"folded",tokens:Z(q),detail:[Y,j].filter(Boolean).join(`
|
|
83
|
+
|
|
84
|
+
`)}]:[],...b]:[],messages:su([...z,...I]),visible:k.length,archived:A.length,open:E,tokens:ce,untrimmed:he}}function iu(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var qh=0.97,KU=0.97,P$=0.5,HU=0.05,WU=20000,zU=24000;function jc(e){return{target:WU,hard:zU,index:Math.floor(iu(e)*HU)}}function Fh(e){let n=e.usage;return n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite}class Uc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,n,i=()=>{return}){this.records=e;this.fold=n;this.cwd=i}budget(e){return jc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let n=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(n>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,n/this.lastEstimate))}previewLimit(e){return Math.floor(iu(e)*qh/this.ratio)}prepare(e,n,i,c){let p=iu(i),f=jc(i),g=e.reduce((z,ce)=>z+U(ce),0)+Li(n),x=this.records().at(-1)?.entry.seq??0,I=()=>c?[...c,...this.records().filter((z)=>z.entry.seq>x)]:this.records(),b=()=>ke(I(),i,f,{cwd:this.cwd(),trim:{fixed:g,limit:Math.floor(p*qh/this.ratio)}}),E=I().findLast((z)=>z.raw?.role==="assistant"),T=E?I().filter((z)=>z.entry.seq>E.entry.seq&&z.raw):[],k=E?.raw,A=()=>E!==void 0&&(E.entry.seq===this.reshapedAfter||I().some((z)=>z.entry.type==="compaction"&&z.entry.seq>E.entry.seq)),L=this.dueSeal(i);if(L!==void 0)this.fold(L,!1),this.reshapedAfter=E?.entry.seq??-1;let q=b(),Y=T.reduce((z,ce)=>z+U(ce.raw),0);if(this.lastEstimate===0&&E&&k&&!A()){let z=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,ce=g+q.untrimmed-U(k)-Y;if(z>0&&ce>0)this.ratio=Math.min(2,Math.max(0.5,z/ce))}let V=((z)=>{let ce=g+z.untrimmed,he=g+z.tokens;return((E&&k&&!A()&&Fh(k)>0?Fh(k)+Math.round(this.ratio*Y):void 0)??Math.round(ce*this.ratio))-Math.round((ce-he)*this.ratio)})(q);if(V>p*KU){let z=V-q.open*this.ratio,ce=Math.max(1000,Math.floor((p*P$-z-f.index)/this.ratio)),he=E?.entry.seq??-1,ve=I().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,fe=Math.max(this.lastFoldSeq,ve),me=(fe>0?I().filter((qe)=>qe.entry.seq>fe&&qe.raw?.role==="assistant").length:999)<=1;if(!me||this.consecutivePartialFolds<2){let qe=qc(I(),ce);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=me?this.consecutivePartialFolds+1:1,q=b()}}else this.consecutivePartialFolds=0;this.lastEstimate=g+q.tokens;let X=q.messages,se=g+q.tokens;if(Math.round(se*this.ratio)>p)X=VU(X,Math.floor((p-g)/this.ratio)),se=g+X.reduce((z,ce)=>z+U(ce),0);return this.lastEstimate=se,{messages:su([...e,...X]),estimate:se}}settle(e){let n=this.dueSeal(e);if(n===void 0)return;this.fold(n,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let n=this.records();if(xl(n)===void 0){let i=n.findLast((x)=>x.raw?.role==="assistant"),c=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||n.some((x)=>x.entry.type==="compaction"&&x.entry.seq>i.entry.seq)),g=(i?n.filter((x)=>x.entry.seq>i.entry.seq&&x.raw):[]).reduce((x,I)=>x+U(I.raw),0);if(p||!c||Fh(c)+g<Math.floor(iu(e)*qh))return}return ou(n)}recover(e){let n=iu(e),i=jc(e),c=ke(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((n*P$-(n-c.open*this.ratio)-i.index)/this.ratio),f=qc(this.records(),p);if(f===void 0)return!1;return this.fold(f,!0),this.reshapedAfter=this.records().findLast((g)=>g.raw?.role==="assistant")?.entry.seq??-1,!0}}function VU(e,n){let i=e.reduce((p,f)=>p+U(f),0);if(i<=n)return e;let c=[];for(let p of e){let f=p;if(f.role!=="toolResult"||i<=n){c.push(p);continue}let g=U(p);if(g<=1500){c.push(p);continue}let x=Math.max(500,Math.floor(g/2)),I=f.content.map((T)=>{if(T.type!=="text")return T;return{...T,text:bo(T.text,x)}}),b={...f,content:I},E=U(b);i-=g-E,c.push(b)}return c}var JU=2000;function au(e,n){let i=[];for(let c of n.replace(/\r\n/g,`
|
|
85
|
+
`).split(`
|
|
86
|
+
`))for(let p=0;p<Math.max(c.length,1);){let f=Math.min(c.length,p+JU);if(f<c.length&&/[\uD800-\uDBFF]/.test(c.charAt(f-1)))f--;i.push({source:e,text:c.slice(p,f)}),p=f>p?f:p+1}return i}function uu(e){let n=[],i=us(e.records),c=new Map(i.map((f)=>[f.call,f])),p=new Set(i.flatMap((f)=>f.result?[f.result]:[]));for(let f of e.records){let g=f.raw;if(g.role==="user")n.push(...au(f.entry.type==="user"&&f.entry.notices?"NOTICE":"USER",Cs(g)));else if(g.role==="assistant"){for(let x of g.content)if(x.type==="text"&&x.text.trim())n.push(...au("ASSISTANT",x.text));else if(x.type==="toolCall"){let I=c.get(x);if(I)for(let b of hl(I))n.push(...au(b.source,b.text))}}else if(g.role==="toolResult"&&!p.has(g))n.push(...au(g.isError?"TOOL_ERROR":"TOOL_OUTPUT",ru(g)))}return n.map((f,g)=>({chunk:e.id,line:g,...f}))}function Bc(e,n){let i=e.find((c)=>c.entry.seq===n);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return au("USER",Cs(i.raw)).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Gc(e,n){let i=e.find((c)=>c.entry.seq===n)?.entry;if(i?.type!=="extension"||!i.display)return;return au("EXTENSION",i.display.text).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Kc(e,n=""){return e.map((i,c)=>{let p=e[c-1],f=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${n}${f?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
|
|
87
|
+
`)}import{join as Rg}from"path";import{existsSync as J$}from"fs";import{realpath as Q$}from"fs/promises";import{dirname as X$,isAbsolute as lB,join as Y$,relative as dB,resolve as Wh,sep as fB}from"path";import{existsSync as QU,watch as XU}from"fs";import{readdir as YU,stat as ZU}from"fs/promises";import{basename as jh,dirname as eB,join as M$,resolve as tB}from"path";class Uh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,n,i,c=150){this.host=e;this.slots=n;this.watching=i;this.debounceMs=c}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,n=[]){let i=[],c=[];for(let x of[...new Set(e)]){let I;try{I=await YU(x)}catch(b){if(b instanceof Error&&"code"in b&&b.code==="ENOENT")continue;throw b}for(let b of I.sort()){let E=M$(x,b),T=(await ZU(E)).isDirectory()?M$(E,"index.ts"):E;if(!T.endsWith(".ts")||T.endsWith(".d.ts"))continue;try{c.push({definition:await this.read(T),path:T})}catch(k){let A=jh(T)==="index.ts"?jh(eB(T)):jh(T,".ts");if(this.slots.has(A))throw Error(`Duplicate plugin: ${A}`);let L={id:A,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${A}; repair the file and reload`)}};i.push({definition:L,path:T}),this.slots.set(A,{definition:L,path:T,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let p=n.filter((x)=>![...c,...i].some((I)=>I.definition.id===x.definition.id)),f=[...p,...c],g=this.order(f.map(({definition:x})=>x));for(let x of g){let I=f.find((E)=>E.definition===x)?.path,b=p.some((E)=>E.definition===x);try{await this.host.install(x,I,b)}catch(E){this.slots.set(x.id,{definition:x,path:I,builtin:b,enabled:!0,error:E instanceof Error?E.message:String(E)})}}if(this.watching())for(let x of[...f,...i]){if(!QU(x.path))continue;let I=XU(x.path,()=>{let b=x.definition.id,E=this.debounceTimers.get(b);if(E)clearTimeout(E);let T=setTimeout(()=>{this.debounceTimers.delete(b),this.host.reload(b).catch((k)=>{let A=this.slots.get(b);if(A)A.error=k instanceof Error?k.message:String(k)})},this.debounceMs);T.unref?.(),this.debounceTimers.set(b,T)});I.on("error",(b)=>{let E=this.slots.get(x.definition.id);if(E)E.error=b.message,this.host.changed()}),this.watchers.push(I)}}order(e,n=!1){let i=new Map;for(let x of e){if(this.validate(x),i.has(x.id)||!n&&this.slots.has(x.id))throw Error(`Duplicate plugin: ${x.id}`);i.set(x.id,x)}let c=[],p=new Set,f=new Set,g=(x)=>{if(f.has(x.id))return;if(p.has(x.id))throw Error(`Plugin dependency cycle: ${x.id}`);p.add(x.id);for(let I of x.deps??[]){let b=i.get(I);if(b)g(b);else if(!this.slots.has(I))throw Error(`Missing plugin dependency: ${I}`)}p.delete(x.id),f.add(x.id),c.push(x)};for(let x of e)g(x);return c}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((n)=>typeof n!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let n=await import(`${tB(e)}?v=${++this.revision}`);if(!n.default)throw Error("Plugin module must export a default definition");return this.validate(n.default),n.default}}async function v$(e,n,i=!1){if(!Number.isSafeInteger(n)||n<1||n>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let c=new AbortController,p;try{return await Promise.race([i?Promise.resolve(e(c.signal)):Promise.resolve().then(()=>e(c.signal)),new Promise((f,g)=>{p=setTimeout(()=>{c.abort(),g(Error(`Plugin callback timed out after ${n}ms`))},n)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as rB}from"async_hooks";import{isDeepStrictEqual as O$}from"util";var ga=new rB;function Ps(){let e=ga.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function cu(e){let n=structuredClone(e),i=(c)=>{if(!c||typeof c!=="object"||Object.isFrozen(c))return;Object.freeze(c);for(let p of Object.values(c))i(p)};return i(n),n}function _$(e,n){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Entry replacement must be a body");for(let I of["seq","time","session_id","raw"])if(I in n)throw Error(`Entry replacement contains protected field: ${I}`);let i=JSON.parse(JSON.stringify(n,(I,b)=>{if(typeof b==="function"||typeof b==="symbol"||typeof b==="number"&&!Number.isFinite(b))throw Error("Entry replacement must contain JSON values");return b}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let c=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 f={...e};for(let I of new Set([...Object.keys(e),...Object.keys(c)])){if(!p.includes(I)&&!O$(f[I],c[I]))throw Error(`Entry replacement changed protected field: ${I}`);if(["seq","time","session_id","raw"].includes(I))throw Error(`Entry replacement contains protected field: ${I}`)}let g=(I)=>I===void 0||typeof I==="string",x=!0;switch(e.type){case"user":x=typeof c.text==="string"&&(c.attachments===void 0||Array.isArray(c.attachments)&&c.attachments.every((I)=>I&&typeof I.name==="string"&&typeof I.mimeType==="string"&&Yc.includes(I.kind)&&typeof I.data==="string"));break;case"assistant":x=g(c.error)&&Array.isArray(c.parts)&&c.parts.every((I)=>I&&(["text","thinking"].includes(I.type)&&typeof I.text==="string"||I.type==="tool_call"&&typeof I.id==="string"&&typeof I.name==="string"&&("input"in I)));break;case"tool_result":x=typeof c.output==="string"&&(c.images===void 0||Array.isArray(c.images)&&c.images.every((I)=>I&&typeof I.mimeType==="string"&&typeof I.data==="string"));break;case"extension":{let I=c.display;x="payload"in c&&(I===void 0||I!==null&&typeof I==="object"&&("text"in I)&&typeof I.text==="string"&&(!("title"in I)||g(I.title)));break}case"notice_pending":{let b=["text"],E=f.notice,T=c.notice;if(x=!!T&&typeof T==="object"&&!Array.isArray(T),!x)break;let k=T;for(let A of new Set([...Object.keys(E),...Object.keys(k)]))if(b.includes(A)){if(typeof k[A]!=="string")x=!1}else if(!O$(E[A],k[A]))x=!1;break}case"run":x=g(c.error);break;case"compaction":break}if(!x)throw Error("Invalid entry replacement content");return i}function L$(e,n,i,c,p,f){let g=c;for(let x of i.generations)for(let I of x.hooks.get("entry.before_append")??[]){if(x.disabled)break;let b={phase:"before",violated:!1};try{let E=ga.run(b,()=>{let T=cu(g),k=performance.now(),A=I(T,{sessionID:p,seq:f});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 L=A===void 0?void 0:_$(g,A);if(b.violated)throw Error("entry.before_append attempted a database write");if(performance.now()-k>e)throw Error("entry.before_append exceeded budget");return L});if(E&&JSON.stringify(E)!==JSON.stringify(g))g=E;x.beforeFailures=0,x.failures=0}catch(E){x.failures=x.beforeFailures++,n(x,E)}}return g}function nB(e,n){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return n;if(e==="entry.after_append")return cu(n);return structuredClone(n)}async function N$(e,n,i,c,p,f,g,x,I="end"){let b=f;for(let E of c){if(E.disabled)continue;let T=E.hooks.get(p)??[];for(let k of T){if(E.disabled)break;let A=E.hookOptions.get(k);if(p==="prompt.fragments"&&(A?.promptPosition??"end")!==I)continue;let L=p==="prompt.fragments"?JSON.stringify([g?.id,b]):void 0,q=L===void 0?void 0:E.promptCache.get(k)?.get(L);try{let Y=nB(p,b),j=A?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:g,connection:x}):j,X=await n((se)=>k(Y,{runtime:e.runtime,session:g,connection:x,signal:se}),V);if(L!==void 0){let se=X===void 0?b:X;if(!Array.isArray(se)||se.some((z)=>typeof z!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(se))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let Z=E.promptCache.get(k)??new Map;Z.set(L,[...se]),E.promptCache.set(k,Z)}if(E.failures=0,X!==void 0&&p!=="entry.after_append")b=X}catch(Y){if(q)b=structuredClone(q);if(i(E,Y),A?.errorMode==="propagate")throw Y}}}return b}class Hc{host;generations;released=!1;constructor(e,n){this.host=e;this.generations=n}async invoke(e,n,i,c,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,n,i,c,p)}has(e,n){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((c)=>n===void 0||(i.hookOptions.get(c)?.promptPosition??"end")===n))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((n)=>({...n,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${n.name}`);return n.execute(...i)}})))}waiting(e){return this.generations.some((n)=>!n.disabled&&n.gates.some((i)=>i(e)))}resolveHistory(e,n){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let c of i.historyResolvers){let p=c(e,n);if(p)return p}}}policy(e){return this.generations.findLast((n)=>!n.disabled&&n.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 oB}from"fs";import{dirname as sB,resolve as D$}from"path";var Bh=new WeakMap;function q$(e){return[...e].map((n)=>{let i=Boolean(n.path&&(Boolean(n.definition.webEntry)||oB(D$(sB(D$(n.path)),"web.tsx"))));if(n.current&&!Bh.has(n.current))Bh.set(n.current,crypto.randomUUID());return{id:n.definition.id,description:n.definition.description,builtin:n.builtin??!1,web:n.enabled&&!n.current?.disabled?n.current?.web??[]:[],webBundle:i,webRevision:n.current?Bh.get(n.current):void 0,version:n.definition.version,deps:n.definition.deps??[],status:!n.enabled?"disabled":n.current?.disabled||!n.current?"error":"enabled",error:n.error??n.current?.error,registrations:n.current?[...[...n.current.hooks.keys()].map((c)=>({kind:"hook",name:c})),...n.current.tools.map((c)=>({kind:"tool",name:c.name})),...n.current.routes.map((c)=>({kind:"route",method:c.method,path:c.path})),...n.current.websockets.map((c)=>({kind:"websocket",path:c.path})),...n.current.commands.map((c)=>({kind:"command",id:c.id})),...n.current.web.map((c)=>({kind:"web",id:c.id})),...[...n.current.policies.keys()].map((c)=>({kind:"policy",id:c})),...n.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class Gh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,n,i){this.host=e;this.deadline=n;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,n,i){let c=this.host.pin(),p=(async()=>{try{let f=[];for(let g of c.generations){if(g.disabled)continue;for(let x of g.hooks.get(e)??[]){let I=g.hookOptions.get(x)?.timeoutMs,b=typeof I==="function"?I({runtime:this.host.runtime,session:n,connection:i}):I;f.push(this.deadline((E)=>x(n,{runtime:this.host.runtime,session:n,connection:i,signal:E}),b,!0).catch((E)=>this.fail(g,E)))}}await Promise.all(f)}finally{await c.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,n,i){let c=i===void 0?void 0:cu(i),p=(this.entryQueues.get(n)??Promise.resolve()).then(async()=>{try{if(c)await ga.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",c,this.host.runtime.get(n)))}finally{await e.release()}});this.entryQueues.set(n,p),this.pending.add(p);let f=()=>{if(this.pending.delete(p),this.entryQueues.get(n)===p)this.entryQueues.delete(n)};p.then(f,f)}}function F$(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 iB(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 aB(e,n){let i=n.sessionID?e.get(n.sessionID):void 0;if(n.sessionID&&!i)throw Error("Completion session not found");let c=n.model??i?.model??e.options.defaultModel;if(typeof c!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=xn(e.options.models,c);if(!p&&n.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(n.model===void 0||!p){let f=(await e.models()).models.filter((x)=>x.available===!0),g=p?tt(p):c;if(!f.some((x)=>x.id===g)){let x=f[0];if(x)p=xn(e.options.models,x.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function j$(e,n){iB(n);let i=await aB(e,n),c=n.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(c)||c<=0||c>i.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(n.signal?.aborted)throw Error("Completion cancelled");let p="",f=!1;try{let g=[...n.system?[{role:"system",content:n.system,timestamp:Date.now()}]:[],{role:"user",content:n.prompt,timestamp:Date.now()}],x=e.options.models.streamSimple(i,{messages:g},{maxTokens:c,signal:n.signal});for await(let I of x){if(n.signal?.aborted)throw Error("cancelled");if(I.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${F$(I.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(I.type==="text_delta")p+=I.delta;if(I.type==="done"){if(I.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(I.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${I.reason}\uFF09`);f=!0}}}catch(g){if(n.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${F$(g instanceof Error?g.message:String(g))}`)}if(n.signal?.aborted)throw Error("Completion cancelled");if(!f)throw Error("Model completion ended without a stop response; retry");return{text:p,model:tt(i)}}var uB=["active","archived","all"];function U$(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function cB(e){let{projectID:n,children:i,archive:c,since:p}=e;if(n!==void 0&&n!==null&&typeof n!=="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(c!==void 0&&!uB.includes(c))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 mB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function B$(e){function n(i,c={}){let{types:p,bodies:f}=c;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let g=U$(c.limit),x=c.after??0;if(!Number.isSafeInteger(x)||x<0)throw Error("sessions after must be a non-negative integer");let I=(e.get(i)?.entries(x)??[]).filter((b)=>p===void 0||p.includes(b.type)).slice(0,g);return structuredClone(f===!1?I.map(mB):I)}return{list(i={}){cB(i);let c=i.limit===void 0?void 0:U$(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((f)=>i.projectID===void 0||f.projectID===i.projectID).filter((f)=>i.since===void 0||f.created>=i.since);return structuredClone(c===void 0?p:p.slice(0,c))},get(i){return structuredClone(e.get(i)?.info())},entries:n}}async function G$(e,n,i,c,p,f){let g={definition:n,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},x=e.runtime.store.db,I=new Map,b=!1,E=!0,T=()=>{if(!E||g.disposed)throw Error("Plugin registration scope is closed")},k=(j,V)=>{if(T(),!b){I.set(j,V);return}if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,j);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,j,V)},A={get:(j)=>{T();let V=I.has(j)?I.get(j):x.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(n.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let X=JSON.stringify(V);if(X===void 0)throw Error("Plugin KV values must be JSON serializable");k(j,X)},delete:(j)=>k(j,null)},L=()=>{if(T(),b)throw Error("Register resources during setup only")},q=[...n.migrations??[]].sort((j,V)=>j.version-V.version),Y=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||Y.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(Y.add(j.version),x.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(n.id,j.version))continue;x.transaction(()=>{if(j.sql!==void 0)x.run(j.sql);else j.up({...A,db:x});for(let[V,X]of I)if(X===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,V);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,V,X);x.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(n.id,j.version)})(),I.clear()}return await c(async()=>n.setup({runtime:e.runtime,sessions:B$(e.runtime),complete:(j)=>j$(e.runtime,j),kv:A,database:x,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{L(),g.gates.push(j)},registerNoticeSource:(j,V)=>{if(L(),!j||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");g.noticeSources.set(j,{...V})},provide:(j,V)=>{if(L(),j.pluginID!==n.id)throw Error("Service key must belong to the providing plugin");if(g.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);g.services.set(j.name,V)},on:(j,V,X)=>{if(L(),X?.promptPosition&&j!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let se=g.hooks.get(j)??[];if(se.push(V),g.hooks.set(j,se),X)g.hookOptions.set(V,X)},registerHistoryResolver:(j)=>{L(),g.historyResolvers.push(j)},registerTool:(j,V)=>{if(L(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||pB(e,p,n.id).has(j.name.toLowerCase())||g.tools.some((se)=>se.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let X=i?"always":"defer";if(typeof V?.defer==="boolean")X=V.defer?"defer":"always";else if(V?.defer!==void 0)X=V.defer;g.tools.push({...j,defer:X,source:`plugin:${n.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(L(),!(j.path.startsWith(`/api/plugins/${n.id}/`)||(n.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(g.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");g.routes.push(j)},registerWebSocket:(j)=>{if(L(),!j.path.startsWith(`/api/plugins/${n.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(g.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");g.websockets.push(j)},registerCommand:(j)=>{L(),g.commands.push(j)},registerWebContribution:(j)=>{L(),g.web.push(j)},registerToolPolicy:(j,V)=>{L(),g.policies.set(j,V)},appendExtension:(j,V)=>{if(Ps(),T(),!b)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{L(),g.deactivators.push(j)},onDispose:(j)=>{L(),g.disposers.push(j)}})),x.transaction(()=>{for(let[j,V]of I)if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,j);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,j,V)})(),I.clear(),b=!0,g}catch(j){throw E=!1,await f(g),j}}function pB(e,n,i){let c=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,f]of n){if(p===i)continue;for(let g of f.current?.tools??[])c.add(g.name.toLowerCase())}return c}class Kh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let n of e.connections)n.close(1012,"Plugin changed");this.retired.add(e);for(let n of e.deactivators.splice(0).reverse())try{await this.deadline(n)}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 n of e.disposers.reverse())try{await this.deadline(n)}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 K$(e,n,i,c){for(let p of n){let f=p.current;if(!f||f.disabled||f.retired)continue;let g=f.websockets.find((x)=>x.path===c);if(!g)continue;return{connect:(x)=>{let I=!1;f.references++,f.connections.add(x);let b={send:(T)=>{if(I||f.retired||f.disabled)return;x.send(T)},close:(T,k)=>x.close(T,k)},E=async(T)=>{if(I||f.retired||f.disabled){x.close(1012,"Plugin unavailable");return}try{await i(T),f.failures=0}catch(k){if(f.failures++,f.error=k instanceof Error?k.message:String(k),x.close(1011,"Plugin callback failed"),f.failures>=e.failureThreshold){f.disabled=!0;for(let A of f.connections)A.close(1011,"Plugin disabled")}}};return{open:()=>E(()=>g.open?.(b)),message:(T)=>E(()=>g.message(b,T)),close:async()=>{if(I)return;I=!0,f.connections.delete(x);try{await i(()=>g.close?.(b))}catch(T){f.error=T instanceof Error?T.message:String(T)}finally{f.references--,await e.collect(f)}}}}}}return}function Hh(e,n){let i=e.split("/"),c=new URL(n.url).pathname.split("/");if(i.length!==c.length)return;let p={};return i.every((g,x)=>{let I=c[x];if(I===void 0)return!1;if(!g.startsWith(":"))return I===g;try{p[g.slice(1)]=decodeURIComponent(I)}catch{return!1}return I.length>0})?p:void 0}async function H$(e,n,i,c,p){let f=e.pin();try{let g=f.generations.find((x)=>x.definition.id===i)?.commands.find((x)=>x.id===c);if(!g)throw new y("Plugin command is unavailable");return await n(()=>g.execute(p))}finally{await f.release()}}function W$(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.method===n.method&&Hh(p.path,n)!==void 0))}finally{i.release()}}function z$(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.public===!0&&p.method===n.method&&Hh(p.path,n)!==void 0))}finally{i.release()}}async function V$(e,n,i){let c=e.pin(),p=!0;try{for(let f of c.generations)for(let g of f.routes){if(g.method!==i.method)continue;let x=Hh(g.path,i);if(x){let I=await n(()=>g.handler(i,x),g.timeoutMs);if(!I)return;if(I.body&&I.body instanceof ReadableStream){p=!1;let b=!1,E=()=>{if(b)return;b=!0,c.release()},T=I.body.getReader(),k=new ReadableStream({async pull(A){try{let{done:L,value:q}=await T.read();if(L)A.close(),E();else A.enqueue(q)}catch(L){A.error(L),E()}},async cancel(A){try{await T.cancel(A)}finally{E()}}});return new Response(k,{status:I.status,statusText:I.statusText,headers:I.headers})}return I}}return}finally{if(p)await c.release()}}class zh{runtime;options;slots=new Map;retirement=new Kh(this.deadline.bind(this));observers=new Gh(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,n={}){this.runtime=e;this.options=n;if(n.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(n.beforeAppendBudgetMs)||n.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new Uh(this,this.slots,()=>n.watch===!0,n.watchDebounceMs??150),this.timeoutMs=n.timeoutMs??5000,this.failureThreshold=n.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 n=this.slots.get(e.pluginID);if(!n?.enabled||!n.current||n.current.disabled||n.current.retired)throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=n.current.services.get(e.name);if(!e.validate(i))throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((n)=>n.enabled&&n.current&&!n.current.disabled&&n.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 n=this.pin();try{await n.invoke("project.delete",e)}finally{await n.release()}}exclusive(e){let n=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=n.then(()=>{},()=>{}),n}discover(e,n=[]){for(let i of e)this.directories.add(Wh(i));return this.catalog.discover(e,n).finally(()=>this.changed())}async pluginPath(e){let n=await Q$(e),i=[...this.directories,Y$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((c)=>Y$(c.directory,".basalt","plugins"))];for(let c of i){if(!J$(c))continue;let p=dB(await Q$(c),n);if(p&&p!==".."&&!p.startsWith(`..${fB}`)&&!lB(p)){if(!n.endsWith(".ts")||n.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return n}}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 n=await this.pluginPath(e),i=await this.checkEntry(n);if(!i.ok)throw new ut(i.errors);let c=await this.catalog.read(n);return await this.installDefinition(c,n,!1),c.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let n=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:n.success,errors:n.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,n=!1){return this.catalog.order(e,n)}install(e,n,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,n,i)})}async installDefinition(e,n,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let c=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:n,builtin:i,enabled:c?.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 n=this.require(e);if(!n.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!n.builtin){let x=await this.checkEntry(n.path);if(!x.ok)throw new ut(x.errors)}let i=n.builtin&&!J$(n.path)?n.definition:await this.catalog.read(n.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!n.enabled)throw Error("Enable the plugin before reloading");let c=this.order([...this.slots.values()].map((x)=>x.definition.id===e?i:x.definition),!0),p=await this.stage(i),f=n.current;n.definition=i,n.current=p,n.error=void 0,n.discoveryFailed=!1;let g=new Map(this.slots);this.slots.clear();for(let x of c){let I=g.get(x.id);if(I)this.slots.set(x.id,I)}if(f)await this.retirement.retire(f)}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,n){return this.exclusive(async()=>{let i=this.require(e);if(n===i.enabled&&(!n||i.current&&!i.current.disabled))return;if(!n){for(let g of this.slots.values())if(g.enabled&&g.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${g.definition.id}`)}let c=n&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.definition;if(c.id!==e)throw Error("Enable cannot change plugin id");let p=n?await this.stage(c):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(n));let f=i.current;if(i.definition=c,n)i.discoveryFailed=!1;if(i.enabled=n,i.current=p,i.error=void 0,f)await this.retirement.retire(f)})}require(e){if(this.closed)throw Error("Plugin host is closed");let n=this.slots.get(e);if(!n)throw Error(`Plugin not found: ${e}`);return n}async stage(e,n=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 G$(this,e,n,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,n,i){this.observers.notify(e,n,i)}resolveHistory(e,n){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let c of i.current.historyResolvers){let p=c(e,n);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((n)=>n.enabled&&n.current&&!n.current.disabled&&n.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((n)=>n.enabled&&n.current&&!n.current.disabled?[n.current]:[]);for(let n of e)n.references++;return new Hc(this,e)}async invoke(e,n,i,c,p,f="end"){return N$(this,this.deadline.bind(this),this.fail.bind(this),e,n,i,c,p,f)}pinEntry(e){if(ga.getStore()?.phase==="after")return;let n;for(let i of this.slots.values()){let c=i.current;if(!i.enabled||!c||c.disabled||e.type==="extension"&&e.namespace===c.definition.id)continue;if(!c.hooks.has("entry.before_append")&&!c.hooks.has("entry.after_append"))continue;n??=[],n.push(c),c.references++}if(!n)return;return new Hc(this,n)}beforeEntry(e,n,i,c){return L$(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,n,i,c)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,n){if(e.failures++,e.error=n instanceof Error?n.message:String(n),e.failures>=this.failureThreshold){e.disabled=!0;for(let i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,n,i){this.observers.finishEntry(e,n,i)}deadline(e,n=this.timeoutMs,i=!1){return v$(e,n,i)}appendExtension(e,n){return Ps(),new Promise((i)=>{let c=this.runtime.get(e);if(!c)throw Error("Extension target session does not exist");if(!n.namespace||!n.kind||!Number.isSafeInteger(n.schemaVersion)||n.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...n});c.refreshEntries(),i(p)})}list(){return q$(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let n=this.require(e),i=await this.webBuilder.entry(n.path,n.definition.webEntry);if(i&&n.path)await this.webBuilder.build(i,X$(Wh(n.path)));return{ok:!0}}catch(n){if(n instanceof pl)return{ok:!1,errors:n.errors};return{ok:!1,errors:[{file:null,line:null,message:n instanceof Error?n.message:String(n)}]}}}async webBundle(e){let n=this.slots.get(e);if(!n?.enabled||!n.path||n.current?.disabled)return;let i=await this.webBuilder.entry(n.path,n.definition.webEntry);if(!i)return;return this.webBuilder.build(i,X$(Wh(n.path)))}async webCSS(e){await this.webBundle(e);let n=this.slots.get(e);if(!n?.enabled||!n.path||n.current?.disabled)return;let i=await this.webBuilder.entry(n.path,n.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,n,i){return H$(this,this.deadline.bind(this),e,n,i)}hasRoute(e){return W$(this,e)}isPublicRoute(e){return z$(this,e)}route(e){return V$(this,this.deadline.bind(this),e)}websocket(e){return K$(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 Z$}from"fs";import{join as hB}from"path";var gB=500,yB=1000,xB=3600000,IB=5000,bB=2000,EB=3,SB=1073741824;class Vh{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=hB(e.dataDir,Wo),this.features={...$o(),...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 n=this.engineStatus,i=n?.backfill;if(!n||!i)return{...e,state:"backfilling"};if(i.state==="done"){let c=n.entries;return{...e,state:"ready",lag:n.lag,total:c,indexed:Math.max(0,c-n.lag)}}return{...e,lag:n.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...n.etaSec!==void 0?{etaSec:n.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let n of["","-wal"])try{e+=Z$(this.indexPath+n).size}catch{}return e}budget(){let e=0;try{e=Z$(this.options.store.path).size}catch{}return Math.max(SB,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(),Qn(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((n)=>{this.flushes.set(e,()=>n(this.status())),this.post({type:"flush",id:e})})}pause(e){let n=this.worker;if(!n)return e();Atomics.store(this.flags,$e,1),n.postMessage({type:"pause"}),Atomics.wait(this.flags,Tt,0,IB);try{return e()}finally{Atomics.store(this.flags,$e,0),Atomics.notify(this.flags,$e)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=qo(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,$e,0),Atomics.store(this.flags,Tt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(n)=>this.receive(e,n.data),e.onerror=(n)=>this.crashed(e,n.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,n){if(e!==this.worker){if(n.type==="stopped")this.stopped?.();return}switch(n.type){case"status":this.update(n.status);break;case"flushed":{this.update(n.status),this.flushes.get(n.id)?.(),this.flushes.delete(n.id);break}case"error":if(n.fatal)this.crashed(e,n.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,n,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<EB&&this.usable)this.restarts++,this.start();else this.failure=n,console.error("search index unavailable:",n),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,$e,0),Atomics.notify(this.flags,$e);let n=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([n,Bun.sleep(bB)]),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,gB-(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)Qn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),xB),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 n=Math.max(0,yB-(performance.now()-this.lastPush)),i=()=>{if(this.statusTimer=void 0,this.closed)return;let c=this.status(),p=JSON.stringify({...c,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(c)};if(n===0)i();else this.statusTimer=setTimeout(i,n),this.statusTimer.unref?.()}}import{existsSync as lu,mkdirSync as CB,readdirSync as aP,readFileSync as nP,realpathSync as Jh,statSync as Al,writeFileSync as Qh}from"fs";import{dirname as kl,isAbsolute as Xh,relative as uP,resolve as $B}from"path";import{existsSync as Wc}from"fs";import{dirname as AB,join as pu}from"path";import{mkdirSync as wB,writeFileSync as TB}from"fs";import{tmpdir as RB}from"os";import{join as eP}from"path";var Sl=2000,Pe=30000;function u(e){return{content:[{type:"text",text:e}],details:void 0}}function mu(e,n){return e.map((i,c)=>{let p=i.length>Sl?`${i.slice(0,Sl)}\u2026 [line truncated]`:i;return`${String(n+c).padStart(6)} ${p}`}).join(`
|
|
88
|
+
`)}function je(e,n){if(e.length<=n)return e;let i=Math.floor(n*0.4),c=n-i,p=e.length-i-c,f=e.slice(i,e.length-c).split(`
|
|
89
|
+
`).length-1;return`${e.slice(0,i)}
|
|
90
|
+
|
|
91
|
+
\u2026 [${p} characters, ~${f} lines omitted] \u2026
|
|
92
|
+
|
|
93
|
+
${e.slice(-c)}`}var kB=0;function rt(e,n){if(e.length<=n)return e;let i=je(e,n);try{let c=eP(RB(),"basalt-output");wB(c,{recursive:!0});let p=eP(c,`${process.pid}-${Date.now().toString(36)}-${kB++}.txt`);return TB(p,e),`${i}
|
|
94
|
+
[Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return i}}var tP=120000,rP=600000,ya;function wl(){if(ya!==void 0)return ya||void 0;let n=(process.env.PATH??"").split(";").map((c)=>c.trim()).filter(Boolean);for(let c of n){let p=pu(c,"bash.exe");if(Wc(p))return ya=p,p}for(let c of n){let p=pu(c,"git.exe");if(Wc(p)){let f=AB(c),g=pu(f,"bin","bash.exe");if(Wc(g))return ya=g,g;let x=pu(f,"usr","bin","bash.exe");if(Wc(x))return ya=x,x}}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?pu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?pu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let c of i)if(Wc(c))return ya=c,c;ya="";return}class Tl{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let n=new Uint8Array(this.gbkPending.length+e.length);n.set(this.gbkPending),n.set(e,this.gbkPending.length);let i=0;while(i<n.length){if(n[i]<128){i+=1;continue}let p=n[i+1];if(p===void 0)break;let f=p>=48&&p<=57?4:2;if(i+f>n.length)break;i+=f}return this.gbkPending=n.slice(i),this.gbk.decode(n.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});if(this.isGbk)return this.decodeGbk(e);try{return this.utf8.decode(e,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(e)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(!this.isGbk)return this.utf8.decode();let e=this.gbkPending;return this.gbkPending=new Uint8Array(0),e.length>0?this.gbk.decode(e):""}}function xa(e,n){let i=process.platform==="win32",c=n??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(c==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(c==="bash")return{argv:[wl()??"bash","-c",e],shellName:"bash",isWindows:!0};if(c==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=wl();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 er(e,n){let i=await ze(e,n.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:c,isWindows:p}=xa(e,n.shell),f=Bun.spawn(c,{cwd:n.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,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"}:{},...n.extraPath?{[Object.keys(process.env).find((se)=>se.toLowerCase()==="path")??"PATH"]:n.extraPath}:{}}}),g=!1,x=()=>{try{if(p)f.kill();else process.kill(-f.pid,"SIGKILL")}catch{}},I=setTimeout(()=>{g=!0,x()},n.timeout);n.signal?.addEventListener("abort",x,{once:!0});let b=Pe*2,E="",T="",k=0,A=0,L="",q=(se=!1)=>{let Z=k-E.length-T.length,z=Z>0?`${E}
|
|
95
|
+
\u2026 [${Z} characters omitted] \u2026
|
|
96
|
+
${T}`:E+T;if(!se)return je(z,Pe);return rt(L.length===k?L:z,Pe)},Y=()=>{let se=new Tl;return async(Z)=>{for await(let ce of Z){let he=se.decode(ce);if(k+=he.length,L.length<4000000)L+=he;if(E.length<b)E+=he;else T=(T+he).slice(-b);if(n.onOutput){let ve=performance.now();if(ve-A>=80)A=ve,n.onOutput(q())}}let z=se.flush();if(z){if(k+=z.length,L.length<4000000)L+=z;if(E.length<b)E+=z;else T=(T+z).slice(-b)}}},j=Promise.all([Y()(f.stdout),Y()(f.stderr)]),V=await f.exited;if(clearTimeout(I),n.signal?.removeEventListener("abort",x),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))T+=`
|
|
97
|
+
[background processes are still running; their later output is not captured]`;return{output:q(!0),code:g?null:V,timedOut:g}}class Yh{seen=new Map;mark(e,n=Al(e).mtimeMs){this.seen.set(e,n)}check(e){let n=this.seen.get(e);if(n===void 0)return"unread";return Al(e).mtimeMs!==n?"changed":void 0}}var oP=2000,PB=500,MB=10485760,Rl=20,vB=6,OB=40000,_B=80000;function LB(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 cP(e,n,i=[],c){let p=(L)=>Xh(L)?L:$B(e,L),f=(L)=>{let q=uP(e,L);return q&&!q.startsWith("..")&&!Xh(q)?q:L},g=(L)=>{let q=L;while(!lu(q)&&kl(q)!==q)q=kl(q);let Y=Jh(q);if(i.some((j)=>lu(j)&&iP(Jh(j),Y))&&!iP(Jh(e),Y))throw Error("External directories are read-only")},x=(L,q,Y)=>{let j=p(L);if(!lu(j))throw Error(`No such file or directory: ${j}${FB(j)}`);let V=Al(j);if(V.isDirectory()){let me=aP(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),qe=me.slice(0,PB),xt=me.length-qe.length;return u(`${qe.join(`
|
|
98
|
+
`)}${xt>0?`
|
|
99
|
+
\u2026 and ${xt} more entries`:""}`||"(empty directory)").content}let X=nP(j),se=LB(X);if(se){if(V.size>MB)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return n.mark(j),[{type:"text",text:`Read image ${f(j)} (${se}, ${V.size} bytes)`},{type:"image",data:X.toString("base64"),mimeType:se}]}if(X.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);n.mark(j);let Z=X.toString("utf8");if(!Z)return u("(empty file)").content;let z=Z.replace(/\r?\n$/,"").split(/\r?\n/),ce=(q??1)-1;if(ce>=z.length)throw Error(`offset ${q} is past the end of the file (${z.length} lines)`);let he=Math.min(z.length,ce+(Y??oP)),ve=0,fe=ce;while(fe<he){let me=z[fe]?.length??0;if(fe>ce&&ve+me>OB)break;ve+=me,fe++}let ie=mu(z.slice(ce,fe),ce+1);if(fe<he)ie+=`
|
|
100
|
+
|
|
101
|
+
(Showing lines ${ce+1}-${fe} of ${z.length} (truncated at line ${fe} due to safety budget). Use offset/limit to read specific windows.)`;else if(ce>0||fe<z.length)ie+=`
|
|
102
|
+
|
|
103
|
+
(Showing lines ${ce+1}-${fe} of ${z.length}. Use offset/limit to read other parts.)`;return u(ie).content},I=v({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.
|
|
104
|
+
- path may be absolute or relative to the working directory.
|
|
105
|
+
- By default reads up to ${oP} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
|
|
106
|
+
- Lines longer than ${Sl} characters are truncated.
|
|
107
|
+
- Reading a directory lists its entries (directories end with /).
|
|
108
|
+
- Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
|
|
109
|
+
- To read several files at once, give paths instead of path (up to ${Rl}, 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.
|
|
110
|
+
- Always read a file before editing or overwriting it.`,parameters:s({path:o(l({description:"File or directory path"})),offset:o(w({minimum:1,description:"1-based line number to start from"})),limit:o(w({minimum:1,description:"Maximum number of lines to return"})),paths:o(W(s({path:l({description:"File or directory path"}),offset:o(w({minimum:1,description:"1-based line number to start from"})),limit:o(w({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:Rl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(L,q){let Y=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(Y.length===0)throw Error("Give path, or paths to read several files");if(Y.length===1){let Z=Y[0];return{content:x(Z.path,Z.offset,Z.limit),details:void 0}}if(Y.length>Rl)throw Error(`Read at most ${Rl} paths per call`);let j=[],V=[],X=0,se=(Z)=>{let z=j.at(-1);if(Z.type==="text"&&z?.type==="text")z.text+=`
|
|
111
|
+
|
|
112
|
+
${Z.text}`;else j.push(Z)};for(let Z of Y){let z=`==> ${f(p(Z.path))} <==`;if(X>=_B){se({type:"text",text:`${z}
|
|
113
|
+
(Skipped due to total read safety budget; read in separate calls)`});continue}try{let ce=x(Z.path,Z.offset,Z.limit);for(let he=0;he<ce.length;he++){let ve=ce[he];if(!ve)continue;if(ve.type==="text")X+=ve.text.length,se(he===0?{...ve,text:`${z}
|
|
114
|
+
${ve.text}`}:ve);else se(ve)}}catch(ce){let he=ce instanceof Error?ce.message:String(ce);V.push(he),se({type:"text",text:`${z}
|
|
115
|
+
Error: ${he}`})}}if(V.length===Y.length)throw Error(V.join(`
|
|
116
|
+
`));return{content:j,details:void 0}}}),b=async(L,q,Y,j)=>{let V=j?.update,X=await er(L,{cwd:e,timeout:120000,signal:Y,extraPath:c?.extraPath,shell:typeof c?.shell==="function"?c.shell():c?.shell,onOutput:V?(he)=>V(u(`${j.prefix}
|
|
117
|
+
|
|
118
|
+
$ ${L}
|
|
119
|
+
${he.trimEnd()}`)):void 0}),se=X.output.trimEnd()||"(no output)",Z=X.timedOut?"killed after 120s timeout":X.code===0?"exit code 0":`exit code ${X.code}`,z=X.timedOut||X.code!==0,ce=z?`
|
|
120
|
+
${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
|
|
121
|
+
|
|
122
|
+
$ ${L}
|
|
123
|
+
${se}
|
|
124
|
+
[${Z}]${ce}`,failed:z}},E=(L,q=!1)=>{let Y=n.check(L);if(Y==="changed")return`Note: ${f(L)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(Y==="unread"&&q)return`Note: ${f(L)} existed and had not been read; it was replaced whole.`;return},T=v({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
|
|
125
|
+
- An existing file is replaced whole, including changes made since you last read it.
|
|
126
|
+
- Prefer the edit tool for changing existing files; use write for new files or full rewrites.
|
|
127
|
+
- 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.
|
|
128
|
+
- Do not create documentation or README files unless asked.`,parameters:s({path:l({description:"File path"}),content:l({description:"The full file content"}),then_run:o(l({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(L,q,Y,j){let V=p(q.path);g(V);let X=lu(V),se;if(X){if(Al(V).isDirectory())throw Error(`${V} is a directory`);se=E(V,!0)}CB(kl(V),{recursive:!0}),Qh(V,q.content),n.mark(V);let Z=q.content?q.content.split(`
|
|
129
|
+
`).length:0,z=`${X?"Overwrote":"Created"} ${f(V)} (${Z} lines)${se?`
|
|
130
|
+
${se}`:""}`;if(q.then_run){let ce=await b(q.then_run,`${f(V)} was written as given`,Y,{prefix:z,update:j});if(z+=ce.out,ce.failed)return{...u(z),isError:!0}}return u(z)}}),k=(L,q,Y,j)=>{let V=p(L);if(!lu(V))throw Error(`File not found: ${V} (use write to create it)`);g(V);let X=E(V),se=nP(V,"utf8"),Z=se,z=Z.includes(`\r
|
|
131
|
+
`),ce=[],he=[],ve=0,fe=0;return q.forEach((ie,me)=>{let qe=j?`edits[${Y+me}]: `:"";try{if(ie.old_string===ie.new_string)throw Error(`${qe}old_string and new_string are identical`);if(!ie.old_string)throw Error(`${qe}old_string is empty (use write to create or replace a whole file)`);let xt=z&&!ie.old_string.includes(`\r
|
|
132
|
+
`),Je=xt?ie.old_string.replace(/\n/g,`\r
|
|
133
|
+
`):ie.old_string,Yt=xt?ie.new_string.replace(/\n/g,`\r
|
|
134
|
+
`):ie.new_string,Fe=NB(Z,Je).map((At)=>[At,At+Je.length]);if(Fe.length===0)Fe=DB(Z,Je);if(Fe.length===0)throw Error(`${qe}old_string not found in ${f(V)}; read the relevant lines and copy the exact text.${qB(Z,Je)}`);if(Fe.length>1&&!ie.replace_all){let At=Fe.map(([st])=>sP(Z,st)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${At}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=sP(Z,Fe[0][0]),Ft=ie.replace_all?Fe:[Fe[0]],dt="",vt=0;for(let[At,st]of Ft)dt+=Z.slice(vt,At)+Yt,vt=st;Z=dt+Z.slice(vt),ve++,fe+=Ft.length;let hr=Z.split(/\r?\n/),pr=Ue+Yt.split(/\r?\n/).length-1,Ut=Math.max(1,Ue-1),ot=Math.min(hr.length,pr+1);if(ot-Ut+1<=vB+2)ce.push(mu(hr.slice(Ut-1,ot),Ut));else ce.push(`${mu(hr.slice(Ut-1,Ue+1),Ut)}
|
|
135
|
+
\u2026 (${pr-Ue-3} lines as given)
|
|
136
|
+
${mu(hr.slice(pr-2,ot),pr-1)}`)}catch(xt){he.push(xt instanceof Error?xt.message:String(xt))}}),{path:V,original:se,content:Z,echoes:ce,applied:ve,total:fe,count:q.length,note:X,failed:he}},A=v({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.
|
|
137
|
+
- No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
|
|
138
|
+
- 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.
|
|
139
|
+
- 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.
|
|
140
|
+
- 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.
|
|
141
|
+
- To create a file use write; to delete or move files use bash.
|
|
142
|
+
- 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.
|
|
143
|
+
- 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:s({path:o(l({description:"File path (the default for edits items without their own path)"})),old_string:o(l({description:"The exact text to replace (only when edits is absent)"})),new_string:o(l({description:"The replacement text (only when edits is absent)"})),replace_all:o(D({description:"Replace every occurrence (default false)"})),edits:o(W(s({path:o(l({description:"The file of this replacement, when it is not path"})),old_string:l({description:"The exact text to replace"}),new_string:l({description:"The replacement text"}),replace_all:o(D({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:o(l({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(L,q,Y,j){let V=q.edits&&q.edits.length>0?q.edits.map((ie)=>({path:ie.path??q.path,step:ie})):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 X=V.length>1,se=new Map;V.forEach((ie,me)=>{if(!ie.path)throw Error(`${X?`edits[${me}]: `:""}path is required`);let qe=p(ie.path),xt=se.get(qe)??{raw:ie.path,steps:[],offset:me};xt.steps.push(ie.step),se.set(qe,xt)});let Z=[],z=[];for(let ie of se.values())try{let me=k(ie.raw,ie.steps,ie.offset,X);if(me.applied>0)Z.push(me);z.push(...me.failed)}catch(me){let qe=me instanceof Error?me.message:String(me);z.push(`${X?`edits[${ie.offset}]: `:""}${qe}`)}if(Z.length===0)throw Error(z.join(`
|
|
144
|
+
`));let ce=[];try{for(let ie of Z)Qh(ie.path,ie.content),ce.push(ie)}catch(ie){for(let me of ce)Qh(me.path,me.original);throw ie}for(let ie of Z)n.mark(ie.path);let ve=Z.map((ie)=>{let me=ie.total===1?"1 occurrence":`${ie.total} occurrences`,qe=ie.note?`
|
|
145
|
+
${ie.note}`:"";if(!X)return`Edited ${f(ie.path)} (${me}).${qe}
|
|
146
|
+
${ie.echoes[0]}`;let xt=ie.failed.length>0?`, ${ie.failed.length} failed`:"";return`Edited ${f(ie.path)} (${ie.applied} edits${xt}, ${me}). Regions are shown as they were right after each edit; later edits may shift line numbers.${qe}
|
|
147
|
+
${ie.echoes.map((Je,Yt)=>`--- edit ${Yt+1}
|
|
148
|
+
${Je}`).join(`
|
|
149
|
+
`)}`}).join(`
|
|
150
|
+
|
|
151
|
+
`),fe=!1;if(q.then_run){let ie=await b(q.then_run,"The edits above were applied",Y,{prefix:ve,update:j});if(ve+=ie.out,ie.failed)fe=!0}if(z.length>0)ve+=`
|
|
152
|
+
|
|
153
|
+
${z.length===1?"1 edit":`${z.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
|
|
154
|
+
- ${z.join(`
|
|
155
|
+
- `)}`,fe=!0;return fe?{...u(ve),isError:!0}:u(ve)}});return[we(I,"cat","view","read_file","view_file","open_file","open"),we(T,"write_file","create_file","new_file","save_file"),we(A,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function NB(e,n){let i=[];for(let c=e.indexOf(n);c!==-1;c=e.indexOf(n,c+n.length))i.push(c);return i}function sP(e,n){let i=1;for(let c=0;c<n;c++)if(e.charCodeAt(c)===10)i++;return i}function DB(e,n){let i=n.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),c=[],p=e.split(`
|
|
156
|
+
`),f=0;for(let I of p)c.push(f),f+=I.length+1;let g=p.map((I)=>I.replace(/\r$/,"").trimEnd()),x=[];for(let I=0;I+i.length<=g.length;I++)if(i.every((b,E)=>g[I+E]===b)){let b=I+i.length-1,E=c[b]+p[b].replace(/\r$/,"").length,T=n.endsWith(`
|
|
157
|
+
`)&&E<e.length?e[E]==="\r"?2:1:0;x.push([c[I],E+T]),I+=i.length-1}return x}function qB(e,n){let i=(x)=>x.replace(/\s+/g," ").trim(),c=i(n);if(!c)return"";let p=e.split(/\r?\n/),f=n.split(/\r?\n/).length;for(let x=0;x+f<=p.length;x++)if(i(p.slice(x,x+f).join(`
|
|
158
|
+
`))===c)return` A match ignoring whitespace exists at line ${x+1}; copy the exact indentation and line breaks from the read output:
|
|
159
|
+
${je(mu(p.slice(x,x+f),x+1),4000)}`;let g=n.split(/\r?\n/).find((x)=>x.trim())?.trim();if(g){let x=p.findIndex((I)=>I.includes(g));if(x!==-1)return` Its first line appears at line ${x+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 FB(e){let n=kl(e);if(!lu(n))return"";let c=e.slice(n.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!c)return"";let p=aP(n).filter((f)=>{let g=f.toLowerCase().replace(/\.[^.]*$/,"");return g&&(g.includes(c)||c.includes(g))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function iP(e,n){let i=uP(e,n);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!Xh(i)}var Zh=20,eg=80,jB=5,mP=(e)=>e!==void 0&&e>0?e:void 0;function Cl(e,n){let i=(f)=>{if(n)return n(f);if(f.source&&f.source!=="self"||f.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},c=v({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.
|
|
160
|
+
- 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).
|
|
161
|
+
- Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),pattern:l({minLength:1,description:"Text to search for"}),also:o(W(l({minLength:1}),{maxItems:jB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:o(l({description:"Only search this chunk"})),seq:o(w({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:o(D({description:"Default false"})),head_limit:o(w({minimum:1,maximum:Zh,description:`Hits to return (default ${Zh})`})),offset:o(w({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(f,g){let x=i(g),I=mP(g.seq),b=()=>$s(x.records),E=`session_id=${x.sessionID}`,T=I!==void 0&&g.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
162
|
+
`:"",k;if(I!==void 0){let z=Bc(x.records,I)??Gc(x.records,I);if(!z)throw Error(`No user message with seq ${I}`);k=[z]}else{let z=b(),ce=g.chunk_id?z.filter((he)=>he.id===g.chunk_id):z;if(g.chunk_id&&!ce.length)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);k=ce.map(uu)}let A=(z)=>g.case_sensitive?z:z.toLowerCase(),L=[g.pattern,...(g.also??[]).filter(Boolean)].map(A),q=g.head_limit??Zh,Y=g.offset??0,j=[],V=new Map,X=0;for(let z of k)z.forEach((ce,he)=>{let ve=A(ce.text);if(!L.every((ie)=>ve.includes(ie)))return;if(V.set(ce.chunk,(V.get(ce.chunk)??0)+1),X++,X<=Y||j.length>=q)return;let fe=z.slice(Math.max(0,he-2),he+3);j.push(`${E} chunk ${ce.chunk} line ${ce.line}:
|
|
163
|
+
${Kc(fe," ")}`)});if(!X)return u(`${T}No matches`);if(!j.length)return u(`${T}No matches at offset ${Y} (total ${X})`);let se=X-Y-j.length,Z=V.size>1?` (all matches by chunk: ${[...V].map(([z,ce])=>`${z} ${ce}`).join(", ")})`:"";return u(`${T}${j.join(`
|
|
164
|
+
|
|
165
|
+
`)}${se>0?`
|
|
166
|
+
|
|
167
|
+
\u2026 ${se} more matches${Z}; continue with offset=${Y+j.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=v({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:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),chunk_id:o(l({description:"Chunk to read"})),seq:o(w({description:"User message to read (from a user-text-reference)"})),offset:o(w({minimum:0,description:"First line (default 0)"})),limit:o(w({minimum:1,maximum:eg,description:`Lines to return (default ${eg})`}))}),async execute(f,g){let x=i(g),I=mP(g.seq),b=()=>$s(x.records),E=`session_id=${x.sessionID}`,T=I!==void 0&&g.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
168
|
+
`:"",k;if(I!==void 0){if(k=Bc(x.records,I)??Gc(x.records,I),!k)throw Error(`No user message with seq ${I}`)}else if(g.chunk_id){let Y=b().find((j)=>j.id===g.chunk_id);if(!Y)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);k=uu(Y)}else{let Y=b().map((j)=>`${E} ${j.id} (${j.status}, ${uu(j).length} lines)`);return u(Y.length?`Pass chunk_id or seq. Chunks in this session:
|
|
169
|
+
${Y.join(`
|
|
170
|
+
`)}`:"This session has no history yet")}let A=g.offset??0,L=k.slice(A,A+(g.limit??eg));if(!L.length)return u(`No lines at offset ${A} (total ${k.length})`);let q=k.length-A-L.length;return u(`${T}${E} ${I!==void 0?`seq=${I}`:g.chunk_id}
|
|
171
|
+
${Kc(L)}${q>0?`
|
|
172
|
+
|
|
173
|
+
\u2026 ${q} more lines; continue with offset=${A+L.length}`:""}`)}});return[c,p]}import{statSync as UB}from"fs";import{isAbsolute as pP,relative as BB,resolve as lP}from"path";var $l=200,GB=30000,Pl=Bun.which("rg");async function tg(e,n,i){let c=Bun.spawn(e,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,f,g]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(g>1)throw Error(f.trim()||`${e[0]} exited with ${g}`);return p}function dP(e){let n=(f)=>f?pP(f)?f:lP(e,f):e,i=(f)=>{let g=BB(e,f);return g&&!g.startsWith("..")&&!pP(g)?g:f},c=v({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).
|
|
174
|
+
- Respects .gitignore and skips .git. Use it instead of find or ls -R.
|
|
175
|
+
- To search file contents, use grep.`,parameters:s({pattern:l({description:"Glob pattern, matched relative to path"}),path:o(l({description:"Directory to search (default: working directory)"}))}),async execute(f,g,x){let I=n(g.path),b;if(Pl)b=(await tg([Pl,"--files","--hidden","--glob","!.git","--glob",g.pattern],I,x)).split(`
|
|
176
|
+
`).filter(Boolean);else{b=[];for await(let A of new Bun.Glob(g.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(A))b.push(A)}if(!b.length)return u("No files found");let E=b.map((A)=>{let L=lP(I,A);try{return{path:L,time:UB(L).mtimeMs}}catch{return{path:L,time:0}}});E.sort((A,L)=>L.time-A.time);let T=E.slice(0,$l).map((A)=>i(A.path)),k=b.length-T.length;return u(`${T.join(`
|
|
177
|
+
`)}${k>0?`
|
|
178
|
+
\u2026 ${k} more files; narrow the pattern`:""}`)}}),p=v({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
|
|
179
|
+
- output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
|
|
180
|
+
- Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
|
|
181
|
+
- Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
|
|
182
|
+
- Use this instead of running grep or rg through bash.`,parameters:s({pattern:l({description:"Regular expression"}),path:o(l({description:"File or directory to search (default: working directory)"})),glob:o(l({description:"Only search files matching this glob"})),output:o(m([a("files"),a("content"),a("count")],{description:"Output mode (default files)"})),ignore_case:o(D()),context:o(w({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(f,g,x){let I=n(g.path),b=g.output??"files",E;if(Pl){let A=[Pl,"--hidden","--glob","!.git","--max-columns","400","--max-columns-preview"];if(g.ignore_case)A.push("-i");if(g.glob)A.push("--glob",g.glob);if(b==="files")A.push("-l");else if(b==="count")A.push("-c");else if(A.push("-n","--no-heading"),g.context)A.push("-C",String(g.context));A.push("--",g.pattern,I),E=await tg(A,e,x)}else{let A=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(g.ignore_case)A.push("-i");if(g.glob)A.push(`--include=${g.glob}`);if(b==="files")A.push("-l");else if(b==="count")A.push("-c");else if(A.push("-n"),g.context)A.push(`-C${g.context}`);A.push("--",g.pattern,I),E=await tg(A,e,x)}let T=`${e}/`,k=E.split(`
|
|
183
|
+
`).filter(Boolean).map((A)=>A.startsWith(T)?A.slice(T.length):A).filter((A)=>b!=="count"||!A.endsWith(":0"));if(!k.length)return u("No matches");if(b==="files"&&k.length>$l)return u(`${k.slice(0,$l).join(`
|
|
184
|
+
`)}
|
|
185
|
+
\u2026 ${k.length-$l} more files; narrow the search`);return u(rt(k.join(`
|
|
186
|
+
`),GB))}});return[we(c,"find","find_files","list_files","file_search","ls","list","list_dir"),we(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function fP(e){return we(v({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
|
|
187
|
+
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.
|
|
188
|
+
- Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
|
|
189
|
+
- 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.
|
|
190
|
+
- 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:s({todos:W(s({content:l({minLength:1,description:"What to do, in imperative form"}),status:m(Lg.map((n)=>a(n)))}))}),async execute(n,i){let c=i.todos.map((g)=>({content:g.content,status:g.status}));e(c);let p=c.filter((g)=>g.status==="completed").length,f=c.find((g)=>g.status==="in_progress");return u(`Todo list updated (${p}/${c.length} completed${f?`; in progress: ${f.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function We(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}function hP(e){let n=We(e);return{target:n,hard:n,index:n}}class Ml{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,n=()=>{return},i){this.records=e;this.cwd=n;if(i)this.defaultPolicy=new Uc(e,i,n)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??hP(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??We(e)}prepare(e,n,i,c,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,n,i,c);let f=e.reduce((b,E)=>b+U(E),0)+Li(n),g=Math.max(0,We(i)*this.recoveryRatio-f),x=ke(c??this.records(),i,hP(i),{cwd:this.cwd()}).messages,I=x.reduce((b,E)=>b+U(E),0);if(p&&I>g)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(I>g&&x.length>1){let b=x.shift();if(b)I-=U(b);while(x[0]?.role==="toolResult"){let E=x.shift();if(E)I-=U(E)}}if(I>g){let b=x.at(-1),E=b&&"content"in b&&typeof b.content==="string"?b.content:"[Context omitted: use history tools to retrieve earlier messages.]";x.length=0;let T=E;while(T&&U({role:"user",content:T,timestamp:0})>g)T=T.slice(Math.ceil(T.length/2));if(T)x.push({role:"user",content:T,timestamp:0});I=x.reduce((k,A)=>k+U(A),0)}return this.lastMessageCount=x.length,{messages:[...e,...x],estimate:f+I}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as gP,readFileSync as KB}from"fs";import{homedir as HB}from"os";import{dirname as WB,join as yP}from"path";var zB=`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.
|
|
191
|
+
|
|
192
|
+
# How to work
|
|
193
|
+
|
|
194
|
+
- 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.
|
|
195
|
+
- 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.
|
|
196
|
+
- 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.
|
|
197
|
+
- 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.
|
|
198
|
+
|
|
199
|
+
# Making changes
|
|
200
|
+
|
|
201
|
+
- 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.
|
|
202
|
+
- 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.
|
|
203
|
+
- 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.
|
|
204
|
+
- 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).
|
|
205
|
+
- Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
|
|
206
|
+
- 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.
|
|
207
|
+
|
|
208
|
+
# Verifying
|
|
209
|
+
|
|
210
|
+
- 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.
|
|
211
|
+
- 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.
|
|
212
|
+
- 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.
|
|
213
|
+
- 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.
|
|
214
|
+
- 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.
|
|
215
|
+
|
|
216
|
+
# Tools
|
|
217
|
+
|
|
218
|
+
- Tool calls are the only way to act; describing an action does not perform it.
|
|
219
|
+
- 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.
|
|
220
|
+
- 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.
|
|
221
|
+
- 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.
|
|
222
|
+
- 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.
|
|
223
|
+
- 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.
|
|
224
|
+
- 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 &&.
|
|
225
|
+
- 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.
|
|
226
|
+
|
|
227
|
+
# Honesty
|
|
228
|
+
|
|
229
|
+
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
230
|
+
- Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
|
|
231
|
+
- When the user asks you to run something, run it, even when you can predict the result.
|
|
232
|
+
- If a step failed, was skipped or could not be verified, say which one and why.
|
|
233
|
+
|
|
234
|
+
# Safety
|
|
235
|
+
|
|
236
|
+
- 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.
|
|
237
|
+
- 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.
|
|
238
|
+
- 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.
|
|
239
|
+
- Never print, log or commit secrets such as API keys, tokens or passwords.
|
|
240
|
+
|
|
241
|
+
# Communication
|
|
242
|
+
|
|
243
|
+
- Reply in the same language the user writes in.
|
|
244
|
+
- 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.
|
|
245
|
+
- 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.
|
|
246
|
+
- Do not use emojis unless the user does or asks for them.
|
|
247
|
+
- 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.
|
|
248
|
+
- Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,VB=`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.
|
|
249
|
+
|
|
250
|
+
# Tools
|
|
251
|
+
|
|
252
|
+
- 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.
|
|
253
|
+
- 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.
|
|
254
|
+
- Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
|
|
255
|
+
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
|
|
256
|
+
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
257
|
+
|
|
258
|
+
# Communication
|
|
259
|
+
|
|
260
|
+
- Reply in the same language the user writes in.
|
|
261
|
+
- Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
|
|
262
|
+
- Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,JB=["AGENTS.md","CLAUDE.md"],QB=20000;function xP(e){let n=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?zB:VB}],i=[];if(e.globalInstructions?.trim())i.push(rg("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let c of XB(e.project.directory))i.push(rg(c.path,c.content));if(e.project.instructions.trim())i.push(rg(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)n.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
|
|
263
|
+
|
|
264
|
+
# Instructions from the user and project
|
|
265
|
+
|
|
266
|
+
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.
|
|
267
|
+
|
|
268
|
+
${i.join(`
|
|
269
|
+
|
|
270
|
+
`)}`});return n.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
|
|
271
|
+
|
|
272
|
+
${YB(e)}`}),n}function rg(e,n){return`<instructions source="${e}">
|
|
273
|
+
${je(n.trim(),QB)}
|
|
274
|
+
</instructions>`}function XB(e){let n=[],i=e;for(let c=0;c<20;c++){for(let f of JB){let g=yP(i,f);if(gP(g)){try{n.unshift({path:g,content:KB(g,"utf8")})}catch{}break}}if(gP(yP(i,".git"))||i===HB())break;let p=WB(i);if(p===i)break;i=p}return n}function YB(e){let n=e.now??new Date,i=n.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),c=n.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:f}=xa("",e.shell),g=[`Working directory: ${p}`,`Shell: ${f}`,`Date: ${i} (${c})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project){let x=ZB(e.project.directory);g.push(x??"Git: not a git repository")}return`<environment>
|
|
275
|
+
${g.join(`
|
|
276
|
+
`)}
|
|
277
|
+
</environment>`}function ZB(e){let n=(...x)=>{try{let I=Bun.spawnSync(["git",...x],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0});return I.exitCode===0?I.stdout.toString().trim():void 0}catch{return}},i=n("rev-parse","--abbrev-ref","HEAD");if(i===void 0)return;let c=n("status","--short")??"",p=c?c.split(`
|
|
278
|
+
`):[],f=p.length>30?[...p.slice(0,30),`\u2026 ${p.length-30} more`]:p,g=n("log","--oneline","-5")??"";return[`Git branch: ${i}`,`Git status at session start:${f.length?`
|
|
279
|
+
${f.join(`
|
|
280
|
+
`)}`:" clean"}`,g?`Recent commits:
|
|
281
|
+
${g}`:"Recent commits: none"].join(`
|
|
282
|
+
`)}function tr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Cl(e.records,e.history):[],c=e.directory??process.cwd();return[...cP(c,new Yh,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...dP(c),fP(e.onTodos),...i]}class Di{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||!Dg.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Ng.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 n=this.settings();if(e.scope==="global")if(e.mode===null)delete n.global;else n.global=e.mode;else{let i=e.scope==="tool"?n.tools:n.sources,c=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[c];else i[c]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(n)),n}partition(e){let n=this.settings();return e.map((c)=>{let p=c,f=p.source??"core",g=c.name.toLowerCase(),x=p.defer??"always",I="suggestion";if(n.global)x=n.global,I="global";if(Object.hasOwn(n.sources,f))x=n.sources[f]??x,I="source";if(Object.hasOwn(n.tools,g))x=n.tools[g]??x,I="tool";if(f==="core"||p.builtin&&p.defer!=="defer")x="always",I="suggestion";return{name:c.name,source:f,mode:x,origin:I,deferred:x==="defer"}})}}function ng(e){return{name:e.name,description:e.description,parameters:e.parameters}}function eG(e,n,i){let c=e.prepareArguments?e.prepareArguments(i):i;return tu(e,{type:"toolCall",id:n,name:e.name,arguments:c})}class og{retrieved=new Map;stub(e){let n=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${n}
|
|
283
|
+
(Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:s({},{additionalProperties:!0}),execute:async(i,c,p,f)=>{let g=JSON.stringify(ng(e)),x;try{x=eG(e,i,c??{})}catch(E){return{...u(`Invalid arguments for ${e.name}: ${String(E)}
|
|
284
|
+
Schema: ${g}`),isError:!0}}let I=await e.execute(i,x,p,f),b=I.content.map((E)=>E.type==="text"?{...E,text:rt(E.text,Pe)}:E);return{...I,content:b}}}}assemble(e,n,i){let c=new Set(n.filter((f)=>f.deferred).map((f)=>f.name));if(!c.size)return e;let p=e.filter((f)=>c.has(f.name)&&i(f.name)).sort((f,g)=>f.name<g.name?-1:f.name>g.name?1:0);return[...e.filter((f)=>!c.has(f.name)),...p.map((f)=>this.stub(f)),we(v({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:s({query:l(),max_results:o(w({minimum:1,maximum:100}))}),execute:async(f,g)=>{let x=g.query.trim().toLowerCase(),I=x.startsWith("select:")?x.slice(7).split(",").map((E)=>E.trim()):void 0,b=p.filter((E)=>i(E.name)&&(I?I.includes(E.name.toLowerCase()):`${E.name} ${E.description}`.toLowerCase().includes(x))).slice(0,g.max_results??5);return u(JSON.stringify(b.map((E)=>{let T=JSON.stringify(ng(E)),k=this.retrieved.get(E.name);if(k?.schema===T)return{name:E.name,status:"\u5DF2\u53D6\u56DE",callID:k.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(E.name,{schema:T,callID:f}),ng(E)})))}}),"tool_search")]}}async function vl(e,n,i){let c=await n.setup(e),p=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!i)return c;if(i.has("session.setup"))c=await i.invoke("session.setup",c,e);if(i.has("tools.configure"))c=await i.invoke("tools.configure",c,e);let f=c.systemPrompt,g=c.systemParts?.at(-1);if(g?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let E=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),T=f.length-g.detail.length;f=f.slice(0,T)+E.join("")+g.detail}let x=await i.invoke("prompt.fragments",[],e),I=[...c.tools,...i.tools()],b=i.has("tools.visible")?await i.invoke("tools.visible",I,e):I;return{...c,systemPrompt:f+x.join(""),tools:b}}var tG=3,IP={attempts:1/0,delayMs:2000},rG=/\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 nG(e,n){if(e.stopReason!=="error")return!1;if(li(e,n))return!1;return!rG.test(e.errorMessage??"")}function oG(e,n){return new Promise((i,c)=>{if(n.aborted)return c(n.reason);let p=setTimeout(()=>{n.removeEventListener("abort",f),i()},e),f=()=>{clearTimeout(p),c(n.reason)};n.addEventListener("abort",f,{once:!0})})}async function bP(e,n,i,c,p,f,g,x,I=!1){let b=I?void 0:await n?.invoke("run.start",{text:f},e);if(b)f=b.text;if(x.throwIfAborted(),f===void 0)await c.resume();else await c.prompt(f,g);let E=0,T=0;while(E<tG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!li(q,p.contextWindow)){if(!nG(q,p.contextWindow)||T>=IP.attempts)return;T++,await oG(IP.delayMs,x),await c.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}x.throwIfAborted(),E++,await c.retry()}let A=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&A?.stopReason==="error"&&li(A,p.contextWindow))throw Error(i.overflowError??"Context exceeds the request budget")}async function EP(e,n,i,c,p,f){f.throwIfAborted();let g,x;try{x=await Promise.race([vl(e,n,i()),new Promise((k,A)=>{g=()=>A(f.reason),f.addEventListener("abort",g,{once:!0})})])}finally{if(g)f.removeEventListener("abort",g)}f.throwIfAborted();let I=i(),b=(k)=>{if(!I)return k;return{...k,execute:async(A,L,q,Y)=>{let j=c()??x.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?I.policy(j):void 0;if(j&&!V?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${j}`);let X=await I.invoke("tool.before_call",{name:k.name,callID:A,args:L},e);if(X.block)throw Error(X.block);let se=await K.run(e,()=>k.execute(A,X.args,q,Y));return I.invoke("tool.after_result",se,e)}}};if(I)x.tools=x.tools.map(b);let E=x.tools,T=()=>{if(!E.some((A)=>A.name==="history_grep")){if(e.records.some((L)=>L.entry.type==="compaction")){let q=Cl(()=>e.records,(Y)=>n.runtime?.resolveHistory?.(e.id,Y)).map(b);for(let Y of q)if(!E.some((j)=>j.name===Y.name))E.push(Y)}}let k=new Di(n.store).partition(E);return x.tools=p.assemble(E,k,(A)=>e.permitsTool(A)),x.tools};return x.tools=T(),{setup:x,executionTools:E,assemble:T}}function SP(e,n,i,c,p,f,g){return{response:async(x)=>{let I=await n()?.invoke("model.after_response",x,e)??x;if(I.role==="assistant")for(let b of I.content){if(b.type!=="toolCall"||b.name.toLowerCase()!=="tool_call")continue;let E=b.arguments.name;if(typeof E==="string"){let T=g.find((k)=>k.name.toLowerCase()===E.toLowerCase());b.arguments.name=T?.name??E}}return I},payload:(x)=>n()?.invoke("model.before_request",x,e)??Promise.resolve(x),transformContext:(x)=>n()?.invoke("transformContext",x,e)??Promise.resolve(x),boundary:async()=>{if(c())return!0;let x=await n()?.invoke("step.after",{notices:[]},e);for(let b of x?.notices??[])e.notice(b);await f.work;let I=await f.flushNotices();if(I&&!p())e.agent?.steer(I)},prepare:async(x,I,b)=>{if(c())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let E=await n()?.invoke("model.check",{},e);if(E?.error)throw Error(E.error);let T=await n()?.invoke("step.before",{notices:[]},e);for(let j of T?.notices??[])e.notice(j);await f.work,await f.flushNotices();let k=await n()?.invoke("projection.before",e.records,e),A=await n()?.invoke("projection.prefix",[],e)??[],L=e.context.prepare([...x,...A],I,b,k,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&L.estimate>We(b))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=L.messages,Y=await n()?.invoke("projection.after",q,e)??q;return su(Y)}}}async function wP(e,n,i){let c=n.store.pendingNotices(e.id);if(!c.length)return;let p=c,f=n.plugins?.pin();try{if(f){let A=await f.invoke("notice.deliver",c,e);p=c.map((L,q)=>({...L,text:A[q]?.text??L.text}))}}finally{await f?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let g=p.map((A)=>A.text).join(`
|
|
285
|
+
`),x=p.map((A)=>n.plugins?.noticeSource(A.sourceKind)),I=Math.max(800,...x.map((A)=>A?.summaryLimit??800)),b=g.length>I?`
|
|
286
|
+
[\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",T=`${x.find((A)=>A?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
|
|
287
|
+
${g.slice(0,I)}${b}`,k={role:"user",content:T,timestamp:Date.now()};return i({type:"user",text:T,notices:c.map(({text:A,...L})=>L)},k),k}class sg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,n,i,c,p,f,g,x){this.session=e;this.context=n;this.isStopped=i;this.isRunning=c;this.waiting=p;this.start=f;this.invalidateAgent=g;this.append=x}recover(){for(let e of this.context.store.pendingNotices(this.session.id)){if(e.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:e.dedupeKey,sourceKind:e.sourceKind,sourceID:e.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if(this.context.store.pendingNotices(this.session.id).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let n={...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,n)||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=wP(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((n)=>n.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var sG=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 ig(e){let n={};for(let[i,c]of Object.entries(e)){if(!sG.has(i.toLowerCase())){n[i]=c;continue}let p=/^bearer\s+/i.exec(c)?.[0];n[i]=p?`${p}***`:"***"}return n}function TP(e,n,i,c){let f=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((Z,z)=>({id:`system-${z}`,label:Z.label,detail:Z.detail,tokens:O(Z.detail)+(z===0?16:0)})),g=i.tools.map((Z)=>{let z=Z,ce=z.defer==="defer"||Z.description.includes("(Parameters not inlined: use toolsearch");return{name:Z.name,description:Z.description,group:z.group??"\u5185\u7F6E",schema:Z.parameters,deferred:ce}});f.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Li(i.tools),detail:JSON.stringify(g,null,2)});let x=f.reduce((Z,z)=>Z+z.tokens,0),I=c!==void 0?e.records.filter((Z)=>Z.entry.seq<=c):e.records,b=ke(I,n,e.context.budget(n),{inspect:!0,cwd:i.cwd,trim:{fixed:x,limit:e.context.previewLimit(n)}}),E,T=0,k=0;for(let Z of I){if(Z.raw?.role!=="assistant")continue;let z=Z.raw.usage;E??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},E.input+=z.input,E.output+=z.output,E.cacheRead+=z.cacheRead,E.cacheWrite+=z.cacheWrite,E.cost+=z.cost.total;let ce=Z.entry.generationMs??Z.raw.generationMs;if(typeof ce==="number"&&ce>0&&z.output>0)T+=ce,k+=z.output}if(E&&T>0&&k>0)E.generationMs=T,E.tps=Number((k/(T/1000)).toFixed(1));let A=x+b.tokens,L=e.context.calibrationRatio??1,q=Math.round(A*L),Y=I.findLast((Z)=>Z.raw?.role==="assistant"),j=Y?.raw,X=(Y?I.filter((Z)=>Z.entry.seq>Y.entry.seq&&Z.raw):I.filter((Z)=>Z.raw)).length>0,se;if(j){let Z=j.usage,z=Z.input+Z.cacheRead+Z.cacheWrite;if(z>0)se=z}return{contextWindow:n.contextWindow,usableWindow:We(n),items:[...f,...b.items],calibratedTokens:q,calibrationRatio:L,lastInputTokens:se,hasPendingOutput:X,tools:g,usage:E}}class pt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class oe extends Error{constructor(e="session"){super(`${e} is busy`)}}var ag="medium";class Ol{row;ctx;events;notices;lease;policyID;discovery=new og;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let n=await vl(this,this.ctx,e);return new Di(this.ctx.store).partition(n.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new oe;this.policyID=e,this.reset()}historyScope(e){if(this.lease)return this.lease.resolveHistory(this,e);return this.ctx.plugins?.resolveHistory(this,e)}permitsTool(e){let n=this.policyID??this.setup?.toolPolicy;if(!n)return this.info().parentID===null;return(this.lease?.policy(n)??this.ctx.plugins?.toolPolicy(n))?.(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,n,i){this.row=e;this.ctx=n;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new sg(this,n,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=n.store.lastSeq(e.id);let c=n.store.lastEntry(e.id,"run");this.stopped=c?.type==="run"&&c.state==="end"&&c.reason==="aborted";let p=this.entries().findLast((g)=>g.type==="extension"&&g.namespace==="session"&&g.kind==="stop_requested"),f=this.entries().findLast((g)=>g.type==="run"&&g.state==="start");if(p&&p.seq>(f?.seq??0))this.stopped=!0;if(c?.type==="run"&&c.state==="start"){let g=this.records.some((I)=>I.entry.seq>c.seq&&I.entry.type==="user"),x=n.store.pendingNotices(e.id).some((I)=>I.wake&&I.recovery!=="discard");if(!this.stopped&&(g||x))this.recoveryStart=c.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new Ml(()=>this.records,()=>this.cwd,(g,x)=>this.appendCompaction(g,x)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=xn(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:ig(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:ig(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??ag}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:n,projectID:i,model:c,thinking:p,metadata:f,created:g,updated:x,todos:I}=this.row;return{id:e,title:n,projectID:i,model:c,thinking:p??ag,metadata:f,created:g,updated:x,archivedAt:this.row.archivedAt,status:this.status,todos:I,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let n=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,n)}entriesBefore(e,n){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-n));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,n,i){return this.ctx.store.entriesAround(this.row.id,e,n,i)}entriesFrom(e,n){return this.ctx.store.entriesFrom(this.row.id,e,n)}entries(e=0){return this.ctx.store.entries(this.row.id).filter((n)=>n.seq>e)}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 n=(async()=>{let i=xn(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 c=this.ctx.plugins?.pin(),p;try{p=this.setup??await vl(this,this.ctx,c)}finally{await c?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new Di(this.ctx.store).partition(p.tools),(g)=>this.permitsTool(g));let f=TP(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:f};return f})();if(e!==void 0)return n;this.snapshotInFlight=n;try{return await n}finally{if(this.snapshotInFlight===n)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new pt}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"||!xn(this.ctx.models,e))throw new t(`unknown model ${e}`);let n=this.row.model;if(n===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:n,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let n=e?.trim()?e.trim():null;if(this.row.thinking===n)return;this.save({thinking:n}),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,n){this.startRun(e,n)}steer(e,n){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,n);return}this.stopped=!1;let i=Ph(e,n),c=this.append({type:"user",text:e,...n?.length?{attachments:n}:{}},i);if(this.recallableSteers.set(c.seq,i),this.events.changed(),this.agent)this.agent.steer(i);else this.pendingSteers.push(i)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let n=this.records.find((f)=>f.entry.seq===e);if(n?.entry.type!=="user"||n.raw===void 0)return!1;if("notices"in n.entry&&n.entry.notices)return!1;let i=n.raw,c=this.pendingSteers.indexOf(i);if(c<0){let f=JSON.stringify(i);c=this.pendingSteers.findIndex((g)=>JSON.stringify(g)===f)}let p=!1;if(c>=0)this.pendingSteers.splice(c,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[n,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(n),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,n,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 oe;if(e!==void 0)this.stopped=!1;let c=xn(this.ctx.models,this.row.model);if(!c&&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:iG(e,n)},this.ctx.store.updateSession(this.row);let f=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let g=this.append({type:"user",text:e,...n?.length?{attachments:n}:{}});this.pendingUserSeq=g.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 x=this.records.filter((T)=>T.entry.seq>f),I=x.filter((T)=>T.entry.type==="user"&&!T.raw);if(I.length>1)return{reason:"interrupted"};let b=I[0];if(b?.entry.type==="user"){if(x.some((T)=>T.entry.seq>b.entry.seq&&T.raw?.role==="assistant"))return{reason:"interrupted"};e=b.entry.text,n=b.entry.attachments,this.pendingUserSeq=b.entry.seq}for(let T of us(x.filter((k)=>k.raw))){if(T.result)continue;let{body:k,raw:A}=l$(T.call);this.append(k,A)}if(!b&&this.waitingForInput())return{reason:"waiting_user"};let E=this.records.findLast((T)=>T.entry.seq>f&&T.raw)?.raw;if(!b&&E?.role==="assistant")return Mh(E);if(!b&&!E&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!c)throw Error(`unknown model ${this.row.model}`);let g=await this.prepareAgent(c,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let x=this.pendingSteers.shift();if(x)g.steer(x)}return await bP(this,this.lease,this.setup,g,c,e,n,p.signal,i!==void 0&&e===void 0),Mh(this.records.findLast((x)=>x.entry.seq>f&&x.raw?.role==="assistant")?.raw)}).then((g)=>p.signal.aborted?{reason:"aborted"}:g,(g)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(g)}).then(async(g)=>{try{if(!this.suspended&&g.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())g={reason:"waiting_user"};if(g.reason!=="interrupted")g=await this.lease?.invoke("run.end",{reason:g.reason,error:g.error},this)??g}}catch(x){g={reason:"error",error:String(x)}}finally{try{await this.lease?.release()}catch(x){g={reason:"error",error:String(x)}}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",...g});let x=xn(this.ctx.models,this.row.model);if(x)this.context.settle(x)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,n){if(!this.agent){let{setup:i,executionTools:c,assemble:p}=await EP(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,n);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=p$({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((f)=>!this.pendingSteers.includes(f.raw)).flatMap((f)=>f.raw?[f.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??ag,captureRequest:(f)=>{this.lastRequestSnapshot=f},captureResponse:(f)=>{this.lastResponseSnapshot=f},steerConsumed:(f)=>this.markSteerConsumed(f),hooks:{tools:p,...SP(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,c),message:(f,g)=>{if(this.suspended&&g.role==="assistant"&&(g.stopReason==="aborted"||g.stopReason==="error"))return;if(g.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,g);let x=this.loaded?.find((I)=>I.entry.seq===this.pendingUserSeq);if(x)x.raw=g;this.pendingUserSeq=void 0;return}if(g.role==="assistant")this.context.calibrate(g);this.append(f,g)},draft:(f)=>{this.draftParts=f,this.events.draft(f)}}})}return this.agent}notice(e,n=!1){if(this.closed)return;if(n)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 n of e)this.loaded?.push(n);for(let{entry:n}of e)this.events.entry(n)}appendCompaction(e,n){this.assertWritable();let i=this.measureCompactionSavings(e,n);this.append({type:"compaction",through:e,partial:n,...i?{saved:i}:{}})}measureCompactionSavings(e,n){let i=xn(this.ctx.models,this.row.model);if(!i)return;let c=this.context.budget(i),p=ke(this.records,i,c,{cwd:this.cwd}).tokens,f={entry:{type:"compaction",through:e,partial:n,seq:this.seq+1,time:0}},g=ke([...this.records,f],i,c,{cwd:this.cwd}).tokens;return{before:p,after:g}}compact(){this.assertWritable();let e=ou(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,n){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,n);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 iG(e,n){let c=(e.trim()||n?.map((p)=>p.name).join(" ")||"").split(`
|
|
288
|
+
`)[0]?.trim()??"";return c.length>40?`${c.slice(0,40)}\u2026`:c}var kP=new Set(["user","assistant","tool_result","run","compaction"]),aG=new Set(["user","assistant","toolResult"]);function AP(e,n,i){return{format:Ql,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:n.filter((c)=>kP.has(c.entry.type)).map((c)=>c.raw===void 0?{entry:c.entry}:{entry:c.entry,raw:c.raw})}}function Lo(e){if(!fr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Ql)return uG(e);if(fr(e.info)&&Array.isArray(e.messages))return mG(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 uG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let n=e.session;if(!fr(n))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,c=e.records.flatMap((p,f)=>{let g=`records[${f}]`;if(!fr(p)||!fr(p.entry))throw new t(`${g} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let x=p.entry;if(x.type==="notice_pending"||x.type==="extension")return[];if(typeof x.type!=="string"||!kP.has(x.type))throw new t(`${g} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(x.type)}`);let{seq:I,time:b}=x;if(typeof I!=="number"||!Number.isSafeInteger(I)||I<=i)throw new t(`${g} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof b!=="number"||!Number.isFinite(b))throw new t(`${g} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=I,cG(x,g);let E=p.raw;if(E!==void 0&&!(fr(E)&&typeof E.role==="string"&&aG.has(E.role)))throw new t(`${g} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:x,...E===void 0?{}:{raw:E}}]});return{title:Or(n.title),model:typeof n.model==="string"?n.model:void 0,thinking:typeof n.thinking==="string"?n.thinking:null,todos:Array.isArray(n.todos)?n.todos.flatMap($P):[],created:Hs(n.created)??Date.now(),updated:Hs(n.updated)??Date.now(),needsRaw:!1,records:c}}function cG(e,n){let i=(c)=>new t(`${n}\uFF08${String(e.type)}\uFF09${c}`);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"&&Pg.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 mG(e){let n=e.info,i=fr(n.time)?n.time:{},c=fr(n.model)?n.model:void 0,p=e.messages.filter(fr).sort(pG),f=[],g=0,x=0,I=(Y,j)=>{x=Math.max(x,j??x),g+=1,f.push({entry:{...Y,seq:g,time:x}})},b=!1,E=(Y,j)=>{if(!b)return;b=!1,I({type:"run",state:"end",reason:Y,...j?{error:j}:{}},void 0)};for(let Y of p){let j=fr(Y.info)?Y.info:{},V=Array.isArray(Y.parts)?Y.parts.filter(fr):[],X=Hs(fr(j.time)?j.time.created:void 0);if(j.role==="user"){E("done");let se=lG(V);if(!se)continue;I({type:"run",state:"start"},X),I(se,X),b=!0}else if(j.role==="assistant"){if(!b)I({type:"run",state:"start"},X),b=!0;hG(j,V,I);let se=CP(j.error);if(se)E(se.aborted?"aborted":"error",se.aborted?void 0:se.message)}}E("done");let T=p.findLast((Y)=>fr(Y.info)&&Y.info.role==="assistant"),k=fr(T?.info)?T.info:void 0,A=Or(c?.providerID)||Or(k?.providerID),L=Or(c?.id)||Or(k?.modelID),q=A&&L?`${A}/${L}`:void 0;return{title:Or(n.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap($P):[],created:Hs(i.created)??f[0]?.entry.time??Date.now(),updated:Hs(i.updated)??f.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:f}}function pG(e,n){let i=(p)=>(fr(p.info)&&fr(p.info.time)?Hs(p.info.time.created):void 0)??0,c=(p)=>fr(p.info)?Or(p.info.id):"";return i(e)-i(n)||c(e).localeCompare(c(n))}function lG(e){let n=e.filter((c)=>c.type==="text"&&c.synthetic!==!0&&c.ignored!==!0).map((c)=>Or(c.text)).join(`
|
|
289
|
+
|
|
290
|
+
`),i=e.flatMap((c)=>c.type==="file"?dG(c):[]);if(!n.trim()&&i.length===0)return;return{type:"user",text:n,...i.length?{attachments:i}:{}}}function dG(e){let n=Or(e.mime)||"application/octet-stream",i=Or(e.filename)||"file",c=Or(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(c);if(p){let f=p[3]??"";if(n.startsWith("image/"))return[{name:i,mimeType:n,kind:"image",data:p[2]?f:btoa(f)}];if(n.startsWith("text/")||n==="application/json"){let g=p[2]?new TextDecoder().decode(Uint8Array.from(atob(f),(x)=>x.charCodeAt(0))):f;return[{name:i,mimeType:n,kind:"text",data:g}]}return[]}if(c.startsWith("file://"))try{return[{name:i,mimeType:n,kind:"path",data:decodeURIComponent(new URL(c).pathname)}]}catch{return[]}return[]}function fG(e){let n=[[]];for(let i of e){if(i.type==="step-start"){if(n.at(-1)?.length)n.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")n.at(-1)?.push(i)}return n.filter((i)=>i.length>0)}function hG(e,n,i){let c=`${Or(e.providerID)}/${Or(e.modelID)}`,p=CP(e.error),f=fG(n);f.forEach((g,x)=>{let I=g.flatMap((T)=>{if(T.type==="reasoning")return Or(T.text).trim()?[{type:"thinking",text:Or(T.text)}]:[];if(T.type==="text")return T.ignored!==!0&&Or(T.text).trim()?[{type:"text",text:Or(T.text)}]:[];return[{type:"tool_call",id:RP(T.callID),name:Or(T.tool),input:fr(T.state)&&fr(T.state.input)?T.state.input:{}}]}),b=x===f.length-1,E=gG(g);i({type:"assistant",parts:I,model:c,...b&&p&&!p.aborted?{error:p.message}:{}},E);for(let T of g){if(T.type!=="tool")continue;let k=fr(T.state)?T.state:{},A=k.status==="error",L=k.status==="pending"||k.status==="running",q=A?[Or(k.output),Or(k.error)].filter(Boolean).join(`
|
|
291
|
+
`):L?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Or(k.output);i({type:"tool_result",callID:RP(T.callID),name:Or(T.tool),output:q,isError:A||L},Hs(fr(k.time)?k.time.end:void 0))}})}function RP(e){return Or(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function CP(e){if(!fr(e))return;let n=fr(e.data)?e.data:{};return{message:Or(n.message)||Or(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function gG(e){for(let n of e){let i=fr(n.time)?Hs(n.time.start):fr(n.state)?yG(n.state):void 0;if(i!==void 0)return i}return}function yG(e){return fr(e.time)?Hs(e.time.start):void 0}function $P(e){if(!fr(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 PP(e,n){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:c})=>{let p=c.time;switch(c.type){case"user":return{entry:c,raw:xG(c,p)};case"assistant":{let f=c.parts.flatMap((x)=>{if(x.type==="text")return[{type:"text",text:x.text}];if(x.type==="thinking")return[];return[{type:"toolCall",id:x.id,name:x.name,arguments:IG(x.input)}]}),g=f.some((x)=>x.type==="toolCall");return{entry:c,raw:{role:"assistant",content:f,api:n.api,provider:n.provider,model:n.id,usage:i,stopReason:c.error?"error":g?"toolUse":"stop",...c.error?{errorMessage:c.error}:{},timestamp:p}}}case"tool_result":return{entry:c,raw:{role:"toolResult",toolCallId:c.callID,toolName:c.name,content:[{type:"text",text:c.output}],isError:c.isError,timestamp:p}};default:return{entry:c}}})}function xG(e,n){let i=(e.attachments??[]).flatMap((f)=>f.kind==="path"?[`<file path=${JSON.stringify(f.data)} />`]:f.kind==="text"?[`<file name=${JSON.stringify(f.name)}>
|
|
292
|
+
${f.data}
|
|
293
|
+
</file>`]:[]),c=(e.attachments??[]).filter((f)=>f.kind==="image").map((f)=>({type:"image",data:f.data,mimeType:f.mimeType})),p=[...i,...e.text.trim()?[e.text]:[]].join(`
|
|
294
|
+
|
|
295
|
+
`);return{role:"user",content:c.length?[{type:"text",text:p},...c]:p,timestamp:n}}function fr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Or(e){return typeof e==="string"?e:""}function Hs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function IG(e){return fr(e)?e:{}}function rr(e,n){let i=e.at(-1)?.entry.seq??0,c,p,f;for(let{entry:b}of e){if(b.type==="run"&&b.state==="start")c=b.seq;if(b.seq===n)if(b.type==="user"&&!b.notices)i=(c??b.seq)-1;else p=c;if(b.type==="run"&&b.state==="end"){if(p!==void 0&&c===p)f=b.seq;c=void 0}}let g=e.find((b)=>b.entry.seq===n)?.entry;if(n!==void 0&&!g)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(g&&!(g.type==="user"&&!g.notices)){if(p!==void 0&&f===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=f??g.seq}else if(n===void 0&&c!==void 0)i=e.findLast(({entry:b})=>b.type==="run"&&b.state==="end")?.entry.seq??0;let x=e.filter(({entry:b})=>b.seq<=i&&(b.type!=="compaction"||b.through<=i)),I=new Map(x.map(({entry:b},E)=>[b.seq,E+1]));return x.map((b,E)=>{let T=structuredClone(b);if(T.entry.seq=E+1,T.entry.type==="compaction"){let k=T.entry.through,A=x.findLast(({entry:L})=>L.seq<=k);T.entry.through=A?I.get(A.entry.seq)??0:0}return T})}function nr(e){let n=new Map,i=[];for(let c of e){if(c.type==="assistant"){for(let g of c.parts)if(g.type==="tool_call"&&g.name==="todo")n.set(g.id,g.input)}if(c.type!=="tool_result"||c.name!=="todo"||c.isError)continue;let p=n.get(c.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let f=[];for(let g of p.todos){if(!g||typeof g!=="object"||!("content"in g)||typeof g.content!=="string"||!("status"in g)||g.status!=="pending"&&g.status!=="in_progress"&&g.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");f.push({content:g.content,status:g.status})}i=f}return i}import{Buffer as Ll}from"buffer";import{createHash as MP}from"crypto";import{isDeepStrictEqual as _l}from"util";var qi="@blob:";function du(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Nl(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(qi)){let f=Ll.from(p.data,"base64");if(f.byteLength>0&&f.toString("base64")===p.data){let g=MP("sha256").update(f).digest("hex");return n.put(g,p.mimeType,new Uint8Array(f.buffer,f.byteOffset,f.byteLength)),i=!0,{...p,data:`${qi}${g}`}}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(qi)){let f=Ll.from(p.data,"base64");if(f.byteLength>0&&f.toString("base64")===p.data){let g=MP("sha256").update(f).digest("hex");return n.put(g,p.mimeType,new Uint8Array(f.buffer,f.byteOffset,f.byteLength)),i=!0,{...p,data:`${qi}${g}`}}}return p});if(!i)return e;return{...e,images:c}}return e}function Ia(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.startsWith(qi)){let f=p.data.slice(qi.length),g=n.get(f);if(g!==void 0)return i=!0,{...p,data:Ll.from(g.buffer,g.byteOffset,g.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.startsWith(qi)){let f=p.data.slice(qi.length),g=n.get(f);if(g!==void 0)return i=!0,{...p,data:Ll.from(g.buffer,g.byteOffset,g.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,images:c}}return e}function zc(e,n){if(!du(n))return n;if(e.type==="user"){let{merged:i,images:c}=Dc(e.text,e.attachments),p=c.length>0?[{type:"text",text:i},...c]:i,f=Object.keys(n),{role:g,timestamp:x,content:I}=n;if(f.length===3&&g==="user"&&typeof x==="number"&&"content"in n&&_l(I,p))return{role:"user",timestamp:x};return n}if(e.type==="tool_result"){let{role:i,toolCallId:c,toolName:p,isError:f,timestamp:g,content:x}=n;if(i!=="toolResult"||c!==e.callID||typeof p!=="string"||f!==e.isError||typeof g!=="number")return n;let I=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in n?!_l(n.details,e.meta):e.meta!==void 0)return n;let{role:E,toolCallId:T,toolName:k,content:A,details:L,isError:q,timestamp:Y,...j}=n;if(_l(x,I))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:g};if(Array.isArray(x)){let V=e.images??[],X=0,se=!0,Z=x.map((z)=>{if(du(z)&&z.type==="image"){let ce=V[X++],he=Object.keys(z);if(ce&&he.length===3&&z.mimeType===ce.mimeType&&z.data===ce.data)return{type:"image",mimeType:z.mimeType};se=!1}return z});if(se&&X===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:Z,...j,timestamp:g}}return n}if(e.type==="assistant"){let{role:i,content:c}=n;if(i!=="assistant"||!Array.isArray(c)||c.length!==e.parts.length)return n;let p=!1,f=c.map((g,x)=>{let I=e.parts[x];if(du(g)){if(g.type==="text"&&I?.type==="text"&&g.text===I.text){p=!0;let b={...g};return delete b.text,b}if(g.type==="thinking"&&I?.type==="thinking"&&g.thinking===I.text){p=!0;let b={...g};return delete b.thinking,b}if(g.type==="toolCall"&&I?.type==="tool_call"&&g.id===I.id&&g.name===I.name&&"arguments"in g&&_l(g.arguments,I.input)){p=!0;let b={...g};return delete b.id,delete b.name,delete b.arguments,b}}return g});if(!p)return n;return{...n,content:f}}return n}function ug(e,n){if(!du(n))return n;if(e.type==="user"){let{role:i,timestamp:c}=n;if(i==="user"&&!("content"in n)&&typeof c==="number"&&Object.keys(n).length===2){let{merged:p,images:f}=Dc(e.text,e.attachments);return{role:"user",content:f.length>0?[{type:"text",text:p},...f]:p,timestamp:c}}return n}if(e.type==="tool_result"){let{role:i,timestamp:c}=n;if(i==="toolResult"&&(!("content"in n)||!("toolCallId"in n))&&typeof c==="number"){let{role:f,toolName:g,content:x,timestamp:I,...b}=n,E;if(Array.isArray(x)){let T=e.images??[],k=0;E=x.map((A)=>{if(du(A)&&A.type==="image"&&!("data"in A)){let L=T[k++];if(L)return{type:"image",mimeType:A.mimeType,data:L.data}}return A})}else E=[{type:"text",text:e.output},...(e.images??[]).map((T)=>({type:"image",mimeType:T.mimeType,data:T.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof g==="string"?g:e.name,content:E,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...b,timestamp:c}}return n}if(e.type==="assistant"){let{role:i,content:c}=n;if(i!=="assistant"||!Array.isArray(c))return n;let p=!1,f=c.map((g,x)=>{let I=e.parts[x];if(du(g)){if(g.type==="text"&&!("text"in g)&&I?.type==="text"){p=!0;let{type:b,...E}=g;return{type:b,text:I.text,...E}}if(g.type==="thinking"&&!("thinking"in g)&&I?.type==="thinking"){p=!0;let{type:b,...E}=g;return{type:b,thinking:I.text,...E}}if(g.type==="toolCall"&&!("arguments"in g)&&I?.type==="tool_call"){p=!0;let{type:b,...E}=g;return{type:b,id:I.id,name:I.name,arguments:structuredClone(I.input),...E}}}return g});if(!p)return n;return{...n,content:f}}return n}function vP(e){let n=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),c={put(I,b,E){n.run(I,b,E)},get(I){return i.get(I)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),f=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),g=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),x=0;return e.transaction(()=>{for(let I of p){let b;try{b=JSON.parse(I.body)}catch{continue}let E=Ia(b,c),T=Nl(E,c),k=T===b?I.body:JSON.stringify(T),A=I.raw;if(I.raw!==null)try{let L=JSON.parse(I.raw),q=ug(E,L),Y=zc(E,q);A=JSON.stringify(Y)}catch{A=I.raw}if(k!==I.body)f.run(k,A,I.session_id,I.seq),x++;else if(A!==I.raw)g.run(A,I.session_id,I.seq),x++}})(),x}import{Database as bG}from"bun:sqlite";import{chmodSync as OP,existsSync as EG,mkdirSync as SG}from"fs";import{dirname as wG}from"path";var cg=[`
|
|
296
|
+
CREATE TABLE projects (
|
|
297
|
+
id TEXT PRIMARY KEY,
|
|
298
|
+
name TEXT NOT NULL,
|
|
299
|
+
directory TEXT NOT NULL UNIQUE,
|
|
300
|
+
instructions TEXT NOT NULL DEFAULT '',
|
|
301
|
+
created INTEGER NOT NULL,
|
|
302
|
+
updated INTEGER NOT NULL
|
|
303
|
+
);
|
|
304
|
+
CREATE TABLE automations (
|
|
305
|
+
id TEXT PRIMARY KEY,
|
|
306
|
+
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
307
|
+
name TEXT NOT NULL,
|
|
308
|
+
prompt TEXT NOT NULL,
|
|
309
|
+
schedule TEXT NOT NULL,
|
|
310
|
+
model TEXT NOT NULL,
|
|
311
|
+
enabled INTEGER NOT NULL,
|
|
312
|
+
created INTEGER NOT NULL,
|
|
313
|
+
updated INTEGER NOT NULL,
|
|
314
|
+
next_run INTEGER,
|
|
315
|
+
last_run INTEGER,
|
|
316
|
+
last_session_id TEXT
|
|
317
|
+
);
|
|
318
|
+
CREATE TABLE sessions (
|
|
319
|
+
id TEXT PRIMARY KEY,
|
|
320
|
+
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
321
|
+
automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
|
|
322
|
+
title TEXT NOT NULL DEFAULT '',
|
|
323
|
+
model TEXT NOT NULL,
|
|
324
|
+
todos TEXT NOT NULL DEFAULT '[]',
|
|
325
|
+
created INTEGER NOT NULL,
|
|
326
|
+
updated INTEGER NOT NULL
|
|
327
|
+
);
|
|
328
|
+
CREATE INDEX sessions_project ON sessions(project_id);
|
|
329
|
+
CREATE TABLE entries (
|
|
330
|
+
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
331
|
+
seq INTEGER NOT NULL,
|
|
332
|
+
time INTEGER NOT NULL,
|
|
333
|
+
body TEXT NOT NULL,
|
|
334
|
+
raw TEXT,
|
|
335
|
+
PRIMARY KEY (session_id, seq)
|
|
336
|
+
) WITHOUT ROWID;
|
|
337
|
+
`,"","","",`
|
|
338
|
+
ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
|
|
339
|
+
ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
|
|
340
|
+
ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
|
|
341
|
+
CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
|
|
342
|
+
ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
|
|
343
|
+
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,
|
|
344
|
+
PRIMARY KEY (namespace, key));
|
|
345
|
+
CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
|
|
346
|
+
PRIMARY KEY (namespace, version));
|
|
347
|
+
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);
|
|
348
|
+
CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
|
|
349
|
+
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
350
|
+
END;
|
|
351
|
+
CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
|
|
352
|
+
INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
|
|
353
|
+
END;
|
|
354
|
+
CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
|
|
355
|
+
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
356
|
+
END;
|
|
357
|
+
CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
|
|
358
|
+
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
359
|
+
END;
|
|
360
|
+
CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
|
|
361
|
+
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
362
|
+
END;
|
|
363
|
+
CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
|
|
364
|
+
INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
|
|
365
|
+
END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
|
|
366
|
+
WHERE json_extract(body,'$.type')='compaction';
|
|
367
|
+
CREATE TABLE IF NOT EXISTS blobs (
|
|
368
|
+
hash TEXT PRIMARY KEY,
|
|
369
|
+
mime TEXT NOT NULL,
|
|
370
|
+
data BLOB NOT NULL
|
|
371
|
+
) WITHOUT ROWID;
|
|
372
|
+
CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`];var TG=[20,50,100,200,400,800];function RG(e){if(!e||typeof e!=="object")return!1;let n="code"in e&&typeof e.code==="string"?e.code:"";if(n==="SQLITE_BUSY"||n.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let c="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(c)}function mg(e){let n=0;while(!0)try{return e()}catch(i){let c=TG[n];if(c===void 0||!RG(i))throw i;n++,Bun.sleepSync(c)}}function _P(e,n){if(e!==":memory:")SG(wG(e),{recursive:!0});let i=new bG(e,{create:!0,strict:!0}),c=(f,g=!0)=>new Proxy(function(...x){return Reflect.apply(f,this,x)},{apply(x,I,b){Ps();let E=n.length===0&&!i.inTransaction,T=g?Reflect.get(f,"immediate"):void 0,k=()=>{let A=[];n.push(A);let L=!1;try{let q=typeof T==="function"?Reflect.apply(T,f,b):Reflect.apply(x,I,b);return L=!0,q}finally{n.pop();let q=n.at(-1);if(L&&q)q.push(...A);else for(let Y of A)if(L)Y.commit();else Y.rollback()}};return E?mg(k):k()},get(x,I){let b=Reflect.get(f,I);if(["deferred","immediate","exclusive"].includes(String(I))&&typeof b==="function")return c(b,!1);return b}}),p=new Proxy(i,{get(f,g){let x=Reflect.get(f,g,f);if(typeof x!=="function")return x;return(...I)=>{Ps();let T=(g==="run"||g==="exec")&&n.length===0&&!i.inTransaction?mg(()=>Reflect.apply(x,f,I)):Reflect.apply(x,f,I);if(g==="transaction"&&typeof T==="function")return c(T,!0);if(g!=="query"&&g!=="prepare")return T;if(!T||typeof T!=="object")throw Error("Invalid SQL statement");return new Proxy(T,{get(k,A,L){let q=Reflect.get(k,A,k);if(typeof q!=="function")return q;return(...Y)=>{Ps();let X=(A==="run"||A==="get"||A==="all"||A==="values")&&n.length===0&&!i.inTransaction?mg(()=>Reflect.apply(q,k,Y)):Reflect.apply(q,k,Y);return X===k?L:X}}})}}});if(e!==":memory:")OP(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"),kG(p),p.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),p.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let f of["-wal","-shm"]){let g=e+f;if(EG(g))OP(g,384)}return p}function kG(e,n=cg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>n.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${n.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let c=i;c<n.length;c++)e.transaction(()=>{let p=n[c]??"",f=Array.isArray(p)?p:c>=4?AG(p):[p];for(let g of f)try{if(g.trim())e.run(g)}catch(x){if(!(x instanceof Error)||!/already exists|duplicate column name/i.test(x.message))throw x}e.run(`PRAGMA user_version = ${c+1}`)})()}function AG(e){let n=[],i=0,c=0,p=[],f=!1,g=0,x=(I)=>{let b=e.slice(i,I).trim();if(b)n.push(b);i=I+1,p=[],f=!1,g=0};while(c<e.length){let I=e[c];if(I==="'"||I==='"'||I==="`"||I==="["){let b=I==="["?"]":I;c++;while(c<e.length)if(e[c]===b)if(b!=="]"&&e[c+1]===b)c+=2;else break;else c++;c++;continue}if(I==="-"&&e[c+1]==="-"){let b=e.indexOf(`
|
|
373
|
+
`,c);c=b===-1?e.length:b+1;continue}if(I==="/"&&e[c+1]==="*"){let b=e.indexOf("*/",c+2);c=b===-1?e.length:b+2;continue}if(/[A-Za-z_]/.test(I)){let b=c+1;while(b<e.length&&/[A-Za-z0-9_$]/.test(e[b]))b++;let E=e.slice(c,b).toUpperCase();if(p.length<3)p.push(E),f=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(f){if(E==="BEGIN"||E==="CASE"&&g>0)g++;else if(E==="END"&&g>0)g--}c=b;continue}if(I===";"&&g===0)x(c);c++}return x(e.length),n}var Dl=(e)=>({...e}),ql=(e)=>{let n;if(e.metadata)try{n=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!n?.["automations.id"])n={...n,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:n,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"}};class Fl{path;plugins;entryTransactions=[];db;blobs;constructor(e){this.path=e;this.db=_P(e,this.entryTransactions),this.blobs={put:(n,i,c)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(n,i,c)},get:(n)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(n)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY updated DESC").all().map(Dl)}project(e){let n=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return n?Dl(n):void 0}projectByDirectory(e){let n=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return n?Dl(n):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.id)}deleteProject(e){this.db.query("DELETE FROM projects WHERE id = ?").run(e)}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(ql)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(ql)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(ql)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((n)=>n.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,n,i){this.insertSessionWithRecords(n,rr(this.records(e),i))}insertSessionWithRecords(e,n){this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(n.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:c,raw:p}of n){let{seq:f,time:g,...x}=c,I=x,b=Nl(I,this.blobs),E=p===void 0?null:JSON.stringify(zc(I,p));i.run(e.id,f,g,JSON.stringify(b),E)}})()}truncationEpoch(e){let n=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!n)throw Error("Session no longer exists");return n.truncation_epoch}truncateSession(e,n){this.db.transaction(()=>{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,n,n),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(n-1,e.id),this.updateSession(e)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,n){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let c of e)i.run(n,c)})()}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.db.query("DELETE FROM sessions WHERE id = ?").run(e)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,n,i,c){Ps();let p=this.plugins,f=p?.pinEntry(i),g;try{return g=this.db.transaction(()=>{let x=Math.max(n??0,this.lastSeq(e)+1),b=(f&&p?p.beforeEntry(f,i,e,x):void 0)??i,E=JSON.stringify(b),T=f?JSON.parse(E):b,k={...T,seq:x,time:Date.now()},A=Nl(T,this.blobs),L=A===T&&!f?E:JSON.stringify(A),q=c===void 0?null:JSON.stringify(zc(T,c));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,x,k.time,L,q),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return k})(),g}finally{if(f&&p){let x={commit:()=>p.finishEntry(f,e,g),rollback:()=>p.finishEntry(f,e)},I=this.entryTransactions.at(-1);if(I)I.push(x);else x.commit()}}}setEntryRaw(e,n,i){let c=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,n);if(!c)throw Error("pending message entry is missing or already completed");let p=Ia(JSON.parse(c.body),this.blobs),f=zc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(f),e,n).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,n=0){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,n).map((i)=>({...Ia(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}))}deleteEntry(e,n){this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,n)}entriesRange(e,n,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,n,i).map((c)=>({...Ia(JSON.parse(c.body),this.blobs),seq:c.seq,time:c.time}))}alignToUser(e,n){if(n<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,n)?.seq??1}alignToTurnEnd(e,n){let i=this.lastSeq(e),c=(I)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,I),p=c(n),f=p?.type==="run"&&p.state==="start"?n+1:n;if(f>=i)return i;let g=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,f,f);if(!g)return i;if(g.end)return g.seq;let x=c(g.seq-1);return x?.type==="run"&&x.state==="start"&&g.seq-1>f?g.seq-2:g.seq-1}entriesAround(e,n,i,c){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let f=Math.min(Math.max(1,n),p),g=this.alignToUser(e,Math.max(1,f-i)),x=this.alignToTurnEnd(e,Math.min(p,f+c));return this.window(e,g,x,p)}entriesFrom(e,n,i){let c=this.lastSeq(e),p=Math.max(1,n);if(p>c)return{entries:[],from:p,to:c,hasBefore:c>0,hasAfter:!1};let f=this.alignToTurnEnd(e,Math.min(c,p+i-1));return this.window(e,p,f,c)}window(e,n,i,c){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,n);return{entries:this.entriesRange(e,n,i+1),from:n,to:i,hasBefore:p!==null,hasAfter:i<c}}replayStart(e,n,i){let c=this.lastSeq(e),p=this.lastEntry(e,"compaction"),f=p?.type==="compaction"?p.through+1:1,g=Math.max(1,c-i+1,Math.min(f,c-n+1));return this.alignToUser(e,g)}records(e,n=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,n).map((i)=>{let c=Ia(JSON.parse(i.body),this.blobs);return{entry:{...c,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:ug(c,JSON.parse(i.raw))}}})}lastEntry(e,n){let i=this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,n);return i?{...Ia(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,n){let i=this.truncationEpoch(e),c=n;if(this.plugins){let p=this.plugins.pin();try{let f=await p.invoke("notice.enqueue",n,this.plugins.runtime.get(e));if(f===null)return!1;n={...f,dedupeKey:c.dedupeKey,wake:c.wake&&f.wake,recovery:c.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).some((x)=>x.type==="notice_pending"&&x.notice.dedupeKey===n.dedupeKey||x.type==="user"&&x.notices?.some((I)=>I.dedupeKey===n.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:n}),!0})()}pendingNotices(e){let n=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,n),c=new Set;for(let f of i)if(f.type==="user"&&f.notices)for(let g of f.notices)c.add(g.dedupeKey);else if(f.type==="extension"&&f.namespace==="basalt.notice"&&f.kind==="discarded"&&f.payload&&typeof f.payload==="object"&&"dedupeKey"in f.payload&&typeof f.payload.dedupeKey==="string")c.add(f.payload.dedupeKey);let p=[];for(let f of i)if(f.type==="notice_pending"&&!c.has(f.notice.dedupeKey))p.push(f.notice);return p}}function ue(e){let n=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(n).toString("base64url")}`}import{existsSync as CG,readdirSync as NP,statSync as DP}from"fs";import{join as qP}from"path";function Vc(e){try{return DP(e).size}catch{return 0}}function FP(e){try{return Math.round(DP(e).mtimeMs)}catch{return}}function jP(e){let n=0,i=0;try{let c=NP(e,{withFileTypes:!0});for(let p of c){let f=qP(e,p.name);if(p.isDirectory()){let g=jP(f);n+=g.bytes,i+=g.files}else if(p.isFile())n+=Vc(f),i+=1}}catch{return{bytes:0,files:0}}return{bytes:n,files:i}}function $G(e){if(!CG(e))return[];try{return NP(e,{withFileTypes:!0}).flatMap((n)=>{let i=qP(PG(e),n.name),c=FP(i);if(n.isDirectory()){let p=jP(i);return[{name:n.name,kind:"directory",bytes:p.bytes,files:p.files,...c!==void 0?{modified:c}:{}}]}if(n.isFile())return[{name:n.name,kind:"file",bytes:Vc(i),...c!==void 0?{modified:c}:{}}];return[]}).sort((n,i)=>i.bytes-n.bytes||n.name.localeCompare(i.name))}catch{return[]}}function PG(e){return e}function Ws(e,n){let i=e.db.query(`PRAGMA ${n}`).get();if(!i)return 0;let c=Object.values(i)[0];return typeof c==="number"?c:0}function LP(e,n){try{let i=e.db.query(`PRAGMA ${n}`).get();if(!i)return;let c=Object.values(i)[0];return c!==void 0&&c!==null?String(c):void 0}catch{return}}var MG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},vG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function OG(e){let n=new Map;try{let i=new Map,c=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let f of c)i.set(f.name,f.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let f of p){let g=i.get(f.name)??f.name;if(g.startsWith("sqlite_autoindex_")){let I=g.slice(17),b=I.lastIndexOf("_");if(b>0)g=I.slice(0,b)}let x=n.get(g)??{bytes:0,pages:0};n.set(g,{bytes:x.bytes+(Number(f.bytes)||0),pages:x.pages+(Number(f.pages)||0)})}}catch{}return n}function _G(e){let n=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
|
|
374
|
+
count(*) AS total,
|
|
375
|
+
sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
|
|
376
|
+
sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
|
|
377
|
+
sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
|
|
378
|
+
sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
|
|
379
|
+
FROM sessions`).get(),c=e.db.query(`SELECT
|
|
380
|
+
count(*) AS total,
|
|
381
|
+
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
382
|
+
coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
|
|
383
|
+
min(time) AS oldest_time,
|
|
384
|
+
max(time) AS newest_time
|
|
385
|
+
FROM entries`).get(),f=e.db.query(`SELECT
|
|
386
|
+
coalesce(json_extract(body, '$.type'), 'unknown') AS type,
|
|
387
|
+
count(*) AS count,
|
|
388
|
+
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
389
|
+
coalesce(sum(octet_length(raw)), 0) AS raw_bytes
|
|
390
|
+
FROM entries
|
|
391
|
+
GROUP BY type
|
|
392
|
+
ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((I)=>({type:String(I.type||"unknown"),count:Number(I.count)||0,bodyBytes:Number(I.body_bytes)||0,rawBytes:Number(I.raw_bytes)||0})),g=f.find((I)=>I.type==="compaction")?.count??0,x=[];try{let I=new Map,b=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let k of b)I.set(k.namespace,Number(k.max_ver)||0);let E=e.db.query(`SELECT
|
|
393
|
+
namespace,
|
|
394
|
+
count(*) AS keys,
|
|
395
|
+
coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
|
|
396
|
+
FROM plugin_kv
|
|
397
|
+
GROUP BY namespace
|
|
398
|
+
ORDER BY bytes DESC, keys DESC`).all(),T=new Set;for(let k of E){T.add(k.namespace);let A=I.get(k.namespace);x.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...A!==void 0?{migrationVersion:A}:{}})}for(let[k,A]of I.entries())if(!T.has(k))x.push({namespace:k,keys:0,bytes:0,migrationVersion:A})}catch{}return{projectCount:n,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(c?.total)||0,totalBodyBytes:Number(c?.body_bytes)||0,totalRawBytes:Number(c?.raw_bytes)||0,compactionCount:g,...c?.oldest_time?{oldestEntryTime:Number(c.oldest_time)}:{},...c?.newest_time?{newestEntryTime:Number(c.newest_time)}:{},entryTypes:f,pluginNamespaces:x}}function jl(e,n){let i=Ws(e,"page_size"),c=Ws(e,"page_count"),p=Ws(e,"freelist_count"),f=e.db.query("PRAGMA journal_mode").get(),g=e.db.query("SELECT sqlite_version() AS v").get(),x=Ws(e,"synchronous"),I=Ws(e,"auto_vacuum"),b=Ws(e,"cache_size"),E=b<0?Math.abs(b)*1024:b*i,T=Ws(e,"foreign_keys")===1,k=Ws(e,"busy_timeout"),A=LP(e,"encoding")??"UTF-8",L=LP(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?FP(e.path):void 0,Y=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),j=OG(e),V=$G(n);return{dataDir:n,databasePath:e.path,dataBytes:V.reduce((X,se)=>X+se.bytes,0),database:{size:Vc(e.path),walSize:Vc(`${e.path}-wal`),shmSize:Vc(`${e.path}-shm`),sqliteVersion:g?.v??"unknown",journalMode:f?.journal_mode??"unknown",synchronous:MG[x]??String(x),foreignKeys:T,busyTimeout:k,encoding:A,autoVacuum:vG[I]??String(I),cacheSizeBytes:E,pageSize:i,pageCount:c,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Ws(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:L},analytics:_G(e),entries:V,tables:Y.map(({name:X,sql:se})=>{let Z=X.replaceAll('"','""'),z=e.db.query(`SELECT count(*) AS count FROM "${Z}"`).get().count,ce=e.db.query(`PRAGMA table_info("${Z}")`).all().map((ie)=>ie.name),he=e.db.query(`PRAGMA index_list("${Z}")`).all().length,ve=Boolean(se&&/WITHOUT\s+ROWID/i.test(se)),fe=j.get(X);return{name:X,rows:z,...fe?{bytes:fe.bytes,pages:fe.pages}:{},indexes:he,columns:ce,withoutRowid:ve}})}}function LG(e){let n;try{n=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(n.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),c=new Set;for(let f of i)for(let g of f.body.matchAll(/@blob:([0-9a-f]{64})/g)){let x=g[1];if(x)c.add(x)}let p=[];for(let f of n)if(!c.has(f.hash))p.push(f.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let f=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let g of p)f.run(g)})()}catch{return 0}return p.length}function UP(e,n,i){let c=jl(e,n);if(i.vacuum)vP(e.db),LG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:c,after:jl(e,n)}}var NG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Ul{plugins;builtinNames;registered=new Map;constructor(e,n){this.plugins=e;this.builtinNames=n}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let n=e.name.trim().toLowerCase();if(!n)throw Error("Tool name cannot be empty");if(NG.has(n))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((c)=>c.toLowerCase()),...this.list().map((c)=>c.name.toLowerCase())]).has(n))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(n,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function BP(e,n){let i=Vr(n);return{id:e,name:n.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:n.contextWindow,maxTokens:n.maxTokens}}async function GP(e,n){let c=(await e.options.models.getAvailable().catch(()=>[])).map((f)=>({...BP(tt(f),f),available:!0})),p=new Set(c.map((f)=>f.id));for(let f of[n,...e.list(!0,{archive:"all"}).map((g)=>g.model)]){if(p.has(f))continue;let g=xn(e.options.models,f);if(!g)continue;p.add(f),c.push({...BP(f,g),available:!1})}return{models:c}}function KP(e,n){if(typeof n!=="string"||!xn(e.options.models,n))throw new t(`unknown model ${n}`);return n}import{existsSync as DG,statSync as qG}from"fs";import{basename as FG,resolve as jG}from"path";class pg{runtime;sessions;emit;arm;constructor(e,n,i,c){this.runtime=e;this.sessions=n;this.emit=i;this.arm=c}requireProject(e){let n=this.runtime.store.project(e);if(!n)throw new y("no such project");return n}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let n=jG(e.directory.trim());if(!DG(n)||!qG(n).isDirectory())throw new t(`${n} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(n);if(i)return i;let c=Date.now(),p={id:ue("p"),name:e.name?.trim()||FG(n)||n,directory:n,instructions:e.instructions??"",created:c,updated:c};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,n){let c={...this.requireProject(e),...typeof n.name==="string"&&n.name.trim()?{name:n.name.trim()}:{},...typeof n.instructions==="string"?{instructions:n.instructions}:{},updated:Date.now()};this.runtime.store.updateProject(c);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:c}),c}async deleteProject(e){let n=this.requireProject(e),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new oe("a session in this project");await this.runtime.plugins.invokeProjectDelete(n),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 uK}from"fs";import{homedir as cK}from"os";import{join as fu}from"path";var XP=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),UG={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"]},BG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),fg={'"':['"'],"\u201C":["\u201D",'"']},lg=(e)=>e!==void 0&&/\s/.test(e),YP=(e)=>[...new Set(e)],Jc=(e)=>[...e].length;var GG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function KG(e,n){let i=e.trim().toLowerCase(),c=new Date(n),p=c.getFullYear(),f=c.getMonth(),g=c.getDate();if(i==="today")return{start:new Date(p,f,g).getTime(),end:new Date(p,f,g+1).getTime()};if(i==="yesterday")return{start:new Date(p,f,g-1).getTime(),end:new Date(p,f,g).getTime()};let x=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(x)return{start:n-Number(x[1])*GG[x[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 I=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!I)return null;let b=Number(I[1]),E=Number(I[3]);if(E<1||E>12)return null;if(I[4]===void 0){if(I[5]!==void 0)return null;return{start:new Date(b,E-1,1).getTime(),end:new Date(b,E,1).getTime()}}let T=Number(I[4]),k=Number(I[5]??0),A=Number(I[6]??0),L=Number(I[7]??0);if(k>23||A>59||L>59)return null;let q=new Date(b,E-1,T,k,A,L);if(q.getMonth()!==E-1||q.getDate()!==T)return null;if(I[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(b,E-1,T+1).getTime()}}var HG=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),hg=(e,n)=>e===void 0?n:n===void 0?e:Math.max(e,n),gg=(e,n)=>e===void 0?n:n===void 0?e:Math.min(e,n);function dg(e,n,i,c,p,f){let g=i.trim(),x=(b,E)=>e.diagnostics.push({code:b,message:E,filter:n});if(!g)return x("empty_filter",`${n}: \u7F3A\u5C11\u53D6\u503C`);if(c&&n!=="is")return x("unsupported_negation",`-${n}: \u4E0D\u652F\u6301\u53D6\u53CD`);let I=p?[g]:g.split(",").map((b)=>b.trim()).filter(Boolean);switch(n){case"in":case"project":for(let b of I){let E=b.toLowerCase();if(n==="in"&&E==="this")e.currentSession=!0;else if(n==="in"&&E==="title")e.fields.push("title");else e.projectID.push(b)}return;case"session":for(let b of I)if(b.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(b);return;case"from":case"role":for(let b of I){let E=UG[b.toLowerCase()];if(E)e.fields.push(...E);else x("bad_filter_value",`${n}:${b} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...I);return;case"model":e.model.push(...I);return;case"is":for(let b of I){let E=b.toLowerCase();if(E==="error")e.isError=!c;else if(E==="archived")e.archived=!c;else if(E==="compacted")e.compacted=!c;else x("bad_filter_value",`is:${b} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let b=KG(g,f);if(!b)return x("bad_filter_value",`${n}:${g} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(n==="after")e.after=hg(e.after,b.start);else if(n==="before")e.before=gg(e.before,b.start);else if(e.after=hg(e.after,b.start),b.end!==void 0)e.before=gg(e.before,b.end)}}}function WG(e,n){let i={},c=(L,q)=>{let Y=YP([...L??[],...q]);return Y.length?Y:void 0},p=c(e?.projectID,n.projectID),f=c(e?.sessionID,n.sessionID),g=c(e?.fields,n.fields),x=c(e?.tools,n.tools),I=c(e?.model,n.model);if(p)i.projectID=p;if(f)i.sessionID=f;if(g)i.fields=g;if(x)i.tools=x;if(I)i.model=I;let b=n.isError??e?.isError,E=n.archived??e?.archived,T=n.compacted??e?.compacted;if(b!==void 0)i.isError=b;if(E!==void 0)i.archived=E;if(T!==void 0)i.compacted=T;let k=hg(e?.after,n.after),A=gg(e?.before,n.before);if(k!==void 0)i.after=k;if(A!==void 0)i.before=A;if(k!==void 0&&A!==void 0&&k>=A)n.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function HP(e,n){let i=fg[e[n]]??['"'],c="",p=n+1;while(p<e.length){let f=e[p],g=e[p+1];if(f==="\\"&&g!==void 0&&(g==="\\"||g==='"'||g==="\u201C"||g==="\u201D")){c+=g,p+=2;continue}if(i.includes(f))return{text:c,next:p+1,closed:!0};c+=f,p++}return{text:c,next:p,closed:!1}}function WP(e){let n=e[e.length-1];if(e.length<2||!n||n.esc||n.c!==":"&&n.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 c=i.toLowerCase();return XP.has(c)?c:void 0}function zP(e,n,i){let c=e==="word"&&!i&&Jc(n)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(n)&&!/^\p{N}+$/u.test(n);return{kind:e,text:n,prefix:i,fuzzy:c}}function zG(e,n){let i=[],c=e.length,p=0;while(p<c){if(lg(e[p])){p++;continue}let f=!1;if(e[p]==="-"){if(p+1>=c||lg(e[p+1])){p++;continue}f=!0,p++}if(fg[e[p]]){let A=HP(e,p);if(p=A.next,!A.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let L=A.text.trim();if(L)i.push({kind:"term",negated:f,term:zP("phrase",L,!1)});continue}let g=[],x;while(p<c&&!lg(e[p])){let A=e[p],L=e[p+1];if(A==="\\"&&L!==void 0&&BG.has(L)){g.push({c:L,esc:!0}),p+=2;continue}let q=fg[A]?WP(g):void 0;if(q){let Y=HP(e,p);if(p=Y.next,!Y.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});x={key:q,value:Y.text,quoted:!0};break}g.push({c:A,esc:!1}),p++}if(x){i.push({kind:"filter",negated:f,...x});continue}let I=g.findIndex((A,L)=>L>0&&!A.esc&&(A.c===":"||A.c==="\uFF1A")),b=I>0?WP(g.slice(0,I+1)):void 0;if(b){i.push({kind:"filter",negated:f,key:b,value:g.slice(I+1).map((A)=>A.c).join(""),quoted:!1});continue}if(!f&&g.length===2&&g.every((A)=>!A.esc)&&g[0]?.c==="O"&&g[1]?.c==="R"){i.push({kind:"or"});continue}let E=g[g.length-1],T=g.length>1&&E!==void 0&&!E.esc&&E.c==="*",k=(T?g.slice(0,-1):g).map((A)=>A.c).join("");if(k)i.push({kind:"term",negated:f,term:zP("word",k,T)})}return i}var VG=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function VP(e){let n=[];return{rest:e.replace(VG,(c,p,f,g,x)=>{let I=g.toLowerCase();if(!XP.has(I))return c;let b=x.startsWith('"')&&x.length>=2;return n.push({key:I,value:b?x.slice(1,-1).replace(/\\(["\\])/g,"$1"):x,negated:f==="-",quoted:b}),p}).trim(),filters:n}}var JP={n:`
|
|
399
|
+
`,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function JG(e){let n=[...e],i=0,c=(E)=>{let T=n.slice(i,i+E).join("");if(T.length!==E||!/^[0-9a-fA-F]+$/.test(T))return;return i+=E,String.fromCodePoint(Number.parseInt(T,16))},p=()=>{let E=n[i++];if(E===void 0)return{kind:"lit",ch:"\\"};if(E in JP)return{kind:"lit",ch:JP[E]};if("dDwWsS".includes(E))return{kind:"any"};if(E==="b"||E==="B")return{kind:"zero"};if(E>="1"&&E<="9"){while(n[i]!==void 0&&/\d/.test(n[i]))i++;return{kind:"any"}}if(E==="k"||E==="p"||E==="P"){let T=n[i];if(T==="<"||T==="{"){let k=T==="<"?">":"}",A=n.indexOf(k,i);i=A<0?n.length:A+1}return{kind:"any"}}if(E==="c")return i++,{kind:"any"};if(E==="x"){let T=c(2);return T===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:T}}if(E==="u"){if(n[i]==="{"){let k=n.indexOf("}",i),A=k<0?"":n.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 T=c(4);return T===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:T}}return{kind:"lit",ch:E}},f=()=>{if(n[i]==="^")i++;while(i<n.length&&n[i]!=="]")i+=n[i]==="\\"?2:1;return i++,{kind:"any"}},g=()=>{let E="capture";if(n[i]==="?"){let k=n[i+1],A=n[i+2];if(k===":")E="plain",i+=2;else if(k==="="||k==="!")E="look",i+=2;else if(k==="<"&&(A==="="||A==="!"))E="look",i+=3;else if(k==="<"){let L=n.indexOf(">",i);i=L<0?n.length:L+1}else{E="opaque";while(i<n.length&&n[i]!==":"&&n[i]!==")")i++;if(n[i]===":")i++}}let T=b();if(n[i]===")")i++;if(E==="look")return{kind:"zero"};return{kind:"group",alts:T,opaque:E==="opaque"}},x=()=>{let E=n[i],T=1,k=!0;if(E==="*"||E==="?")T=0,i++;else if(E==="+")i++;else if(E==="{"){let A=/^\{(\d+)(?:,(\d*))?\}/.exec(n.slice(i,i+24).join(""));if(!A)return{quantified:!1,min:1};T=Number(A[1]),i+=A[0].length}else return{quantified:!1,min:1};if(n[i]==="?")i++;return{quantified:k,min:T}},I=()=>{let E=[];while(i<n.length){let T=n[i];if(T==="|"||T===")")break;i++;let k;if(T==="(")k=g();else if(T==="[")k=f();else if(T==="\\")k=p();else if(T===".")k={kind:"any"};else if(T==="^"||T==="$")k={kind:"zero"};else if(T==="*"||T==="+"||T==="?")k={kind:"zero"};else k={kind:"lit",ch:T};E.push({atom:k,...x()})}return E};function b(){let E=[I()];while(n[i]==="|")i++,E.push(I());return E}return b()}function QP(e){let n=[],i="",c=()=>{if(i)n.push([i]);i=""},p=(f)=>{for(let g of f){let x=g.atom;if(x.kind==="lit")if(g.min>=1){if(i+=x.ch,g.quantified)c()}else c();else if(x.kind==="group"&&!x.opaque&&g.min>=1)if(x.alts.length===1&&!g.quantified)p(x.alts[0]);else c(),n.push(...ZP(x.alts));else c()}};return p(e),c(),n}function ZP(e){if(e.length===1)return QP(e[0]);let n=[];for(let i of e){let c=QP(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!c.length)return[];n.push(c.reduce((p,f)=>Jc(f)>Jc(p)?f:p))}return[YP(n)]}var QG=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function XG(e){return!/^\s*$/.test(e)&&(Jc(e)>=2||QG.test(e))}function YG(e){let n;try{n=ZP(JG(e))}catch{return[]}let i=n.filter((I)=>I.every(XG)),c=i.filter((I)=>I.length===1).map((I)=>I[0]),p=i.filter((I)=>{if(I.length!==1)return!0;let b=I[0];return!c.some((E)=>E!==b&&E.includes(b))}),f=new Set,g=p.filter((I)=>{let b=JSON.stringify(I);if(f.has(b))return!1;return f.add(b),!0}),x=(I)=>Math.min(...I.map(Jc));return g.sort((I,b)=>x(b)-x(I))}function ZG(e){let n=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(n)}function eK(e,n){let i=`m${n?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(c){let p=c instanceof Error?c.message:String(c),f="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))f="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))f="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))f="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))f="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${f}`}}}function Bl(e,n={}){let i=n.now??Date.now(),c=e.q??"",p=HG(),f=p.diagnostics,g,x=[];if(e.mode==="regex"){let q=VP(c);for(let Y of q.filters)dg(p,Y.key,Y.value,Y.negated,Y.quoted,i);g=q.rest}else{let q=VP(c),Y=/^\/([\s\S]+)\/$/.exec(q.rest);if(Y){for(let j of q.filters)dg(p,j.key,j.value,j.negated,j.quoted,i);g=Y[1]}else{x=[{include:[],exclude:[]}];for(let j of zG(c,f)){let V=x[x.length-1];if(j.kind==="or")x.push({include:[],exclude:[]});else if(j.kind==="filter")dg(p,j.key,j.value,j.negated,j.quoted,i);else(j.negated?V.exclude:V.include).push(j.term)}x=x.filter((j)=>j.include.length||j.exclude.length)}}let I=x.flatMap((q)=>[...q.include,...q.exclude]),b=g!==void 0?ZG(g):I.some((q)=>/\p{Lu}/u.test(q.text)),E=e.caseSensitive??b,T=e.caseSensitive===void 0&&b,k,A;if(g){let q=eK(g,E);if("message"in q)A={code:"bad_regex",message:q.message};else{let Y=YG(g);k={source:g,flags:q.flags,literals:Y,deepScan:Y.length===0}}}let L=WG(e.filters,p);return{mode:g!==void 0?"regex":"text",branches:x,...k?{regex:k}:{},filters:L,currentSession:p.currentSession,caseSensitive:E,smartCase:T,wholeWord:e.wholeWord??!1,fuzzy:x.some((q)=>q.include.some((Y)=>Y.fuzzy)),hasPositive:k!==void 0||x.some((q)=>q.include.length>0),hasFilters:Object.keys(L).length>0||p.currentSession,...A?{error:A}:{},diagnostics:f}}var xg={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},eM=new WeakMap;function tM(e){let n=e.query("PRAGMA data_version").get()?.data_version??0,i=eM.get(e);if(i?.version===n)return i.terms;let c=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return eM.set(e,{version:n,terms:c}),c}var yg=32,tK=1024,Qc=(e)=>`"${e.replaceAll('"','""')}"`;function rK(e,n){let i=Array.from({length:n.length+1},(c,p)=>p);for(let c=0;c<e.length;c++){let p=[c+1];for(let f=0;f<n.length;f++)p.push(Math.min((p[f]??0)+1,(i[f+1]??0)+1,(i[f]??0)+Number(e[c]!==n[f])));i=p}return i[n.length]??e.length}function Ig(e,n){let i=ft(n.trim());if(!i||i.length>64)return[];let c=tM(e),p=c.filter((x)=>x.t.startsWith(i)).slice(0,8).map((x)=>x.t);if(p.length>=8||i.length<4)return p;let f=i.length>=8?2:1,g=[];for(let x of c){if(Math.abs(x.t.length-i.length)>f)continue;if(rK(i,x.t)<=f)g.push(x.t);if(g.length>=8)break}return[...new Set([...p,...g])].slice(0,8)}function rM(e,n){let i=!1,c=[],p=[],f=n.filters,g=(Y,j)=>{if(!j?.length)return;p.push(`${Y} IN (${j.map(()=>"?").join(",")})`),c.push(...j)};if(g("s.project_id",f.projectID),f.sessionID?.length){p.push(`(${f.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let Y of f.sessionID)c.push(Y,Y)}if(f.archived!==void 0)p.push(`s.archived_at IS ${f.archived?"NOT ":""}NULL`);let x=p.length?p.join(" AND "):"1",I=[...c];if(g("r.kind",f.fields?.map((Y)=>Oe[Y])),g("r.tool",f.tools),f.model?.length){p.push(`(${f.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let Y of f.model)c.push(Y,Y)}if(f.isError!==void 0)p.push("r.err = ?"),c.push(Number(f.isError));if(f.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
|
|
400
|
+
SELECT max(json_extract(body,'$.through')) FROM store.entries
|
|
401
|
+
WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
|
|
402
|
+
),0)) = ?`),c.push(Number(f.compacted));if(f.after!==void 0)p.push("r.time >= ?"),c.push(f.after);if(f.before!==void 0)p.push("r.time < ?"),c.push(f.before);let b=e.query("SELECT v FROM meta WHERE k='layout'").get(),E=b&&JSON.parse(b.v).msg==="trigram",T=!n.hasPositive||Boolean(n.regex?.deepScan),k=(Y)=>{let j=(se)=>{let Z=ft(se);if(!Y&&E){if([...Z].length<3){let ie=[...Z].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(Z,`${Z}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(Z);if([...Z].length===1&&ie.length>yg)ie.length=yg,i=!0;if(!ie.length)return Qc("__basalt_no_short_match__");return`(${ie.map((me)=>Qc(me.term)).join(" OR ")})`}return Qc(Z)}let z=/^[\p{Script=Latin}\p{N}]+$/u.test(se)?[Z]:Ho(se),ce=z.filter((ie)=>!/^[a-z0-9]{1,2}$/.test(ie)),he=ce.length?ce:z;if(!he.length){T=!0;return}let ve=he.map((ie,me)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(ie),xt=he.length>2&&me>0&&me<he.length-1;if(qe||xt){let Fe=e.query("SELECT n FROM term WHERE t=?").get(ie)?.n??0;return{expression:Qc(ie),frequency:Fe}}let Je=[ie],Yt=0;for(let Fe of tM(e)){if(!Fe.t.includes(ie))continue;if(Yt+=Fe.n,Fe.t!==ie)Je.push(Fe.t);if(Je.length>=yg){i=!0;break}}return{expression:`(${Je.map(Qc).join(" OR ")})`,frequency:Yt}});return ve.sort((ie,me)=>ie.frequency-me.frequency),`(${ve.slice(0,(ve[0]?.frequency??1/0)<=tK?1:2).map((ie)=>ie.expression).join(" AND ")})`},V=n.regex?n.regex.literals:n.branches.map((se)=>se.include.map((Z)=>Z.text));if(n.regex){let se=V.map((Z)=>Z.map(j));if(se.some((Z)=>Z.some((z)=>!z)))return;return se.map((Z)=>`(${Z.join(" OR ")})`).join(" AND ")||void 0}let X=V.map((se)=>{let Z=se.filter((z)=>!/^[a-z0-9]{1,2}$/i.test(z));return(Z.length?Z:se).map(j)});if(X.some((se)=>!se.length||se.some((Z)=>!Z)))return;return X.map((se)=>`(${se.join(" AND ")})`).join(" OR ")||void 0},A=k(!1),L=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:L,scan:T,where:p.length?p.join(" AND "):"1",bindings:c,forks:q,sessionWhere:x,sessionBindings:I,partial:i,candidateLimit:n.branches.some((Y)=>Y.include.length>0&&Y.include.every((j)=>[...j.text].length<2))?512:void 0}}function nM(e){let n=1/0,i=-1/0;for(let c of e)n=Math.min(n,c.relevance),i=Math.max(i,c.relevance);return e.map((c)=>({...c,relevance:n===i?-1:-(0.5+0.5*(i-c.relevance)/(i-n))}))}function Gl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(xg).map(([i,c])=>`WHEN ${Oe[i]} THEN ${c}`).join(" ")} ELSE 1 END) *
|
|
403
|
+
(0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function oM(e,n,i,c){let p=Math.max(0,c-i)/86400000;return Math.max(0.000000001,-e)*xg[n]*(0.3+0.7/(1+p/30))}function bg(e,n){return e.sort((i,c)=>(n==="best"?c.score-i.score:0)||(n==="recent"?c.time-i.time:0)||(i.sessionID<c.sessionID?-1:Number(i.sessionID>c.sessionID))||c.seq-i.seq||i.field.localeCompare(c.field))}var Sg=512;function sM(e,n,i){let c=performance.now(),p=n.partial;wg(e,n),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[f,g]of[["fts",n.msg],["fts_out",n.out]]){if(!g)continue;let x=n.candidateLimit??2000,I=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
|
|
404
|
+
ORDER BY ${n.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(g,n.candidateLimit?x+1:x);if(n.candidateLimit&&I.length>x)I.length=x,p=!0;else if(!n.candidateLimit&&I.length===x){let E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
|
|
405
|
+
AND rowid NOT IN (SELECT value FROM json_each(?))`).all(g,JSON.stringify(I.map((T)=>T.doc)));for(let T of E)I.push(T)}let b=nM(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
|
|
406
|
+
FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(b))}return i?.("match",performance.now()-c),p}function iM(e,n,i,c,p){let f=performance.now();if(n.candidateLimit){let x=e.query(`
|
|
407
|
+
SELECT r.session_id,r.seq,${Gl(c)} AS score
|
|
408
|
+
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
409
|
+
${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
410
|
+
WHERE ${n.where} LIMIT ${n.candidateLimit+1}
|
|
411
|
+
`).all(...n.bindings);if(x.length>n.candidateLimit)x.length=n.candidateLimit,n.partial=!0;let I=new Map;for(let b of x){let E=i?b.seq:0,T=JSON.stringify([b.session_id,E]),k=I.get(T);if(!k||b.score>k.score)I.set(T,{...b,seq:E})}return p?.("filter",performance.now()-f),[...I.values()].sort((b,E)=>E.score-b.score||(b.session_id<E.session_id?-1:Number(b.session_id>E.session_id))||E.seq-b.seq)}let g=e.query(`
|
|
412
|
+
SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Gl(c)}) AS score
|
|
413
|
+
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
414
|
+
${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
415
|
+
WHERE ${n.where}
|
|
416
|
+
GROUP BY r.session_id${i?",r.seq":""}
|
|
417
|
+
ORDER BY score DESC,r.session_id,seq DESC LIMIT ${n.candidateLimit?n.candidateLimit+1:-1}
|
|
418
|
+
`).all(...n.bindings);return p?.("filter",performance.now()-f),g}var aM=new WeakMap,nK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
|
|
419
|
+
SELECT id,forked_from_id,forked_from_seq FROM store.sessions
|
|
420
|
+
WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
|
|
421
|
+
UNION
|
|
422
|
+
SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
|
|
423
|
+
FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
|
|
424
|
+
WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
|
|
425
|
+
)`;function wg(e,n){if(!n.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(`${nK} 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();aM.set(e,new Map(i.map((c)=>[c.ancestor,c.through])))}function Eg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
|
|
426
|
+
SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
|
|
427
|
+
JOIN store.sessions ps ON ps.id=pr.session_id
|
|
428
|
+
WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
|
|
429
|
+
AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
|
|
430
|
+
AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
|
|
431
|
+
SELECT 1 FROM store.entries original JOIN store.entries copied
|
|
432
|
+
ON copied.session_id=r.session_id AND copied.seq=r.seq
|
|
433
|
+
WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
|
|
434
|
+
))
|
|
435
|
+
))`}function uM(e,n,i,c,p){let f=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let g=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,x=n.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
|
|
436
|
+
INSERT INTO temp.search_window SELECT r.* FROM ref r ${g>4000?"INDEXED BY ref_time":""}
|
|
437
|
+
${x} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${n.where} AND ${Eg(n)}
|
|
438
|
+
ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${c} OFFSET ?`).run(...n.bindings,...n.forks?n.bindings:[],i);let I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(I===c){let b=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(b)e.query(`
|
|
439
|
+
INSERT INTO temp.search_window SELECT r.* FROM ref r ${x}
|
|
440
|
+
WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
|
|
441
|
+
AND ${n.where} AND ${Eg(n)} AND NOT EXISTS (
|
|
442
|
+
SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
|
|
443
|
+
)`).run(b.session_id,b.seq,...n.bindings,...n.forks?n.bindings:[]),I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-f),I}function cM(e,n,i,c,p,f,g){let x=performance.now(),I=n.group==="none",b=n.sort==="recent"?"time DESC":"relevance DESC,time DESC",E=e.query(`
|
|
444
|
+
SELECT r.session_id,${I?"r.seq":"0"} AS seq,
|
|
445
|
+
max(${Gl(p)}) AS relevance,max(r.time) AS time
|
|
446
|
+
FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
|
|
447
|
+
WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
|
|
448
|
+
GROUP BY r.session_id${I?",r.seq":""}
|
|
449
|
+
ORDER BY ${b},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(f),c,i);return g?.("group",performance.now()-x),E}function mM(e,n,i,c,p,f){let g=performance.now(),x=p?n:{...n,forks:!1},I=e.query(`
|
|
450
|
+
SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
|
|
451
|
+
${x.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
452
|
+
WHERE r.session_id=? ${c?"AND r.seq=?":""}
|
|
453
|
+
AND ${n.where} AND ${Eg(x)}
|
|
454
|
+
${n.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${n.candidateLimit+1}`:""}`).all(i.session_id,...c?[i.seq]:[],...n.bindings,...x.forks?n.bindings:[]);return f?.("filter",performance.now()-g),I}function Tg(e,n,i,c){if(!n.forks)return[];let p=aM.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
|
|
455
|
+
SELECT DISTINCT r.session_id,s.title,e.body
|
|
456
|
+
FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
|
|
457
|
+
CROSS JOIN ref r ON r.session_id=l.child
|
|
458
|
+
JOIN store.sessions s ON s.id=r.session_id
|
|
459
|
+
LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
|
|
460
|
+
WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${n.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...n.bindings).filter((f)=>{if(i.seq===0)return f.title===c;if(!f.body)return!1;let g=JSON.parse(f.body);return Ke(g,!0).some((x)=>x.part===i.part&&x.kind===Qr[i.kind]&&x.text===c)}).map((f)=>f.session_id)}function oK(e,n){let i=n?e:ft(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let c="",p=[],f=[],g=0;for(let x of e){let I=n?x:ft(x);c+=I;for(let b=0;b<I.length;b++)p.push(g),f.push(g+x.length);g+=x.length}return{normalized:c,starts:p,ends:f}}function Kl(e,n){if(n.regex){let I=new RegExp(n.regex.source,`${n.regex.flags}g`),b=[];for(let E of e.matchAll(I)){if(n.wholeWord&&!pM(e,E.index,E.index+E[0].length))continue;b.push([E.index,E.index+E[0].length])}return b.length?b:void 0}let{normalized:i,starts:c,ends:p}=oK(e,n.caseSensitive),f=(I)=>{let b=n.caseSensitive?I.text:ft(I.text),E=[],T=i.indexOf(b);while(T>=0&&b){let k=c?c[T]:T,A=p?p[T+b.length-1]:T+b.length,L=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(I.text));if(k!==void 0&&A!==void 0&&(!I.prefix||L)&&(!n.wholeWord||pM(e,k,A)))E.push([k,A]);T=i.indexOf(b,T+Math.max(1,b.length))}return E};if(!n.branches.length)return[];let g=[],x=!1;for(let I of n.branches){if(I.exclude.some((E)=>f(E).length))continue;let b=I.include.map(f);if(b.some((E)=>!E.length))continue;x=!0,g.push(...b.flat())}return x?g:void 0}function pM(e,n,i){let c=/[\p{L}\p{N}_]/u;return(n===0||!c.test(e.slice(n-1,n)))&&(i===e.length||!c.test(e.slice(i,i+1)))}function Hl(e,n){let i=e.split(`
|
|
461
|
+
`),c=new Set,p=0,f=i.map((g,x)=>{let I=p;if(n.some(([b,E])=>b<=I+g.length&&E>=I))for(let b=Math.max(0,x-1);b<=Math.min(i.length-1,x+1);b++)c.add(b);return p+=g.length+1,I});if(!c.size)c.add(0);return[...c].sort((g,x)=>g-x).slice(0,5).map((g)=>{let x=i[g]??"",I=f[g]??0,b=n.filter(([A,L])=>L>I&&A<I+x.length),E=Math.max(0,(b[0]?.[0]??I)-I-100),T=x.slice(E,E+300),k=b.map(([A,L])=>[Math.max(0,A-I-E),Math.min(T.length,L-I-E)]);return{text:T,line:g+1,ranges:k.filter(([A,L])=>A<L)}})}var lM=3;function sK(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 dM(e,n){return n.score-e.score||(e.sessionID<n.sessionID?-1:Number(e.sessionID>n.sessionID))||n.seq-e.seq}function iK(e,n){if(!e)return{offset:0,key:n,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===n&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let c="window"in i?i.window:0,p="seen"in i?i.seen:[],f="emitted"in i?i.emitted:[],g="after"in i?i.after:void 0;if(g!==void 0&&!sK(g))throw Error("invalid best cursor");let x=(I)=>Array.isArray(I)&&I.every((b)=>typeof b==="string"&&b.length<=1024);if(typeof c==="number"&&Number.isSafeInteger(c)&&c>=0&&x(p)&&x(f))return{offset:i.offset,key:n,now:i.now,window:c,seen:p,emitted:f,after:g}}}catch{}throw Error("invalid search cursor")}function Mn(e,n){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:n})).toString();return iK(e.cursor,i)}async function Wr(e,n,i){let c="search"in e?e.search:e,p=performance.now(),f=(Fe)=>{if(!i.signal?.aborted)i.onEvent(Fe)};if(i.signal?.aborted)return;let g=Mn(n,i.sessionID);if(n.filters?.sessionID?.length===1)n={...n,group:"none"};let x=Bl(n,{now:g.now});if(x.error){f({type:"error",...x.error});return}if(x.currentSession){if(!i.sessionID){f({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}x.filters.sessionID=[i.sessionID]}if(!n.deep&&x.regex?.deepScan){f({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let I=performance.now(),b=c.withIndex((Fe)=>rM(Fe,x));if(!b){f({type:"error",code:"unavailable",message:c.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()-I);let E=b.partial,T=g.after,k=new Map,A=new Map,L=[],q=!1,Y=new Map,j=new WeakMap,V=new Map,X=new Map,{offset:se,window:Z}=g,z=[...g.seen],ce=[...g.emitted],he=!1,ve=Math.max(1,Math.min(200,n.limit??30)),fe=Math.min(b.candidateLimit??2000,n.group==="none"?Sg:Math.min(2000,Math.max(Sg,ve*32))),ie=(Fe,Ue)=>{let Ft=k.get(Ue);if(Ft)return Ft;let dt=Fe.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Ue);if(dt)k.set(Ue,dt);return dt??void 0},me=(Fe,Ue,Ft)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(Ue.session_id))return;if(i.excludeEntry?.sessionID===Ue.session_id&&i.excludeEntry.seq===Ue.seq)return;let dt=ie(Fe,Ue.session_id);if(!dt)return;let vt=Qr[Ue.kind];if(!vt)return;let hr=dt.title;if(Ue.seq!==0){let st=`${Ue.session_id}:${Ue.seq}`,Jt=X.get(st);if(!Jt){let an=Ft?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!Ft&&!an)return;let Ht=Ft??JSON.parse(an?.body??"null");Jt=Ke(Ht,!0),X.set(st,Jt)}let Zt=Jt.find((an)=>an.part===Ue.part&&an.kind===vt);if(!Zt)return;hr=Zt.text}let pr=Kl(hr,x);if(!pr)return;let Ut=A.get(dt.id);if(Ut===void 0)Ut=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(dt.id)?.through??0,A.set(dt.id,Ut);let ot=Ue.seq>0&&Ue.seq<=Ut;if(x.filters.compacted!==void 0&&ot!==x.filters.compacted)return;let At={sessionID:dt.id,seq:Ue.seq,time:Ue.time,field:vt,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:oM(Ue.relevance,vt,Ue.time,g.now),flags:{archived:dt.archived_at!==null,compacted:ot,partial:hr.length>Ai+Ei}};return Y.set(At,{text:hr,ranges:pr}),L.push(At),q=!0,V.set(At,{doc:Ue.doc,part:Ue.part}),At},qe=(Fe)=>{let Ue=performance.now(),Ft=[...Fe].sort((ot,At)=>ot.time-At.time||ot.sessionID.localeCompare(At.sessionID)),dt=[],vt=new Map;for(let ot of Ft){let At=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)??c.withIndex((Eo)=>ie(Eo,Jt?.forked_from_id??""));let an=`${Jt?.id??ot.sessionID}:${ot.seq}:${At?.part}:${At?.doc}`,Ht=vt.get(an);if(Ht){if(Ht.sessionID!==ot.sessionID)Ht.forks=[...new Set([...Ht.forks??[],ot.sessionID])]}else vt.set(an,ot),dt.push(ot)}let hr=[],pr=new Map,Ut=new Map;for(let ot of dt){let At=`${ot.sessionID}:${ot.seq}`,st=Ut.get(At);if(!st){Ut.set(At,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},Ut.set(At,Zt),j.set(Zt,Jt)}for(let ot of bg([...Ut.values()],n.sort??"best")){let At=k.get(ot.sessionID);if(!At)continue;let st=n.group==="none"?void 0:pr.get(At.id);if(!st)st={session:{id:At.id,title:At.title,projectID:At.project_id,updated:At.updated},hits:[],more:0,...E&&n.group!=="none"?{moreIsLowerBound:!0}:{}},hr.push(st),pr.set(At.id,st);if(st.hits.length<lM||n.group==="none")st.hits.push(ot);else st.more++}return i.onTiming?.("group",performance.now()-Ue),hr},xt=(Fe)=>{for(let Ue of Fe)for(let Ft of Ue.hits){if(i.allowedSessionIDs&&Ft.forks)Ft.forks=Ft.forks.filter((hr)=>i.allowedSessionIDs?.has(hr));let dt=performance.now(),vt=new Map;for(let hr of j.get(Ft)??[Ft]){let pr=Y.get(hr);if(!pr)continue;for(let Ut of Hl(pr.text,pr.ranges)){let ot=`${Ut.line}:${Ut.text}`,At=vt.get(ot);if(!At)vt.set(ot,Ut);else At.ranges=[...new Map([...At.ranges,...Ut.ranges].map((st)=>[st.join(":"),st])).values()]}}Ft.snippet=[...vt.values()],i.onTiming?.("snippet",performance.now()-dt)}},Je=n.deep||b.scan,Yt=(Fe,Ue)=>{let Ft=ie(Fe,Ue.session_id);if(!Ft)return[];let dt=mM(Fe,b,Ue,n.group==="none",Ft.forked_from_id!==null,i.onTiming);if(b.candidateLimit&&dt.length>b.candidateLimit)dt.length=b.candidateLimit,E=!0;let vt=L.length,hr=performance.now();for(let pr of dt){if(i.signal?.aborted)break;let Ut=me(Fe,pr);if(!Ut)continue;let ot=Tg(Fe,b,pr,Y.get(Ut)?.text??"");if(ot.length)Ut.forks=ot}return i.onTiming?.("body",performance.now()-hr),L.slice(vt)};if(Je){E=!1;let Fe=[],Ue=new Set,Ft=c.withIndex((st)=>{wg(st,b);for(let Ht 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(Ht.id,Ht);let Jt=new Set(st.query(`SELECT s.id FROM store.sessions s WHERE ${b.sessionWhere}`).all(...b.sessionBindings).map((Ht)=>Ht.id)),Zt=(Ht)=>{if(Ue.has(Ht.id))return;Ue.add(Ht.id);let Eo=Ht.forked_from_id?k.get(Ht.forked_from_id):void 0;if(Eo)Zt(Eo);if(Jt.has(Ht.id))Fe.push(Ht)};for(let Ht of k.values())Zt(Ht);return(st.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
|
|
462
|
+
SELECT s.id FROM store.sessions s WHERE ${b.sessionWhere}
|
|
463
|
+
)`).get(...b.sessionBindings)?.n??0)+Jt.size})??0,dt=0,vt=0,hr=0;if(x.regex?.deepScan)f({type:"groups",groups:[]});let pr=new Set,Ut=new Set,ot=new Map,At=()=>{let st=qe(L),Jt=[];for(let Zt of st){let an=Zt.session.id,Ht=n.group==="none"?void 0:ot.get(an);if(n.group!=="none"&&Ut.has(an)&&!Ht)continue;if(!Ht){if(Ut.add(an),vt<g.offset){vt++;continue}if(hr>=ve){he=!0;break}hr++,se++}if(n.group!=="none"){let Eo=(Ht?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,lM-(Ht?.shown??0));let hu=(Ht?.shown??0)+Zt.hits.length;Zt.more=Eo-hu,ot.set(an,{shown:hu,count:Eo})}Jt.push(Zt)}if(Jt.length)xt(Jt),f({type:"groups",groups:Jt});L.length=0,Y.clear(),V.clear(),X.clear()};for(let st of Fe){if(i.signal?.aborted||he)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||he)break;let an=c.withIndex((Ht)=>{let Eo=Ht.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)Eo.unshift({seq:0,time:st.updated,body:null});for(let Fi of Eo){if(i.signal?.aborted)break;let gu=Fi.body?JSON.parse(Fi.body):void 0;if(gu?.type==="assistant")Zt=gu.model;let IM=gu?Ke(gu,!0):[{part:0,kind:"title",text:st.title}];for(let Go of IM){if(i.signal?.aborted)break;let Ms={session_id:st.id,seq:Fi.seq,part:Go.part,doc:Number(BigInt(Bun.hash(Go.text))&0x1fffffffffffffn),kind:Oe[Go.kind],tool:Go.tool??null,err:Number(Go.err??!1),model:Go.model??(Go.tool?Zt:void 0)??null,time:Fi.time,relevance:-1};if(!Ht.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
|
|
464
|
+
JOIN store.sessions s ON s.id=r.session_id WHERE ${b.where}`).get(Ms.session_id,Ms.seq,Ms.kind,Ms.tool,Ms.err,Ms.model,Ms.time,...b.bindings))continue;let zs=st,kg=new Set;while(zs.forked_from_id&&zs.forked_from_seq!==null&&Fi.seq<=zs.forked_from_seq&&!kg.has(zs.id)){kg.add(zs.id);let yu=k.get(zs.forked_from_id);if(!yu)break;zs=yu}let Ag=`${zs.id}:${Fi.seq}:${Go.part}:${Bun.hash(Go.text)}`;if(pr.has(Ag))continue;let Cg=me(Ht,Ms,gu);if(Cg){if(pr.add(Ag),b.forks){let yu=Ht.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(st.id,Fi.seq,Go.part);if(yu){let $g=Tg(Ht,b,{...Ms,doc:yu.doc},Go.text);if($g.length)Cg.forks=$g}}}}}let hu=Eo.at(-1);if(hu)Jt=hu.seq;return Eo.length});if(an===void 0){f({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(dt+=an,f({type:"progress",scanned:dt,total:Ft}),i.signal?.aborted)return;if(At(),!an||he)break;await Bun.sleep(0)}}}else c.withIndex((Fe)=>{if(E=sM(Fe,b,i.onTiming)||E,x.regex?x.regex.literals.every((dt)=>dt.some((vt)=>[...vt].length<3)):x.branches.some((dt)=>dt.include.length>0&&dt.include.every((vt)=>[...vt.text].length<3)))Fe.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(n.sort!=="recent"){let dt=iM(Fe,b,n.group==="none",g.now,i.onTiming);if(E||=b.partial,b.candidateLimit&&dt.length>b.candidateLimit)dt.length=b.candidateLimit,E=!0;let vt=[];for(let pr of dt){if(i.signal?.aborted)return;let Ut=vt[ve]?.key.score;if(Ut!==void 0&&pr.score+0.000000000001<Ut)break;let ot=L.length,At=Yt(Fe,pr);L.splice(ot);let st=bg([...At],"best")[0];if(!st)continue;let Jt={score:st.score,sessionID:st.sessionID,seq:n.group==="none"?st.seq:0};if(g.after&&dM(Jt,g.after)<=0)continue;if(vt.push({key:Jt,hits:At}),vt.sort((Zt,an)=>dM(Zt.key,an.key)),vt.length>ve+1)vt.length=ve+1}he=vt.length>ve;let hr=vt.slice(0,ve);for(let pr of hr)L.push(...pr.hits);T=hr.at(-1)?.key;return}let Ft=0;for(;;){if(i.signal?.aborted)return;let dt=uM(Fe,b,Z,fe,i.onTiming),vt=b.candidateLimit!==void 0&&Z+dt>=b.candidateLimit;E||=vt;let hr=cM(Fe,n,se,ve-Ft+1,g.now,z,i.onTiming);he=hr.length>ve-Ft;let pr=hr.slice(0,ve-Ft);if(!pr.length){if(dt<fe||vt){he=!1;break}Z+=dt,se=0,z=[...new Set([...z,...ce])],ce=[];continue}for(let Ut of pr)if(se++,Yt(Fe,Ut).length){if(Ft++,n.group!=="none")ce.push(Ut.session_id)}if(Ft>=ve){he||=!vt&&dt>=fe;break}if(!he){if(dt<fe||vt)break;Z+=dt,se=0,z=[...new Set([...z,...ce])],ce=[]}}});if(i.signal?.aborted)return;if(!Je){let Fe=qe(L);xt(Fe),f({type:"groups",groups:Fe})}if(!q){let Fe=x.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)f({type:"suggest",terms:c.withIndex((Ue)=>Ig(Ue,Fe))??[]})}f({type:"done",cursor:he?Buffer.from(JSON.stringify(!Je&&n.sort!=="recent"?{...g,offset:0,window:0,seen:[],emitted:[],after:T}:{...g,offset:se,window:Z,seen:z,emitted:ce})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:E,index:c.status()})}function Oo(e,n){return e.withIndex((i)=>Ig(i,n))??[]}function fM(e,n,i){let c=v({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:s({query:o(m([l({maxLength:2000}),Pn()])),scope:o(m([a("session"),a("project"),a("all"),a(""),Pn()])),fields:o(m([W(Br({type:"string",enum:[...In]})),Pn()])),tool:o(m([l(),Pn()])),isError:o(m([D(),Pn()])),after:o(m([l(),J(),Pn()])),before:o(m([l(),J(),Pn()])),limit:o(m([w(),Pn()])),session:o(m([l(),Pn()])),seq:o(m([w(),Pn()])),around:o(m([w(),Pn()]))}),async execute(p,f,g){let x={query:f.query?.trim(),scope:f.scope||void 0,fields:f.fields?.length?f.fields:void 0,tool:f.tool?.trim(),isError:f.isError??void 0,after:f.after??void 0,before:f.before??void 0,limit:f.limit||void 0,session:f.session?.trim(),seq:f.seq??void 0,around:f.around??void 0},I=x.query?.trim(),b=!I&&Boolean(x.session?.trim())&&Number.isSafeInteger(x.seq)&&(x.seq??0)>=1;if(b&&x.around!==void 0&&(!Number.isInteger(x.around)||x.around<0||x.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(x.scope&&!["session","project","all"].includes(x.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(g?.aborted)throw Error("History search cancelled");let E=e.sessions().find((ie)=>ie.id===i);if(!E)throw Error("History session is unavailable");let T=(ie)=>{if(ie===void 0||ie===0||typeof ie==="string"&&!ie.trim())return;if(typeof ie==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(ie))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let me=typeof ie==="number"?ie:Date.parse(ie);if(!Number.isFinite(me)||Math.abs(me)>8640000000000000){if(typeof ie==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return me},k=b?void 0:T(x.after),A=b?void 0:T(x.before);if(k!==void 0&&A!==void 0&&k>=A)throw Error("after must precede before");let L=[];if(b&&x.session&&x.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===x.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let me=x.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(x.session,Math.max(1,x.seq-me),x.seq+me);if(!qe.some((Je)=>Je.seq===x.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}]
|
|
465
|
+
${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
|
|
466
|
+
`).slice(0,4000)}`}).join(`
|
|
467
|
+
|
|
468
|
+
`)||"No history content"}],details:{groups:L,count:qe.length}}}if(!I)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(x.limit)?Math.max(1,Math.min(30,Math.trunc(x.limit??10))):10,Y=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((ie)=>{if(x.scope==="session")return ie.id===i;if((x.scope??"project")==="project"&&E.projectID)return ie.projectID===E.projectID;return!0}).map((ie)=>ie.id)),V={q:I,filters:{tools:x.tool?.trim()?[x.tool.trim()]:void 0,isError:x.isError,after:k,before:A},group:"none",limit:q},X=Bl(V);if(X.error)throw Error(X.error.message);if(x.fields?.length){if(X.filters.fields=x.fields.filter((ie)=>(ie in Oe)),X.filters.fields.length!==x.fields.length)throw Error("Unknown search field")}if((x.scope??"project")==="session")X.filters.sessionID=[i];else if((x.scope??"project")==="project"&&E.projectID)X.filters.projectID=[E.projectID];let se=n.status().state!=="ready",Z=!1;if(!se){let ie=X.filters.fields??Object.keys(Oe).filter((xt)=>(xt in Oe)),me=ie.filter((xt)=>xt!=="title"),qe=me.length?[me]:[];if(ie.includes("title"))qe.push(["title"]);for(let xt of qe){if(L.length>=q&&Z)break;if(await Wr(n,{...V,limit:Math.max(1,q-L.length),filters:{...X.filters,fields:xt}},{signal:g,excludeEntry:Y===void 0?void 0:{sessionID:i,seq:Y},sessionID:i,allowedSessionIDs:j,onEvent(Je){if(Je.type==="groups")L.push(...Je.groups);if(Je.type==="done")Z||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")se=!0;else throw Error(Je.message)}}),se)break}}let z=[],ce=0;if(se){L.length=0;let ie=performance.now()+2000;e:for(let me of e.sessions()){if(!j.has(me.id))continue;if(X.filters.sessionID&&!X.filters.sessionID.includes(me.id))continue;if(X.filters.projectID&&(!me.projectID||!X.filters.projectID.includes(me.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(me.id,qe);if(xt)Je.push({body:"null",seq:0,time:me.updated}),xt=!1;if(!Je.length)break;for(let Yt of Je){if(Yt.seq>0)qe=Yt.seq;if(g?.aborted)throw Error("History search cancelled");if(ce>=1e4||performance.now()>ie){Z=!0;break e}if(ce++,me.id===i&&Yt.seq===Y)continue;if(X.filters.after!==void 0&&Yt.time<X.filters.after||X.filters.before!==void 0&&Yt.time>=X.filters.before)continue;let Fe=Yt.seq===0?[{part:0,kind:"title",text:me.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Ue of Fe){if(X.filters.fields&&!X.filters.fields.includes(Ue.kind))continue;if(X.filters.tools&&(!Ue.tool||!X.filters.tools.includes(Ue.tool)))continue;if(X.filters.isError!==void 0&&Boolean(Ue.err)!==X.filters.isError)continue;let Ft=Kl(Ue.text,X);if(!Ft)continue;if(L.length>=q&&Ue.kind!=="title"){Z=!0;break e}(Ue.kind==="title"?z:L).push({session:{id:me.id,title:me.title,projectID:me.projectID,updated:me.updated},more:0,hits:[{sessionID:me.id,seq:Yt.seq,time:Yt.time,field:Ue.kind,tool:Ue.tool,isError:Boolean(Ue.err),snippet:Hl(Ue.text,Ft),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(g?.aborted)throw Error("History search cancelled");if(z.length>Math.max(0,q-L.length))Z=!0;if(L.push(...z.slice(0,q)),L.sort((ie,me)=>Number(ie.hits[0]?.field==="title")-Number(me.hits[0]?.field==="title")),L.length>q)Z=!0;L.length=Math.min(L.length,q);let he=new Map;for(let ie of L)for(let me of ie.hits){let qe=he.get(ie.session.id)??[];qe.push(`[${ie.session.title.replace(/[\r\n]/g," ")} \xB7 ${me.sessionID} \xB7 ${me.seq} \xB7 ${new Date(me.time).toISOString()} \xB7 ${me.field}${me.tool?`/${me.tool}`:""}]
|
|
469
|
+
${me.snippet.slice(0,3).map((xt)=>{let Je=xt.text;for(let[Yt,Fe]of[...xt.ranges].sort((Ue,Ft)=>Ft[0]-Ue[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Fe)}\u3011${Je.slice(Fe)}`;return Je}).join(`
|
|
470
|
+
`)}`),he.set(ie.session.id,qe)}let ve="";if(se){if(ve="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",n.status().state==="disabled")ve="\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 fe=L.reduce((ie,me)=>ie+me.hits.length,0);return{content:[{type:"text",text:[ve,se&&Z?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ce} \u6761`:"",[...he.values()].map((ie)=>ie.join(`
|
|
471
|
+
|
|
472
|
+
`)).join(`
|
|
473
|
+
|
|
474
|
+
`),fe===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 ${fe} \u6761\uFF1B${Z?"\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(`
|
|
475
|
+
`)}],details:{groups:L,count:fe}}}});return Object.assign(c,{source:"history",builtin:!0,defer:"defer"})}async function hM(e,n){let i=n.projectID?e.store.project(n.projectID):void 0,c=i?.directory??process.cwd(),f=n.info().kind==="sub",g=()=>f||n.records.some((b)=>b.entry.type==="compaction"),x=e.options.tools??tr({directory:i?.directory,records:()=>n.records,history:(b)=>e.resolveHistory(n.id,b),onTodos:(b)=>n.setTodos(b),shell:()=>e.serverShell(),hasCompacted:g});if(e.options.tools===void 0)x.push(fM(e.store,e.search,n.id));let I=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:xP({project:i,globalInstructions:pK(e),shell:e.serverShell()});return{systemPrompt:I.map((b)=>b.detail).join(""),systemParts:I,tools:[...x,...e.tools.snapshot()],cwd:c}}var mK=[fu(".basalt","AGENTS.md"),fu(".agents","AGENTS.md"),fu(".opencode","AGENTS.md"),fu(".claude","CLAUDE.md"),fu(".codex","AGENTS.md")];function pK(e){let n=e.options.homeDir??cK();for(let i of mK){let c=fu(n,i);try{if(aK(c))return uK(c,"utf8")}catch{return}}return}class $r{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 pg(this,this.sessions,(n)=>this.emit(n)),this.defaultModel=e.defaultModel,this.store=new Fl(Rg(e.dataDir,"basalt.db")),this.plugins=new zh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Ul(this.plugins,()=>this.builtinToolNames()),this.search=new Vh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(n)=>this.emit({type:"search_status",status:n})});for(let n of this.store.allSessions()){let i=this.open(n,"restore");this.sessions.set(n.id,i),this.restored.add(i)}}static async create(e){let n=new $r(e);try{return await n.initialize(),n}catch(i){throw await n.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Rg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Rg(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 GP(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((c)=>c.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let n=[...this.sessions.values()];if(await Promise.all(n.map((c)=>c.noticesIdle())),n.some((c)=>c.status==="busy"||!e.includes(c)))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{...jl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>UP(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,n){return this.projectOperations.updateProject(e,n)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,n={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let c=n.archive??"active";return c==="all"||i.archivedAt!==null===(c==="archived")}).sort((i,c)=>c.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((n)=>n.info().parentID===e).map((n)=>n.info())}resolveHistory(e,n){let i=this.get(e);if(!i)throw new t("History session is unavailable");let c=i.historyScope(n);if(c)return c;if(n.source&&n.source!=="self"||n.session_id&&n.session_id!==i.id)throw new t("History source is unavailable");return{sessionID:i.id,records:i.records}}openStoredSession(e,n="restore"){let i=this.open(e,n);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let n=e.model??this.defaultModel;if(!xn(this.options.models,n))throw new t(`unknown model ${n}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),c={id:ue("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:n,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(c);let p=this.open(c);return this.sessions.set(c.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,n,i){n={...n,archivedAt:null},this.store.copySession(e,n,i);let c=this.open(n);return this.sessions.set(n.id,c),this.plugins.notify("session.fork",c),this.emit({type:"session",session:c.info()}),c}exportSession(e){let n=this.get(e);if(!n)throw new y("no such session");let i=n.info(),c=i.projectID?this.store.project(i.projectID):void 0;return AP(i,this.store.records(e),c?{name:c.name,directory:c.directory}:void 0)}importSession(e,n={}){if(n.model!==void 0)this.checkModel(n.model);if(n.projectID)this.projectOperations.requireProject(n.projectID);let i=[n.model,e.model,this.defaultModel].find((g)=>g!==void 0&&xn(this.options.models,g)!==void 0),c=i?xn(this.options.models,i):void 0;if(!i||!c)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:ue("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:n.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?PP(e.records,c):e.records);let f=this.open(p);return this.sessions.set(p.id,f),this.emit({type:"session",session:f.info()}),f}truncateHistory(e,n){let i=this.sessions.get(e.id);if(!i)throw new y("no such session");if(i.assertWritable(),i.status==="busy")throw new oe;if(!xn(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 p of this.sessions.values()){if(p.info().parentID!==e.id)continue;if(p.status==="busy")p.abort();p.close()}this.store.truncateSession(e,n);let c=this.open(e,"replay");return this.sessions.set(e.id,c),this.emit({type:"truncated",sessionID:e.id,after:n-1,truncationEpoch:this.store.truncationEpoch(e.id)}),c}setArchived(e,n){let i=this.sessions.get(e);if(!i)throw new y("no such session");if(i.info().parentID)throw new t("\u8BF7\u5F52\u6863\u6216\u6062\u590D\u6240\u5C5E\u4F1A\u8BDD\uFF08\u542B\u5B50\u4F1A\u8BDD\uFF09");let c=this.sessionTree(i);if(c.some((p)=>p.status==="busy"))throw new oe;if(i.isArchived===n)return i.info();this.store.setArchived(c.map((p)=>p.id),n?Date.now():null);for(let p of c)p.refreshArchive();for(let p of c)p.archiveChanged();return i.info()}sessionTree(e){let n=[e];for(let i=0;i<n.length;i++){let c=n[i];if(!c)continue;for(let p of this.sessions.values())if(p.info().parentID===c.id)n.push(p)}return n}deleteSession(e){let n=this.sessions.get(e);if(!n)throw new y("no such session");if(n.status==="busy")throw new oe;let i=this.sessionTree(n).slice(1),c=()=>{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});n.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",n),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return c();n.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(c)}open(e,n="create"){let i=e.id,c=new Ol(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>hM(this,p)},{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(n!=="restore")this.plugins.notify(n==="create"?"session.create":"session.open",c);return c}get toolLoading(){return new Di(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(!Jl.includes(e))throw new t(`Invalid shell type; must be ${Jl.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 KP(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 n of this.listeners)try{n(e)}catch(i){console.error("runtime listener failed",i)}}}var Re={now:()=>Date.now(),after(e,n){let i=setTimeout(n,e);return()=>clearTimeout(i)}};var gM=1048576,yM=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,n=30000,i,c){this.cwd=e;this.outputLimit=n;this.terminal=i;this.shellPreference=c}setTerminalObserver(e){this.terminal=e}start(e,n,i){let c=i?.observer,p=i?.clock??Re;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let Y=rd(e);if(Y.length>0)throw Error(nd(Y))}if(this.list().filter((Y)=>Y.state==="running").length>=yM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${yM}\uFF09`);let g=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:x,isWindows:I}=xa(e,g),b=Bun.spawn(x,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!I,windowsHide:!0}),E={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:b,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(E.id,E);let T=()=>{for(let Y of E.waiters.splice(0))Y()},k=async(Y,j)=>{let V=new Tl;for await(let se of Y){let Z=V.decode(se);E.output+=Z,c?.output(Z,j);let z=Buffer.from(E.output);if(z.length>gM){let ce=z.length-gM;while(ce<z.length&&(z[ce]??0)>>6===2)ce++;let he=z.subarray(ce).toString(),ve=E.output.length-he.length;E.unreadDroppedBytes+=Buffer.byteLength(E.output.slice(Math.max(0,E.readAt-E.dropped),ve)),E.output=he,E.dropped+=ve}T()}let X=V.flush();if(E.output+=X,X)c?.output(X,j)},A,L=Promise.all([k(b.stdout,"stdout"),k(b.stderr,"stderr")]).catch((Y)=>{A=Y,this.kill(E)}),q=!1;if(E.done=(async()=>{if(E.code=await b.exited,E.timer?.(),this.kill(E),await L,A)throw A;if(E.state==="running")E.state="exited";if(q=!0,c?.end(E.state,E.code),!c&&E.state!=="killed")this.terminal?.(E);T()})().catch((Y)=>{if(E.state="exited",E.output+=`
|
|
476
|
+
[\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(Y)}]`,!q)c?.end(E.state,E.code);if(c)throw Y;if(!c)this.terminal?.(E,Y);T()}),n!==void 0)E.timer=p.after(n,()=>{if(E.state==="running")E.state="timeout",this.kill(E)});return E}find(e){let n=this.jobs.get(e);if(!n)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return n}kill(e){try{if(process.platform==="win32"){let n=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(n.exitCode!==0&&n.exitCode!==128&&e.proc.exitCode===null)throw Error("\u65E0\u6CD5\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B\u6811\uFF0C\u8BF7\u68C0\u67E5\u8FDB\u7A0B\u6743\u9650")}else process.kill(-e.proc.pid,"SIGKILL")}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ESRCH"))throw n}}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,n,i=0,c=!1,p){let f=this.find(e),g=n?new RegExp(n):void 0,x=Date.now()+i;p?.throwIfAborted();while(f.state==="running"){p?.throwIfAborted();let k=f.output.slice(Math.max(0,f.readAt-f.dropped));if((g?g.test(k):!c)||Date.now()>=x)break;await new Promise((A,L)=>{let q=()=>{clearTimeout(j);let V=f.waiters.indexOf(Y);if(V>=0)f.waiters.splice(V,1);L(p?.reason)},Y=()=>{clearTimeout(j),p?.removeEventListener("abort",q);let V=f.waiters.indexOf(Y);if(V>=0)f.waiters.splice(V,1);A()},j=setTimeout(Y,Math.max(0,x-Date.now()));f.waiters.push(Y),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let I=f.unreadDroppedBytes;f.unreadDroppedBytes=0;let b=f.output.slice(Math.max(0,f.readAt-f.dropped));f.readAt=f.dropped+f.output.length;let E=b.slice(-this.outputLimit),T=I+Buffer.byteLength(b.slice(0,b.length-E.length));return{job:f,output:`${T?`[truncated ${T} bytes]
|
|
477
|
+
`:""}${E}`}}async write(e,n,i=!1,c){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let f=p.proc.stdin;if(!f||typeof f==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(n){let g=await ze(n,c);if(g)throw Error(g);f.write(n)}if(i)await f.end();else await f.flush()}async stop(e){let n=this.find(e);if(n.state==="running")n.state="killed",this.kill(n);return await n.done,{id:n.id,state:n.state,code:n.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 Wl=new WeakMap,zl=new WeakMap;function or(e,n){let i=Wl.get(e);if(!i)i=n(),Wl.set(e,i);return i}function ir(e){zl.set(e,(zl.get(e)??0)+1)}function sr(e,n){let i=(zl.get(n)??1)-1;if(zl.set(n,i),i>0)return!1;if(n.close(),Wl.get(e)===n)Wl.delete(e);return!0}async function G(e){let n=await e.json();if(!n||typeof n!=="object"||Array.isArray(n))throw new t("expected a JSON object");return n}function P(e,n){let i=e[n];if(!i)throw new t(`${n} is required`);return i}var Ln=100,ar=1e4,lK=60000,dK=200,Tn=()=>l(),xM=()=>o(w({minimum:1,maximum:ar})),Xc=()=>o(l({minLength:1,maxLength:128})),fK=m([s({click:m([Tn(),s({selector:Tn()})])}),s({type:s({label:Tn(),text:Tn()})}),s({waitText:Tn(),timeoutMs:xM()}),s({expectText:Tn(),within:o(Tn())}),s({waitSelector:Tn(),timeoutMs:xM()}),s({expectCount:s({selector:Tn(),n:w({minimum:0})})}),s({snapshot:s({selector:Tn(),depth:o(w({minimum:0,maximum:dK}))})}),s({expectCalls:s({onOpen:o(W(Tn())),onClose:o(w({minimum:0}))})}),s({expectValue:s({label:Tn(),value:Tn()})})]),hK=s({status:w({minimum:100,maximum:599}),body:wr(),delayMs:o(w({minimum:0,maximum:ar}))}),gK=m([a("paths"),a("request"),a("verify"),a("ui_test"),a("list"),a("docs"),a("check"),a("load"),a("reload"),a("enable"),a("disable")]),yK=m([a("page"),a("tab"),a("card"),a("sidebar")]),Si=s({action:gK,path:o(l({minLength:1,maxLength:4096})),method:o(Tn()),body:o(bs(Tn(),wr())),importTimeoutMs:o(w({minimum:1,maximum:ar})),timeoutMs:o(w({minimum:1,maximum:lK})),sessionID:Xc(),scope:o(m([a("user"),a("all")])),id:Xc(),slot:Xc(),view:Xc(),codeBlock:Xc(),kind:o(yK),props:o(bs(Tn(),wr())),context:o(bs(Tn(),wr())),steps:o(W(fK,{maxItems:Ln})),mockRoutes:o(bs(Tn(),hK)),topic:o(l({maxLength:100})),grep:o(l({minLength:1,maxLength:200}))});
|
|
478
|
+
export{t,y,ci,ui,pi,Ur,Fr,Po,In,di,mi,hi,Bt,fi,gi,yi,bi,To,_e,et,_t,K,ko,ze,Pt,W,o,s,Br,D,w,a,J,l,m,h,ae,Cn,Ro,Io,Co,Mo,we,v,tt,ut,R,O,U,ke,Pe,u,je,rt,er,We,tr,pt,oe,Lo,rr,nr,ue,Mn,Wr,Oo,$r,Re,Wt,or,ir,sr,G,P,No,Ln,ar,Si};
|