@bkm016/basalt 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{chunk-0039s4jt.js → chunk-02d3x4mj.js} +3 -3
- package/{chunk-ky55taar.js → chunk-0xd9mnc2.js} +327 -316
- package/{chunk-ckjw3b61.js → chunk-13gvs0ax.js} +2 -2
- package/{chunk-0d51ggzj.js → chunk-1n7dat03.js} +4 -4
- package/{chunk-ppxv5q7y.js → chunk-1zj3zvw5.js} +3 -3
- package/{chunk-2ek3wq4b.js → chunk-29qrxygd.js} +1 -1
- package/{chunk-7p6e2f5s.js → chunk-30rjf7my.js} +3 -3
- package/{chunk-v2srrqcv.js → chunk-38g3gctw.js} +2 -2
- package/{chunk-3j2kkgsc.js → chunk-4dw43syb.js} +1 -1
- package/{chunk-t66jqz12.js → chunk-4gtgqcct.js} +2 -2
- package/chunk-66h5qpc6.js +479 -0
- package/{chunk-qmdpgbg3.js → chunk-755sy11p.js} +1 -1
- package/{chunk-n015c8nx.js → chunk-7zkswxvk.js} +1 -1
- package/{chunk-91r5nvth.js → chunk-82v8jh1h.js} +2 -2
- package/{chunk-12trygzx.js → chunk-95964592.js} +16 -16
- package/{chunk-nmtk9xra.js → chunk-9as0p561.js} +2 -2
- package/{chunk-pn413hjw.js → chunk-a1352w87.js} +1 -1
- package/{chunk-rnt1ckk9.js → chunk-a1rb1a48.js} +5 -5
- package/{chunk-fzcmzbsq.js → chunk-a98wma9j.js} +1 -1
- package/{chunk-kgkrccr1.js → chunk-asyr3gnq.js} +2 -2
- package/{chunk-5gxj9560.js → chunk-ax04trym.js} +1 -1
- package/chunk-b2bxqeb4.js +2 -0
- package/{chunk-xjw78yey.js → chunk-bdjr0kfr.js} +4 -4
- package/{chunk-7kjr9gdx.js → chunk-bk4rpnm8.js} +2 -2
- package/{chunk-47vf66t6.js → chunk-c0zfefq8.js} +1 -1
- package/{chunk-kpvaqb7c.js → chunk-c6q04xrd.js} +2 -2
- package/chunk-c71173py.js +25 -0
- package/{chunk-adys4qq4.js → chunk-cmwdjes8.js} +5 -5
- package/{chunk-dcwdmpw2.js → chunk-d0a1jxk5.js} +1 -1
- package/{chunk-2nrkqq45.js → chunk-d5j74pcp.js} +7 -7
- package/{chunk-pkpj7s2k.js → chunk-dfh9m9n7.js} +1 -1
- package/{chunk-26cz8et8.js → chunk-dq01v5eq.js} +1 -1
- package/{chunk-fpxc6qjr.js → chunk-e1x629v0.js} +2 -2
- package/{chunk-86xhmz7k.js → chunk-en218k4y.js} +1 -1
- package/{chunk-3hg7yn1t.js → chunk-fgwda4m0.js} +1 -1
- package/chunk-gbjn6d81.js +2 -0
- package/{chunk-x496kg3v.js → chunk-gkf5jwvj.js} +1 -1
- package/{chunk-k3q5jqjj.js → chunk-hb4f2v34.js} +2 -2
- package/{chunk-mr807v9n.js → chunk-hbnmymaq.js} +1 -1
- package/{chunk-818nd6s1.js → chunk-jj4hqbrx.js} +2 -2
- package/{chunk-jyv9cae6.js → chunk-jn5pqy5v.js} +1 -1
- package/{chunk-yyy2yp6f.js → chunk-jtsve11b.js} +9 -9
- package/chunk-m1eam0s5.js +2 -0
- package/{chunk-6vnjg5x9.js → chunk-mbpb5c7w.js} +1 -1
- package/{chunk-t40fag3z.js → chunk-msm9hmk9.js} +1 -1
- package/{chunk-j781n7ca.js → chunk-n0ybj4h9.js} +2 -2
- package/{chunk-jp5afrwm.js → chunk-n2jcx65v.js} +2 -2
- package/{chunk-2ks2tnac.js → chunk-nrsd810j.js} +2 -2
- package/chunk-pnspvnyd.js +2 -0
- package/chunk-pz2afna8.js +2 -0
- package/{chunk-d37gemt2.js → chunk-q9f4xb0w.js} +3 -3
- package/{chunk-hd3x1w46.js → chunk-qaeyhe65.js} +1 -1
- package/chunk-qnkrrwmg.js +2 -0
- package/{chunk-e6c2mzxc.js → chunk-r4ttdkrz.js} +2 -2
- package/{chunk-r9aatvwm.js → chunk-stj493dn.js} +2 -2
- package/{chunk-g3ed130w.js → chunk-tevejprz.js} +4 -4
- package/{chunk-k3rmjrf1.js → chunk-v3ee9z3f.js} +1 -1
- package/{chunk-4n49ptbz.js → chunk-vtqr7dm8.js} +2 -2
- package/{chunk-z3ch1wg6.js → chunk-xh444pfn.js} +14 -14
- package/{chunk-pehyqj8k.js → chunk-zc9ar0r4.js} +1 -1
- package/{chunk-ef9yhnk3.js → chunk-zyyzk5ha.js} +1 -1
- package/compiled.js +9 -9
- package/package.json +1 -1
- package/ui-test-worker.js +8 -8
- package/web/chunk-08sq3cwm.js +1 -0
- package/web/chunk-0pghpg4y.js +2 -0
- package/web/chunk-12qf1r6m.js +1 -0
- package/web/chunk-24fjnnee.js +1 -0
- package/web/chunk-24jhbz82.js +24 -0
- package/web/{chunk-v14s4vgc.js → chunk-2dvbeqt0.js} +1 -1
- package/web/chunk-2hrswh3d.js +2 -0
- package/web/chunk-2j2atyjw.js +1 -0
- package/web/{chunk-s7e93552.js → chunk-2x4g9t37.js} +4 -4
- package/web/{chunk-hstbgb83.js → chunk-3ak5dg10.js} +5 -5
- package/web/chunk-3ecrkvr3.js +106 -0
- package/web/chunk-3h3g3ca3.js +1 -0
- package/web/chunk-3hr3ew9w.js +1 -0
- package/web/chunk-3pcrxg6m.js +1 -0
- package/web/{chunk-7a4xk6j9.js → chunk-3pd0qt83.js} +5 -5
- package/web/chunk-3txxt0a7.js +1 -0
- package/web/chunk-43g4wd7a.js +1 -0
- package/web/{chunk-nky3bqfg.js → chunk-4a6gdrbs.js} +1 -1
- package/web/{chunk-d0m0h0eb.js → chunk-5a4mj3qz.js} +1 -1
- package/web/{chunk-rkjkynm3.js → chunk-5baeh8q7.js} +11 -11
- package/web/{chunk-qq2v8h6d.js → chunk-5dr4tkem.js} +4 -4
- package/web/chunk-5jdrev9p.js +36 -0
- package/web/{chunk-p0cjvjdx.js → chunk-5v2c0aqk.js} +1 -1
- package/web/chunk-5z2n4z9x.css +1 -0
- package/web/{chunk-6e38yf3a.js → chunk-601k823s.js} +4 -4
- package/web/{chunk-8dp7h6w8.js → chunk-60axh4sa.js} +16 -16
- package/web/chunk-66wb0p6e.js +62 -0
- package/web/{chunk-qcge7d6s.js → chunk-6e87m0nm.js} +2 -2
- package/web/chunk-6y55gk1n.js +1 -0
- package/web/{chunk-8wg44w91.js → chunk-79e08rk1.js} +2 -2
- package/web/{chunk-svh2gkx8.js → chunk-7qkav30b.js} +1 -1
- package/web/chunk-814kkkmq.js +8 -0
- package/web/chunk-8jcvdd5d.js +2 -0
- package/web/{chunk-rbdvc8x7.js → chunk-8w7fyb3v.js} +1 -1
- package/web/chunk-8w8atrdh.js +1 -0
- package/web/{chunk-sda7cyrt.js → chunk-8z0r0wtk.js} +21 -21
- package/web/chunk-935mjq1c.js +39 -0
- package/web/chunk-942g3eqn.js +1 -0
- package/web/{chunk-1gx0zpmp.js → chunk-98y92vmh.js} +9 -9
- package/web/chunk-9ctg0f30.js +3 -0
- package/web/chunk-9fnr00kv.js +4 -0
- package/web/{chunk-fe31sv6t.js → chunk-9yfftz38.js} +1 -1
- package/web/chunk-a0ryzdnp.js +7 -0
- package/web/chunk-a61zrp66.js +1 -0
- package/web/{chunk-dtg5yhhs.js → chunk-af9evdza.js} +1 -1
- package/web/chunk-arnzrqnm.js +1 -0
- package/web/chunk-avxk6jpc.js +2 -0
- package/web/{chunk-c01176kn.js → chunk-awkdw9rw.js} +2 -2
- package/web/{chunk-tkp72r9b.js → chunk-b5h52neg.js} +1 -1
- package/web/chunk-bwy3e58v.js +1 -0
- package/web/{chunk-ja7w629n.js → chunk-c57f714b.js} +2 -2
- package/web/chunk-c6yacwbc.js +30 -0
- package/web/{chunk-823b7866.js → chunk-ctzkqx2g.js} +18 -18
- package/web/{chunk-w37n09px.js → chunk-db3twjvk.js} +10 -10
- package/web/{chunk-hbkasy6c.js → chunk-ddyyc20r.js} +22 -22
- package/web/{chunk-z0zrp8n8.js → chunk-dnv8dx72.js} +1 -1
- package/web/{chunk-jzte2phh.js → chunk-dwjmr0zj.js} +1 -1
- package/web/chunk-dz7g1gnv.js +2 -0
- package/web/{chunk-cez1k71m.js → chunk-eadfxfkw.js} +1 -1
- package/web/{chunk-d9wdsjkk.js → chunk-eqndhs21.js} +2 -2
- package/web/{chunk-cyjnert7.js → chunk-ewx42c11.js} +16 -16
- package/web/chunk-f7jpakwh.js +1 -0
- package/web/{chunk-r4ffr96e.js → chunk-ff1pmd3g.js} +1 -1
- package/web/chunk-fjb3ksfd.js +78 -0
- package/web/chunk-fpb2dd2d.js +2 -0
- package/web/{chunk-fv6vm14n.js → chunk-frnh4zqf.js} +2 -2
- package/web/{chunk-0j9a7811.js → chunk-gn8kyz76.js} +6 -6
- package/web/chunk-gv99c8zv.js +1 -0
- package/web/chunk-h0767tjv.js +1 -0
- package/web/chunk-hqynf99g.js +1 -0
- package/web/{chunk-jam45rqg.js → chunk-jccz14ye.js} +2 -2
- package/web/{chunk-33w36n91.js → chunk-kcjz03h5.js} +2 -2
- package/web/chunk-ket6g0yd.js +1 -0
- package/web/chunk-m9q5nr8f.js +1 -0
- package/web/chunk-mdfksj61.js +1 -0
- package/web/chunk-me7dza1c.js +1 -0
- package/web/{chunk-8773nwdc.js → chunk-myd6sc76.js} +1 -1
- package/web/{chunk-sf101c23.js → chunk-mykrm8ba.js} +2 -2
- package/web/chunk-mzzaet63.js +1 -0
- package/web/chunk-n0wazxgz.js +1 -0
- package/web/{chunk-1s8zg6fb.js → chunk-nnyc889n.js} +5 -5
- package/web/{chunk-xabcx3ry.js → chunk-nvpp0ghj.js} +3 -3
- package/web/chunk-nvt9tkt4.js +1139 -0
- package/web/{chunk-dgwkqcz6.js → chunk-p9hfcamx.js} +2 -2
- package/web/chunk-ph1dgffm.js +1 -0
- package/web/chunk-q34as3v6.js +1 -0
- package/web/{chunk-sd3cdqcm.js → chunk-qh62nkem.js} +2 -2
- package/web/{chunk-j1bw5v1g.js → chunk-qq6m2my8.js} +2 -2
- package/web/{chunk-f93pe4kb.js → chunk-qsqtwf34.js} +4 -4
- package/web/{chunk-85gdsmt4.js → chunk-qz6r9v1z.js} +1 -1
- package/web/chunk-rad2s9ha.js +1 -0
- package/web/{chunk-8nv7q5ac.js → chunk-rasjtvsb.js} +15 -15
- package/web/{chunk-s38s9ff9.js → chunk-rayf24gy.js} +28 -28
- package/web/{chunk-cn0tmwjs.js → chunk-rrpn5r5w.js} +2 -2
- package/web/{chunk-m5y2d4zv.js → chunk-s37beysw.js} +1 -1
- package/web/chunk-s60s09mb.js +1 -0
- package/web/chunk-sk1wkgjw.js +4 -0
- package/web/{chunk-xqyazzm7.js → chunk-spbs56wz.js} +5 -5
- package/web/{chunk-h5cfg3vv.js → chunk-t893141g.js} +2 -2
- package/web/chunk-tftc5v89.js +24 -0
- package/web/chunk-tfvcs2xx.js +1 -0
- package/web/{chunk-q1xxs319.js → chunk-ts6jsfdk.js} +4 -4
- package/web/{chunk-xsz1dfm2.js → chunk-v1exk5wd.js} +20 -20
- package/web/{chunk-3q0v8w45.js → chunk-veam6vk4.js} +79 -79
- package/web/{chunk-xb9m0092.js → chunk-vqmj6peg.js} +1 -1
- package/web/{chunk-cn1xpg3q.js → chunk-vsjpnwsr.js} +2 -2
- package/web/{chunk-et8q775x.js → chunk-w3w18stt.js} +5 -5
- package/web/chunk-wdq2tp9e.js +1 -0
- package/web/chunk-wkf5xfyr.js +1 -0
- package/web/{chunk-fx4mackk.js → chunk-wzd2a4k5.js} +4 -4
- package/web/{chunk-jjjtv2r1.js → chunk-xa43ndfj.js} +2 -2
- package/web/chunk-xh4xn1az.js +1 -0
- package/web/{chunk-2axwda8c.js → chunk-xx11yv61.js} +7 -7
- package/web/chunk-xzwxcxb4.js +1 -0
- package/web/chunk-y1qty77a.js +1 -0
- package/web/{chunk-4anjs6yp.js → chunk-y2rzeb4v.js} +2 -2
- package/web/chunk-ys2tns0p.js +1 -0
- package/web/chunk-z05x9cbm.js +1 -0
- package/web/{chunk-mf6xng5b.js → chunk-zb2bkr7f.js} +2 -2
- package/web/{chunk-wj3ymejj.js → chunk-zdyys4ar.js} +3 -3
- package/web/chunk-zgavhnt8.js +1 -0
- package/web/index.html +1 -1
- package/worker.js +1 -1
- package/chunk-2gcp3xdc.js +0 -2
- package/chunk-320174qe.js +0 -2
- package/chunk-dvb5nd2x.js +0 -2
- package/chunk-frt9k18g.js +0 -480
- package/chunk-ndt6rjt9.js +0 -2
- package/chunk-xy2bxwq8.js +0 -2
- package/chunk-yzevjkms.js +0 -25
- package/chunk-zdyd8hbn.js +0 -2
- package/web/chunk-0jfda4jw.js +0 -2
- package/web/chunk-2p3fkhy8.js +0 -1
- package/web/chunk-3sz5qcwj.js +0 -1
- package/web/chunk-433c80pc.js +0 -1
- package/web/chunk-48cnmhvd.js +0 -106
- package/web/chunk-5r37rwq1.js +0 -4
- package/web/chunk-6bwgdvf6.js +0 -1
- package/web/chunk-7f1t7z72.js +0 -2
- package/web/chunk-7x35g67d.js +0 -78
- package/web/chunk-8pzg8qw4.js +0 -1
- package/web/chunk-8r0s8tx7.js +0 -1
- package/web/chunk-9p5dfvav.js +0 -1
- package/web/chunk-9q9w9pay.js +0 -1
- package/web/chunk-a3teqvz2.js +0 -39
- package/web/chunk-ahztazsg.js +0 -1
- package/web/chunk-bd8ftfxn.js +0 -3
- package/web/chunk-c03bt2pz.js +0 -1
- package/web/chunk-c1ha2xg6.js +0 -8
- package/web/chunk-cgng31df.js +0 -1
- package/web/chunk-cvd4f51j.js +0 -1
- package/web/chunk-cybvxssy.js +0 -1
- package/web/chunk-d22wq71s.js +0 -1
- package/web/chunk-dynajx8x.js +0 -2
- package/web/chunk-f3vv7n52.js +0 -1
- package/web/chunk-fpa81dv7.js +0 -62
- package/web/chunk-g17n6asp.js +0 -1
- package/web/chunk-g9dzaw9e.js +0 -30
- package/web/chunk-gcwhx3av.js +0 -1139
- package/web/chunk-gf8vm6b5.js +0 -1
- package/web/chunk-gnmeyy4h.js +0 -1
- package/web/chunk-hn7mhsbg.js +0 -1
- package/web/chunk-jfvxxp5c.js +0 -1
- package/web/chunk-k8h8zx6r.js +0 -24
- package/web/chunk-m3ajw575.js +0 -1
- package/web/chunk-mz9b5bsa.js +0 -1
- package/web/chunk-np33kmn4.js +0 -1
- package/web/chunk-nvk8mazs.js +0 -1
- package/web/chunk-nyw5ewgv.js +0 -1
- package/web/chunk-p56dcqpr.js +0 -1
- package/web/chunk-pdn4r8x4.js +0 -1
- package/web/chunk-qpt34d8d.js +0 -1
- package/web/chunk-qskt3tqa.js +0 -1
- package/web/chunk-qt3n897m.js +0 -4
- package/web/chunk-r1rt48h9.js +0 -1
- package/web/chunk-r7tgd2fm.js +0 -7
- package/web/chunk-rznszqmy.js +0 -1
- package/web/chunk-s1pefd34.js +0 -1
- package/web/chunk-sc29azev.js +0 -1
- package/web/chunk-t4jc4nac.js +0 -1
- package/web/chunk-t7g366a5.js +0 -24
- package/web/chunk-thbqwq6b.js +0 -1
- package/web/chunk-v94v68xg.js +0 -36
- package/web/chunk-wcphswcx.js +0 -2
- package/web/chunk-wwcnvyjh.css +0 -1
- package/web/chunk-xce8n339.js +0 -1
- package/web/chunk-xfd3b01q.js +0 -1
- package/web/chunk-xtss82z2.js +0 -1
package/chunk-frt9k18g.js
DELETED
|
@@ -1,480 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Wo,Qr,W}from"./chunk-t66jqz12.js";import{Go,He,Tt,zo,Zn,jo,Ei,Pi,gt,Vo,Ne,Zr,Ke}from"./chunk-yzevjkms.js";import{zn,Ti,Kr}from"./chunk-j781n7ca.js";import{Ie,te,$o,jn,I,Vn,ht,Me,dr,U,Le,Kn,ft,de,$t,oe,Xr,Ho,Oe,re,ot,Qn,qo,ye,ki,vi,be,Xn,d,Ri,Q,Jr,G,Ci}from"./chunk-0d51ggzj.js";import{Jn,M,Yn,Ve,_i,Ht,ke}from"./chunk-jp5afrwm.js";import{r,Xe}from"./chunk-bwawt15q.js";var Hg=r(function(sH,Kg){var vv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],ed=/[\n\r\u2028\u2029]/,Mv=/[\s#!"$&'():;<=>@\\^`|~]/g;Kg.exports=function(o){var i=!1;return o.map(function(c){if(i&&typeof c==="string"&&ed.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(ed.test(c.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(c.pattern==="")return"''";return c.pattern.replace(Mv,"\\$&")}if("op"in c&&typeof c.op==="string"){if(vv.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(ed.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(iH,Yg){var Qg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Wg=new RegExp("^"+Qg+"$"),zg="|&;()<> \\t",Ov="'([^']*?)'",Xg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Vg="\\$'"+Xg+"'",rm=new RegExp("\\$'"+Xg+"(?:(')|\\\\?$)","g"),_v="abeEfnrtv",Lv=`\x07\b\x1B\x1B\f
|
|
3
|
-
\r \v`,Nv=/^#$/,td="'",Jg='"',Su="$",Bi="",Dv=4294967296;for(tm=0;tm<4;tm++)Bi+=(Dv*Math.random()).toString(16);var tm,qv=new RegExp("^"+Bi);function Fv(e,o){var i=o.lastIndex,c=[],p;while(p=o.exec(e))if(c[c.length]=p,o.lastIndex===p.index)o.lastIndex+=1;return o.lastIndex=i,c}function jv(e,o,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 o+Bi+JSON.stringify(c)+Bi;return o+c}var Uv=/\\([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 Bv(e,o){var i=o.charAt(0);if(i==="c"){var c=o.charAt(1);return c==="?"?"\x7F":String.fromCharCode(c.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var p=parseInt(o.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(i>="0"&&i<="7")return String.fromCharCode(parseInt(o,8)&255);var g=_v.indexOf(o);return g<0?o:Lv.charAt(g)}function Gv(e){return e.replace(Uv,Bv).split("\x00")[0]}function Kv(e,o){return rm.lastIndex=o,!!rm.exec(e)[1]}function Hv(e,o,i){if(!i)i={};var c=i.escape||"\\",p=i.splitUnquoted===!0?`
|
|
4
|
-
`:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",g="(\\"+c+`['"$\\`+c+zg+"]|\\$\\$|\\$(?!"+Vg.slice(2)+`)|[^\\s'"$`+zg+"])+",y='"(?:\\'+c+'[\\s\\S]|[^"\\'+c+'])*"',b=new RegExp(["("+Qg+")","("+Vg+"|"+g+"|"+y+"|"+Ov+")+"].join("|"),"g"),E=Fv(e,b);if(E.length===0)return[];if(!o)o={};var S=!1;return E.map(function(w){var R=w[0];if(!R||S)return;if(Wg.test(R))return{op:R};var A=!1,C=!1,L="",q=[],X=!1,j=null,V=!1,J;function ee(){J+=1;var ce,Fe,It=R.charAt(J);if(It==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var Je=1;ce=J;while(Je>0&&ce<R.length){if(R.charAt(ce)==="{"&&R.charAt(ce-1)==="$")Je+=1;else if(R.charAt(ce)==="}")Je-=1;ce+=1}if(Je!==0)throw Error("Bad substitution: "+R.slice(J));ce-=1,Fe=R.slice(J,ce),J=ce}else if(/[*@#?$!-]/.test(It))Fe=It;else{var Yt=R.slice(J);if(ce=Yt.match(/[^\w\d_]/),!ce)Fe=Yt,J=R.length;else Fe=Yt.slice(0,ce.index),J+=ce.index-1}return jv(o,"",Fe)}function ae(){if(j===null)return;if(j===0){if(L!=="")q[q.length]=L,L=""}else{q[q.length]=L,L="";for(var ce=1;ce<j;ce+=1)q[q.length]=""}j=null}for(J=0;J<R.length;J++){var K=R.charAt(J);if(p&&K!==Su)ae();if(V=V||!A&&(K==="*"||K==="?"),C)L+=K,C=!1;else if(A)if(K===A)A=!1;else if(A==td)L+=K;else if(K===c)if(J+=1,K=R.charAt(J),K===Jg||K===c||K===Su)L+=K;else L+=c+K;else if(K===Su)L+=ee();else L+=K;else if(K===Jg||K===td)A=K,X=!0;else if(Wg.test(K))return{op:R};else if(Nv.test(K)){S=!0;var ue={comment:e.slice(w.index+J+1)};if(L.length)return[L,ue];return[ue]}else if(K===c)C=!0;else if(K===Su&&R.charAt(J+1)===td&&Kv(R,J))ae(),X=!0,L+=Gv(R.slice(J+2,rm.lastIndex-1)),J=rm.lastIndex-1;else if(K===Su){var he=ee();if(!p)L+=he;else for(var _e=0;_e<he.length;_e+=1){var Ee=he.charAt(_e);if(p.indexOf(Ee)<0)ae(),L+=Ee;else if(j===null)j=Ee===" "||Ee==="\t"||Ee===`
|
|
5
|
-
`?0:1;else if(Ee!==" "&&Ee!=="\t"&&Ee!==`
|
|
6
|
-
`)j+=1}}else L+=K}if(V)return{op:"glob",pattern:L};if(p){if(j!==null&&j>0){q[q.length]=L,L="";for(var se=1;se<j;se+=1)q[q.length]=""}if(L!==""||X&&q.length===0)q[q.length]=L;return q}return L}).reduce(function(w,R){if(typeof R>"u")return w;return[].concat(R).forEach(function(A){w[w.length]=A}),w},[])}Yg.exports=function(o,i,c){var p=Hv(o,i,c);if(typeof i!=="function")return p;return p.reduce(function(g,y){if(typeof y==="object")return g[g.length]=y,g;var b=y.split(RegExp("("+Bi+".*?"+Bi+")","g"));if(b.length===1)return g[g.length]=b[0],g;return b.filter(Boolean).forEach(function(E){g[g.length]=qv.test(E)?JSON.parse(E.split(Bi)[1]):E}),g},[])}});var Fo={};Xe(Fo,{ArchivedError:()=>dt,BadRequestError:()=>t,BusyError:()=>ie,DEFAULT_TIMEOUT:()=>a$,FoldingPolicy:()=>Gc,MAX_ATTACHMENTS:()=>et,MAX_TIMEOUT:()=>u$,MAX_TOOL_OUTPUT:()=>Te,NotFoundError:()=>f,PluginCheckError:()=>pt,ProcessRegistry:()=>Wt,Type:()=>io,aliased:()=>ve,budget:()=>Bc,calls:()=>ls,clip:()=>pe,clipSaved:()=>nt,dataDir:()=>tt,definePlugin:()=>k,estimateMessage:()=>F,estimateTokens:()=>D,estimateTools:()=>Ni,extensionTranscript:()=>Hc,findWindowsBash:()=>tr,foldPoint:()=>jc,foldedThrough:()=>Ia,formatLines:()=>Wc,gateShellCommand:()=>je,groupRuns:()=>Os,historyTodos:()=>ir,newID:()=>ne,normalizeRunRecords:()=>qh,processRegistry:()=>sr,project:()=>Re,projectUserText:()=>Di,releaseProcesses:()=>lr,requestBody:()=>N,resolveShellCommand:()=>Sa,retainProcesses:()=>ar,routeParam:()=>v,runShell:()=>rr,sealPoint:()=>au,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>El,text:()=>u,timerClock:()=>Ce,tool:()=>x,toolSession:()=>z,transcript:()=>pu,usable:()=>$e,userTranscript:()=>Kc,validAttachment:()=>Pt,workState:()=>wl});var Do={};Xe(Do,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>wR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>kR,EventStream:()=>Jn,InMemoryCredentialStore:()=>jn,InMemoryModelsStore:()=>Vn,ModelsError:()=>I,StringEnum:()=>Fq,Type:()=>io,appendAssistantMessageDiagnostic:()=>ke,calculateCost:()=>Q,clampThinkingLevel:()=>G,cleanupSessionResources:()=>Ti,collapseSystemMessages:()=>Oe,contentText:()=>dr,createAssistantMessageDiagnostic:()=>Ht,createAssistantMessageEventStream:()=>Yn,createFauxCore:()=>SR,createInitialSystemMessage:()=>Kn,createModels:()=>Xn,createProvider:()=>d,declarationsEqual:()=>Qn,defaultProviderAuthContext:()=>$o,envApiKeyAuth:()=>h,extractDiagnosticError:()=>_i,fauxAssistantMessage:()=>Oo,fauxProvider:()=>No,fauxText:()=>Nn,fauxThinking:()=>Lo,fauxToolCall:()=>xq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>Xr,getCurrentSystemPrompt:()=>Ho,getCurrentTools:()=>oe,getDeclaredTools:()=>ye,getInitialSystemMessage:()=>de,getModelType:()=>ht,getOverflowPatterns:()=>_q,getSupportedThinkingLevels:()=>Jr,getSystemMessageText:()=>U,getToolStateChanges:()=>qo,hasApi:()=>Ri,hasNonAdditiveToolChanges:()=>vi,hasToolRedefinitions:()=>ki,isContextOverflow:()=>ma,isModelType:()=>Me,isRecoverableLength:()=>Oq,isRetryableAssistantError:()=>CR,lazyApi:()=>te,lazyOAuth:()=>le,lazyStream:()=>Ie,modelsAreEqual:()=>Ci,normalizeContext:()=>ft,parseJsonWithRepair:()=>Qr,parseStreamingJson:()=>W,reduceAssistantMessageFrames:()=>$q,registerSessionResourceCleanup:()=>zn,renderSystemMessageUpdate:()=>Le,repairJson:()=>Wo,resolveTranscript:()=>re,resolveTranscriptTools:()=>be,retryAssistantCall:()=>qq,retryDelayMs:()=>AR,toToolDeclaration:()=>ot,uuidv7:()=>Kr,validateToolArguments:()=>ou,validateToolCall:()=>TU,withoutInitialSystemMessage:()=>$t});var H={};Xe(H,{Counted:()=>pd,Entries:()=>dn,EntriesRegExp:()=>ld,Every:()=>un,EveryAll:()=>Cn,GraphemeCount:()=>EM,HasPropertyKey:()=>me,IsArray:()=>Ge,IsBigInt:()=>Nr,IsBoolean:()=>ln,IsClassInstance:()=>gy,IsConstructor:()=>cd,IsDeepEqual:()=>Ra,IsEqual:()=>P,IsFunction:()=>fs,IsGreaterEqualThan:()=>wa,IsGreaterThan:()=>Hi,IsInteger:()=>im,IsLessEqualThan:()=>hs,IsLessThan:()=>Tu,IsMaxLength:()=>yy,IsMinLength:()=>xy,IsMultipleOf:()=>hy,IsNull:()=>ho,IsNumber:()=>_t,IsObject:()=>ut,IsObjectNotArray:()=>Xo,IsString:()=>yt,IsSymbol:()=>md,IsUndefined:()=>Bt,IsUnsafePropertyKey:()=>Ru,IsValueLike:()=>Wi,Keys:()=>Se,ShiftLeft:()=>bt,Some:()=>Ta,SomeAll:()=>Iy,Symbols:()=>by,Values:()=>dd});var Zi={};Xe(Zi,{Hash:()=>bd,HashCode:()=>ex});var Lt={};Xe(Lt,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>we,ExtendsUnion:()=>Bd,IsExtendsFalse:()=>Hd,IsExtendsTrue:()=>Kd,IsExtendsTrueLike:()=>so,IsExtendsUnion:()=>Gd,Match:()=>br});var io={};Xe(io,{Any:()=>Pa,Array:()=>B,BigInt:()=>vu,Boolean:()=>O,Call:()=>dw,Capitalize:()=>bw,Codec:()=>gm,Conditional:()=>Cw,Constructor:()=>ys,ConstructorParameters:()=>$w,Cyclic:()=>bs,Decode:()=>ox,DecodeBuilder:()=>hm,Dependent:()=>Yi,Encode:()=>sx,EncodeBuilder:()=>fm,Enum:()=>Ky,Evaluate:()=>kn,Exclude:()=>Mw,Extends:()=>Rn,ExtendsResult:()=>Lt,Extract:()=>_w,Function:()=>xs,Generic:()=>ti,Identifier:()=>Mu,Immutable:()=>ix,Index:()=>qw,Infer:()=>$u,InstanceType:()=>cT,Instantiate:()=>Ao,Integer:()=>_,Interface:()=>VS,Intersect:()=>$n,IsAny:()=>vr,IsArray:()=>wt,IsBigInt:()=>mo,IsBoolean:()=>Wn,IsCall:()=>Ua,IsCodec:()=>Hn,IsConstructor:()=>tn,IsCyclic:()=>Qt,IsDependent:()=>Dr,IsEnum:()=>sn,IsEnumValue:()=>Gy,IsFunction:()=>rn,IsGeneric:()=>Ca,IsIdentifier:()=>mx,IsImmutable:()=>ea,IsInfer:()=>on,IsInteger:()=>hn,IsIntersect:()=>ze,IsKind:()=>Ae,IsLiteral:()=>xt,IsNever:()=>co,IsNull:()=>Ss,IsNumber:()=>kr,IsObject:()=>Qe,IsOptional:()=>mn,IsParameter:()=>fx,IsReadonly:()=>ra,IsRecord:()=>Gt,IsRef:()=>jt,IsRefine:()=>ym,IsRest:()=>ai,IsSchema:()=>Pr,IsString:()=>an,IsSymbol:()=>ws,IsTemplateLiteral:()=>ur,IsThis:()=>vm,IsTuple:()=>mt,IsUndefined:()=>rs,IsUnion:()=>xe,IsUnknown:()=>nn,IsUnsafe:()=>dm,IsVoid:()=>po,KeyOf:()=>pT,Literal:()=>s,Lowercase:()=>Ew,Mapped:()=>IT,Module:()=>aR,Never:()=>zt,NonNullable:()=>wT,Null:()=>vn,Number:()=>Y,Object:()=>l,Omit:()=>RT,Optional:()=>n,Parameter:()=>na,Parameters:()=>CT,Partial:()=>$T,Pick:()=>DT,Readonly:()=>ax,ReadonlyObject:()=>Ef,ReadonlyType:()=>jT,Record:()=>Ts,RecordKey:()=>ii,RecordPattern:()=>gn,RecordValue:()=>fr,Ref:()=>cn,Refine:()=>ux,Required:()=>tR,Rest:()=>sa,ReturnType:()=>nR,Script:()=>pR,String:()=>a,Symbol:()=>Ma,TemplateLiteral:()=>hS,This:()=>$m,Tuple:()=>Ur,Uncapitalize:()=>Sw,Undefined:()=>La,Union:()=>m,Unknown:()=>Rr,Unsafe:()=>qr,Uppercase:()=>ww,Void:()=>Mm,With:()=>gp});var tu={};Xe(tu,{Clear:()=>Kk,Entries:()=>WF,Get:()=>JF,Has:()=>VF,IsDate:()=>Ya,IsDateTime:()=>Rp,IsDuration:()=>kp,IsEmail:()=>Ap,IsHostname:()=>Lp,IsIPv4:()=>qp,IsIPv6:()=>Fp,IsIdnEmail:()=>Np,IsIdnHostname:()=>Dp,IsIri:()=>Up,IsIriReference:()=>jp,IsJsonPointer:()=>Gp,IsJsonPointerUriFragment:()=>Bp,IsRegex:()=>Kp,IsRelativeJsonPointer:()=>Hp,IsTime:()=>Za,IsUri:()=>Vp,IsUriReference:()=>Wp,IsUriTemplate:()=>zp,IsUrl:()=>Jp,IsUuid:()=>Qp,Reset:()=>Wk,Set:()=>zF,Test:()=>Hk});var Eu="shell-guard",Ng=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class f extends Error{constructor(e){super(e);this.name="NotFoundError"}}function Dg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function qg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function Av(e,o){if(e===o)return 0;let i=Array.from({length:o.length+1},(c,p)=>p);for(let c=1;c<=e.length;c++){let p=i[0]??0;i[0]=c;for(let g=1;g<=o.length;g++){let y=i[g]??0;i[g]=Math.min((i[g]??0)+1,(i[g-1]??0)+1,p+(e[c-1]===o[g-1]?0:1)),p=y}}return i[o.length]??0}function Fg(e,o){let i=Dg(e);if(!i)return[];let c=qg(e),p=[];for(let g of o){let y=g.id.indexOf("/"),b=y>=0?g.id.slice(y+1):"",S=[g.id,g.name,b].filter(Boolean).map((R)=>({compact:Dg(R),tokens:qg(R)})).filter((R)=>R.compact.length>0),w=Number.POSITIVE_INFINITY;for(let R of S)if(R.compact===i)w=Math.min(w,0);else if(R.compact.includes(i)||i.includes(R.compact)){let A=Math.abs(R.compact.length-i.length);w=Math.min(w,1+A/Math.max(R.compact.length,i.length))}else{let A=0;for(let C of c)if(R.tokens.has(C))A++;if(A>0){let C=A/Math.max(c.size,R.tokens.size);w=Math.min(w,10+(1-C)*10)}}if(!Number.isFinite(w)&&i.length>=4){let R=Math.max(2,Math.floor(i.length*0.34));for(let A of S){if(Math.abs(A.compact.length-i.length)>R)continue;let C=Av(i,A.compact);if(C<=R)w=Math.min(w,100+C)}}if(Number.isFinite(w))p.push({model:g,score:w})}return p.sort((g,y)=>g.score-y.score||g.model.id.localeCompare(y.model.id))}function Cv(e,o,i=5){return Fg(e,o).slice(0,Math.max(1,i)).map((c)=>c.model)}function Fr(e,o){let i=Fg(e,o);if(i.length===0)return;let c=i.filter((g)=>g.score===0);if(c.length===1&&c[0])return c[0].model;if(c.length>1)return;let p=i.filter((g)=>g.score<10);if(p.length===1&&p[0])return p[0].model;return}function Wr(e,o){let i=[...o].sort((y,b)=>y.id.localeCompare(b.id)),c=(y)=>y.name===y.id?y.id:`${y.id} (${y.name})`,p=Cv(e,i).map(c),g=i.map(c);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${g.length}): ${g.length>0?g.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
|
|
7
|
-
`)}var mi=["openai-completions","openai-responses","anthropic-messages"];function $r(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let o=e.trim().toLowerCase();if(!o)return;let i=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let 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 Ql(e){if(e>=1e6&&e%1e5===0)return`${e/1e6}m`;if(e>=1000&&e%1000===0)return`${e/1000}k`;return String(e)}function Pv(e){let o=e.trim();if(!o)return;let i,c,p=o,g=p.match(/\s*\[(.*?)\]\s*$/);if(g&&g.index!==void 0){p=p.slice(0,g.index).trim();let w=g[1]?.split(",").map((A)=>A.trim()).filter(Boolean)??[],R=0;for(let A of w){let C=A.indexOf("=");if(C>=0){let L=A.slice(0,C).trim().toLowerCase(),q=$r(A.slice(C+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=$r(A);if(R===0)i=L;else if(R===1)c=L;R++}}}else{let w=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(w?.[1]&&w[2])p=w[1].trim(),i=$r(w[2])}let y=p.indexOf("="),b,E;if(y<0)b=p.trim(),E=b;else b=p.slice(0,y).trim(),E=p.slice(y+1).trim()||b;if(!b)return;let S={id:b,name:E};if(i!==void 0)S.contextWindow=i;if(c!==void 0)S.maxTokens=c;return S}function er(e){return e.split(/\r?\n/).map(Pv).filter((o)=>o!==void 0)}function Co(e){return e.map((o)=>{let i=o.name===o.id?o.id:`${o.id}=${o.name}`,c=[];if(o.contextWindow!==void 0)c.push(Ql(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)c.push(Ql(o.maxTokens));else c.push(`max=${Ql(o.maxTokens)}`);return c.length>0?`${i} [${c.join(", ")}]`:i}).join(`
|
|
8
|
-
`)}var jg=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var On=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],hi=["text","regex"],fi=["best","recent"],gi=["session","none"];var Ft=4,yi="https://basalt.work",bi=["https://basalt.work","https://www.basalt.work"],Hr=7420;var Xl=["auto","bash","powershell","cmd"];var Io=["active","archived","all"],Si="session.group";var Ug=["pending","in_progress","completed"],Yl="basalt-session",em=["image","text","path"];var Bg=["defer","always"],Gg=["global","tool","source"];function Pe(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let i=o;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:o};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:o}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:o};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:o}}}function wi(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var et=10,$v=15000000;function Pt(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&em.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=$v}function Zl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}var Wv=Hg(),rd=Zg();import{AsyncLocalStorage as zv}from"async_hooks";var z=new zv;var Vv=3,ey=160,Jv=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),Qv=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),ny=/^[A-Za-z_][A-Za-z0-9_]*=/,Xv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),Yv=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),Zv=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,eM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),tM=new Set(["command","builtin","nohup","time","exec"]),rM=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 nm(e){return{out:e.out,depth:e.depth+1}}function ty(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function nd(e,o,i,c){let p=e.length,g=0,y=o;while(y<p){let b=e.charAt(y);if(b==="\\"){y+=2;continue}if(b==="'"||b==='"'||b==="`"){let E=y+1;while(E<p){let S=e.charAt(E);if(S==="\\"){E+=2;continue}if(S===b)break;E++}y=E+1;continue}if(b===i)g++;else if(b===c){if(g--,g===0)return y+1}y++}return p}function nM(e){let o={text:"",subs:[],heredocs:[]},i=[],c=[],p=e.length,g=0,y=0,b=null,E=(S)=>{if(e.charAt(S)==="`"){let C=S+1;while(C<p){let L=e.charAt(C);if(L==="\\"){C+=2;continue}if(L==="`")break;C++}return o.subs.push(e.slice(S+1,C)),C<p?C+1:p}if(e.charAt(S+1)==="("){let C=nd(e,S+1,"(",")");if(e.charAt(S+2)==="(")return i.push(e.slice(S,C)),C;return o.subs.push(e.slice(S+2,C-1)),C}let R=nd(e,S+1,"{","}"),A=e.slice(S+2,R-1);for(let C=0;C<A.length;C++){let L=A.charAt(C);if(L==="\\"){C++;continue}if(L==="`"){let q=A.indexOf("`",C+1);o.subs.push(q<0?A.slice(C+1):A.slice(C+1,q)),C=q<0?A.length:q;continue}if(L==="$"&&A.charAt(C+1)==="("){let q=nd(A,C+1,"(",")");o.subs.push(A.slice(C+2,q-1)),C=q-1}}return R};while(g<p){let S=e.charAt(g);if(b==="'"){if(S==="'")b=null;i.push(S),g++;continue}if(b==='"'){if(S==="\\"){if(!'$`"\\\n'.includes(e.charAt(g+1)))i.push("\\");i.push(S,e.charAt(g+1)),g+=2;continue}if(S==='"'){b=null,i.push(S),g++;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}i.push(S),g++;continue}if(S==="'"||S==='"'){b=S,i.push(S),g++;continue}if(S==="\\"){i.push(S,e.charAt(g+1)),g+=2;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}if(S==="#"){let w=i.at(-1);if(w===void 0||`
|
|
9
|
-
;&|()`.includes(w)){while(g<p&&e.charAt(g)!==`
|
|
10
|
-
`)g++;continue}i.push(S),g++;continue}if(S==="<"&&e.charAt(g+1)==="<"&&e.charAt(g+2)!=="<"){let w=g+2;if(e.charAt(w)==="-")w++;i.push(e.slice(g,w));let R=w;while(R<p&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let A="";while(R<p){let C=e.charAt(R);if(C==="'"||C==='"'){let L=e.indexOf(C,R+1);if(L<0)break;A+=e.slice(R+1,L),R=L+1;continue}if(C==="\\"){A+=e.charAt(R+1),R+=2;continue}if(` \r
|
|
11
|
-
;&|()<>`.includes(C))break;A+=C,R++}if(A)c.push(A);g=w;continue}if(S===`
|
|
12
|
-
`){if(c.length>0){let w=Zv.test(i.slice(y).join(""));g++;for(let R of c.splice(0)){let A=g,C=p;while(g<p){let L=e.indexOf(`
|
|
13
|
-
`,g),q=L<0?p:L;if(e.slice(g,q).trim()===R){C=g,g=L<0?p:L+1;break}g=L<0?p:L+1}if(w&&C>A)o.heredocs.push(e.slice(A,C))}}else g++;i.push(";",`
|
|
14
|
-
`),y=i.length;continue}i.push(S),g++}return o.text=i.join(""),o}function wu(e,o){if(o.depth>Vv)return;let i=nM(e),c;try{c=rd(i.text)}catch{return}let p=[];for(let g of c){if(typeof g==="string"){p.push({kind:"word",text:g});continue}if("pattern"in g){p.push({kind:"word",text:g.pattern});continue}if("op"in g)p.push({kind:"op",text:g.op})}oM(p,o);for(let g of i.subs)wu(g,nm(o));for(let g of i.heredocs)wu(g,nm(o))}function oM(e,o){let i=[],c=()=>{if(i.length>0)sM(i,o);i=[]};for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;if(g.kind==="op"){if(Xv.has(g.text)){c();continue}if(Yv.has(g.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(g.text)}c()}function sM(e,o){let i=0;for(;;){let y=e[i];if(y===void 0)return;if(Qv.has(y)||ny.test(y)){i++;continue}let b=aM(ty(y),e,i);if(b===i)break;i=b}let c=e[i];if(c===void 0)return;let p=ty(c),g=e.slice(i+1);if(p==="git"){cM(c,g,o);return}if(Jv.has(p)){iM(g,o);return}if(p==="powershell"||p==="pwsh")ry(g,/^-(command|c)$/i,o);if(p==="cmd")ry(g,/^\/[ck]$/i,o)}function ry(e,o,i){for(let c=0;c<e.length;c++)if(o.test(e[c]??"")){let p=e.slice(c+1).join(" ");if(p.trim())wu(p,nm(i));return}}function iM(e,o){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 g=p[1]||e[i+1];if(g)wu(g,nm(o));return}if(c.startsWith("-")||c==="")continue;return}}function aM(e,o,i){if(tM.has(e)){let g=i+1;while(o[g]?.startsWith("-"))g++;return g}let c=rM.get(e);if(!c)return i;let p=i+1;for(;;){let g=o[p];if(g===void 0)return p;if(c.includes(g)){p+=2;continue}if(ny.test(g)||g.startsWith("-")){p++;continue}return p}}function Qo(e,o){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(o))}function ro(e,o){return e.some((i)=>i===`--${o}`||i.startsWith(`--${o}=`))}var uM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Qo(e,"f")||Qo(e,"i")||ro(e,"force")||ro(e,"interactive"))&&!(Qo(e,"n")||ro(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Qo(e,"f")||ro(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Qo(e,"f")||ro(e,"force")||Qo(e,"C")||ro(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>Qo(e,"f")||ro(e,"force")||ro(e,"force-with-lease")||ro(e,"force-if-includes")||ro(e,"delete")||ro(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>ro(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Qo(e,"D")||Qo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>ro(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>Qo(e,"f")||ro(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(Qo(e,"f")||ro(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function cM(e,o,i){let c=0;for(;;){let E=o[c];if(E===void 0)break;if(eM.has(E)){c+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(E)||/^-[Cc].+/.test(E)||E.startsWith("-")){c++;continue}break}let p=o[c]?.toLowerCase();if(!p)return;let g=uM[p];if(!g)return;let y=g(o.slice(c+1));if(!y)return;let b=[e,...o.slice(c)].join(" ");i.out.push({rule:p,fragment:b.length>ey?`${b.slice(0,ey)}\u2026`:b,reason:y})}function sd(e){let o={out:[],depth:0};return wu(e,o),o.out}function oy(e){let o=e.slice(0,5).map((c)=>`${c.fragment}\uFF08${c.reason}\uFF09`),i=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${i}`}var od=new Map;function mM(e,o,i,c,p){let g=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((y)=>{let b=(S)=>{if(!od.delete(g))return;p?.removeEventListener("abort",E),y(S)},E=()=>{sy(e,g),b("aborted")};if(od.set(g,{session:e,finish:b}),e.appendExtension({namespace:Eu,kind:"requested",schemaVersion:1,payload:{id:g,sessionID:e.id,command:o.slice(0,4000),summary:c.slice(0,5).map(({fragment:S,reason:w})=>({fragment:S,reason:w})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)E();else p?.addEventListener("abort",E,{once:!0})})}function sy(e,o){try{e.appendExtension({namespace:Eu,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Mo(e,o,i){let c=od.get(o);if(!c||c.session!==e){if(!pM(e,o))return"unknown";return sy(e,o),"expired"}return e.appendExtension({namespace:Eu,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),c.finish(i?"approved":"denied"),"answered"}function pM(e,o){let i=!1;for(let c of e.entries()){if(c.type!=="extension"||c.namespace!==Eu)continue;let p=c.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==o)continue;if(c.kind==="requested")i=!0;else if(c.kind==="answered"||c.kind==="cancelled")return!1}return i}function id(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${oy(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function je(e,o){let i=sd(e);if(!i.at(0))return;let p=oy(i),g=z.getStore();if(g?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${id(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let y=await mM(g,e,p,i,o);if(y==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${y==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{existsSync as lM,mkdirSync as dM,writeFileSync as fM}from"fs";import{homedir as hM}from"os";import{join as Gi}from"path";function tt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=hM();if(process.platform==="win32")return Gi(e.LOCALAPPDATA??Gi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Gi(o,"Library","Application Support","basalt");return Gi(e.XDG_DATA_HOME??Gi(o,".local","share"),"basalt")}function gM(e){return Gi(e,".basalt","tmp")}function ad(e){let o=gM(e);dM(o,{recursive:!0});let i=Gi(o,".gitignore");if(!lM(i))fM(i,`*
|
|
15
|
-
!.gitignore
|
|
16
|
-
`);return o}function om(e){try{let o=ad(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var ds={assign:0,create:0,clone:0,discard:0,update:0};function Ki(e,o,i){return e>=o&&e<=i}function uy(e){return e===8205}function yM(e){return Ki(e,55296,56319)}function iy(e){return Ki(e,127462,127487)}function cy(e){return Ki(e,65024,65039)}function my(e){return Ki(e,768,879)||Ki(e,6832,6911)||Ki(e,7616,7679)||Ki(e,65056,65071)}function sm(e){return e>65535?2:1}function ay(e,o){while(o<e.length){let i=e.codePointAt(o);if(my(i)||cy(i))o+=sm(i);else break}return o}function ud(e,o){let i=e.codePointAt(o),c=o+sm(i);c=ay(e,c);while(c<e.length-1&&uy(e.codePointAt(c))){let p=e.codePointAt(c+1);c+=1+sm(p),c=ay(e,c)}if(iy(i)&&c<e.length&&iy(e.codePointAt(c)))c+=sm(e.codePointAt(c));return c}function py(e){return e>=768&&(yM(e)||my(e)||cy(e)||uy(e))}function ly(e){let o=0,i=0;while(i<e.length)i=ud(e,i),o++;return o}function xM(e,o){let i=0,c=0;while(c<e.length)if(c=ud(e,c),++i>=o)return!0;return!1}function IM(e,o){let i=0,c=0;while(c<e.length)if(c=ud(e,c),++i>o)return!1;return!0}function dy(e,o){if(o===0)return!0;if(e.length<o)return!1;let i=0;while(!0){if(py(e.charCodeAt(i)))return xM(e,o);if(++i>=o)return!0}}function fy(e,o){if(e.length<=o)return!0;let i=0;while(!0){if(py(e.charCodeAt(i)))return IM(e,o);if(++i>o)return!1}}function Ge(e){return Array.isArray(e)}function Nr(e){return P(typeof e,"bigint")}function ln(e){return P(typeof e,"boolean")}function cd(e){if(Bt(e)||!fs(e))return!1;let o=Function.prototype.toString.call(e);if(/^class\s/.test(o))return!0;if(/\[native code\]/.test(o))return!0;return!1}function fs(e){return P(typeof e,"function")}function im(e){return Number.isInteger(e)}function ho(e){return P(e,null)}function _t(e){return Number.isFinite(e)}function Xo(e){return ut(e)&&!Ge(e)}function ut(e){return P(typeof e,"object")&&!ho(e)}function yt(e){return P(typeof e,"string")}function md(e){return P(typeof e,"symbol")}function Bt(e){return P(e,void 0)}function P(e,o){return e===o}function Hi(e,o){return e>o}function Tu(e,o){return e<o}function hs(e,o){return e<=o}function wa(e,o){return e>=o}function hy(e,o){if(Nr(e)||Nr(o))return BigInt(e)%BigInt(o)===0n;let i=0.0000000001;if(!_t(e))return!0;if(im(e)&&1/o%1===0)return!0;let c=e%o;return Math.min(Math.abs(c),Math.abs(c-o),Math.abs(c+o))<i}function gy(e){if(!ut(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(ho(o))return!1;return P(typeof o.constructor,"function")&&!(P(o.constructor,globalThis.Object)||P(o.constructor.name,"Object"))}function Wi(e){return Nr(e)||ln(e)||ho(e)||_t(e)||yt(e)||Bt(e)}function EM(e){return ly(e)}function yy(e,o){return fy(e,o)}function xy(e,o){return dy(e,o)}function un(e,o,i){return e.every((c,p)=>p<o||i(c,p))}function Cn(e,o,i){let c=!0;return e.forEach((p,g)=>{if(g>=o&&!i(p,g))c=!1}),c}function Ta(e,o){return e.some((i,c)=>o(i,c))}function Iy(e,o){let i=!1;return e.forEach((c,p)=>{if(o(c,p))i=!0}),i}function pd(e,o){return e.reduce((i,c,p)=>o(c,p)?++i:i,0)}function bt(e,o,i){return P(e.length,0)?i():o(e[0],e.slice(1))}function Ru(e){return P(e,"__proto__")||P(e,"constructor")||P(e,"prototype")}function me(e,o){return Ru(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function ld(e){return Se(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function dn(e){return Object.entries(e)}function Se(e){return Object.getOwnPropertyNames(e)}function by(e){return Object.getOwnPropertySymbols(e)}function dd(e){return Object.values(e)}function SM(e,o){if(!ut(o))return!1;let i=Se(e);return P(i.length,Se(o).length)&&i.every((c)=>Ra(e[c],o[c]))}function wM(e,o){return Ge(o)&&P(e.length,o.length)&&e.every((i,c)=>Ra(e[c],o[c]))}function Ra(e,o){return Ge(e)?wM(e,o):ut(e)?SM(e,o):P(e,o)}var TM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function RM(e){return TM.test(e)}function wn(e,o){return`(${e} && ${o})`}function xr(e,o){return`(${e} || ${o})`}function Bn(e){return`!(${e})`}function am(e){return`Array.isArray(${e})`}function Ey(e){return`typeof ${e} === "bigint"`}function kM(e){return`typeof ${e} === "boolean"`}function AM(e){return`Number.isInteger(${e})`}function CM(e){return`${e} === null`}function Sy(e){return`Number.isFinite(${e})`}function wy(e){return wn(Ty(e),Bn(am(e)))}function Ty(e){return`typeof ${e} === "object" && ${e} !== null`}function Ry(e){return`typeof ${e} === "string"`}function PM(e){return`typeof ${e} === "symbol"`}function fd(e){return`${e} === undefined`}function $M(e){return`typeof ${e} === "function"`}function vM(e){return`Guard.IsConstructor(${e})`}function uo(e,o){return`${e} === ${o}`}function ky(e,o){return`${e} > ${o}`}function hd(e,o){return`${e} < ${o}`}function zi(e,o){return`${e} <= ${o}`}function ku(e,o){return`${e} >= ${o}`}function MM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function OM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function gs(e,o,i,c){return P(o,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${c}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${o}) || (${c}))`}function _M(e,o,i){return`${e}.some((${o[0]}, ${o[1]}) => ${i})`}function LM(e,o,i){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${i}) result = true }); return result })(${e})`}function um(e,o,i){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${i}) ? ++result : result, 0)`}function Ay(e){return`Object.entries(${e})`}function Vi(e){return`Object.getOwnPropertyNames(${e})`}function Ji(e,o){return P(o,'"__proto__"')||P(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function Cy(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function NM(e){return`[${e.join(", ")}]`}function Ys(e,o){return`((${e.join(", ")}) => ${o})`}function Ir(e,o){return`${e}(${o.join(", ")})`}function gd(e,o){return`new ${e}(${o.join(", ")})`}function Et(e,o){return`${e}${RM(o)?`.${o}`:`[${qe(o)}]`}`}function qe(e){if(!Wi(e))throw Error("Unsupported Constant");return yt(e)?JSON.stringify(e):`${e}`}function DM(e,o,i){return`(${e} ? ${o} : ${i})`}function cm(e){return`{ ${e.join("; ")}; }`}function Ns(e,o){return`const ${e} = ${o}`}function Py(e,o){return`if(${e}) { ${o} }`}function mm(e){return`return ${e}`}function Pn(e){return P(e.length,0)?"true":e.reduce((o,i)=>wn(o,i))}function yd(e){return P(e.length,0)?"false":e.reduce((o,i)=>xr(o,i))}function qM(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function FM(e){return e instanceof Boolean}function jM(e){return e instanceof Number}function UM(e){return e instanceof String}function $y(e){return globalThis.ArrayBuffer.isView(e)}function vy(e){return e instanceof globalThis.RegExp}function BM(e){return e instanceof globalThis.Date}function GM(e){return e instanceof globalThis.Set}function KM(e){return e instanceof globalThis.Map}var WM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Yo(){return WM}function Zs(e){return Yo().immutableTypes?Object.freeze(e):e}function fn(e,o){return ds.assign+=1,Zs({...e,...o})}function zM(e){return e}function VM(e){return me(e,"~kind")||me(e,"~unsafe")}function JM(e){let o={};for(let i of Se(e)){if(Ru(i))continue;let c=Object.getOwnPropertyDescriptor(e,i);if(c.value=Qi(c.value),P(c.enumerable,!0))o[i]=c.value;else Object.defineProperty(o,i,c)}return o}function QM(e){let o={};for(let i of Se(e)){if(Ru(i))continue;o[i]=Qi(e[i])}for(let i of by(e))o[i]=Qi(e[i]);return o}function XM(e){return gy(e)?zM(e):VM(e)?JM(e):QM(e)}function YM(e){return e.map((o)=>Qi(o))}function ZM(e){return e.slice()}function eO(e){return new RegExp(e.source,e.flags)}function tO(e){return new Map(Qi([...e.entries()]))}function rO(e){return new Set(Qi([...e.values()]))}function Qi(e){return $y(e)?ZM(e):vy(e)?eO(e):KM(e)?tO(e):GM(e)?rO(e):Ge(e)?YM(e):ut(e)?XM(e):e}function ka(e){return ds.clone+=1,Qi(e)}function nO(e,o){for(let i of Object.keys(o))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:o[i]});return e}function My(e,o){return{...e,...o}}function vt(e,o,i={}){ds.create+=1;let c=My(o,i),p=Yo().enumerableKind?My(c,e):nO(c,e);return Zs(p)}function Zo(e,o){ds.discard+=1;let i={};for(let c of Se(e)){if(o.includes(c))continue;let p=Object.getOwnPropertyDescriptor(e,c);p.value=ka(p.value),Object.defineProperty(i,c,p)}return Zs(i)}function St(e,o,i){ds.update+=1;let c=Yo(),p=ka(e);for(let g of Object.keys(o))Object.defineProperty(p,g,{configurable:!0,writable:!0,enumerable:c.enumerableKind,value:o[g]});for(let g of Object.keys(i))Object.defineProperty(p,g,{configurable:!0,enumerable:!0,writable:!0,value:i[g]});return Zs(p)}function Ae(e,o){return ut(e)&&me(e,"~kind")&&P(e["~kind"],o)}function Pr(e){return ut(e)}function De(e,o,i){return vt({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:i},{})}function ei(e){return Ae(e,"Deferred")}function oO(e){return St(e,{"~readonly":!0},{})}function Cu(e,o){return St(oO(e),{},o)}function Oy(e,o,i,c){let p=fe(e,o,i);return Cu(p,c)}function sO(e){return St(e,{"~optional":!0},{})}function Pu(e,o){return St(sO(e),{},o)}function _y(e,o,i,c){let p=fe(e,o,i);return Pu(p,c)}function B(e,o){return vt({"~kind":"Array"},{type:"array",items:e},o)}function wt(e){return Ae(e,"Array")}function Aa(e){return Zo(e,["~kind","type","items"])}function ys(e,o,i={}){return vt({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},i)}function tn(e){return Ae(e,"Constructor")}function Ly(e){return Zo(e,["~kind","type","parameters","instanceType"])}function xs(e,o,i={}){return vt({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},i)}function rn(e){return Ae(e,"Function")}function Ny(e){return Zo(e,["~kind","type","parameters","returnType"])}function cn(e,o){return vt({["~kind"]:"Ref"},{$ref:e},o)}function jt(e){return Ae(e,"Ref")}function ti(e,o){return vt({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Ca(e){return Ae(e,"Generic")}function Pa(e){return vt({["~kind"]:"Any"},{},e)}function vr(e){return Ae(e,"Any")}var Dy="(?!)";function zt(e){return vt({"~kind":"Never"},{not:{}},e)}function co(e){return Ae(e,"Never")}function Is(e,o={}){return De("AddOptional",[e],o)}function Xi(e,o={}){return Pu(e,o)}function n(e){return Xi(e)}function mn(e){return Pr(e)&&me(e,"~optional")}function qy(e){return Se(e).filter((o)=>!mn(e[o]))}function pm(e){return Se(e)}function lm(e){return dd(e)}function l(e,o={}){let i=qy(e),c=i.length>0?{required:i}:{};return vt({"~kind":"Object"},{type:"object",...c,properties:e},o)}function Qe(e){return Ae(e,"Object")}function Fy(e){return Zo(e,["~kind","type","properties","required"])}function Rr(e){return vt({["~kind"]:"Unknown"},{},e)}function nn(e){return Ae(e,"Unknown")}function bs(e,o,i){let c=Se(e).reduce((p,g)=>({...p,[g]:St(e[g],{},{$id:g})}),{});return vt({["~kind"]:"Cyclic"},{$defs:c,$ref:o},i)}function Qt(e){return Ae(e,"Cyclic")}function qr(e){return St(e,{["~unsafe"]:null},{})}function dm(e){return Xo(e)&&me(e,"~unsafe")&&ho(e["~unsafe"])}function Tn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function $u(...e){let[o,i]=Tn(e,{2:(c,p)=>[c,p,p],1:(c)=>[c,Rr(),Rr()]});return vt({["~kind"]:"Infer"},{type:"infer",name:o,extends:i},{})}function on(e){return Ae(e,"Infer")}function Yi(e,o,i,c={}){return vt({"~kind":"Dependent"},{if:e,then:o,else:i},c)}function Dr(e){return Ae(e,"Dependent")}function jy(e){return Zo(e,["~kind","if","then","else"])}function Uy(e){return Xo(e)}function By(e){return Se(e).filter((i)=>isNaN(i)).reduce((i,c)=>[...i,e[c]],[])}function Gy(e){return yt(e)||_t(e)}function Ky(e,o){let i=Uy(e)?By(e):e;return vt({"~kind":"Enum"},{enum:i},o)}function sn(e){return Ae(e,"Enum")}function $n(e,o={}){return vt({"~kind":"Intersect"},{allOf:e},o)}function ze(e){return Ae(e,"Intersect")}function Hy(e){return Zo(e,["~kind","allOf"])}var xd=void 0;function iO(){try{return zy("null")(),!0}catch{return!1}}function Wy(){if(Bt(xd))xd=iO();return xd&&Yo().useAcceleration}function zy(...e){return new globalThis.Function(...e)}function jr(){throw Error("Unreachable")}function aO(e){let o=new Set,i=e;while(i&&i!==Object.prototype){for(let c of Reflect.ownKeys(i))if(c!=="constructor"&&typeof c!=="symbol")o.add(c);i=Object.getPrototypeOf(i)}return[...o]}function uO(e){return typeof e==="number"}var Gn;(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"})(Gn||(Gn={}));var $a=BigInt("14695981039346656037"),[cO,mO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],pO=Array.from({length:256}).map((e,o)=>BigInt(o)),Xy=new Float64Array(1),Yy=new DataView(Xy.buffer),Zy=new Uint8Array(Xy.buffer);function bn(e){$a=$a^pO[e],$a=$a*cO%mO}function lO(e){bn(Gn.Array);for(let o of e)ri(o)}function dO(e){bn(Gn.BigInt),Yy.setBigInt64(0,e);for(let o of Zy)bn(o)}function Jy(e){bn(Gn.Boolean),bn(e?1:0)}function fO(e){bn(Gn.Constructor),ri(e.toString())}function hO(e){bn(Gn.Date),ri(e.getTime())}function gO(e){bn(Gn.Function),ri(e.toString())}function yO(e){bn(Gn.Null)}function Qy(e){bn(Gn.Number),Yy.setFloat64(0,e,!0);for(let o of Zy)bn(o)}function xO(e){bn(Gn.Object);for(let o of aO(e).sort())ri(o),ri(e[o])}function IO(e){bn(Gn.RegExp),Id(e.toString())}var bO=new TextEncoder;function Id(e){bn(Gn.String);for(let o of bO.encode(e))bn(o)}function EO(e){bn(Gn.Symbol),ri(e.toString())}function SO(e){bn(Gn.TypeArray);let o=new Uint8Array(e.buffer);for(let i=0;i<o.length;i++)bn(o[i])}function wO(e){return bn(Gn.Undefined)}function ri(e){return $y(e)?SO(e):BM(e)?hO(e):vy(e)?IO(e):FM(e)?Jy(e.valueOf()):UM(e)?Id(e.valueOf()):jM(e)?Qy(e.valueOf()):uO(e)?Qy(e):Ge(e)?lO(e):ln(e)?Jy(e):Nr(e)?dO(e):cd(e)?fO(e):ho(e)?yO(e):ut(e)?xO(e):yt(e)?Id(e):md(e)?EO(e):Bt(e)?wO(e):fs(e)?gO(e):jr()}function ex(e){return $a=BigInt("14695981039346656037"),ri(e),$a}function bd(e){return ex(e).toString(16).padStart(16,"0")}function tx(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 TO=tx;function rx(){return TO}class fm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,i=Hn(o)?(g)=>this.decode(o["~codec"].decode(g)):this.decode,c=Hn(o)?(g)=>o["~codec"].encode(e(g)):e,p={decode:i,encode:c};return St(this.type,{"~codec":p},{})}}class hm{constructor(e){this.type=e}Decode(e){return new fm(this.type,e)}}function gm(e){return new hm(e)}function ox(e,o){return gm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function sx(e,o){return gm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Hn(e){return Pr(e)&&me(e,"~codec")&&ut(e["~codec"])&&me(e["~codec"],"encode")&&me(e["~codec"],"decode")}function ix(e){return va(e)}function ea(e){return Pr(e)&&me(e,"~immutable")}function Es(e,o={}){return De("AddReadonly",[e],o)}function ta(e,o={}){return Cu(e,o)}function ax(e){return ta(e)}function ra(e){return Pr(e)&&me(e,"~readonly")}function kO(e,o){let i=ym(e)?[...e["~refine"],o]:[o];return St(e,{"~refine":i},{})}function ux(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,()=>"Refine Error"]});return kO(o,{check:i,error:c})}function AO(e){return Xo(e)&&me(e,"check")&&me(e,"error")&&fs(e.check)&&fs(e.error)}function ym(e){return Pr(e)&&me(e,"~refine")&&Ge(e["~refine"])&&un(e["~refine"],0,(o)=>AO(o))}var cx="-?(?:0|[1-9][0-9]*)n";function vu(e){return vt({"~kind":"BigInt"},{type:"bigint"},e)}function mo(e){return Ae(e,"BigInt")}function O(e){return vt({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return Ae(e,"Boolean")}function Mu(e){return vt({"~kind":"Identifier"},{name:e})}function mx(e){return Ae(e,"Identifier")}var xm="-?(?:0|[1-9][0-9]*)";function _(e){return vt({"~kind":"Integer"},{type:"integer"},e)}function hn(e){return Ae(e,"Integer")}class px extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function CO(e){return Nr(e)?"bigint":ln(e)?"boolean":_t(e)?"number":yt(e)?"string":(()=>{throw new px(e)})()}function s(e,o){return vt({"~kind":"Literal"},{type:CO(e),const:e},o)}function Im(e){return Nr(e)||ln(e)||_t(e)||yt(e)}function lx(e){return xt(e)&&Nr(e.const)}function dx(e){return xt(e)&&ln(e.const)}function bm(e){return xt(e)&&_t(e.const)}function Em(e){return xt(e)&&yt(e.const)}function xt(e){return Ae(e,"Literal")}function vn(e){return vt({"~kind":"Null"},{type:"null"},e)}function Ss(e){return Ae(e,"Null")}var Sm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Y(e){return vt({"~kind":"Number"},{type:"number"},e)}function kr(e){return Ae(e,"Number")}function Ma(e){return vt({"~kind":"Symbol"},{type:"symbol"},e)}function ws(e){return Ae(e,"Symbol")}function na(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,g],1:(p)=>[p,Rr(),Rr()]});return vt({"~kind":"Parameter"},{name:o,extends:i,equals:c},{})}function fx(e){return Ae(e,"Parameter")}var wm=".*";function a(e){return vt({"~kind":"String"},{type:"string"},e)}function an(e){return Ae(e,"String")}function m(e,o={}){return vt({"~kind":"Union"},{anyOf:e},o)}function xe(e){return Ae(e,"Union")}function hx(e){return Zo(e,["~kind","anyOf"])}function Ou(e){let o=gx(e);return P(o.length,2)?o[0]:[]}function PO(e){return!0}function yx(e){return bt(e,(o,i)=>$O(o)?yx(i):!1,()=>!0)}function xx(e){return P(e.length,0)?!1:yx(e)}function $O(e){return xe(e)?xx(e.anyOf):xt(e)?PO(e.const):!1}function Tm(e){return xx(e)}function Rm(e){return vt({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function Ix(e,o,i=[]){return bt(e,(c,p)=>Ix(p,o,[...i,`${c}${o}`]),()=>i)}function vO(e,o){return P(e.length,0)?[`${o}`]:Ix(e,o)}function bx(e,o,i=[]){return bt(o,(c,p)=>bx(e,p,[...i,...Ex(e,c)]),()=>i)}function Ex(e,o){return xe(o)?bx(e,o.anyOf):xt(o)?vO(e,o.const):jr()}function Sx(e,o){return bt(o,(i,c)=>Sx(Ex(e,i),c),()=>e)}function MO(e){return e.map((o)=>s(o))}function OO(e){let o=Sx([],e),i=MO(o);return m(i)}function _O(e){return P(e.length,0)?jr():P(e.length,1)&&xt(e[0])?e[0]:OO(e)}function Ed(e){let o=Ou(e);return P(o.length,0)?a():Tm(o)?_O(o):Rm(e)}function _u(e){let o=Ed(e);return ur(o)?a():o}function no(e,o){let c={[e]:o};return vt({["~kind"]:"Record"},{type:"object",patternProperties:c})}function wx(e){return no(es,e)}function Tx(e){return l({true:e,false:e})}function Ur(e,o={}){let[i,c,p]=[e,e.length,!1];return vt({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:c},o)}function mt(e){return Ae(e,"Tuple")}function Rx(e){return Zo(e,["~kind","type","items","minItems","additionalItems"])}function LO(e){return Zo(e,["~readonly"])}function Sd(e,o){return St(LO(e),{},o)}function kx(e,o,i,c){let p=fe(e,o,i);return Sd(p,c)}function Ax(e,o={}){return De("RemoveReadonly",[e],o)}function Cx(e,o={}){return Sd(e,o)}function NO(e){return Zo(e,["~optional"])}function wd(e,o){return St(NO(e),{},o)}function Px(e,o,i,c){let p=fe(e,o,i);return wd(p,c)}function $x(e,o={}){return De("RemoveOptional",[e],o)}function km(e,o={}){return wd(e,o)}function Td(e){return e.reduceRight((i,c,p)=>({[p]:c,...i}),{})}function vx(e){let o=Td(e.items);return l(o)}function Rd(e){return Qe(e)||mt(e)}function DO(e,o){return ra(e)?ra(o)?!0:!1:!1}function qO(e,o){return mn(e)?mn(o)?!0:!1:!1}function FO(e,o){let i=DO(e,o),c=qO(e,o),p=Ar([e,o]),g=Cx(km(p));return i&&c?ta(Xi(g)):i&&!c?ta(g):!i&&c?Xi(g):g}function jO(e,o,i){return i in e?i in o?FO(e[i],o[i]):e[i]:(i in o)?o[i]:zt()}function UO(e,o){return[...new Set([...Se(e),...Se(o)])].reduce((p,g)=>({...p,[g]:jO(e,o,g)}),{})}function Mx(e){return Qe(e)?e.properties:mt(e)?Td(e.items):{}}function Ox(e,o){let i=Mx(e),c=Mx(o),p=UO(i,c);return l(p)}function BO(e,o){let i=Oa(e,o);return P(i,Nu)?e:P(i,Du)?o:P(i,Lu)?o:zt()}function GO(e,o){let i=Rd(e),c=Rd(o);return i&&c?Ox(e,o):i&&!c?e:!i&&c?o:BO(e,o)}function _x(e,o){return co(e)?e:vr(e)?e:nn(e)?o:co(o)?o:vr(o)?o:nn(o)?e:GO(e,o)}function KO(e,o){return xe(e)||xe(o)}function HO(e,o){let i=ko(e),c=ko(o);return KO(i,c)?Ar([i,c]):_x(i,c)}function Lx(e,o,i=[]){return bt(o,(c,p)=>Lx(e,p,[...i,HO(c,e)]),()=>P(i.length,0)?[e]:i)}function Nx(e,o,i=[]){return bt(e,(c,p)=>Nx(p,o,[...i,...qu([c],o)]),()=>i)}function qu(e,o=[]){return bt(e,(i,c)=>xe(i)?qu(c,Nx(i.anyOf,o)):qu(c,Lx(i,o)),()=>o)}function WO(e,o){let i=Rn({},e,o);return so(i)?[]:[e]}function Dx(e,o,i=[]){return bt(e,(c,p)=>Dx(p,o,[...i,...WO(c,o)]),()=>i)}function Am(e,o){let i=ko(e),c=xe(i)?i.anyOf:[i],p=Dx(c,o);return oo(p)}function ts(e,o,i){let c=Ar([e,o]),p=Am(i,e);return oo([c,p])}function eo(e,o=[]){return bt(e,(i,c)=>eo(c,[...o,s(i)]),()=>oo(o))}function Ar(e){let o=qu(e),i=kd(o);return oo(i)}function Mn(e){let o=_u(e);return ko(o)}function oo(e){let o=kd(e);return ni(o)}function ko(e){return Dr(e)?ts(e.if,e.then,e.else):sn(e)?eo(e.enum):ze(e)?Ar(e.allOf):ur(e)?Mn(e.pattern):xe(e)?oo(e.anyOf):e}function ni(e){return P(e.length,1)?e[0]:P(e.length,0)?zt():m(e)}function qx(e,o){let i=eo(e);return oi(i,o)}function Fx(e,o){return no(si,o)}function jx(e,o){let i=Ar(e);return oi(i,o)}function Ux(e,o){return yt(e)||_t(e)?l({[e]:o}):P(e,!1)?l({false:o}):P(e,!0)?l({true:o}):l({})}function Bx(e,o){return no(_a,o)}function Gx(e,o){return me(e,"pattern")&&(yt(e.pattern)||e.pattern instanceof RegExp)?no(e.pattern.toString(),o):no(es,o)}function Kx(e,o){let i=Ou(e);return Tm(i)?oi(Mn(e),o):no(e,o)}function zO(e){return xe(e)?oa(e.anyOf):[e]}function oa(e,o=[]){return bt(e,(i,c)=>oa(c,[...o,...zO(i)]),()=>o)}function VO(e){return e.some((o)=>an(o)||kr(o)||hn(o))}function JO(e,o){return P(VO(e),!0)?no(es,o):void 0}function QO(e,o){return e.reduce((i,c)=>xt(c)&&(yt(c.const)||_t(c.const))?{...i,[c.const]:o}:i,{})}function XO(e,o){let i=QO(e,o);return l(i)}function Hx(e,o){let i=oa(e),c=JO(i,o);return Pr(c)?c:XO(i,o)}function oi(e,o){return vr(e)?wx(o):Wn(e)?Tx(o):sn(e)?qx(e.enum,o):hn(e)?Fx(e,o):ze(e)?jx(e.allOf,o):xt(e)?Ux(e.const,o):kr(e)?Bx(e,o):xe(e)?Hx(e.anyOf,o):an(e)?Gx(e,o):ur(e)?Kx(e.pattern,o):l({})}function Ad(e,o,i){return ct([e])?St(oi(e,o),{},i):Cm(e,o,i)}function Wx(e,o,i,c,p){let g=fe(e,o,i),y=fe(e,o,c);return Ad(g,y,p)}var si=`^${xm}$`,_a=`^${Sm}$`,es=`^${wm}$`;function Cm(e,o,i={}){return De("Record",[e,o],i)}function Ts(e,o,i={}){return Ad(e,o,i)}function zx(e,o){return no(e,o)}function Pm(e){return P(e,es)?a():P(e,si)?_():P(e,_a)?Y():Ed(e)}function gn(e){return Se(e.patternProperties)[0]}function ii(e){let o=gn(e);return Pm(o)}function fr(e){return e.patternProperties[gn(e)]}function Gt(e){return Ae(e,"Record")}function sa(e){return vt({"~kind":"Rest"},{type:"rest",items:e},{})}function ai(e){return Ae(e,"Rest")}function $m(e){return vt({["~kind"]:"This"},{$ref:"#"},e)}function vm(e){return Ae(e,"This")}function La(e){return vt({"~kind":"Undefined"},{type:"undefined"},e)}function rs(e){return Ae(e,"Undefined")}function Mm(e){return vt({"~kind":"Void"},{type:"void"},e)}function po(e){return Ae(e,"Void")}function ZO(e,o){return P(e,"Array")?B(o[0]):P(e,"Capitalize")?_m(o[0]):P(e,"ConstructorParameters")?Fm(o[0]):P(e,"Evaluate")?mE(o[0]):P(e,"Exclude")?jm(o[0],o[1]):P(e,"Extract")?Um(o[0],o[1]):P(e,"Index")?Bu(o[0],o[1]):P(e,"InstanceType")?Bm(o[0]):P(e,"Lowercase")?Lm(o[0]):P(e,"NonNullable")?Gm(o[0]):P(e,"Omit")?Km(o[0],o[1]):P(e,"Parameters")?Hm(o[0]):P(e,"Partial")?Wm(o[0]):P(e,"Pick")?zm(o[0],o[1]):P(e,"Readonly")?Vm(o[0]):P(e,"KeyOf")?Gu(o[0]):P(e,"Record")?Cm(o[0],o[1]):P(e,"Required")?Jm(o[0]):P(e,"ReturnType")?Qm(o[0]):P(e,"Uncapitalize")?Nm(o[0]):P(e,"Uppercase")?Dm(o[0]):Uu(cn(e),o)}function ia(){throw Error("Unreachable")}function Yx(e,o=[]){return bt(e,(i,c)=>Yx(c,[...o,i[1]]),()=>o)}function Ds(e){return P(e.length,3)?[e[0],...Yx(e[1])]:[]}function Zx(e){return na(e[0],e[2],e[4])}function eI(e){return na(e[0],e[2],e[2])}function tI(e){return na(e[0],Rr(),e[2])}function rI(e){return na(e,Rr(),Rr())}function nI(e){return e}function oI(e){return Ds(e)}function sI(e){return e[1]}function iI(e){return Ds(e)}function aI(e){return e[1]}function uI(e){return ZO(e[0],e[1])}function cI(e){return null}function mI(e){return a()}function pI(e){return Y()}function lI(e){return O()}function dI(e){return La()}function fI(e){return vn()}function hI(e){return _()}function gI(e){return vu()}function yI(e){return Rr()}function xI(e){return Pa()}function II(e){return l({})}function bI(e){return zt()}function EI(e){return Ma()}function SI(e){return Mm()}function wI(e){return $m()}function TI(e){return s(BigInt(e))}function RI(e){return s(P(e,"true"))}function kI(e){return s(parseFloat(e))}function AI(e){return s(e)}function CI(e){return e[1]}function PI(e){return s(e)}function $I(e){return P(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function vI(e){return e[1]}function MI(e){return Om(e)}function OI(e){return P(e.length,6)?Yi(e[1],e[3],e[5]):Yi(e[1],e[3],Rr())}function _I(e){return e.length>0}function LI(e){return e.reduce((o,i)=>P(i.length,3)?[...o,[i[1]]]:[...o,[]],[])}function NI(e){return P(e.length,6)?[e[1],e[3],e[5]]:[]}function DI(e){return Ge(e)&&P(e.length,3)?e[1]:e}function qI(e){return P(e.length,2)?e[1]:[]}function Vx(e,o){return o.reduce((i,c)=>{let p=c;return P(p.length,1)?Bu(i,p[0]):P(p.length,0)?B(i):ia()},e)}function Jx(e,o){return P(o.length,3)?qm(e,o[0],o[1],o[2]):e}function e_(e,o){return Ge(o)&&P(o.length,0)?e:Xm(e,o)}function FI(e){let[o,i,c,p,g]=e;return e_(o?Jx(Gu(Vx(i,c)),p):Jx(Vx(i,c),p),g)}function Cd(e,o){return P(o.length,3)?(()=>{let[i,c,p]=o,g=Cd(c,p);if(P(i,"&"))return ze(g)?$n([e,...g.allOf]):$n([e,g]);if(P(i,"|"))return xe(g)?m([e,...g.anyOf]):m([e,g]);ia()})():e}function jI(e){return e}function UI(e){let[o,i]=e;return Cd(o,i)}function BI(e){return e}function GI(e){let[o,i]=e;return Cd(o,i)}function KI(e){return cE(e[1])}function HI(e){return e[1]}function WI(e){return ti(e[0],e[2])}function zI(e){return P(e.length,4)?$u(e[1],e[3]):P(e.length,2)?$u(e[1],Rr()):ia()}function VI(e){return e}function JI(e){return`${e}`}function QI(e){return e}function XI(e){return e}function YI(e){return hn(e[3])?si:kr(e[3])?_a:ws(e[3])?es:an(e[3])?es:ia()}function ZI(e){return e}function eb(e){return e.length>0}function tb(e){return e.length>0}function rb(e){let[o,i,c,p,g]=e;return{[i]:o&&c?Es(Is(g)):o&&!c?Es(g):!o&&c?Is(g):g}}function nb(e){return e}function ob(e){return Ds(e)}function sb(e){return e.reduce((o,i)=>me(i,si)||me(i,_a)||me(i,es)?[o[0],fn(o[1],i)]:[fn(o[0],i),o[1]],[{},{}])}function ib(e){return sb(e[1])}function ab(e){let[o,i]=e,c=P(Se(i).length,0)?{}:{patternProperties:i};return l(o,c)}function ub(e){return P(e.length,5)?Es(Is(e[4])):P(e.length,3)?e[2]:P(e.length,4)?P(e[2],"readonly")?Es(e[3]):Is(e[3]):ia()}function cb(e){if(!Ge(e)||!P(e.length,3))return e;let[o,i,c]=e;return o&&c?Es(Is(i)):o&&!c?Es(i):!o&&c?Is(i):i}function mb(e){return P(e.length,2)?sa(e[1]):P(e.length,1)?e[0]:ia()}function pb(e){return Ds(e)}function lb(e){return Ur(e[1])}function db(e){return Es(Is(e[4]))}function fb(e){return Es(e[3])}function hb(e){return Is(e[3])}function gb(e){return e[2]}function yb(e){return e}function xb(e){return P(e.length,2)?sa(e[1]):P(e.length,1)?e[0]:ia()}function Ib(e){return Ds(e)}function bb(e){return xs(e[1],e[4])}function Eb(e){return ys(e[2],e[5])}function Qx(e,o){return P(e,"remove")?Ax(o):P(e,"add")?Es(o):o}function Sb(e){return P(e.length,2)&&P(e[0],"-")?"remove":P(e.length,2)&&P(e[0],"+")?"add":P(e.length,1)?"add":"none"}function Xx(e,o){return P(e,"remove")?$x(o):P(e,"add")?Is(o):o}function wb(e){return P(e.length,2)&&P(e[0],"-")?"remove":P(e.length,2)&&P(e[0],"+")?"add":P(e.length,1)?"add":"none"}function Tb(e){return P(e.length,2)?[e[1]]:[]}function Rb(e){return Ge(e[6])&&P(e[6].length,1)?Fu(Mu(e[3]),e[5],e[6][0],Qx(e[1],Xx(e[8],e[10]))):Fu(Mu(e[3]),e[5],cn(e[3]),Qx(e[1],Xx(e[8],e[10])))}function kb(e){return cn(e)}function Ab(e){return BigInt(e)}function Cb(e){return parseFloat(e)}function Pb(e){return P(e,"true")}function $b(e){return e}function vb(e){return null}function Mb(e){return}function Ob(e){return{[e[0]]:e[2]}}function _b(e){return Ds(e)}function t_(e){return e.reduce((o,i)=>fn(o,i),{})}function Lb(e){return t_(e[1])}function Nb(e){return Ds(e)}function Db(e){return e[1]}function qb(e){return e}function Fb(e){return vu()}function jb(e){return a()}function Ub(e){return Y()}function Bb(e){return _()}function Gb(e){return zt()}function Kb(e){return s(e)}function Hb(e){return e}function Wb(e){return m(e[1])}function zb(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Vb(e){return[e[0],...e[1]]}function Jb(e){return e}function Qb(e){return e[1]}function Xb(e){return Ds(e)}function Yb(e){return P(e.length,2)?e[1]:[]}function Zb(e){let o=e[2],i=e[3],[c,p]=e[4],g=P(Se(p).length,0)?{}:{patternProperties:p};return{[e[1]]:ti(o,ju(i,c,g))}}function eE(e){let o=e[2],[i,c]=e[3],p=P(Se(c).length,0)?{}:{patternProperties:c};return{[e[1]]:ju(o,i,p)}}function tE(e){return{[e[1]]:ti(e[2],e[4])}}function rE(e){return{[e[1]]:e[3]}}function nE(e){return null}function oE(e){return e}function sE(e){return Ds(e)}function iE(e){return e[1]}function aE(e){let[o,i]=[e[0],e[1]];return pE(fn(o,sb(i)[0]))}function uE(e){return e}function Ku(e){return P(e.length,2)}function Rt(e,o,i){return Ku(e)?o(e[0],e[1]):i()}function o_(e,o){return P(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Or(e,o){for(let i=0;i<e.length;i++){let c=o_(e[i],o);if(Ku(c))return c}return[]}function Pd(e,o){return Array.from({length:o-e+1},(i,c)=>String.fromCharCode(e+c))}var lE=[...Pd(97,122),...Pd(65,90)],$d="0",vd=Pd(49,57),Na=[$d,...vd],dE=" ",Da=`
|
|
17
|
-
`;var ui="_",Ym=".",fE="$",Zm="-";var hE="//",gE="/*",i_="*/";function yE(e){let o=e.indexOf(i_);return P(o,-1)?"":e.slice(o+2)}function xE(e){let o=e.indexOf(Da);return P(o,-1)?"":e.slice(o)}function a_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function ep(e){let o=a_(e);return o.startsWith(gE)?ep(yE(o.slice(2))):o.startsWith(hE)?ep(xE(o.slice(2))):o}function En(e){let o=e.trimStart();return o.startsWith(gE)?En(yE(o.slice(2))):o.startsWith(hE)?En(xE(o.slice(2))):o}function tp(e,o){return Rt(Or([e],o),(i,c)=>[i,c],()=>["",o])}function u_(e,o){return e.includes(o)}function qa(e,o,i,c=""){return Rt(Or(e,i),(p,g)=>u_(o,p)?qa(e,o,g,c):qa(e,o,g,`${c}${p}`),()=>[c,i])}function c_(e){return Or(vd,e)}var m_=[...Na,ui];function p_(e){return qa(m_,[ui],e)}function l_(e){return Rt(Or([$d],e),(o,i)=>[o,i],()=>Rt(c_(e),(o,i)=>Rt(p_(i),(c,p)=>[`${o}${c}`,p],()=>[]),()=>[]))}function rp(e){return l_(En(e))}function d_(e){return tp(Zm,e)}function f_(e){return Rt(d_(e),(o,i)=>Rt(rp(i),(c,p)=>[`${o}${c}`,p],()=>[]),()=>[])}function IE(e){return f_(En(e))}function h_(e){return Rt(IE(e),(o,i)=>Rt(Or(["n"],i),(c,p)=>[`${o}`,p],()=>[]),()=>[])}function Md(e){return h_(e)}function Od(e,o){return Or([e],o)}function Z(e,o){return P(e,"")?["",o]:e.startsWith(Da)?Od(e,ep(o)):e.startsWith(dE)?Od(e,o):Od(e,En(o))}var bE=[...lE,ui,fE];function g_(e){return Or(bE,e)}var y_=[...bE,...Na];function EE(e,o=""){return Rt(Or(y_,e),(i,c)=>EE(c,`${o}${i}`),()=>[o,e])}function x_(e){return Rt(g_(e),(o,i)=>Rt(EE(i),(c,p)=>[`${o}${c}`,p],()=>[]),()=>[])}function Br(e){return x_(En(e))}var I_=[...Na,ui];function b_(e){return Ku(Or([Ym],e))}function SE(e){return Rt(qa(I_,[ui],e),(o,i)=>P(o,"")?[]:[o,i],()=>[])}function E_(e){return Rt(Or([Ym],e),(o,i)=>Rt(SE(i),(c,p)=>[`0${o}${c}`,p],()=>[]),()=>[])}function S_(e){return Rt(rp(e),(o,i)=>Rt(Or([Ym],i),(c,p)=>Rt(SE(p),(g,y)=>[`${o}${c}${g}`,y],()=>[`${o}`,p]),()=>[`${o}`,i]),()=>[])}function w_(e){return b_(e)?E_(e):S_(e)}function wE(e){return w_(En(e))}function T_(e){return tp(Zm,e)}function R_(e){return Rt(T_(e),(o,i)=>Rt(wE(i),(c,p)=>[`${o}${c}`,p],()=>[]),()=>[])}function np(e){return R_(En(e))}function k_(e){return P(e,"")?[]:[e.slice(0,1),e.slice(1)]}function TE(e,o){return bt(e,(i,c)=>o.startsWith(i)?!0:TE(c,o),()=>!1)}function ci(e,o,i=""){return Rt(k_(o),(c,p)=>TE(e,o)?[i,o]:ci(e,p,`${i}${c}`),()=>[])}function A_(e,o,i){return Rt(Or([e],i),(c,p)=>Rt(ci([o],p),(g,y)=>Rt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function C_(e,o,i){return Rt(Or([e],i),(c,p)=>Rt(ci([Da,o],p),(g,y)=>Rt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function RE(e,o,i,c){return i?A_(e,o,En(c)):C_(e,o,En(c))}function P_(e,o){return Or(e,o)}function $_(e,o){return RE(e,e,!1,o)}function v_(e,o){return Rt(P_(e,o),(i,c)=>$_(i,`${i}${c}`),()=>[])}function op(e,o){return v_(e,En(o))}function kE(e,o){return Rt(ci(e,o),(i,c)=>P(i,"")?[]:[i,c],()=>[])}var T=(e,o,i=()=>[])=>e.length===2?o(e):i(),O_=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([c,p])=>T(Mt(p),([g,y])=>T(Z("=",y),([b,E])=>T(Mt(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[Zx(o),i]),__=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([c,p])=>T(Mt(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[eI(o),i]),L_=(e)=>T(T(Br(e),([o,i])=>T(Z("=",i),([c,p])=>T(Mt(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[tI(o),i]),N_=(e)=>T(Br(e),([o,i])=>[rI(o),i]),PE=(e)=>T(T(O_(e),([o,i])=>[o,i],()=>T(__(e),([o,i])=>[o,i],()=>T(L_(e),([o,i])=>[o,i],()=>T(N_(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[nI(o),i]),$E=(e,o=[])=>T(T(Z(",",e),([i,c])=>T(PE(c),([p,g])=>[[i,p],g])),([i,c])=>$E(c,[...o,i]),()=>[o,e]),D_=(e)=>T(T(T(PE(e),([o,i])=>T($E(i),([c,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[oI(o),i]),Nd=(e)=>T(T(Z("<",e),([o,i])=>T(D_(i),([c,p])=>T(Z(">",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[sI(o),i]),vE=(e,o=[])=>T(T(Z(",",e),([i,c])=>T(Mt(c),([p,g])=>[[i,p],g])),([i,c])=>vE(c,[...o,i]),()=>[o,e]),q_=(e)=>T(T(T(Mt(e),([o,i])=>T(vE(i),([c,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[iI(o),i]),F_=(e)=>T(T(Z("<",e),([o,i])=>T(q_(i),([c,p])=>T(Z(">",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[aI(o),i]),j_=(e)=>T(T(Br(e),([o,i])=>T(F_(i),([c,p])=>[[o,c],p])),([o,i])=>[uI(o),i]),ME=(e)=>T(T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[cI(o),i]),OE=(e)=>T(Z("string",e),([o,i])=>[mI(o),i]),_E=(e)=>T(Z("number",e),([o,i])=>[pI(o),i]),U_=(e)=>T(Z("boolean",e),([o,i])=>[lI(o),i]),B_=(e)=>T(Z("undefined",e),([o,i])=>[dI(o),i]),G_=(e)=>T(Z("null",e),([o,i])=>[fI(o),i]),LE=(e)=>T(Z("integer",e),([o,i])=>[hI(o),i]),K_=(e)=>T(Z("bigint",e),([o,i])=>[gI(o),i]),H_=(e)=>T(Z("unknown",e),([o,i])=>[yI(o),i]),W_=(e)=>T(Z("any",e),([o,i])=>[xI(o),i]),z_=(e)=>T(Z("object",e),([o,i])=>[II(o),i]),V_=(e)=>T(Z("never",e),([o,i])=>[bI(o),i]),NE=(e)=>T(Z("symbol",e),([o,i])=>[EI(o),i]),J_=(e)=>T(Z("void",e),([o,i])=>[SI(o),i]),Q_=(e)=>T(Z("this",e),([o,i])=>[wI(o),i]),X_=(e)=>T(T(Z("${",e),([o,i])=>T(Mt(i),([c,p])=>T(Z("}",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[CI(o),i]),_d=(e)=>T(ci(["${","`"],e),([o,i])=>[PI(o),i]),DE=(e)=>T(T(T(_d(e),([o,i])=>T(X_(i),([c,p])=>T(DE(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T(T(_d(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(_d(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[$I(o),i]),Dd=(e)=>T(T(Z("`",e),([o,i])=>T(DE(i),([c,p])=>T(Z("`",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[vI(o),i]),Y_=(e)=>T(Dd(e),([o,i])=>[MI(o),i]),Z_=(e)=>T(T(T(Z("if",e),([o,i])=>T(Mt(i),([c,p])=>T(Z("then",p),([g,y])=>T(Mt(y),([b,E])=>T(Z("else",E),([S,w])=>T(Mt(w),([R,A])=>[[o,c,g,b,S,R],A])))))),([o,i])=>[o,i],()=>T(T(Z("if",e),([o,i])=>T(Mt(i),([c,p])=>T(Z("then",p),([g,y])=>T(Mt(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[o,i],()=>[])),([o,i])=>[OI(o),i]),eL=(e)=>T(Md(e),([o,i])=>[TI(o),i]),tL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[RI(o),i]),rL=(e)=>T(np(e),([o,i])=>[kI(o),i]),nL=(e)=>T(op(["'",'"'],e),([o,i])=>[AI(o),i]),oL=(e)=>T(T(T(Z("keyof",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[_I(o),i]),qE=(e,o=[])=>T(T(T(Z("[",e),([i,c])=>T(Mt(c),([p,g])=>T(Z("]",g),([y,b])=>[[i,p,y],b]))),([i,c])=>[i,c],()=>T(T(Z("[",e),([i,c])=>T(Z("]",c),([p,g])=>[[i,p],g])),([i,c])=>[i,c],()=>[])),([i,c])=>qE(c,[...o,i]),()=>[o,e]),sL=(e)=>T(qE(e),([o,i])=>[LI(o),i]),iL=(e)=>T(T(T(Z("extends",e),([o,i])=>T(Mt(i),([c,p])=>T(Z("?",p),([g,y])=>T(Mt(y),([b,E])=>T(Z(":",E),([S,w])=>T(Mt(w),([R,A])=>[[o,c,g,b,S,R],A])))))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[NI(o),i]),aL=(e)=>T(T(T(Z("(",e),([o,i])=>T(Mt(i),([c,p])=>T(Z(")",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T(OE(e),([o,i])=>[o,i],()=>T(_E(e),([o,i])=>[o,i],()=>T(U_(e),([o,i])=>[o,i],()=>T(B_(e),([o,i])=>[o,i],()=>T(G_(e),([o,i])=>[o,i],()=>T(LE(e),([o,i])=>[o,i],()=>T(K_(e),([o,i])=>[o,i],()=>T(H_(e),([o,i])=>[o,i],()=>T(W_(e),([o,i])=>[o,i],()=>T(z_(e),([o,i])=>[o,i],()=>T(V_(e),([o,i])=>[o,i],()=>T(NE(e),([o,i])=>[o,i],()=>T(J_(e),([o,i])=>[o,i],()=>T(Q_(e),([o,i])=>[o,i],()=>T(eL(e),([o,i])=>[o,i],()=>T(tL(e),([o,i])=>[o,i],()=>T(rL(e),([o,i])=>[o,i],()=>T(nL(e),([o,i])=>[o,i],()=>T(Y_(e),([o,i])=>[o,i],()=>T(Z_(e),([o,i])=>[o,i],()=>T(xL(e),([o,i])=>[o,i],()=>T(EL(e),([o,i])=>[o,i],()=>T(AL(e),([o,i])=>[o,i],()=>T(kL(e),([o,i])=>[o,i],()=>T(vL(e),([o,i])=>[o,i],()=>T(j_(e),([o,i])=>[o,i],()=>T(ML(e),([o,i])=>[o,i],()=>[])))))))))))))))))))))))))))),([o,i])=>[DI(o),i]),uL=(e)=>T(T(T(Z("with",e),([o,i])=>T(tS(i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[qI(o),i]),FE=(e)=>T(T(oL(e),([o,i])=>T(aL(i),([c,p])=>T(sL(p),([g,y])=>T(iL(y),([b,E])=>T(uL(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[FI(o),i]),jE=(e)=>T(T(T(Z("&",e),([o,i])=>T(FE(i),([c,p])=>T(jE(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[jI(o),i]),UE=(e)=>T(T(FE(e),([o,i])=>T(jE(i),([c,p])=>[[o,c],p])),([o,i])=>[UI(o),i]),BE=(e)=>T(T(T(Z("|",e),([o,i])=>T(UE(i),([c,p])=>T(BE(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[BI(o),i]),sp=(e)=>T(T(UE(e),([o,i])=>T(BE(i),([c,p])=>[[o,c],p])),([o,i])=>[GI(o),i]),cL=(e)=>T(T(Z("readonly",e),([o,i])=>T(sp(i),([c,p])=>[[o,c],p])),([o,i])=>[KI(o),i]),mL=(e)=>T(T(Z("|",e),([o,i])=>T(sp(i),([c,p])=>[[o,c],p])),([o,i])=>[HI(o),i]),pL=(e)=>T(T(Nd(e),([o,i])=>T(Z("=",i),([c,p])=>T(Mt(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[WI(o),i]),lL=(e)=>T(T(T(Z("infer",e),([o,i])=>T(Br(i),([c,p])=>T(Z("extends",p),([g,y])=>T(sp(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[o,i],()=>T(T(Z("infer",e),([o,i])=>T(Br(i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>[])),([o,i])=>[zI(o),i]),Mt=(e)=>T(T(lL(e),([o,i])=>[o,i],()=>T(mL(e),([o,i])=>[o,i],()=>T(cL(e),([o,i])=>[o,i],()=>T(sp(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[VI(o),i]),dL=(e)=>T(np(e),([o,i])=>[JI(o),i]),fL=(e)=>T(Br(e),([o,i])=>[QI(o),i]),hL=(e)=>T(op(["'",'"'],e),([o,i])=>[XI(o),i]),gL=(e)=>T(T(Z("[",e),([o,i])=>T(Br(i),([c,p])=>T(Z(":",p),([g,y])=>T(T(LE(y),([b,E])=>[b,E],()=>T(_E(y),([b,E])=>[b,E],()=>T(OE(y),([b,E])=>[b,E],()=>T(NE(y),([b,E])=>[b,E],()=>[])))),([b,E])=>T(Z("]",E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[YI(o),i]),GE=(e)=>T(T(dL(e),([o,i])=>[o,i],()=>T(fL(e),([o,i])=>[o,i],()=>T(hL(e),([o,i])=>[o,i],()=>T(gL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[ZI(o),i]),KE=(e)=>T(T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[eb(o),i]),HE=(e)=>T(T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[tb(o),i]),WE=(e)=>T(T(KE(e),([o,i])=>T(GE(i),([c,p])=>T(HE(p),([g,y])=>T(Z(":",y),([b,E])=>T(Mt(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[rb(o),i]),ip=(e)=>T(T(T(Z(",",e),([o,i])=>T(Z(`
|
|
18
|
-
`,i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>T(Z(`
|
|
19
|
-
`,i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z(",",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
|
|
20
|
-
`,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))))),([o,i])=>[nb(o),i]),zE=(e,o=[])=>T(T(ip(e),([i,c])=>T(WE(c),([p,g])=>[[i,p],g])),([i,c])=>zE(c,[...o,i]),()=>[o,e]),yL=(e)=>T(T(T(WE(e),([o,i])=>T(zE(i),([c,p])=>T(T(ip(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[ob(o),i]),qd=(e)=>T(T(Z("{",e),([o,i])=>T(yL(i),([c,p])=>T(Z("}",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[ib(o),i]),xL=(e)=>T(qd(e),([o,i])=>[ab(o),i]),IL=(e)=>T(T(T(Br(e),([o,i])=>T(Z("?",i),([c,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(Mt(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([c,p])=>T(Z("readonly",p),([g,y])=>T(Mt(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z("?",i),([c,p])=>T(Z(":",p),([g,y])=>T(Mt(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([c,p])=>T(Mt(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>[])))),([o,i])=>[ub(o),i]),AE=(e)=>T(T(IL(e),([o,i])=>[o,i],()=>T(T(KE(e),([o,i])=>T(Mt(i),([c,p])=>T(HE(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>[])),([o,i])=>[cb(o),i]),VE=(e)=>T(T(T(Z("...",e),([o,i])=>T(AE(i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(AE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[mb(o),i]),JE=(e,o=[])=>T(T(Z(",",e),([i,c])=>T(VE(c),([p,g])=>[[i,p],g])),([i,c])=>JE(c,[...o,i]),()=>[o,e]),bL=(e)=>T(T(T(VE(e),([o,i])=>T(JE(i),([c,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[pb(o),i]),EL=(e)=>T(T(Z("[",e),([o,i])=>T(bL(i),([c,p])=>T(Z("]",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[lb(o),i]),SL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([c,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(Mt(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[db(o),i]),wL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([c,p])=>T(Z("readonly",p),([g,y])=>T(Mt(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[fb(o),i]),TL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([c,p])=>T(Z(":",p),([g,y])=>T(Mt(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[hb(o),i]),RL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([c,p])=>T(Mt(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[gb(o),i]),CE=(e)=>T(T(SL(e),([o,i])=>[o,i],()=>T(wL(e),([o,i])=>[o,i],()=>T(TL(e),([o,i])=>[o,i],()=>T(RL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[yb(o),i]),QE=(e)=>T(T(T(Z("...",e),([o,i])=>T(CE(i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(CE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[xb(o),i]),XE=(e,o=[])=>T(T(Z(",",e),([i,c])=>T(QE(c),([p,g])=>[[i,p],g])),([i,c])=>XE(c,[...o,i]),()=>[o,e]),YE=(e)=>T(T(T(QE(e),([o,i])=>T(XE(i),([c,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Ib(o),i]),kL=(e)=>T(T(Z("(",e),([o,i])=>T(YE(i),([c,p])=>T(Z(")",p),([g,y])=>T(Z("=>",y),([b,E])=>T(Mt(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[bb(o),i]),AL=(e)=>T(T(Z("new",e),([o,i])=>T(Z("(",i),([c,p])=>T(YE(p),([g,y])=>T(Z(")",y),([b,E])=>T(Z("=>",E),([S,w])=>T(Mt(w),([R,A])=>[[o,c,g,b,S,R],A])))))),([o,i])=>[Eb(o),i]),CL=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("readonly",i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("readonly",i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Sb(o),i]),PL=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("?",i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("?",i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[wb(o),i]),$L=(e)=>T(T(T(Z("as",e),([o,i])=>T(Mt(i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Tb(o),i]),vL=(e)=>T(T(Z("{",e),([o,i])=>T(CL(i),([c,p])=>T(Z("[",p),([g,y])=>T(Br(y),([b,E])=>T(Z("in",E),([S,w])=>T(Mt(w),([R,A])=>T($L(A),([C,L])=>T(Z("]",L),([q,X])=>T(PL(X),([j,V])=>T(Z(":",V),([J,ee])=>T(Mt(ee),([ae,K])=>T(ME(K),([ue,he])=>T(Z("}",he),([_e,Ee])=>[[o,c,g,b,S,R,C,q,j,J,ae,ue,_e],Ee]))))))))))))),([o,i])=>[Rb(o),i]),ML=(e)=>T(Br(e),([o,i])=>[kb(o),i]),OL=(e)=>T(Md(e),([o,i])=>[Ab(o),i]),_L=(e)=>T(np(e),([o,i])=>[Cb(o),i]),LL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[Pb(o),i]),NL=(e)=>T(op(['"',"'"],e),([o,i])=>[$b(o),i]),DL=(e)=>T(Z("null",e),([o,i])=>[vb(o),i]),qL=(e)=>T(Z("undefined",e),([o,i])=>[Mb(o),i]),ZE=(e)=>T(T(GE(e),([o,i])=>T(Z(":",i),([c,p])=>T(Fd(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[Ob(o),i]),eS=(e,o=[])=>T(T(ip(e),([i,c])=>T(ZE(c),([p,g])=>[[i,p],g])),([i,c])=>eS(c,[...o,i]),()=>[o,e]),FL=(e)=>T(T(T(ZE(e),([o,i])=>T(eS(i),([c,p])=>T(T(ip(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[_b(o),i]),tS=(e)=>T(T(Z("{",e),([o,i])=>T(FL(i),([c,p])=>T(Z("}",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[Lb(o),i]),rS=(e,o=[])=>T(T(Z(",",e),([i,c])=>T(Fd(c),([p,g])=>[[i,p],g])),([i,c])=>rS(c,[...o,i]),()=>[o,e]),jL=(e)=>T(T(T(Fd(e),([o,i])=>T(rS(i),([c,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Nb(o),i]),UL=(e)=>T(T(Z("[",e),([o,i])=>T(jL(i),([c,p])=>T(Z("]",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[Db(o),i]),Fd=(e)=>T(T(OL(e),([o,i])=>[o,i],()=>T(_L(e),([o,i])=>[o,i],()=>T(LL(e),([o,i])=>[o,i],()=>T(NL(e),([o,i])=>[o,i],()=>T(DL(e),([o,i])=>[o,i],()=>T(qL(e),([o,i])=>[o,i],()=>T(tS(e),([o,i])=>[o,i],()=>T(UL(e),([o,i])=>[o,i],()=>[])))))))),([o,i])=>[qb(o),i]),BL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)n",e),([o,i])=>[Fb(o),i]),GL=(e)=>T(Z(".*",e),([o,i])=>[jb(o),i]),KL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,i])=>[Ub(o),i]),HL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)",e),([o,i])=>[Bb(o),i]),WL=(e)=>T(Z("(?!)",e),([o,i])=>[Gb(o),i]),zL=(e)=>T(kE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,i])=>[Kb(o),i]),VL=(e)=>T(T(BL(e),([o,i])=>[o,i],()=>T(GL(e),([o,i])=>[o,i],()=>T(KL(e),([o,i])=>[o,i],()=>T(HL(e),([o,i])=>[o,i],()=>T(WL(e),([o,i])=>[o,i],()=>T(JL(e),([o,i])=>[o,i],()=>T(zL(e),([o,i])=>[o,i],()=>[]))))))),([o,i])=>[Hb(o),i]),JL=(e)=>T(T(Z("(",e),([o,i])=>T(jd(i),([c,p])=>T(Z(")",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[Wb(o),i]),nS=(e)=>T(T(T(Ld(e),([o,i])=>T(Z("|",i),([c,p])=>T(nS(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T(T(Ld(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[]))),([o,i])=>[zb(o),i]),Ld=(e)=>T(T(VL(e),([o,i])=>T(jd(i),([c,p])=>[[o,c],p])),([o,i])=>[Vb(o),i]),jd=(e)=>T(T(nS(e),([o,i])=>[o,i],()=>T(Ld(e),([o,i])=>[o,i],()=>[])),([o,i])=>[Jb(o),i]),gx=(e)=>T(T(Z("^",e),([o,i])=>T(jd(i),([c,p])=>T(Z("$",p),([g,y])=>[[o,c,g],y]))),([o,i])=>[Qb(o),i]),oS=(e,o=[])=>T(T(Z(",",e),([i,c])=>T(Mt(c),([p,g])=>[[i,p],g])),([i,c])=>oS(c,[...o,i]),()=>[o,e]),QL=(e)=>T(T(T(Mt(e),([o,i])=>T(oS(i),([c,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Xb(o),i]),sS=(e)=>T(T(T(Z("extends",e),([o,i])=>T(QL(i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Yb(o),i]),XL=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([c,p])=>T(Nd(p),([g,y])=>T(sS(y),([b,E])=>T(qd(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[Zb(o),i]),YL=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([c,p])=>T(sS(p),([g,y])=>T(qd(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[eE(o),i]),ZL=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([c,p])=>T(Nd(p),([g,y])=>T(Z("=",y),([b,E])=>T(Mt(E),([S,w])=>[[o,c,g,b,S],w]))))),([o,i])=>[tE(o),i]),eN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([c,p])=>T(Z("=",p),([g,y])=>T(Mt(y),([b,E])=>[[o,c,g,b],E])))),([o,i])=>[rE(o),i]),tN=(e)=>T(T(T(Z("export",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[nE(o),i]),iS=(e)=>T(T(T(Z(";",e),([o,i])=>T(Z(`
|
|
21
|
-
`,i),([c,p])=>[[o,c],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
|
|
22
|
-
`,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[oE(o),i]),aS=(e,o=[])=>T(T(iS(e),([i,c])=>T(Ud(c),([p,g])=>[[i,p],g])),([i,c])=>aS(c,[...o,i]),()=>[o,e]),rN=(e)=>T(T(T(Ud(e),([o,i])=>T(aS(i),([c,p])=>T(T(iS(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,c,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[sE(o),i]),Ud=(e)=>T(T(tN(e),([o,i])=>T(T(XL(i),([c,p])=>[c,p],()=>T(YL(i),([c,p])=>[c,p],()=>T(ZL(i),([c,p])=>[c,p],()=>T(eN(i),([c,p])=>[c,p],()=>[])))),([c,p])=>T(ME(p),([g,y])=>[[o,c,g],y]))),([o,i])=>[iE(o),i]),nN=(e)=>T(T(Ud(e),([o,i])=>T(rN(i),([c,p])=>[[o,c],p])),([o,i])=>[aE(o),i]),uS=(e)=>T(T(nN(e),([o,i])=>[o,i],()=>T(pL(e),([o,i])=>[o,i],()=>T(Mt(e),([o,i])=>[o,i],()=>[]))),([o,i])=>[uE(o),i]);function cS(e){let o=Dd(`\`${e}\``);return P(o.length,2)?o[0]:jr()}function sN(e){return e.join("|")}function iN(e){return e.slice(1,e.length-1)}function aN(e,o,i){return pi(o,`${i}${e}`)}function uN(e,o){return pi(e,`${o}${cx}`)}function cN(e,o){return pi(e,`${o}${xm}`)}function mN(e,o){return pi(e,`${o}${Sm}`)}function pN(e,o){return Hu(m([s("false"),s("true")]),e,o)}function lN(e,o){return pi(e,`${o}${wm}`)}function dN(e,o,i){return pi(o,`${i}${iN(e)}`)}function fN(e,o,i){let c=Wu(e,{});return Hu(c,o,i)}function hN(e,o,i){let c=eo(e);return Hu(c,o,i)}function mS(e,o,i,c=[]){return bt(e,(p,g)=>mS(g,o,i,[...c,Hu(p,[],"")]),()=>pi(o,`${i}(${sN(c)})`))}function Hu(e,o,i){return sn(e)?hN(e.enum,o,i):hn(e)?cN(o,i):xt(e)?aN(e.const,o,i):mo(e)?uN(o,i):Wn(e)?pN(o,i):kr(e)?mN(o,i):an(e)?lN(o,i):ur(e)?dN(e.pattern,o,i):lS(e)?fN(e.parameters[0],o,i):xe(e)?mS(e.anyOf,o,i):Dy}function pi(e,o){return bt(e,(i,c)=>Hu(i,c,o),()=>o)}function gN(e){return`^${pi(e,"")}$`}function pS(e){let o=gN(e);return Rm(o)}function Wu(e,o){return ct(e)?St(pS(e),{},o):Om(e,o)}function dS(e,o,i,c){let p=yo(e,o,i);return Wu(p,c)}function Om(e,o={}){return De("TemplateLiteral",[e],o)}function lS(e){return Pr(e)&&me(e,"action")&&P(e.action,"TemplateLiteral")}function fS(e){return Wu(e,{})}function yN(e){let o=cS(e);return fS(o)}function hS(e,o={}){let i=yt(e)?yN(e):fS(e);return St(i,{},o)}function ur(e){return Ae(e,"TemplateLiteral")}function Bd(e){return vt({["~kind"]:"ExtendsUnion"},{inferred:e})}function Gd(e){return ut(e)&&me(e,"~kind")&&me(e,"inferred")&&P(e["~kind"],"ExtendsUnion")&&ut(e.inferred)}function we(e){return vt({["~kind"]:"ExtendsTrue"},{inferred:e})}function Kd(e){return ut(e)&&me(e,"~kind")&&me(e,"inferred")&&P(e["~kind"],"ExtendsTrue")&&ut(e.inferred)}function Ze(){return vt({["~kind"]:"ExtendsFalse"},{})}function Hd(e){return ut(e)&&me(e,"~kind")&&P(e["~kind"],"ExtendsFalse")}function so(e){return Gd(e)||Kd(e)}function br(e,o,i){return so(e)?o(e.inferred):i()}function xN(e,o,i,c){return br(kt(e,i,c),(p)=>we(fn(fn(e,p),{[o]:i})),()=>Ze())}function IN(e,o){return we(e)}function bN(e,o,i,c,p){return br(kt(e,o,i),(g)=>br(kt(g,o,c),(y)=>we(y),()=>Ze()),()=>br(kt(e,o,p),(g)=>we(g),()=>Ze()))}function EN(e,o,i){let c=eo(i);return kt(e,o,c)}function gS(e,o,i){return bt(i,(c,p)=>br(kt(e,o,c),(g)=>gS(g,o,p),()=>Ze()),()=>we(e))}function SN(e,o,i){let c=Mn(i);return kt(e,o,c)}function yS(e,o,i){return bt(i,(c,p)=>br(kt(e,o,c),(g)=>we(g),()=>yS(e,o,p)),()=>Ze())}function Dt(e,o,i){return vr(i)?IN(e,o):Dr(i)?bN(e,o,i.if,i.then,i.else):sn(i)?EN(e,o,i.enum):on(i)?xN(e,i.name,o,i.extends):ze(i)?gS(e,o,i.allOf):ur(i)?SN(e,o,i.pattern):xe(i)?yS(e,o,i.anyOf):nn(i)?we(e):Ze()}function xS(e,o,i){return on(i)?Dt(e,o,i):vr(i)?we(e):nn(i)?we(e):Bd(e)}function wN(e,o){let i=ea(e),c=ea(o);return i&&c?!0:!i&&c?!0:i&&!c?!1:!0}function IS(e,o,i,c){return wt(c)?wN(o,c)?kt(e,i,c.items):Ze():Dt(e,o,c)}function bS(e,o,i){return mo(i)?we(e):Dt(e,o,i)}function ES(e,o,i){return Wn(i)?we(e):Dt(e,o,i)}function TN(e,o,i,c,p){let g=on(c)?o:c,y=on(c)?c:o,b=mn(o),E=mn(c);return!b&&E?Ze():br(kt(e,g,y),(S)=>zu(S,i,p),()=>Ze())}function RN(e,o,i,c){return bt(c,(p,g)=>TN(e,o,i,p,g),()=>mn(o)?we(e):Ze())}function kN(e,o,i){return bt(o,(c,p)=>RN(e,c,p,i),()=>we(e))}function zu(e,o,i){return kN(e,o,i)}function ap(e,o,i){return po(i)?we(e):kt(e,o,i)}function SS(e,o,i,c){return vr(c)?we(e):nn(c)?we(e):tn(c)?br(zu(e,o,c.parameters),(p)=>ap(p,i,c.instanceType),()=>Ze()):Ze()}function wS(e,o,i,c,p){return br(kt(e,o,p),()=>kt(e,i,p),()=>kt(e,c,p))}function TS(e,o,i){let c=eo(o);return kt(e,c,i)}function RS(e,o,i,c){return vr(c)?we(e):nn(c)?we(e):rn(c)?br(zu(e,o,c.parameters),(p)=>ap(p,i,c.returnType),()=>Ze()):Ze()}function kS(e,o,i){return hn(i)?we(e):kr(i)?we(e):Dt(e,o,i)}function AS(e,o,i){let c=Ar(o);return kt(e,c,i)}function up(e,o,i){return o===i?we(e):Ze()}function AN(e,o,i){return xt(i)?up(e,o,i.const):mo(i)?we(e):Dt(e,s(o),i)}function CN(e,o,i){return xt(i)?up(e,o,i.const):Wn(i)?we(e):Dt(e,s(o),i)}function PN(e,o,i){return xt(i)?up(e,o,i.const):kr(i)?we(e):Dt(e,s(o),i)}function $N(e,o,i){return xt(i)?up(e,o,i.const):an(i)?we(e):Dt(e,s(o),i)}function CS(e,o,i){return Nr(o.const)?AN(e,o.const,i):ln(o.const)?CN(e,o.const,i):_t(o.const)?PN(e,o.const,i):yt(o.const)?$N(e,o.const,i):jr()}function PS(e,o,i){return on(i)?Dt(e,o,i):we(e)}function $S(e,o,i){return Ss(i)?we(e):Dt(e,o,i)}function vS(e,o,i){return kr(i)?we(e):Dt(e,o,i)}function vN(e,o,i){return mn(o)?mn(i)?we(e):Ze():we(e)}function MN(e,o,i){return on(i)&&co(i.extends)?Ze():br(kt(e,o,i),(c)=>vN(c,o,i),()=>Ze())}function ON(e,o){return e.reduce((i,c)=>(c in o)?so(o[c])?{...i,...o[c].inferred}:jr():jr(),{})}function _N(e,o,i){let c={};for(let y of Se(i))c[y]=y in o?MN({},o[y],i[y]):mn(i[y])?on(i[y])?we(fn(e,{[i[y].name]:i[y].extends})):we(e):Ze();let p=dd(c).every((y)=>so(y)),g=p?ON(Se(c),c):{};return p?we(g):Ze()}function LN(e,o,i){let c=_N(e,o,i);return so(c)?we(fn(e,c.inferred)):Ze()}function NN(e,o,i){return LN(e,o,i)}function DN(e,o){return Se(o).reduce((i,c)=>({...i,[c]:me(e,c)?xe(i[c])?m([...i[c].anyOf,o[c]]):m([e[c],o[c]]):o[c]}),e)}function MS(e,o,i,c){return bt(o,(p,g)=>br(kt({},e[p],i),(y)=>MS(e,g,i,DN(c,y)),()=>Ze()),()=>we(c))}function qN(e,o,i,c){let p=Se(o);return MS(o,p,c,e)}function OS(e,o,i){return Gt(i)?qN(e,o,gn(i),fr(i)):Qe(i)?NN(e,o,i.properties):Dt(e,l(o),i)}function FN(e,o){return P(Se(o).length,0)?we(e):Ze()}function jN(e,o,i,c,p){return kt(e,i,p)}function _S(e,o,i,c){return Gt(c)?jN(e,Pm(o),i,Pm(gn(c)),fr(c)):Qe(c)?FN(e,c.properties):vr(c)?we(e):nn(c)?we(e):Ze()}function LS(e,o,i){return an(i)?we(e):Dt(e,o,i)}function NS(e,o,i){return ws(i)?we(e):Dt(e,o,i)}function DS(e,o,i){let c=Mn(o);return kt(e,c,i)}function Wd(e,o){return vt({"~kind":"Inferrable"},{name:e,type:o},{})}function Vu(e){return ut(e)&&me(e,"~kind")&&me(e,"name")&&me(e,"type")&&P(e["~kind"],"Inferrable")&&yt(e.name)&&ut(e.type)}function zd(e){return ai(e)?on(e.items)?wt(e.items.extends)?Wd(e.items.name,e.items.extends.items):nn(e.items.extends)?Wd(e.items.name,e.items.extends):void 0:jr():void 0}function cp(e){return on(e)?Wd(e.name,e.extends):void 0}function Vd(e,o,i=[]){return bt(e,(c,p)=>br(kt({},c,o),()=>Vd(p,o,[...i,c]),()=>{return}),()=>i)}function qS(e,o,i,c){let p=Vd(i,c);return Ge(p)?we(fn(e,{[o]:Ur(p)})):Ze()}function mp(e,o,i,c){let p=Vd(i,c);return Ge(p)?we(fn(e,{[o]:m(p)})):Ze()}function UN(e){return[...e].reverse()}function Jd(e,o){return o?UN(e):e}function BN(e){let o=e.length>0?e[0]:void 0,i=Pr(o)?zd(o):void 0;return Pr(i)}function GN(e,o,i,c,p,g){return br(kt(e,i,p),(y)=>FS(y,o,c,g),()=>Ze())}function KN(e,o,i,c,p){let g=zd(c);return Vu(g)?qS(e,g.name,Jd(i,o),g.type):bt(i,(y,b)=>GN(e,o,y,b,c,p),()=>Ze())}function HN(e,o,i,c){return bt(c,(p,g)=>KN(e,o,i,p,g),()=>P(i.length,0)?we(e):Ze())}function FS(e,o,i,c){return HN(e,o,i,c)}function WN(e,o,i){let c=li(e,hr([],[]),i),p=BN(c);return FS(e,p,Jd(o,p),Jd(c,p))}function jS(e,o,i){let c=cp(i);return Vu(c)?mp(e,c.name,o,c.type):bt(o,(p,g)=>br(kt(e,p,i),(y)=>jS(y,g,i),()=>Ze()),()=>we(e))}function US(e,o,i){let c=li(e,hr([],[]),o);return mt(i)?WN(e,c,i.items):wt(i)?jS(e,c,i.items):Dt(e,Ur(c),i)}function BS(e,o,i){return po(i)?we(e):rs(i)?we(e):Dt(e,o,i)}function GS(e,o,i){return bt(i,(c,p)=>br(kt(e,o,c),(g)=>we(g),()=>GS(e,o,p)),()=>Ze())}function Qd(e,o,i){return bt(o,(c,p)=>br(GS(e,c,i),(g)=>Qd(g,p,i),()=>Ze()),()=>we(e))}function KS(e,o,i){let c=cp(i);return Vu(c)?mp(e,c.name,o,c.type):xe(i)?Qd(e,o,i.anyOf):Qd(e,o,[i])}function HS(e,o,i){return on(i)?Dt(e,o,i):vr(i)?we(e):nn(i)?we(e):Ze()}function WS(e,o,i){return po(i)?we(e):Dt(e,o,i)}function kt(e,o,i){return vr(o)?xS(e,o,i):wt(o)?IS(e,o,o.items,i):mo(o)?bS(e,o,i):Wn(o)?ES(e,o,i):tn(o)?SS(e,o.parameters,o.instanceType,i):Dr(o)?wS(e,o.if,o.then,o.else,i):sn(o)?TS(e,o.enum,i):rn(o)?RS(e,o.parameters,o.returnType,i):hn(o)?kS(e,o,i):ze(o)?AS(e,o.allOf,i):xt(o)?CS(e,o,i):co(o)?PS(e,o,i):Ss(o)?$S(e,o,i):kr(o)?vS(e,o,i):Qe(o)?OS(e,o.properties,i):Gt(o)?_S(e,gn(o),fr(o),i):an(o)?LS(e,o,i):ws(o)?NS(e,o,i):ur(o)?DS(e,o.pattern,i):mt(o)?US(e,o.items,i):rs(o)?BS(e,o,i):xe(o)?KS(e,o.anyOf,i):nn(o)?HS(e,o,i):po(o)?WS(e,o,i):Ze()}function zN(e,o){return Ar([...e,l(o)])}function Xd(e,o,i){return ct(e)?St(zN(e,o),{},i):ju(e,o,i)}function zS(e,o,i,c,p){let g=yo(e,o,i),y=Ju(e,o,c);return Xd(g,y,p)}function ju(e,o,i={}){return De("Interface",[e,o],i)}function Fa(e){return Pr(e)&&me(e,"action")&&P(e.action,"Interface")}function VS(e,o,i={}){return Xd(e,o,i)}function VN(e,o,i){return e.includes(i)?!0:Qu([...e,i],o,o[i])}function JS(e,o,i){let c=lm(i);return aa(e,o,c)}function aa(e,o,i){return bt(i,(c,p)=>Qu(e,o,c)?!0:aa(e,o,p),()=>!1)}function Qu(e,o,i){return jt(i)?VN(e,o,i.$ref):wt(i)?Qu(e,o,i.items):tn(i)?aa(e,o,[...i.parameters,i.instanceType]):rn(i)?aa(e,o,[...i.parameters,i.returnType]):Fa(i)?JS(e,o,i.parameters[1]):ze(i)?aa(e,o,i.allOf):Qe(i)?JS(e,o,i.properties):xe(i)?aa(e,o,i.anyOf):mt(i)?aa(e,o,i.items):Gt(i)?Qu(e,o,fr(i)):!1}function QS(e,o,i){return Qu(e,o,i)}function JN(e,o){return o.reduce((i,c)=>QS([c],e,e[c])?[...i,c]:i,[])}function XS(e){let o=pm(e);return JN(e,o)}function QN(e,o,i){return i.includes(o)?i:(o in e)?Xu(e,e[o],[...i,o]):jr()}function YS(e,o,i){let c=lm(o);return ja(e,c,i)}function ja(e,o,i){return o.reduce((c,p)=>Xu(e,p,c),i)}function Xu(e,o,i){return jt(o)?QN(e,o.$ref,i):wt(o)?Xu(e,o.items,i):tn(o)?ja(e,[...o.parameters,o.instanceType],i):rn(o)?ja(e,[...o.parameters,o.returnType],i):Fa(o)?YS(e,o.parameters[1],i):ze(o)?ja(e,o.allOf,i):Qe(o)?YS(e,o.properties,i):xe(o)?ja(e,o.anyOf,i):mt(o)?ja(e,o.items,i):Gt(o)?Xu(e,fr(o),i):i}function ZS(e,o,i){return Xu(e,i,[o])}function XN(e){return Pa()}function YN(e){return Se(e).reduce((o,i)=>({...o,[i]:ua(e[i])}),{})}function Yu(e){return e.reduce((o,i)=>[...o,ua(i)],[])}function ua(e){return jt(e)?XN(e.$ref):wt(e)?B(ua(e.items),Aa(e)):tn(e)?ys(Yu(e.parameters),ua(e.instanceType)):rn(e)?xs(Yu(e.parameters),ua(e.returnType)):ze(e)?$n(Yu(e.allOf)):Qe(e)?l(YN(e.properties)):Gt(e)?Ts(ii(e),ua(fr(e))):xe(e)?m(Yu(e.anyOf)):mt(e)?Ur(Yu(e.items)):e}function ZN(e,o){return o in e?ua(e[o]):Rr()}function ew(e){return ZN(e.$defs,e.$ref)}function eD(e,o,i){let c=yo(e,hr([],[]),o),p=Ju({},hr([],[]),i);return Ar([...c,l(p)])}function tD(e,o){return Se(e).filter((c)=>o.includes(c)).reduce((c,p)=>{let g=e[p],y=Fa(g)?eD(e,g.parameters[0],g.parameters[1]):g;return{...c,[p]:y}},{})}function tw(e,o,i){let c=ZS(e,o,i),p=tD(e,c);return bs(p,o)}function rw(e,o){return o in e?jt(e[o])?rw(e,e[o].$ref):e[o]:zt()}function Rs(e,o){return rw(e,o)}function nw(e){return Qt(e)?ew(e):dm(e)?Rr():e}function Rn(e,o,i){let c=nw(o),p=nw(i);return kt(e,c,p)}var Lu=0,Zu=1,Nu=2,Du=3;function Oa(e,o){let i=[Rn({},e,o),Rn({},o,e)];return so(i[0])&&so(i[1])?Lu:so(i[0])&&Hd(i[1])?Nu:Hd(i[0])&&so(i[1])?Du:Zu}function Yd(e,o,i=[],c=o){return bt(o,(p,g)=>{let y=Oa(e,p);return P(y,Nu)||P(y,Lu)?c:P(y,Zu)?Yd(e,g,[...i,p],c):Yd(e,g,i,c)},()=>[...i,e])}function rD(e,o,i){let c=ko(e);return vr(c)?[c]:nn(c)?[c]:co(c)?pp(o,i):Qe(c)?pp(o,[...i,c]):pp(o,Yd(c,i))}function pp(e,o=[]){return bt(e,(i,c)=>rD(i,c,o),()=>o)}function kd(e){let o=pp(e);return oa(o)}function Zd(e,o){return St(ko(e),{},o)}function ow(e,o,i,c){let p=fe(e,o,i);return Zd(p,c)}function ec(e,o=[]){return ei(e)&&P(e.action,"Conditional")?jt(e.parameters[0])?ec(e.parameters[2],ec(e.parameters[3],[...o,e.parameters[0].$ref])):ec(e.parameters[2],ec(e.parameters[3],o)):ei(e)&&P(e.action,"Mapped")?ei(e.parameters[1])&&P(e.parameters[1].action,"KeyOf")&&jt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function nD(e,o){return e.reduce((i,c)=>[...i,o.includes(c.name)],[])}function aw(e,o,i=[]){return bt(e,(c,p)=>bt(o,(g,y)=>aw(p,y,[...i,[g,c]]),()=>i),()=>i)}function oD(e){return ur(e)?Mn(e.pattern):sn(e)?eo(e.enum):e}function sD(e){let o=oD(e);return xe(o)?[...o.anyOf]:[o]}function iD(e,o){return e.reduce((i,c)=>[...i,[...c,o]],[])}function sw(e,o){return o.reduce((i,c)=>[...i,...iD(e,c)],[])}function iw(e){return e.reduce((o,i)=>P(i[0],!0)?sw(o,sD(i[1])):sw(o,[i[1]]),[[]])}function uw(e,o,i){let c=ec(i),p=nD(e,c),g=aw(o,p);return ei(i)&&P(i.action,"Conditional")?iw(g):ei(i)&&P(i.action,"Mapped")?iw(g):[o]}function aD(){return["(not-resolvable)",zt()]}function uD(){return["(not-generic)",zt()]}function cD(e,o,i){return[e,ti(o,i)]}function mD(e,o,i){return o in e?cw(e,o,e[o],i):aD()}function cw(e,o,i,c){return Ca(i)?cD(o,i.parameters,i.expression):jt(i)?mD(e,i.$ref,c):uD()}function mw(e,o,i){return cw(e,"(anonymous)",o,i)}function pD(e,o,i){if(on(o)||Ua(o)||so(Rn({},o,i)))return;let c={parameter:e,expect:i,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:c})}function pw(e,o,i,c,p){let g=fe(e,o,p);return pD(i,g,c),fn(e,{[i]:g})}function lD(e,o,i,c,p){let g=fe(e,o,i.extends),y=fe(e,o,i.equals);return bt(p,(b,E)=>ef(pw(e,o,i.name,g,b),o,c,E),()=>ef(pw(e,o,i.name,g,y),o,c,[]))}function ef(e,o,i,c){return bt(i,(p,g)=>lD(e,o,p,g,c),()=>e)}function lw(e,o,i,c){return ef(e,o,i,c)}var tf=0,rf=0;function dD(){if(Tu(rf,Yo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function fD(){dD(),rf++,tf++}function hD(){if(tf--,P(tf,0))rf=0}function gD(e){return Hi(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function yD(e,o){return P(gD(e),o)}function xD(e,o,i,c,p,g){fD();try{let y=lw(e,o,c,g),b=fe(y,hr([...o.callstack,i.$ref],o.visited),p);return fe(y,hr([],[]),b)}finally{hD()}}function ID(e,o,i,c,p,g){return g.reduce((y,b)=>{let E=xD(e,o,i,c,p,b);return[...y,E]},[])}function bD(e,o,i,c,p,g){let y=uw(c,g,p),b=ID(e,o,i,c,p,y);return P(b.length,1)?b[0]:oo(b)}function lp(e,o,i,c){let p=yo(e,o,c),g=mw(e,i,c),y=g[0],b=g[1];return Ca(b)?yD(o,y)?Uu(cn(y),p):bD(e,o,cn(y),b.parameters,b.expression,p):Uu(i,p)}function Uu(e,o){return vt({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function dw(e,o){return lp({},hr([],[]),e,o)}function Ua(e){return Ae(e,"Call")}function ED(e){return Zo(e,["~immutable"])}function fw(e,o){return St(ED(e),{},o)}function hw(e,o,i,c){let p=fe(e,o,i);return fw(p,c)}function gw(e,o){return e(o)}function yw(e,o){return yt(o)?s(gw(e,o)):s(o)}function xw(e,o){let i=Mn(o);return qs(e,i)}function Iw(e,o){let i=o.map((c)=>qs(e,c));return m(i)}function qs(e,o){return xt(o)?yw(e,o.const):ur(o)?xw(e,o.pattern):xe(o)?Iw(e,o.anyOf):o}function _m(e,o={}){return De("Capitalize",[e],o)}function bw(e,o={}){return nf(e,o)}function Lm(e,o={}){return De("Lowercase",[e],o)}function Ew(e,o={}){return of(e,o)}function Nm(e,o={}){return De("Uncapitalize",[e],o)}function Sw(e,o={}){return sf(e,o)}function Dm(e,o={}){return De("Uppercase",[e],o)}function ww(e,o={}){return af(e,o)}var SD=(e)=>e[0].toUpperCase()+e.slice(1),wD=(e)=>e.toLowerCase(),TD=(e)=>e[0].toLowerCase()+e.slice(1),RD=(e)=>e.toUpperCase();function nf(e,o){return ct([e])?St(qs(SD,e),{},o):_m(e,o)}function of(e,o){return ct([e])?St(qs(wD,e),{},o):Lm(e,o)}function sf(e,o){return ct([e])?St(qs(TD,e),{},o):Nm(e,o)}function af(e,o){return ct([e])?St(qs(RD,e),{},o):Dm(e,o)}function Tw(e,o,i,c){let p=fe(e,o,i);return nf(p,c)}function Rw(e,o,i,c){let p=fe(e,o,i);return of(p,c)}function kw(e,o,i,c){let p=fe(e,o,i);return sf(p,c)}function Aw(e,o,i,c){let p=fe(e,o,i);return af(p,c)}function qm(e,o,i,c,p={}){return De("Conditional",[e,o,i,c],p)}function Cw(e,o,i,c,p={}){return uf({},hr([],[]),e,o,i,c,p)}function kD(e,o,i,c,p,g){let y=Rn(e,i,c);return Gd(y)?m([fe(y.inferred,o,p),fe(e,o,g)]):Kd(y)?fe(y.inferred,o,p):fe(e,o,g)}function uf(e,o,i,c,p,g,y){return ct([i,c])?St(kD(e,o,i,c,p,g),{},y):qm(i,c,p,g,y)}function Pw(e,o,i,c,p,g,y){let b=fe(e,o,i),E=fe(e,o,c);return uf(e,o,b,E,p,g,y)}function Fm(e,o={}){return De("ConstructorParameters",[e],o)}function $w(e,o={}){return cf(e,o)}function AD(e){let o=tn(e)?e.parameters:[],i=li({},hr([],[]),o);return Ur(i)}function cf(e,o){return ct([e])?St(AD(e),{},o):Fm(e,o)}function vw(e,o,i,c){let p=fe(e,o,i);return cf(p,c)}function jm(e,o,i={}){return De("Exclude",[e,o],i)}function Mw(e,o,i={}){return tc(e,o,i)}function tc(e,o,i){return ct([e,o])?St(Am(e,o),{},i):jm(e,o,i)}function Ow(e,o,i,c,p){let g=fe(e,o,i),y=fe(e,o,c);return tc(g,y,p)}function Um(e,o,i={}){return De("Extract",[e,o],i)}function _w(e,o,i={}){return mf(e,o,i)}function CD(e,o){let i=Rn({},e,o);return so(i)?[e]:[]}function Lw(e,o,i=[]){return bt(e,(c,p)=>Lw(p,o,[...i,...CD(c,o)]),()=>i)}function Nw(e,o){let i=ko(e),c=xe(i)?i.anyOf:[i],p=Lw(c,o);return oo(p)}function mf(e,o,i){return ct([e,o])?St(Nw(e,o),{},i):Um(e,o,i)}function Dw(e,o,i,c,p){let g=fe(e,o,i),y=fe(e,o,c);return mf(g,y,p)}function PD(e){return e.reduce((o,i)=>Im(i)?[...o,s(i)]:o,[])}function Ba(e){let o=PD(e);return m(o)}function Bu(e,o,i={}){return De("Index",[e,o],i)}function qw(e,o,i={}){let c=Ge(o)?Ba(o):o;return pf(e,c,i)}function Fw(e,o){let i=Rs(e,o);return xo(i)}function jw(e,o,i){let c=ts(e,o,i);return xo(c)}function $D(e,o){let i=Se(e).filter((w)=>!me(o,w)),c=Se(o).filter((w)=>!me(e,w)),p=Se(e).filter((w)=>me(o,w)),g=i.reduce((w,R)=>({...w,[R]:e[R]}),{}),y=c.reduce((w,R)=>({...w,[R]:o[R]}),{}),b=p.reduce((w,R)=>({...w,[R]:Ar([e[R],o[R]])}),{}),E=fn(g,y);return fn(E,b)}function Uw(e){return e.reduce((o,i)=>$D(o,xo(i)),{})}function Bw(e){return e}function Gw(e){let o=vx(Ur(e));return xo(o)}function vD(e,o){return Se(e).filter((p)=>(p in o)).reduce((p,g)=>({...p,[g]:oo([e[g],o[g]])}),{})}function Kw(e,o){return bt(e,(i,c)=>Kw(c,vD(o,xo(i))),()=>o)}function Hw(e){return bt(e,(o,i)=>Kw(i,xo(o)),()=>jr())}function xo(e){return Qt(e)?Fw(e.$defs,e.$ref):Dr(e)?jw(e.if,e.then,e.else):ze(e)?Uw(e.allOf):xe(e)?Hw(e.anyOf):mt(e)?Gw(e.items):Qe(e)?Bw(e.properties):{}}function Ga(e){let o=xo(e);return l(o)}var MD=new RegExp("^(?:0|[1-9][0-9]*)$");function Ka(e){let o=`${e}`;return MD.test(o)?parseInt(o):e}function OD(e){return s(Ka(e))}function Ww(e){return e.map((o)=>zw(o))}function zw(e){return ze(e)?$n(Ww(e.allOf)):xe(e)?m(Ww(e.anyOf)):xt(e)?OD(e.const):e}function Vw(e,o){let i=zw(o),c=Rn({},i,Y());return so(c)?e:xt(o)&&P(o.const,"length")?Y():zt()}function Jw(e,o){let i=Rs(e,o);return lo(i)}function Qw(e,o,i){let c=ts(e,o,i);return lo(c)}function Xw(e){let o=eo(e);return lo(o)}function Yw(e){let o=Ar(e);return lo(o)}function Zw(e){return[`${e}`]}function eT(e){let o=Mn(e);return lo(o)}function tT(e){return e.reduce((o,i)=>[...o,...lo(i)],[])}function lo(e){return Qt(e)?Jw(e.$defs,e.$ref):Dr(e)?Qw(e.if,e.then,e.else):sn(e)?Xw(e.enum):ze(e)?Yw(e.allOf):xt(e)?Zw(e.const):ur(e)?eT(e.pattern):xe(e)?tT(e.anyOf):[]}function Ha(e){return lo(e)}function rc(e,o){return o.map((i)=>nc(e,i))}function nc(e,o){return wt(o)?B(nc(e,o.items)):tn(o)?ys(rc(e,o.parameters),nc(e,o.instanceType)):rn(o)?xs(rc(e,o.parameters),nc(e,o.returnType)):mt(o)?Ur(rc(e,o.items)):xe(o)?m(rc(e,o.anyOf)):ze(o)?$n(rc(e,o.allOf)):vm(o)?l(e):o}function rT(e,o){return nc(e,o)}function _D(e,o){let i=o in e?e[o]:zt();return rT(e,i)}function nT(e,o){return o.reduce((i,c)=>[...i,_D(e,c)],[])}function LD(e,o){let i=Ha(o),c=nT(e,i);return oo(c)}var ND=new RegExp(si);function DD(e){return e.filter((i)=>ND.test(i))}function qD(e){let o=pm(e),i=DD(o),c=nT(e,i);return oo(c)}function oT(e,o){return kr(o)?qD(e):LD(e,o)}function FD(e){return s(Ka(e))}function sT(e){return e.map((o)=>lf(o))}function lf(e){return ze(e)?$n(sT(e.allOf)):xe(e)?m(sT(e.anyOf)):xt(e)?FD(e.const):e}function jD(e,o){return e.reduceRight((i,c,p)=>{let g=Rn({},s(p),o);return so(g)?[c,...i]:i},[])}function UD(e,o){let i=lf(o),c=jD(e,i);return ni(c)}function BD(e){return ni(e)}function iT(e,o){return xt(o)&&P(o.const,"length")?s(e.length):kr(o)||hn(o)?BD(e):UD(e,o)}function aT(e,o){return wt(e)?Vw(e.items,o):Qe(e)?oT(e.properties,o):mt(e)?iT(e.items,o):zt()}function GD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ga(e):e}function pf(e,o,i){return ct([e,o])?St(aT(GD(e),o),{},i):Bu(e,o,i)}function uT(e,o,i,c,p){let g=fe(e,o,i),y=fe(e,o,c);return pf(g,y,p)}function Bm(e,o={}){return De("InstanceType",[e],o)}function cT(e,o={}){return df(e,o)}function KD(e){return tn(e)?e.instanceType:zt()}function df(e,o){return ct([e])?St(KD(e),{},o):Bm(e,o)}function mT(e,o,i,c={}){let p=fe(e,o,i);return df(p,c)}function Gu(e,o={}){return De("KeyOf",[e],o)}function pT(e,o={}){return ff(e,o)}function lT(){return m([Y(),a(),Ma()])}function dT(e){return Y()}function HD(e){return e.reduce((i,c)=>Im(c)?[...i,s(Ka(c))]:jr(),[])}function fT(e){let o=Se(e),i=HD(o);return ni(i)}function hT(e){return ii(e)}function gT(e){let o=e.map((i,c)=>s(c));return ni(o)}function yT(e){return vr(e)?lT():wt(e)?dT(e.items):Qe(e)?fT(e.properties):Gt(e)?hT(e):mt(e)?gT(e.items):zt()}function WD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ga(e):e}function ff(e,o){return ct([e])?St(yT(WD(e)),{},o):Gu(e,o)}function xT(e,o,i,c){let p=fe(e,o,i);return ff(p,c)}function Fu(e,o,i,c,p={}){return De("Mapped",[e,o,i,c],p)}function IT(e,o,i,c,p={}){return hf({},hr([],[]),e,o,i,c,p)}function zD(e){let o=Mn(e);return dp(o)}function VD(e){return e.reduce((o,i)=>[...o,...dp(i)],[])}function JD(e){let o=eo(e);return dp(o)}function QD(e){return _t(e)?[s(`${e}`)]:[s(e)]}function dp(e){return sn(e)?JD(e.enum):xt(e)?QD(e.const):ur(e)?zD(e.pattern):xe(e)?VD(e.anyOf):[e]}function bT(e){return dp(e)}function XD(e){return ur(e)?Mn(e.pattern):e}function YD(e,o,i,c,p,g){let y=fn(e,{[i.name]:c}),b=fe(y,o,p),E=XD(b),S=fe(y,o,g);return bm(E)||Em(E)?{[E.const]:S}:{}}function ZD(e,o,i,c,p,g){return c.reduce((y,b)=>[...y,YD(e,o,i,b,p,g)],[])}function eq(e){return e.reduce((o,i)=>[...o,l(i)],[])}function ET(e,o,i,c,p,g){let y=bT(c),b=ZD(e,o,i,y,p,g),E=eq(b);return Ar(E)}function hf(e,o,i,c,p,g,y){return ct([c])?St(ET(e,o,i,c,p,g),{},y):Fu(i,c,p,g,y)}function ST(e,o,i,c,p,g,y){let b=fe(e,o,c);return hf(e,o,i,b,p,g,y)}function tq(e,o,i){let c=fn(e,o);return Se(o).filter((g)=>i.includes(g)).reduce((g,y)=>({...g,[y]:tw(c,y,o[y])}),{})}function rq(e,o,i){let c=fn(e,o);return Se(o).filter((g)=>!i.includes(g)).reduce((g,y)=>({...g,[y]:fe(c,hr([],[]),o[y])}),{})}function nq(e,o,i){let c=XS(o),p=tq(e,o,c),g=rq(e,o,c),y={...p,...g};return St(y,{},i)}function fp(e,o,i,c){return nq(e,i,c)}function Gm(e,o={}){return De("NonNullable",[e],o)}function wT(e,o={}){return gf(e,o)}function oq(e){let o=m([vn(),La()]);return tc(e,o,{})}function gf(e,o){return ct([e])?St(oq(e),{},o):Gm(e,o)}function TT(e,o,i,c){let p=fe(e,o,i);return gf(p,c)}function Km(e,o,i={}){return De("Omit",[e,o],i)}function RT(e,o,i={}){let c=Ge(o)?Ba(o):o;return yf(e,c,i)}function hp(e){let o=Ga(e);return Qe(o)?o.properties:jr()}function sq(e,o){return Se(e).reduce((c,p)=>o.includes(p)?c:{...c,[p]:e[p]},{})}function kT(e,o){let i=hp(e),c=Ha(o),p=sq(i,c);return l(p)}function yf(e,o,i){return ct([e,o])?St(kT(e,o),{},i):Km(e,o,i)}function AT(e,o,i,c,p){let g=fe(e,o,i),y=fe(e,o,c);return yf(g,y,p)}function Hm(e,o={}){return De("Parameters",[e],o)}function CT(e,o={}){return xf(e,o)}function iq(e){let o=rn(e)?e.parameters:[],i=li({},hr([],[]),o);return Ur(i)}function xf(e,o){return ct([e])?St(iq(e),{},o):Hm(e,o)}function PT(e,o,i,c){let p=fe(e,o,i);return xf(p,c)}function Wm(e,o={}){return De("Partial",[e],o)}function $T(e,o={}){return If(e,o)}function vT(e,o){let i=Rs(e,o),c=ks(i);return bs(fn(e,{[o]:c}),o)}function MT(e,o,i){let c=ts(e,o,i);return ks(c)}function OT(e){let o=Ar(e);return ks(o)}function _T(e){let o=e.map((i)=>ks(i));return m(o)}function LT(e){let o=Se(e).reduce((c,p)=>({...c,[p]:Xi(e[p])}),{});return l(o)}function ks(e){return Qt(e)?vT(e.$defs,e.$ref):Dr(e)?MT(e.if,e.then,e.else):ze(e)?OT(e.allOf):xe(e)?_T(e.anyOf):Qe(e)?LT(e.properties):l({})}function If(e,o){return ct([e])?St(ks(e),{},o):Wm(e,o)}function NT(e,o,i,c){let p=fe(e,o,i);return If(p,c)}function zm(e,o,i={}){return De("Pick",[e,o],i)}function DT(e,o,i={}){let c=Ge(o)?Ba(o):o;return bf(e,c,i)}function aq(e,o){return Se(e).reduce((c,p)=>o.includes(p)?fn(c,{[p]:e[p]}):c,{})}function qT(e,o){let i=hp(e),c=Ha(o),p=aq(i,c);return l(p)}function bf(e,o,i){return ct([e,o])?St(qT(e,o),{},i):zm(e,o,i)}function FT(e,o,i,c,p){let g=fe(e,o,i),y=fe(e,o,c);return bf(g,y,p)}function Vm(e,o={}){return De("ReadonlyObject",[e],o)}function Ef(e,o={}){return Sf(e,o)}var jT=Ef;function UT(e){return va(B(e))}function BT(e,o){let i=Rs(e,o),c=As(i);return bs(fn(e,{[o]:c}),o)}function GT(e,o,i){let c=ts(e,o,i);return As(c)}function KT(e){let o=Ar(e);return As(o)}function HT(e){let o=Se(e).reduce((c,p)=>({...c,[p]:ta(e[p])}),{});return l(o)}function WT(e){return va(Ur(e))}function zT(e){let o=e.map((i)=>As(i));return m(o)}function As(e){return wt(e)?UT(e.items):Qt(e)?BT(e.$defs,e.$ref):Dr(e)?GT(e.if,e.then,e.else):ze(e)?KT(e.allOf):Qe(e)?HT(e.properties):mt(e)?WT(e.items):xe(e)?zT(e.anyOf):e}function Sf(e,o){return ct([e])?St(As(e),{},o):Vm(e)}function VT(e,o,i,c){let p=fe(e,o,i);return Sf(p,c)}function JT(e,o,i,c){return o.visited.includes(c)?i:(c in e)?fe(e,hr(o.callstack,[...o.visited,c]),e[c]):i}function QT(e,o){let i=Rs(e,o),c=Cs(i);return bs(fn(e,{[o]:c}),o)}function XT(e,o,i){let c=ts(e,o,i);return Cs(c)}function YT(e){let o=Ar(e);return Cs(o)}function ZT(e){let o=e.map((i)=>Cs(i));return m(o)}function eR(e){let o=Se(e).reduce((c,p)=>({...c,[p]:km(e[p])}),{});return l(o)}function Cs(e){return Qt(e)?QT(e.$defs,e.$ref):Dr(e)?XT(e.if,e.then,e.else):ze(e)?YT(e.allOf):xe(e)?ZT(e.anyOf):Qe(e)?eR(e.properties):l({})}function Jm(e,o={}){return De("Required",[e],o)}function tR(e,o={}){return wf(e,o)}function wf(e,o){return ct([e])?St(Cs(e),{},o):Jm(e,o)}function rR(e,o,i,c){let p=fe(e,o,i);return wf(p,c)}function Qm(e,o={}){return De("ReturnType",[e],o)}function nR(e,o={}){return Tf(e,o)}function uq(e){return rn(e)?e.returnType:zt()}function Tf(e,o){return ct([e])?St(uq(e),{},o):Qm(e,o)}function oR(e,o,i,c={}){let p=fe(e,o,i);return Tf(p,c)}function Xm(e,o){return De("With",[e,o],{})}function gp(e,o){return Rf(e,o)}function Rf(e,o){return ct([e])?St(e,{},o):Xm(e,o)}function sR(e,o,i,c){let p=fe(e,o,i);return Rf(p,c)}function cq(e){return ai(e)?mt(e.items)?kf(e.items.items):on(e.items)?[e]:jt(e.items)?[e]:[zt()]:[e]}function kf(e){return e.reduce((i,c)=>[...i,...cq(c)],[])}function hr(e,o){return{callstack:e,visited:o}}function ct(e){return bt(e,(o,i)=>jt(o)?!1:ct(i),()=>!0)}function Ju(e,o,i){return Se(i).reduce((c,p)=>({...c,[p]:fe(e,o,i[p])}),{})}function li(e,o,i){let c=yo(e,o,i);return kf(c)}function yo(e,o,i){return i.map((c)=>fe(e,o,c))}function mq(e,o){let i=mn(e)?Pu(o,{}):o,c=ra(e)?Cu(i,{}):i;return ea(e)?oc(c,{}):c}function pq(e,o,i,c,p){return P(i,"AddImmutable")?iR(e,o,c[0],p):P(i,"RemoveImmutable")?hw(e,o,c[0],p):P(i,"AddReadonly")?Oy(e,o,c[0],p):P(i,"RemoveReadonly")?kx(e,o,c[0],p):P(i,"AddOptional")?_y(e,o,c[0],p):P(i,"RemoveOptional")?Px(e,o,c[0],p):P(i,"Capitalize")?Tw(e,o,c[0],p):P(i,"Conditional")?Pw(e,o,c[0],c[1],c[2],c[3],p):P(i,"ConstructorParameters")?vw(e,o,c[0],p):P(i,"Evaluate")?ow(e,o,c[0],p):P(i,"Exclude")?Ow(e,o,c[0],c[1],p):P(i,"Extract")?Dw(e,o,c[0],c[1],p):P(i,"Index")?uT(e,o,c[0],c[1],p):P(i,"InstanceType")?mT(e,o,c[0],p):P(i,"Interface")?zS(e,o,c[0],c[1],p):P(i,"KeyOf")?xT(e,o,c[0],p):P(i,"Lowercase")?Rw(e,o,c[0],p):P(i,"Mapped")?ST(e,o,c[0],c[1],c[2],c[3],p):P(i,"Module")?fp(e,o,c[0],p):P(i,"NonNullable")?TT(e,o,c[0],p):P(i,"Pick")?FT(e,o,c[0],c[1],p):P(i,"Parameters")?PT(e,o,c[0],p):P(i,"Partial")?NT(e,o,c[0],p):P(i,"Omit")?AT(e,o,c[0],c[1],p):P(i,"ReadonlyObject")?VT(e,o,c[0],p):P(i,"Record")?Wx(e,o,c[0],c[1],p):P(i,"Required")?rR(e,o,c[0],p):P(i,"ReturnType")?oR(e,o,c[0],p):P(i,"TemplateLiteral")?dS(e,o,c[0],p):P(i,"Uncapitalize")?kw(e,o,c[0],p):P(i,"Uppercase")?Aw(e,o,c[0],p):P(i,"With")?sR(e,o,c[0],c[1]):De(i,c,p)}function lq(e,o,i){let c=jt(i)?JT(e,o,i,i.$ref):wt(i)?B(fe(e,o,i.items),Aa(i)):Ua(i)?lp(e,o,i.target,i.arguments):tn(i)?ys(yo(e,o,i.parameters),fe(e,o,i.instanceType),Ly(i)):rn(i)?xs(yo(e,o,i.parameters),fe(e,o,i.returnType),Ny(i)):Dr(i)?Yi(fe(e,o,i.if),fe(e,o,i.then),fe(e,o,i.else),jy(i)):ze(i)?$n(yo(e,o,i.allOf),Hy(i)):Qe(i)?l(Ju(e,o,i.properties),Fy(i)):Gt(i)?zx(gn(i),fe(e,o,fr(i))):ai(i)?sa(fe(e,o,i.items)):mt(i)?Ur(li(e,o,i.items),Rx(i)):xe(i)?m(yo(e,o,i.anyOf),hx(i)):i;return mq(i,c)}function fe(e,o,i){return ei(i)?pq(e,o,i.action,i.parameters,i.options):lq(e,o,i)}function Ao(e,o){return fe(e,hr([],[]),o)}function dq(e){return St(e,{"~immutable":!0},{})}function oc(e,o){return St(dq(e),{},o)}function iR(e,o,i,c){let p=fe(e,o,i);return oc(p,c)}function cE(e,o={}){return De("AddImmutable",[e],o)}function va(e,o={}){return oc(e,o)}function mE(e,o={}){return De("Evaluate",[e],o)}function kn(e,o={}){return Zd(e,o)}function pE(e,o={}){return De("Module",[e],o)}function aR(e,o={}){return fp({},hr([],[]),e,o)}function fq(e,o){let i=Oa(e,o);return P(i,Du)?1:P(i,Zu)?1:0}function uR(e,o,i=[]){return bt(o,(c,p)=>P(fq(e,c),1)?uR(e,p,[...i,c]):[...i,e,...o],()=>[...i,e])}function cR(e,o=[]){return bt(e,(i,c)=>cR(c,uR(i,o)),()=>o)}function mR(e){return cR(e)}function pR(...e){let[o,i,c]=Tn(e,{2:(y,b)=>yt(y)?[{},y,b]:[y,b,{}],3:(y,b,E)=>[y,b,E],1:(y)=>[{},y,{}]}),p=uS(i),g=Ge(p)&&P(p.length,2)?fe(o,hr([],[]),p[0]):zt();return St(g,{},c)}function h(e,o){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 g of o){let y=await i.env(g);if(p.throwIfAborted(),y)return{auth:{apiKey:y},source:g}}return}}}function le(e){let o,i=()=>(o??=e.load(),o);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 hR="faux",gR="faux",yR="faux-1",hq="Faux Model",gq="http://localhost:0",yq=3,lR=5,Ip={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Nn(e){return{type:"text",text:e}}function Lo(e){return{type:"thinking",thinking:e}}function xq(e,o,i={}){return{type:"toolCall",id:i.id??Pf("tool"),name:e,arguments:o}}function Iq(e){if(typeof e==="string")return[Nn(e)];return Array.isArray(e)?e:[e]}function Oo(e,o={}){return{role:"assistant",content:Iq(e),api:hR,provider:gR,model:yR,usage:Ip,stopReason:o.stopReason??"stop",...o.deferred===void 0?{}:{deferred:o.deferred},...o.errorMessage===void 0?{}:{errorMessage:o.errorMessage},...o.responseId===void 0?{}:{responseId:o.responseId},timestamp:o.timestamp??Date.now()}}function xR(e){return Math.ceil(e.length/4)}function Pf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function IR(e){if(typeof e==="string")return e;return e.map((o)=>{if(o.type==="text")return o.text;return`[image:${o.mimeType}:${o.data.length}]`}).join(`
|
|
23
|
-
`)}function bR(e){return e.map((o)=>{if(o.type==="text")return o.text;if(o.type==="thinking")return o.thinking;return`${o.name}:${JSON.stringify(o.arguments)}`}).join(`
|
|
24
|
-
`)}function bq(e){return[e.toolName,...e.content.map((o)=>IR([o]))].join(`
|
|
25
|
-
`)}function Eq(e){if(e.role==="system")return[U(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
|
|
26
|
-
`);if(e.role==="user")return IR(e.content);if(e.role==="assistant")return bR(e.content);return bq(e)}function ER(e,o=e.length){let i=o>0?(o-1)*2:0;for(let c=0;c<o;c++)i+=e[c].length;return i}function Sq(e,o){let i=0;while(i<e.length&&i<o.length&&e[i]===o[i])i++;let c=(p)=>i===p.length?"":(i>0?`
|
|
27
|
-
|
|
28
|
-
`:"")+p.slice(i).join(`
|
|
29
|
-
|
|
30
|
-
`);return ER(e,i)+wq(c(e),c(o))}function wq(e,o){let i=Math.min(e.length,o.length),c=0;while(c<i&&e[c]===o[c])c++;return c}function dR(e,o,i,c){let p=o.messages.map((A)=>`${A.role}:${Eq(A)}`),g=ER(p),y=Math.ceil(g/4),b=xR(bR(e.content)),E=y,S=0,w=0,R=i?.sessionId;if(R&&i?.cacheRetention!=="none"){let A=c.get(R);if(A){let C=Sq(A,p);S=Math.ceil(C/4),w=Math.ceil((g-C)/4),E=Math.max(0,y-S)}else w=y;c.set(R,p)}return{...e,usage:{input:E,output:b,cacheRead:S,cacheWrite:w,totalTokens:E+b+S+w,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function Af(e,o,i){let c=[],p=0;while(p<e.length){let g=o+Math.floor(Math.random()*(i-o+1)),y=Math.max(1,g*4);c.push(e.slice(p,p+y)),p+=y}return c.length>0?c:[""]}function Tq(e,o,i,c){let p=structuredClone(e);return{...p,api:o,provider:i,model:c,timestamp:p.timestamp??Date.now(),usage:p.usage??Ip}}function fR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:Ip,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function yp(e,o,i,c){return{role:"assistant",content:[],api:o,provider:i,model:c,usage:Ip,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function sc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Cf(e,o){if(!o||o<=0)return new Promise((c)=>queueMicrotask(c));let i=xR(e)/o*1000;return new Promise((c)=>setTimeout(c,i))}async function xp(e,o,i,c,p,g){let y={...o,content:[],stopReason:"pending"};if(g?.aborted){let b=sc(y);e.push({type:"error",reason:"aborted",error:b}),e.end(b);return}e.push({type:"start",partial:{...y}});for(let b=0;b<o.content.length;b++){if(g?.aborted){let S=sc(y);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}let E=o.content[b];if(E.type==="thinking"){y.content=[...y.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:b,partial:{...y}});for(let S of Af(E.thinking,i,c)){if(await Cf(S,p),g?.aborted){let w=sc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].thinking+=S,e.push({type:"thinking_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"thinking_end",contentIndex:b,content:E.thinking,partial:{...y}});continue}if(E.type==="text"){y.content=[...y.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:b,partial:{...y}});for(let S of Af(E.text,i,c)){if(await Cf(S,p),g?.aborted){let w=sc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].text+=S,e.push({type:"text_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"text_end",contentIndex:b,content:E.text,partial:{...y}});continue}y.content=[...y.content,{type:"toolCall",id:E.id,name:E.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:b,partial:{...y}});for(let S of Af(JSON.stringify(E.arguments),i,c)){if(await Cf(S,p),g?.aborted){let w=sc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}e.push({type:"toolcall_delta",contentIndex:b,delta:S,partial:{...y}})}y.content[b].arguments=E.arguments,e.push({type:"toolcall_end",contentIndex:b,toolCall:E,partial:{...y}})}if(o.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(o.stopReason==="error"||o.stopReason==="aborted"){e.push({type:"error",reason:o.stopReason,error:o}),e.end(o);return}e.push({type:"done",reason:o.stopReason,message:o}),e.end(o)}function SR(e){let o=e.api??Pf(hR),i=e.provider??gR,c=Math.max(1,Math.min(e.tokenSize?.min??yq,e.tokenSize?.max??lR)),p=Math.max(c,e.tokenSize?.max??lR),g=[],y=e.tokensPerSecond,b={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},E=new Map,S=new Map,R=((e.models?.length)?e.models:[{id:yR,name:hq,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((V)=>({id:V.id,name:V.name??V.id,api:o,provider:i,baseUrl:gq,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})),A=async(V,J,ee,ae)=>{let K=typeof V==="function"?await V(J,ee,b,ae):V;return dR(Tq(K,o,i,ae.id),J,ee,E)},C=(V,J,ee)=>{let ae=Yn(),K=g.shift();return b.callCount++,queueMicrotask(async()=>{try{if(await ee?.onResponse?.({status:200,headers:{}},V),!K){let he=yp(Error("No more faux responses queued"),o,i,V.id);he=dR(he,J,ee,E),ae.push({type:"error",reason:"error",error:he}),ae.end(he);return}if(ee?.deferred){let he={provider:V.provider,modelId:V.id,api:V.api,id:Pf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};S.set(he.id,{handle:he,step:K,context:J,options:ee,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await xp(ae,fR(V,he),c,p,y,ee.signal);return}let ue=await A(K,J,ee,V);await xp(ae,ue,c,p,y,ee?.signal)}catch(ue){let he=yp(ue,o,i,V.id);ae.push({type:"error",reason:"error",error:he}),ae.end(he)}}),ae},L=(V,J,ee)=>C(V,J,ee),q=(V,J,ee)=>{let ae=Yn();return b.deferredFetchCount++,queueMicrotask(async()=>{try{await ee?.onResponse?.({status:200,headers:{}},V);let K=S.get(J.id);if(!K||K.handle.provider!==J.provider||K.handle.modelId!==J.modelId||K.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(K.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(K.pendingFetches>0){K.pendingFetches--,await xp(ae,fR(V,K.handle),c,p,y,ee?.signal);return}if(!K.final){let{deferred:ue,signal:he,onResponse:_e,...Ee}=K.options??{};try{K.final=await A(K.step,K.context,Ee,K.model)}catch(se){K.final=yp(se,o,i,K.model.id)}}await xp(ae,K.final,c,p,y,ee?.signal)}catch(K){let ue=yp(K,o,i,V.id);ae.push({type:"error",reason:"error",error:ue}),ae.end(ue)}}),ae},X=async(V,J,ee)=>{b.cancelledDeferred.push(structuredClone(J));let ae=S.get(J.id);if(ae)ae.cancelled=!0;await ee?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return R[0];return R.find((J)=>J.id===V)}return{api:o,provider:i,models:R,stream:C,streamSimple:L,fetchDeferred:q,cancelDeferred:X,getModel:j,state:b,setResponses(V){g=[...V]},appendResponses(V){g.push(...V)},getPendingResponseCount(){return g.length}}}function No(e={}){let o=SR(e);return{provider:d({id:o.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:o.models,api:{stream:o.stream,streamSimple:o.streamSimple,fetchDeferred:o.fetchDeferred,cancelDeferred:o.cancelDeferred}}),api:o.api,models:o.models,getModel:o.getModel,state:o.state,setResponses:o.setResponses,appendResponses:o.appendResponses,getPendingResponseCount:o.getPendingResponseCount}}function Rq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function kq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Aq(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 Cq(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 ic(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Wa(e){ic(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function vf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var Pq=vf(W(""));function Mf(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((c,p)=>Mf(c,o[p]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let i=o;return Object.entries(e).every(([c,p])=>Object.hasOwn(i,c)&&Mf(p,i[c]))}class wR{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:Cq(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=Wa(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:Rq(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Wa(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=Wa(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:kq(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Wa(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=Wa(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let i=vf(o.arguments),c=i===Pq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:c,catchupJson:"",snapshotArguments:c?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Aq(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let i=W(o.catchupJson);if(vf(i)!==o.snapshotArguments){let p=W(o.snapshotArguments);if(!Mf(p,i))return}o.caughtUp=!0,o.snapshotArguments="";let c=o.catchupJson;return o.catchupJson="",c.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:c}}case"toolcall_end":{let o=Wa(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(ic(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){ic(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(i.kind!==o)throw Error(`Assistant message block ${e} is ${i.kind}, not ${o}`);return i}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,i){let c=this.block(e,i);if(c.kind==="toolCall")throw Error("Unreachable text encoder state");let p=c.deltaChars;c.deltaChars+=o.length;let g=Math.max(0,c.coveredChars-p);if(g>=o.length)return;let y=g===0?o:o.slice(g);return i==="text"?{type:"text_delta",contentIndex:e,delta:y}:{type:"thinking_delta",contentIndex:e,delta:y}}}function $f(e,o,i,c,p){if(ic(i),i!==e.content.length){let g=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${g}`)}e.content.push(structuredClone(c)),o.set(i,p)}function ca(e,o,i,c,p){ic(i);let g=o.get(i),y=e.content[i];if(!g||!y)throw Error(`${p} frame has no started block at index ${i}`);if(g.kind!==c||y.type!==c)throw Error(`${p} frame expected ${c} block at index ${i}, found ${y.type}`);if(g.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:y,state:g}}function $q(e){let o,i,c=new Map;for(let p of e){if(p.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(i!==void 0)throw Error(`${i} frame appears before the start frame`);o=structuredClone(p.partial);continue}if(!o){i??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);$f(o,c,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:g}=ca(o,c,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");g.text+=p.delta;break}case"text_end":{let{block:g,state:y}=ca(o,c,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");if(g.text=p.content,delete g.textSignature,p.textSignature!==void 0)g.textSignature=p.textSignature;y.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);$f(o,c,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:g}=ca(o,c,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");g.thinking+=p.delta;break}case"thinking_end":{let{block:g,state:y}=ca(o,c,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");if(g.thinking=p.content,delete g.thinkingSignature,delete g.redacted,p.thinkingSignature!==void 0)g.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)g.redacted=p.redacted;y.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);$f(o,c,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:g,state:y}=ca(o,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");y.json=p.json,g.arguments=W(p.json);break}case"toolcall_delta":{let{block:g,state:y}=ca(o,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call frame state");y.json+=p.delta;break}case"toolcall_end":{let{block:g,state:y}=ca(o,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(g.id=p.id,g.name=p.name,g.arguments=structuredClone(p.arguments),delete g.thoughtSignature,delete g.namespace,p.thoughtSignature!==void 0)g.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)g.namespace=p.namespace;y.ended=!0;break}}}if(!o)return;for(let[p,g]of c){if(g.kind!=="toolCall"||g.ended||g.json.length===0)continue;let y=o.content[p];if(y?.type!=="toolCall")throw Error("Unreachable tool-call frame state");y.arguments=W(g.json)}return o}var TR=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],vq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Mq=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ma(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!Mq.some((c)=>c.test(e.errorMessage))){if(TR.some((c)=>c.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&vq.test(e.errorMessage))return!0}}if(o&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>o)return!0}if(o&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=o*0.99)return!0}return!1}function Oq(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function _q(){return[...TR]}function RR(e){return new RegExp(e.join("|"),"i")}var Lq=RR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),Nq=RR(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),kR=60000;function AR(e,o){let i=e.baseDelayMs*2**Math.max(0,o-1),c=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(c,e.maxAgentDelayMs??kR)}class bp extends Error{constructor(){super("Aborted")}}function Dq(e,o){return new Promise((i,c)=>{if(o?.aborted){c(new bp);return}let p=setTimeout(i,e);o?.addEventListener("abort",()=>{clearTimeout(p),c(new bp)},{once:!0})})}async function qq(e,o,i,c){let p=o?.enabled?o.maxRetries:0,g=0,y;for(;;){let b=await e();if(b.stopReason==="aborted"){if(y)await c?.onRetryFinished?.(!1,y.attempt);return b}if(b.stopReason!=="error"){if(y)await c?.onRetryFinished?.(!0,y.attempt);return b}if(g>=p||!CR(b)){if(y)await c?.onRetryFinished?.(!1,y.attempt,b.errorMessage);return b}g++,y={attempt:g,errorMessage:b.errorMessage||"Unknown error"};let E=AR(o,g);await c?.onRetryScheduled?.(g,p,E,y.errorMessage);try{await Dq(E,i)}catch(S){if(await c?.onRetryFinished?.(!1,g,y.errorMessage),S instanceof bp){let{errorMessage:w,...R}=b;return{...R,stopReason:"aborted"}}throw S}await c?.onRetryAttemptStart?.()}}function CR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(Lq.test(o))return!1;return Nq.test(o)}function Fq(e,o){return qr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function ac(e){return me(e,"~refine")&&Ge(e["~refine"])&&un(e["~refine"],0,(o)=>ut(o)&&me(o,"check")&&me(o,"error")&&fs(o.check)&&fs(o.error))}function yn(e){return ut(e)&&!Ge(e)}function Fs(e){return ln(e)}function Ye(e){return yn(e)||Fs(e)}function za(e){return me(e,"additionalItems")&&Ye(e.additionalItems)}function Po(e){return me(e,"additionalProperties")&&Ye(e.additionalProperties)}function uc(e){return me(e,"allOf")&&Ge(e.allOf)&&e.allOf.every((o)=>Ye(o))}function cc(e){return me(e,"$anchor")&&yt(e.$anchor)}function mc(e){return me(e,"anyOf")&&Ge(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function Ep(e){return me(e,"const")}function Ps(e){return me(e,"contains")&&Ye(e.contains)}function bo(e){return me(e,"default")}function pc(e){return me(e,"dependencies")&&ut(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||Ge(o)&&o.every((i)=>yt(i)))}function lc(e){return me(e,"dependentRequired")&&ut(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Ge(o)&&o.every((i)=>yt(i)))}function Va(e){return me(e,"dependentSchemas")&&ut(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function js(e){return me(e,"$dynamicAnchor")&&yt(e.$dynamicAnchor)}function dc(e){return me(e,"$dynamicRef")&&yt(e.$dynamicRef)}function fc(e){return me(e,"else")&&Ye(e.else)}function Sp(e){return me(e,"enum")&&Ge(e.enum)}function hc(e){return me(e,"exclusiveMaximum")&&(_t(e.exclusiveMaximum)||Nr(e.exclusiveMaximum))}function ns(e){return me(e,"exclusiveMinimum")&&(_t(e.exclusiveMinimum)||Nr(e.exclusiveMinimum))}function pa(e){return me(e,"format")&&yt(e.format)}function Eo(e){return me(e,"$id")&&yt(e.$id)}function gc(e){return me(e,"if")&&Ye(e.if)}function Us(e){return me(e,"items")&&(Ye(e.items)||Ge(e.items)&&e.items.every((o)=>Ye(o)))}function yc(e){return Us(e)&&Ge(e.items)}function xc(e){return me(e,"maximum")&&(_t(e.maximum)||Nr(e.maximum))}function Ic(e){return me(e,"maxContains")&&_t(e.maxContains)}function Ja(e){return me(e,"maxItems")&&_t(e.maxItems)}function bc(e){return me(e,"maxLength")&&_t(e.maxLength)}function Ec(e){return me(e,"maxProperties")&&_t(e.maxProperties)}function os(e){return me(e,"minimum")&&(_t(e.minimum)||Nr(e.minimum))}function Bs(e){return me(e,"minContains")&&_t(e.minContains)}function di(e){return me(e,"minItems")&&_t(e.minItems)}function la(e){return me(e,"minLength")&&_t(e.minLength)}function da(e){return me(e,"minProperties")&&_t(e.minProperties)}function Sc(e){return me(e,"multipleOf")&&(_t(e.multipleOf)||Nr(e.multipleOf))}function wc(e){return me(e,"not")&&Ye(e.not)}function Tc(e){return me(e,"oneOf")&&Ge(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function fa(e){return me(e,"pattern")&&(yt(e.pattern)||e.pattern instanceof RegExp)}function Gs(e){return me(e,"patternProperties")&&ut(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function ss(e){return me(e,"prefixItems")&&Ge(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function Ks(e){return me(e,"properties")&&ut(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function Qa(e){return me(e,"propertyNames")&&(ut(e.propertyNames)||Ye(e.propertyNames))}function jq(e){return me(e,"$recursiveAnchor")&&ln(e.$recursiveAnchor)}function Rc(e){return jq(e)&&P(e.$recursiveAnchor,!0)}function kc(e){return me(e,"$recursiveRef")&&yt(e.$recursiveRef)}function Ac(e){return me(e,"$ref")&&yt(e.$ref)}function is(e){return me(e,"required")&&Ge(e.required)&&e.required.every((o)=>yt(o))}function Cc(e){return me(e,"then")&&Ye(e.then)}function Pc(e){return me(e,"type")&&(yt(e.type)||Ge(e.type)&&e.type.every((o)=>yt(o)))}function Ii(e){return me(e,"uniqueItems")&&ln(e.uniqueItems)}function Ai(e){return me(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function $i(e){return me(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function Uq(e){return Ai(e)||$i(e)||Ta(Se(e),(o)=>wp(e[o]))}function Bq(e){return Ta(e,(o)=>wp(o))}function wp(e){return Ge(e)?Bq(e):ut(e)?Uq(e):!1}function PR(e,o){return wp(o)||Ta(Se(e),(i)=>wp(e[i]))}class Of{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ir(Et("context","Push"),[])}Pop(){return Ir(Et("context","Pop"),[])}AddIndex(e){return Ir(Et("context","AddIndex"),[e])}AddKey(e){return Ir(Et("context","AddKey"),[e])}Merge(e){return Ir(Et("context","Merge"),[e])}}class Ln{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((i)=>this.GetIndices().add(i)),o.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class qn extends Ln{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Yo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var Tp={identifier:"External",variables:[]};function vo(e){let o=`External[${Tp.variables.length}]`;return Tp.variables.push(e),o}function $R(){Tp.variables=[]}function vR(){return{...Tp}}function MR(e,o,i,c){let p=vo(i["~refine"].map((g)=>g));return gs(p,qe(0),["refinement","_"],Ir(Et("refinement","check"),[c]))}function OR(e,o,i,c){return un(i["~refine"],0,(p,g)=>p.check(c))}function _R(e,o,i,c,p,g){return Cn(p["~refine"],0,(y,b)=>y.check(g)||o.AddError({keyword:"~refine",schemaPath:i,instancePath:c,params:{index:b,message:y.error(g)}}))}var Gq=0;function Vt(){return`var_${Gq++}`}function _f(e){return Us(e)&&Ge(e.items)}function Kq(e,o,i,c){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=hd(g,qe(i.items.length)),E=o.AddIndex(g);return gs(c,qe(0),[p,g],xr(b,wn(y,E)))}function Hq(e,o,i,c){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=hd(g,qe(i.items.length));return gs(c,qe(0),[p,g],xr(b,y))}function LR(e,o,i,c){if(!_f(i))return qe(!0);return o.UseUnevaluated()?Kq(e,o,i,c):Hq(e,o,i,c)}function NR(e,o,i,c){if(!_f(i))return!0;return un(c,0,(g,y)=>Tu(y,i.items.length)||So(e,o,i.additionalItems,g)&&o.AddIndex(y))}function DR(e,o,i,c,p,g){if(!_f(p))return!0;return un(g,0,(b,E)=>{let S=`${i}/additionalItems`,w=`${c}/${E}`;return Tu(E,p.items.length)||wo(e,o,S,w,p.additionalItems,b)&&o.AddIndex(E)})}function as(e){return new RegExp(e,"u")}function Wq(e,o){return!e.UseUnevaluated()&&(P(o,!0)||ut(o)&&P(Se(o).length,0))}function zq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Lf(e){let o=[];if(Gs(e))o.push(...Se(e.patternProperties));if(Ks(e))o.push(...Se(e.properties).map(zq));return P(o.length,0)?"(?!)":`(${o.join("|")})`}function Vq(e,o,i){return is(o)&&Ks(o)&&!Gs(o)&&P(o.additionalProperties,!1)&&P(Se(o.properties).length,o.required.length)}function Jq(e,o,i){return uo(Et(Ir(Et("Object","getOwnPropertyNames"),[i]),"length"),qe(o.required.length))}function Qq(e,o,i,c){let[p,g]=[Vt(),Vt()],y=vo(as(Lf(i))),b=to(e,o,i.additionalProperties,`${c}[${p}]`),E=Ir(Et(y,"test"),[p]),S=o.AddKey(p),w=o.UseUnevaluated()?xr(E,wn(b,S)):xr(E,b);return gs(Vi(c),qe(0),[p,g],w)}function qR(e,o,i,c){if(Wq(o,i.additionalProperties))return qe(!0);return Vq(o,i,c)?Jq(o,i,c):Qq(e,o,i,c)}function FR(e,o,i,c){let p=as(Lf(i));return un(Se(c),0,(y,b)=>p.test(y)||So(e,o,i.additionalProperties,c[y])&&o.AddKey(y))}function jR(e,o,i,c,p,g){let y=as(Lf(p)),b=[];return Cn(Se(g),0,(S,w)=>{let R=`${i}/additionalProperties`,A=`${c}/${S}`,C=y.test(S)||wo(e,o,R,A,p.additionalProperties,g[S])&&o.AddKey(S);if(!C)b.push(S);return C})||o.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:c,params:{additionalProperties:b}})}function Mi(e,o,i,c,p){let g=Ns("results","[]"),y=i.map((w,R)=>Ns(`context_${R}`,gd("CheckContext",[]))),b=i.map((w,R)=>Ns(`condition_${R}`,Ir(Ys(["context"],Nt(e,o,w,c)),[`context_${R}`]))),E=i.map((w,R)=>Py(`condition_${R}`,Ir(Et("results","push"),[`context_${R}`]))),S=mm(wn(p,o.Merge("results")));return Ir(Ys([],cm([g,...y,...b,...E,S])),[])}function Xq(e,o,i,c){return Mi(e,o,i.allOf,c,uo(Et("results","length"),qe(i.allOf.length)))}function Yq(e,o,i,c){return Pn(i.allOf.map((p)=>Nt(e,o,p,c)))}function UR(e,o,i,c){return o.UseUnevaluated()?Xq(e,o,i,c):Yq(e,o,i,c)}function BR(e,o,i,c){let p=i.allOf.reduce((g,y)=>{let b=new Ln;return At(e,b,y,c)?[...g,b]:g},[]);return P(p.length,i.allOf.length)&&o.Merge(p)}function GR(e,o,i,c,p,g){let y=[],b=p.allOf.reduce((S,w,R)=>{let A=`${i}/allOf/${R}`,C=new qn,L=mr(e,C,A,c,w,g);if(!L)y.push(C);return L?[...S,C]:S},[]),E=P(b.length,p.allOf.length)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E}function Zq(e,o,i,c){return Mi(e,o,i.anyOf,c,ky(Et("results","length"),qe(0)))}function eF(e,o,i,c){return yd(i.anyOf.map((p)=>Nt(e,o,p,c)))}function KR(e,o,i,c){return o.UseUnevaluated()?Zq(e,o,i,c):eF(e,o,i,c)}function HR(e,o,i,c){let p=i.anyOf.reduce((g,y)=>{let b=new Ln;return At(e,b,y,c)?[...g,b]:g},[]);return Hi(p.length,0)&&o.Merge(p)}function WR(e,o,i,c,p,g){let y=[],b=p.anyOf.reduce((S,w,R)=>{let A=new qn,C=`${i}/anyOf/${R}`,L=mr(e,A,C,c,w,g);if(!L)y.push(A);return L?[...S,A]:S},[]),E=Hi(b.length,0)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E||o.AddError({keyword:"anyOf",schemaPath:i,instancePath:c,params:{}})}function zR(e,o,i,c){return i?qe(!0):qe(!1)}function Nf(e,o,i,c){return i}function VR(e,o,i,c,p,g){return Nf(e,o,p,g)||o.AddError({keyword:"boolean",schemaPath:i,instancePath:c,params:{}})}function JR(e,o,i,c){return Wi(i.const)?uo(c,qe(i.const)):Cy(c,vo(i.const))}function Df(e,o,i,c){return Wi(i.const)?P(c,i.const):Ra(c,i.const)}function QR(e,o,i,c,p,g){return Df(e,o,p,g)||o.AddError({keyword:"const",schemaPath:i,instancePath:c,params:{allowedValue:p.const}})}function XR(e){return!(Bs(e)&&P(e.minContains,0))}function tF(e,o,i,c){let[p,g]=[Vt(),Vt()],y=Bn(uo(Et(c,"length"),qe(0))),b=LM(c,[p,g],wn(Nt(e,o,i.contains,p),o.AddIndex(g)));return wn(y,b)}function rF(e,o,i,c){let[p]=[Vt()],g=Bn(uo(Et(c,"length"),qe(0))),y=_M(c,[p,"_"],Nt(e,o,i.contains,p));return wn(g,y)}function YR(e,o,i,c){if(!XR(i))return qe(!0);return o.UseUnevaluated()?tF(e,o,i,c):rF(e,o,i,c)}function qf(e,o,i,c){if(!XR(i))return!0;return!P(c.length,0)&&Iy(c,(p,g)=>At(e,o,i.contains,p)&&o.AddIndex(g))}function ZR(e,o,i,c,p,g){return qf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:1}})}function ek(e,o,i,c){let p=uo(Et(Vi(c),"length"),qe(0)),g=Pn(dn(i.dependencies).map(([y,b])=>{let E=Bn(Ji(c,qe(y))),S=Nt(e,o,b,c),w=(R)=>Pn(R.map((A)=>Ji(c,qe(A))));return xr(E,Ge(b)?w(b):S)}));return xr(p,g)}function tk(e,o,i,c){let p=P(Se(c).length,0),g=un(dn(i.dependencies),0,([y,b])=>!me(c,y)||(Ge(b)?b.every((E)=>me(c,E)):At(e,o,b,c)));return p||g}function rk(e,o,i,c,p,g){let y=P(Se(g).length,0),b=Cn(dn(p.dependencies),0,([E,S])=>{let w=`${i}/dependencies/${E}`;return!me(g,E)||(Ge(S)?S.every((R)=>me(g,R)||o.AddError({keyword:"dependencies",schemaPath:i,instancePath:c,params:{property:E,dependencies:S}})):mr(e,o,w,c,S,g))});return y||b}function nk(e,o,i,c){let p=uo(Et(Vi(c),"length"),qe(0)),g=Pn(dn(i.dependentRequired).map(([y,b])=>{let E=Bn(Ji(c,qe(y))),S=Pn(b.map((w)=>Ji(c,qe(w))));return xr(E,S)}));return xr(p,g)}function ok(e,o,i,c){let p=P(Se(c).length,0),g=un(dn(i.dependentRequired),0,([y,b])=>!me(c,y)||b.every((E)=>me(c,E)));return p||g}function sk(e,o,i,c,p,g){let y=P(Se(g).length,0),b=Cn(dn(p.dependentRequired),0,([E,S])=>!me(g,E)||Cn(S,0,(w)=>me(g,w)||o.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:c,params:{property:E,dependencies:S}})));return y||b}function ik(e,o,i,c){let p=uo(Et(Vi(c),"length"),qe(0)),g=Pn(dn(i.dependentSchemas).map(([y,b])=>{let E=Bn(Ji(c,qe(y))),S=Nt(e,o,b,c);return xr(E,S)}));return xr(p,g)}function ak(e,o,i,c){let p=P(Se(c).length,0),g=un(dn(i.dependentSchemas),0,([y,b])=>!me(c,y)||At(e,o,b,c));return p||g}function uk(e,o,i,c,p,g){let y=P(Se(g).length,0),b=Cn(dn(p.dependentSchemas),0,([E,S])=>{let w=`${i}/dependentSchemas/${E}`;return!me(g,E)||mr(e,o,w,c,S,g)});return y||b}function ck(e,o,i,c){let p=e.DynamicRef(i)??!1;return Hs(e,o,p,c)}function mk(e,o,i,c){let p=e.DynamicRef(i)??!1;return Ye(p)&&At(e,o,p,c)}function pk(e,o,i,c,p,g){let y=e.DynamicRef(p)??!1;return Ye(y)&&mr(e,o,"#",c,y,g)}function lk(e,o,i,c){return yd(i.enum.map((p)=>{if(Wi(p))return uo(c,qe(p));let g=vo(p);return Cy(c,g)}))}function jf(e,o,i,c){return Ta(i.enum,(p)=>Wi(p)?P(c,p):Ra(c,p))}function dk(e,o,i,c,p,g){return jf(e,o,p,g)||o.AddError({keyword:"enum",schemaPath:i,instancePath:c,params:{allowedValues:p.enum}})}function fk(e,o,i,c){return hd(c,qe(i.exclusiveMaximum))}function Uf(e,o,i,c){return Tu(c,i.exclusiveMaximum)}function hk(e,o,i,c,p,g){return Uf(e,o,p,g)||o.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:c,params:{comparison:"<",limit:p.exclusiveMaximum}})}function gk(e,o,i,c){return ky(c,qe(i.exclusiveMinimum))}function Bf(e,o,i,c){return Hi(c,i.exclusiveMinimum)}function yk(e,o,i,c,p,g){return Bf(e,o,p,g)||o.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:c,params:{comparison:">",limit:p.exclusiveMinimum}})}var nF=[0,31,28,31,30,31,30,31,31,30,31,30,31],oF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function sF(e){return e%4===0&&(e%100!==0||e%400===0)}function Ya(e){let o=oF.exec(e);if(!o)return!1;let i=+o[1],c=+o[2],p=+o[3];return c>=1&&c<=12&&p>=1&&p<=(c===2&&sF(i)?29:nF[c])}var iF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Za(e,o=!0){let i=iF.exec(e);if(!i)return!1;if(o&&!i[4]&&!i[5])return!1;let c=+i[1],p=+i[2],g=+i[3];if(c>23||p>59||g>60)return!1;if(i[5]){let w=+i[6],R=+i[7];if(w>23||R>59)return!1}if(g<60)return!0;let y=i[5]==="-"?-1:1,b=+(i[6]||0),E=+(i[7]||0);return((c*60+p-y*(b*60+E))%1440+1440)%1440===1439}function Rp(e){let o=e.split(/T/i);return o.length===2&&Ya(o[0])&&Za(o[1])}var aF=/^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 kp(e){return aF.test(e)}var uF=/^(?:[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 Ap(e){return uF.test(e)}var xk=/^(?!-).*(?<!-)$/,Ik=/^(?!..--)/,bk=/^[a-zA-Z0-9-]*$/;var eu=/[^\p{ASCII}]/u;var cF=/[0-9]/,Ek=/[\u{0660}-\u{0669}]/u,mF=/[\u{06f0}-\u{06f9}]/u,pF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,lF=/[\u{002d}\u{002b}]/u,Gf=/\p{Mn}/u,dF=/\p{Mc}/u;var Sk=/[\p{Mn}\p{Mc}\p{Me}]/u,Kf=/\p{L}/u,fF=/\p{Nd}/u,wk=/\p{Script=Greek}/u,Cp=/\p{Script=Hebrew}/u,Tk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Rk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Hf=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,kk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,hF=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,gF=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Ak=new RegExp([cF,mF].map((e)=>e.source).join("|"),"u"),Ck=new RegExp([Kf,lF,pF,fF,Gf,dF,hF,gF].map((e)=>e.source).join("|"),"u");function Pk(e){return xk.test(e)&&Ik.test(e)&&bk.test(e)}var us=36,vc=1,Mc=26,xF=38,IF=700,vk=72,Mk=128;function Wf(){throw null}function Pp(e){return e.toLowerCase().startsWith("xn--")}function Ok(e,o,i){e=i?Math.floor(e/IF):e>>1,e+=Math.floor(e/o);let c=0;while(e>(us-vc)*Mc>>1)e=Math.floor(e/(us-vc)),c+=us;return c+Math.floor((us-vc+1)*e/(e+xF))}function $p(e){let o=[],i=Mk,c=0,p=vk,g=e.lastIndexOf("-");if(g>0)for(let b=0;b<g;b++){let E=e.charCodeAt(b);if(E>=128)Wf();o.push(E)}let y=g<0?0:g+1;while(y<e.length){let b=c,E=1,S=us;while(!0){if(y>=e.length)Wf();let R=e.charCodeAt(y++),A;if(R>=97&&R<=122)A=R-97;else if(R>=48&&R<=57)A=R-48+26;else Wf();c+=A*E;let C=S<=p?vc:S>=p+Mc?Mc:S-p;if(A<C)break;E*=us-C,S+=us}let w=o.length+1;p=Ok(c-b,w,b===0),i+=Math.floor(c/w),c%=w,o.splice(c,0,i),c++}return String.fromCodePoint(...o)}function $k(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var bF=new RegExp(eu.source,"gu");function _k(e){let o=e.replace(bF,""),i=o.length,c=i>0?[o,"-"]:[],p=Array.from(e,(S)=>S.codePointAt(0)),g=Mk,y=0,b=vk,E=i;while(E<p.length){let S=1/0;for(let w of p)if(w>=g&&w<S)S=w;y+=(S-g)*(E+1),g=S;for(let w of p){if(w<g)y++;if(w===g){let R=y;for(let A=us;;A+=us){let C=A<=b?vc:A>=b+Mc?Mc:A-b;if(R<C)break;let L=C+(R-C)%(us-C);c.push($k(L)),R=Math.floor((R-C)/(us-C))}c.push($k(R)),b=Ok(y,E+1,E===i),y=0,E++}}y++,g++}return c.join("")}var EF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Lk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,SF=/^(?:R|AL|AN)$/;function Nk(e){if(Pp(e))try{return vp($p(e.slice(4).toLowerCase()))}catch{return!1}return vp(e)}function Dk(e){let o=String.fromCodePoint(e);return Ak.test(o)?"EN":Ek.test(o)?"AN":Gf.test(o)?"NSM":Cp.test(o)?"R":Rk.test(o)?"AL":Kf.test(o)?"L":"ON"}function vp(e){for(let o of e)if(SF.test(Dk(o.codePointAt(0))))return!0;return!1}function Mp(e){let o=!1,i=Lk,c=!1,p=!1,g=!0;for(let y of e){let b=Dk(y.codePointAt(0));if(g){if(b!=="L"&&b!=="R"&&b!=="AL")return!1;o=b==="R"||b==="AL",i=o?EF:Lk,g=!1}if(!i.test(b))return!1;if(b==="EN")c=!0;else if(b==="AN")p=!0}if(o&&c&&p)return!1;return!0}function wF(e){return eu.test(e)&&_k(e).length+4>63}function TF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Op(e){if(wF(e))return!1;if(vp(e)&&!Mp(e))return!1;let o=[...e],i=o.map((g)=>g.codePointAt(0)),c=i.length;if(TF(o))return!1;if(Sk.test(o[0]))return!1;let p=!1;for(let g=0;g<c;g++){let y=i[g],b=o[g];if(kk.test(b))return!1;if(!Ck.test(b))return!1;if(Tk.test(b))p=!0;let E=i[g-1],S=i[g+1];switch(y){case 183:if(E!==108||S!==108)return!1;break;case 885:if(!S||!wk.test(o[g+1]))return!1;break;case 1523:case 1524:if(!E||!Cp.test(o[g-1]))return!1;break;case 8204:if(!E||E<128&&!Hf.test(o[g-1]))return!1;break;case 8205:if(!E||!Hf.test(o[g-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function _p(e){if(!Pp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let i=$p(o);if(!eu.test(i))return!1;return Op(i)}catch{return!1}}function RF(e){return e.length>0&&e.length<=63}function kF(e){return RF(e)&&(_p(e)||Pk(e))}function Uk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>kF(o))}function AF(e){return e.length>0&&e.length<=63}function CF(e){return AF(e)&&(_p(e)||Op(e))}function PF(e){return e.replace(/[\uff01-\uff5e]/g,(o)=>String.fromCharCode(o.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function Bk(e){if(e.length===0||e.includes(" "))return!1;let o=PF(e);if(o.length>253)return!1;let i=o.split("."),c=i.some((p)=>Nk(p));return i.every((p)=>CF(p)&&(!c||Mp(p)))}function Lp(e){return Uk(e)}var $F=/^(?:[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 Np(e){return $F.test(e.normalize("NFC"))}function Dp(e){return Bk(e)}var vF=/^(?:(?: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 qp(e){return vF.test(e)}var MF=/^(?:(?:(?:[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 Fp(e){return MF.test(e)}var OF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,_F=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function jp(e){return!OF.test(e)&&!_F.test(e)&&URL.canParse(e,"http://example.com")}var LF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,NF=/[\x00-\x20<>\^`{|}\\]/,DF=/%(?![0-9a-fA-F]{2})/;function qF(e){return e.length<2048?e.replace(LF,"[::1]"):e}function Up(e){if(NF.test(e))return!1;if(DF.test(e))return!1;return URL.canParse(qF(e))}var FF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Bp(e){return FF.test(e)}var jF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Gp(e){return jF.test(e)}function Kp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var UF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Hp(e){return UF.test(e)}var BF=/^(?:[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 Wp(e){return BF.test(e)}var GF=/^(?:(?:[^\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 zp(e){return GF.test(e)}var KF=/^[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 Vp(e){return KF.test(e)}function Jp(e){return URL.canParse(e)}var HF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Qp(e){return HF.test(e)}var Er=new Map;function Kk(){Er.clear()}function WF(){return[...Er.entries()]}function zF(e,o){Er.set(e,o)}function VF(e){return Er.has(e)}function JF(e){return Er.get(e)}function Hk(e,o){return Er.get(e)?.(o)??!0}function Wk(){Kk(),Er.set("date-time",Rp),Er.set("date",Ya),Er.set("duration",kp),Er.set("email",Ap),Er.set("hostname",Lp),Er.set("idn-email",Np),Er.set("idn-hostname",Dp),Er.set("ipv4",qp),Er.set("ipv6",Fp),Er.set("iri-reference",jp),Er.set("iri",Up),Er.set("json-pointer-uri-fragment",Bp),Er.set("json-pointer",Gp),Er.set("regex",Kp),Er.set("relative-json-pointer",Hp),Er.set("time",Za),Er.set("uri-reference",Wp),Er.set("uri-template",zp),Er.set("uri",Vp),Er.set("url",Jp),Er.set("uuid",Qp)}Wk();function zk(e,o,i,c){return Ir(Et("Format","Test"),[qe(i.format),c])}function Vf(e,o,i,c){return Hk(i.format,c)}function Vk(e,o,i,c,p,g){return Vf(e,o,p,g)||o.AddError({keyword:"format",schemaPath:i,instancePath:c,params:{format:p.format}})}function Jk(e,o,i,c){let p=Cc(i)?i.then:!0,g=fc(i)?i.else:!0;return DM(Nt(e,o,i.if,c),Nt(e,o,p,c),Nt(e,o,g,c))}function Qk(e,o,i,c){let p=Cc(i)?i.then:!0,g=fc(i)?i.else:!0;return At(e,o,i.if,c)?At(e,o,p,c):At(e,o,g,c)}function Xk(e,o,i,c,p,g){let y=Cc(p)?p.then:!0,b=fc(p)?p.else:!0,E=new qn,S=mr(e,E,`${i}/if`,c,p.if,g)?mr(e,E,`${i}/then`,c,y,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"then"}}):mr(e,o,`${i}/else`,c,b,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"else"}});if(S)o.Merge([E]);return S}function QF(e,o,i,c){return Pn(i.items.map((p,g)=>{let y=zi(Et(c,"length"),qe(g)),b=to(e,o,p,`${c}[${g}]`),E=o.AddIndex(qe(g));return xr(y,wn(b,E))}))}function XF(e,o,i,c){return Pn(i.items.map((p,g)=>{let y=zi(Et(c,"length"),qe(g)),b=to(e,o,p,`${c}[${g}]`);return xr(y,b)}))}function YF(e,o,i,c){return o.UseUnevaluated()?QF(e,o,i,c):XF(e,o,i,c)}function ZF(e,o,i,c){return un(i.items,0,(p,g)=>hs(c.length,g)||So(e,o,p,c[g])&&o.AddIndex(g))}function e1(e,o,i,c,p,g){return Cn(p.items,0,(y,b)=>{let E=`${i}/items/${b}`,S=`${c}/${b}`;return hs(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function t1(e,o,i,c){let p=ss(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element"),y=o.AddIndex("index");return gs(c,qe(p),["element","index"],wn(g,y))}function r1(e,o,i,c){let p=ss(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element");return gs(c,qe(p),["element","index"],g)}function n1(e,o,i,c){return o.UseUnevaluated()?t1(e,o,i,c):r1(e,o,i,c)}function o1(e,o,i,c){let p=ss(i)?i.prefixItems.length:0;return un(c,p,(g,y)=>So(e,o,i.items,g)&&o.AddIndex(y))}function s1(e,o,i,c,p,g){let y=ss(p)?p.prefixItems.length:0;return Cn(g,y,(b,E)=>{let S=`${i}/items`,w=`${c}/${E}`;return wo(e,o,S,w,p.items,b)&&o.AddIndex(E)})}function Yk(e,o,i,c){return yc(i)?YF(e,o,i,c):n1(e,o,i,c)}function Zk(e,o,i,c){return yc(i)?ZF(e,o,i,c):o1(e,o,i,c)}function eA(e,o,i,c,p,g){return yc(p)?e1(e,o,i,c,p,g):s1(e,o,i,c,p,g)}function tA(e){return Ps(e)}function rA(e,o,i,c){if(!tA(i))return qe(!0);let[p]=[Vt()],g=um(c,[p,"_"],Nt(e,o,i.contains,p));return zi(g,qe(i.maxContains))}function Jf(e,o,i,c){if(!tA(i))return!0;let p=pd(c,(g)=>At(e,o,i.contains,g));return hs(p,i.maxContains)}function nA(e,o,i,c,p,g){let y=Bs(p)?p.minContains:1;return Jf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:y,maxContains:p.maxContains}})}function oA(e,o,i,c){return zi(c,qe(i.maximum))}function Qf(e,o,i,c){return hs(c,i.maximum)}function sA(e,o,i,c,p,g){return Qf(e,o,p,g)||o.AddError({keyword:"maximum",schemaPath:i,instancePath:c,params:{comparison:"<=",limit:p.maximum}})}function iA(e,o,i,c){return zi(Et(c,"length"),qe(i.maxItems))}function Xf(e,o,i,c){return hs(c.length,i.maxItems)}function aA(e,o,i,c,p,g){return Xf(e,o,p,g)||o.AddError({keyword:"maxItems",schemaPath:i,instancePath:c,params:{limit:p.maxItems}})}function uA(e,o,i,c){return OM(c,qe(i.maxLength))}function Yf(e,o,i,c){return yy(c,i.maxLength)}function cA(e,o,i,c,p,g){return Yf(e,o,p,g)||o.AddError({keyword:"maxLength",schemaPath:i,instancePath:c,params:{limit:p.maxLength}})}function mA(e,o,i,c){return zi(Et(Vi(c),"length"),qe(i.maxProperties))}function Zf(e,o,i,c){return hs(Se(c).length,i.maxProperties)}function pA(e,o,i,c,p,g){return Zf(e,o,p,g)||o.AddError({keyword:"maxProperties",schemaPath:i,instancePath:c,params:{limit:p.maxProperties}})}function lA(e){return Ps(e)}function i1(e,o,i,c){let[p,g]=[Vt(),Vt()],y=um(c,[p,g],wn(Nt(e,o,i.contains,p),o.AddIndex(g)));return ku(y,qe(i.minContains))}function a1(e,o,i,c){let[p]=[Vt()],g=um(c,[p,"_"],Nt(e,o,i.contains,p));return ku(g,qe(i.minContains))}function dA(e,o,i,c){if(!lA(i))return qe(!0);return o.UseUnevaluated()?i1(e,o,i,c):a1(e,o,i,c)}function eh(e,o,i,c){if(!lA(i))return!0;let p=pd(c,(g,y)=>At(e,o,i.contains,g)&&o.AddIndex(y));return wa(p,i.minContains)}function fA(e,o,i,c,p,g){return eh(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:p.minContains}})}function hA(e,o,i,c){return ku(c,qe(i.minimum))}function th(e,o,i,c){return wa(c,i.minimum)}function gA(e,o,i,c,p,g){return th(e,o,p,g)||o.AddError({keyword:"minimum",schemaPath:i,instancePath:c,params:{comparison:">=",limit:p.minimum}})}function yA(e,o,i,c){return ku(Et(c,"length"),qe(i.minItems))}function rh(e,o,i,c){return wa(c.length,i.minItems)}function xA(e,o,i,c,p,g){return rh(e,o,p,g)||o.AddError({keyword:"minItems",schemaPath:i,instancePath:c,params:{limit:p.minItems}})}function IA(e,o,i,c){return MM(c,qe(i.minLength))}function nh(e,o,i,c){return xy(c,i.minLength)}function bA(e,o,i,c,p,g){return nh(e,o,p,g)||o.AddError({keyword:"minLength",schemaPath:i,instancePath:c,params:{limit:p.minLength}})}function EA(e,o,i,c){return ku(Et(Vi(c),"length"),qe(i.minProperties))}function oh(e,o,i,c){return wa(Se(c).length,i.minProperties)}function SA(e,o,i,c,p,g){return oh(e,o,p,g)||o.AddError({keyword:"minProperties",schemaPath:i,instancePath:c,params:{limit:p.minProperties}})}function wA(e,o,i,c){return qM(c,qe(i.multipleOf))}function sh(e,o,i,c){return hy(c,i.multipleOf)}function TA(e,o,i,c,p,g){return sh(e,o,p,g)||o.AddError({keyword:"multipleOf",schemaPath:i,instancePath:c,params:{multipleOf:p.multipleOf}})}function u1(e,o,i,c){return Mi(e,o,[i.not],c,Bn(uo(Et("results","length"),qe(1))))}function c1(e,o,i,c){return Bn(Nt(e,o,i.not,c))}function RA(e,o,i,c){return o.UseUnevaluated()?u1(e,o,i,c):c1(e,o,i,c)}function ih(e,o,i,c){let p=new Ln;return!At(e,p,i.not,c)&&o.Merge([p])}function kA(e,o,i,c,p,g){return ih(e,o,p,g)||o.AddError({keyword:"not",schemaPath:i,instancePath:c,params:{}})}function m1(e,o,i,c){return Mi(e,o,i.oneOf,c,uo(Et("results","length"),qe(1)))}function p1(e,o,i,c){let[p]=[Vt()],g=NM(i.oneOf.map((b)=>Nt(e,o,b,c))),y=um(g,[p,"_"],uo(p,qe(!0)));return uo(y,qe(1))}function AA(e,o,i,c){return o.UseUnevaluated()?m1(e,o,i,c):p1(e,o,i,c)}function CA(e,o,i,c){let p=i.oneOf.reduce((g,y)=>{let b=new Ln;return At(e,b,y,c)?[...g,b]:g},[]);return P(p.length,1)&&o.Merge(p)}function PA(e,o,i,c,p,g){let y=[],b=[],E=p.oneOf.reduce((w,R,A)=>{let C=new qn,L=`${i}/oneOf/${A}`,q=mr(e,C,L,c,R,g);if(q)b.push(A);if(!q)y.push(C);return q?[...w,C]:w},[]),S=P(E.length,1)&&o.Merge(E);if(!S&&P(b.length,0))y.forEach((w)=>w.GetErrors().forEach((R)=>o.AddError(R)));return S||o.AddError({keyword:"oneOf",schemaPath:i,instancePath:c,params:{passingSchemas:b}})}function $A(e,o,i,c){let p=vo(yt(i.pattern)?as(i.pattern):i.pattern);return Ir(Et(p,"test"),[c])}function ah(e,o,i,c){return(yt(i.pattern)?as(i.pattern):i.pattern).test(c)}function vA(e,o,i,c,p,g){return ah(e,o,p,g)||o.AddError({keyword:"pattern",schemaPath:i,instancePath:c,params:{pattern:p.pattern}})}function MA(e,o,i,c){return Pn(dn(i.patternProperties).map(([p,g])=>{let[y,b]=[Vt(),Vt()],E=vo(as(p)),S=Bn(Ir(Et(E,"test"),[y])),w=to(e,o,g,b),R=o.AddKey(y),A=o.UseUnevaluated()?xr(S,wn(w,R)):xr(S,w);return gs(Ay(c),qe(0),[`[${y}, ${b}]`,"_"],A)}))}function OA(e,o,i,c){return un(dn(i.patternProperties),0,([p,g])=>{let y=as(p);return un(dn(c),0,([b,E])=>!y.test(b)||So(e,o,g,E)&&o.AddKey(b))})}function _A(e,o,i,c,p,g){return Cn(dn(p.patternProperties),0,([y,b])=>{let E=`${i}/patternProperties/${y}`,S=as(y);return Cn(dn(g),0,([w,R])=>{let A=`${c}/${w}`;return!S.test(w)||wo(e,o,E,A,b,R)&&o.AddKey(w)})})}function LA(e,o,i,c){return Pn(i.prefixItems.map((p,g)=>{let y=zi(Et(c,"length"),qe(g)),b=to(e,o,p,`${c}[${g}]`),E=o.AddIndex(qe(g)),S=o.UseUnevaluated()?wn(b,E):b;return xr(y,S)}))}function NA(e,o,i,c){return P(c.length,0)||un(i.prefixItems,0,(p,g)=>hs(c.length,g)||So(e,o,p,c[g])&&o.AddIndex(g))}function DA(e,o,i,c,p,g){return P(g.length,0)||Cn(p.prefixItems,0,(y,b)=>{let E=`${i}/prefixItems/${b}`,S=`${c}/${b}`;return hs(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function Xp(e,o){return e.includes(o)||Yo().exactOptionalPropertyTypes}function qA(e,o){return fd(Et(e,o))}function uh(e,o){return Bt(e[o])}function FA(e,o,i,c){let p=is(i)?i.required:[],g=dn(i.properties).map(([y,b])=>{let E=Bn(Ji(c,qe(y))),S=to(e,o,b,Et(c,y)),w=o.AddKey(qe(y)),R=o.UseUnevaluated()?wn(S,w):S,A=p.includes(y)?R:xr(E,R);return Xp(p,y)?A:xr(qA(c,y),A)});return Pn(g)}function jA(e,o,i,c){let p=is(i)?i.required:[];return un(dn(i.properties),0,([y,b])=>{let E=!me(c,y)||So(e,o,b,c[y])&&o.AddKey(y);return Xp(p,y)?E:uh(c,y)||E})}function UA(e,o,i,c,p,g){let y=is(p)?p.required:[];return Cn(dn(p.properties),0,([E,S])=>{let w=`${i}/properties/${E}`,R=`${c}/${E}`,A=()=>!me(g,E)||wo(e,o,w,R,S,g[E])&&o.AddKey(E);return Xp(y,E)?A():uh(g,E)||A()})}function BA(e,o,i,c){let[p,g]=[Vt(),Vt()];return gs(Vi(c),qe(0),[p,g],Nt(e,o,i.propertyNames,p))}function GA(e,o,i,c){return un(Se(c),0,(p,g)=>At(e,o,i.propertyNames,p))}function KA(e,o,i,c,p,g){let y=[];return Cn(Se(g),0,(E,S)=>{let w=`${c}/${E}`,R=`${i}/propertyNames`,A=mr(e,o,R,w,p.propertyNames,E);if(!A)y.push(E);return A})||o.AddError({keyword:"propertyNames",schemaPath:i,instancePath:c,params:{propertyNames:y}})}function HA(e,o,i,c){let p=e.RecursiveRef(i)??!1;return Hs(e,o,p,c)}function WA(e,o,i,c){let p=e.RecursiveRef(i)??!1;return Ye(p)&&At(e,o,p,c)}function zA(e,o,i,c,p,g){let y=e.RecursiveRef(p)??!1;return Ye(y)&&mr(e,o,"#",c,y,g)}function l1(e,o,i,c){let p=Ys(["context","value"],Hs(e,o,i,"value")),g=Ys(["context","value"],cm([Ns("nextContext",gd("CheckContext",[])),Ns("result",Ir(p,["nextContext","value"])),Py("result",o.Merge("[nextContext]")),mm("result")]));return Ir(g,["context",c])}function d1(e,o,i,c){return Hs(e,o,i,c)}function VA(e,o,i,c){let p=e.Ref(i)??!1;return o.UseUnevaluated()?l1(e,o,p,c):d1(e,o,p,c)}function JA(e,o,i,c){let p=e.Ref(i)??!1,g=new Ln,y=Ye(p)&&At(e,g,p,c);if(y)o.Merge([g]);return y}function QA(e,o,i,c,p,g){let y=e.Ref(p)??!1,b=new qn,E=Ye(y)&&mr(e,b,"#",c,y,g);if(E)o.Merge([b]);if(!E)b.GetErrors().forEach((S)=>o.AddError(S));return E}function XA(e,o,i,c){return Pn(i.required.map((p)=>Ji(c,qe(p))))}function YA(e,o,i,c){return un(i.required,0,(p)=>me(c,p))}function ZA(e,o,i,c,p,g){let y=[];return Cn(p.required,0,(E)=>{let S=me(g,E);if(!S)y.push(E);return S})||o.AddError({keyword:"required",schemaPath:i,instancePath:c,params:{requiredProperties:y}})}function e0(e,o,i,c){return P(i,"object")?wy(c):P(i,"array")?am(c):P(i,"boolean")?kM(c):P(i,"integer")?AM(c):P(i,"number")?Sy(c):P(i,"null")?CM(c):P(i,"string")?Ry(c):P(i,"bigint")?Ey(c):P(i,"constructor")?vM(c):P(i,"function")?$M(c):P(i,"symbol")?PM(c):P(i,"undefined")?fd(c):P(i,"void")?fd(c):qe(!0)}function ch(e,o,i,c,p){return P(i,"object")?Xo(p):P(i,"array")?Ge(p):P(i,"boolean")?ln(p):P(i,"integer")?im(p):P(i,"number")?_t(p):P(i,"null")?ho(p):P(i,"string")?yt(p):P(i,"bigint")?Nr(p):P(i,"constructor")?cd(p):P(i,"function")?fs(p):P(i,"symbol")?md(p):P(i,"undefined")?Bt(p):P(i,"void")?Bt(p):!0}function f1(e,o,i,c){return yd(i.map((p)=>e0(e,o,p,c)))}function t0(e,o,i,c,p){return Ta(i,(g)=>ch(e,o,g,c,p))}function r0(e,o,i,c){return Ge(i.type)?f1(e,o,i.type,c):e0(e,o,i.type,c)}function n0(e,o,i,c){return Ge(i.type)?t0(e,o,i.type,i,c):ch(e,o,i.type,i,c)}function o0(e,o,i,c,p,g){return(Ge(p.type)?t0(e,o,p.type,p,g):ch(e,o,p.type,p,g))||o.AddError({keyword:"type",schemaPath:i,instancePath:c,params:{type:p.type}})}function s0(e,o,i,c){let[p,g]=[Vt(),Vt()],y=Ir(Et("context","GetIndices"),[]),b=Ir(Et("indices","has"),[p]),E=Nt(e,o,i.unevaluatedItems,g),S=Ir(Et("context","AddIndex"),[p]),w=gs(c,qe(0),[g,p],wn(xr(b,E),S));return Ir(Ys(["context"],cm([Ns("indices",y),mm(w)])),["context"])}function i0(e,o,i,c){let p=o.GetIndices();return un(c,0,(g,y)=>(p.has(y)||At(e,o,i.unevaluatedItems,g))&&o.AddIndex(y))}function a0(e,o,i,c,p,g){let y=o.GetIndices(),b=[];return Cn(g,0,(S,w)=>{let R=new qn,A=(y.has(w)||mr(e,R,i,c,p.unevaluatedItems,S))&&o.AddIndex(w);if(!A)b.push(w);return A})||o.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:c,params:{unevaluatedItems:b}})}function u0(e,o,i,c){let[p,g]=[Vt(),Vt()],y=Ir(Et("context","GetKeys"),[]),b=Ir(Et("keys","has"),[p]),E=Ir(Et("context","AddKey"),[p]),S=Nt(e,o,i.unevaluatedProperties,g),w=gs(Ay(c),qe(0),[`[${p}, ${g}]`,"_"],xr(b,wn(S,E)));return Ir(Ys(["context"],cm([Ns("keys",y),mm(w)])),["context"])}function c0(e,o,i,c){let p=o.GetKeys();return un(dn(c),0,([g,y])=>p.has(g)||At(e,o,i.unevaluatedProperties,y)&&o.AddKey(g))}function m0(e,o,i,c,p,g){let y=o.GetKeys(),b=[];return Cn(dn(g),0,([S,w])=>{let R=new qn,A=y.has(S)||mr(e,R,i,c,p.unevaluatedProperties,w)&&o.AddKey(S);if(!A)b.push(S);return A})||o.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:c,params:{unevaluatedProperties:b}})}function mh(e){return!P(e.uniqueItems,!1)}function p0(e,o,i,c){if(!mh(i))return qe(!0);let p=Et(gd("Set",[Ir(Et(c,"map"),[Et("Hashing","Hash")])]),"size"),g=Et(c,"length");return uo(p,g)}function l0(e,o,i,c){if(!mh(i))return!0;let p=new Set(c.map(bd)).size,g=c.length;return P(p,g)}function d0(e,o,i,c,p,g){if(!mh(p))return!0;let y=new Set,b=g.reduce((S,w,R)=>{let A=bd(w);if(y.has(A))return[...S,R];return y.add(A),S},[]);return P(b.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:c,params:{duplicateItems:b}})}function Oc(e,o){return Pc(e)&&(Ge(e.type)&&Hi(e.type.length,0)&&un(e.type,0,(i)=>P(i,o))||P(e.type,o))}function h1(e){return Oc(e,"object")}function g1(e){return yn(e)&&(Po(e)||pc(e)||lc(e)||Va(e)||Ks(e)||Gs(e)||Qa(e)||da(e)||Ec(e)||is(e)||$i(e))}function y1(e){return Oc(e,"array")}function x1(e){return yn(e)&&(za(e)||Us(e)||Ps(e)||Ic(e)||Ja(e)||Bs(e)||di(e)||ss(e)||Ai(e)||Ii(e))}function I1(e){return Oc(e,"string")}function b1(e){return yn(e)&&(la(e)||bc(e)||pa(e)||fa(e))}function E1(e){return Oc(e,"number")||Oc(e,"bigint")}function S1(e){return yn(e)&&(os(e)||xc(e)||hc(e)||ns(e)||Sc(e))}function to(e,o,i,c){return o.UseUnevaluated()?wn(wn(o.Push(),Nt(e,o,i,c)),o.Pop()):Nt(e,o,i,c)}function Nt(e,o,i,c){e.Push(i);let p=[];if(Fs(i))return zR(e,o,i,c);if(Pc(i))p.push(r0(e,o,i,c));if(g1(i)){let y=[];if(is(i))y.push(XA(e,o,i,c));if(Po(i))y.push(qR(e,o,i,c));if(pc(i))y.push(ek(e,o,i,c));if(lc(i))y.push(nk(e,o,i,c));if(Va(i))y.push(ik(e,o,i,c));if(Gs(i))y.push(MA(e,o,i,c));if(Ks(i))y.push(FA(e,o,i,c));if(Qa(i))y.push(BA(e,o,i,c));if(da(i))y.push(EA(e,o,i,c));if(Ec(i))y.push(mA(e,o,i,c));let b=Pn(y),E=xr(Bn(wy(c)),b);p.push(h1(i)?b:E)}if(x1(i)){let y=[];if(za(i))y.push(LR(e,o,i,c));if(Ps(i))y.push(YR(e,o,i,c));if(Us(i))y.push(Yk(e,o,i,c));if(Ic(i))y.push(rA(e,o,i,c));if(Ja(i))y.push(iA(e,o,i,c));if(Bs(i))y.push(dA(e,o,i,c));if(di(i))y.push(yA(e,o,i,c));if(ss(i))y.push(LA(e,o,i,c));if(Ii(i))y.push(p0(e,o,i,c));let b=Pn(y),E=xr(Bn(am(c)),b);p.push(y1(i)?b:E)}if(b1(i)){let y=[];if(bc(i))y.push(uA(e,o,i,c));if(la(i))y.push(IA(e,o,i,c));if(pa(i))y.push(zk(e,o,i,c));if(fa(i))y.push($A(e,o,i,c));let b=Pn(y),E=xr(Bn(Ry(c)),b);p.push(I1(i)?b:E)}if(S1(i)){let y=[];if(hc(i))y.push(fk(e,o,i,c));if(ns(i))y.push(gk(e,o,i,c));if(xc(i))y.push(oA(e,o,i,c));if(os(i))y.push(hA(e,o,i,c));if(Sc(i))y.push(wA(e,o,i,c));let b=Pn(y),E=xr(Bn(xr(Sy(c),Ey(c))),b);p.push(E1(i)?b:E)}if(Ac(i))p.push(VA(e,o,i,c));if(kc(i))p.push(HA(e,o,i,c));if(dc(i))p.push(ck(e,o,i,c));if(Ep(i))p.push(JR(e,o,i,c));if(Sp(i))p.push(lk(e,o,i,c));if(gc(i))p.push(Jk(e,o,i,c));if(wc(i))p.push(RA(e,o,i,c));if(uc(i))p.push(UR(e,o,i,c));if(mc(i))p.push(KR(e,o,i,c));if(Tc(i))p.push(AA(e,o,i,c));if(Ai(i))p.push(xr(Bn(am(c)),s0(e,o,i,c)));if($i(i))p.push(xr(Bn(Ty(c)),u0(e,o,i,c)));if(ac(i))p.push(MR(e,o,i,c));let g=Pn(p);return e.Pop(i),g}function So(e,o,i,c){return o.Push()&&At(e,o,i,c)&&o.Pop()}function At(e,o,i,c){e.Push(i);let p=Fs(i)?Nf(e,o,i,c):(!Pc(i)||n0(e,o,i,c))&&(!(ut(c)&&!Ge(c))||(!is(i)||YA(e,o,i,c))&&(!Po(i)||FR(e,o,i,c))&&(!pc(i)||tk(e,o,i,c))&&(!lc(i)||ok(e,o,i,c))&&(!Va(i)||ak(e,o,i,c))&&(!Gs(i)||OA(e,o,i,c))&&(!Ks(i)||jA(e,o,i,c))&&(!Qa(i)||GA(e,o,i,c))&&(!da(i)||oh(e,o,i,c))&&(!Ec(i)||Zf(e,o,i,c)))&&(!Ge(c)||(!za(i)||NR(e,o,i,c))&&(!Ps(i)||qf(e,o,i,c))&&(!Us(i)||Zk(e,o,i,c))&&(!Ic(i)||Jf(e,o,i,c))&&(!Ja(i)||Xf(e,o,i,c))&&(!Bs(i)||eh(e,o,i,c))&&(!di(i)||rh(e,o,i,c))&&(!ss(i)||NA(e,o,i,c))&&(!Ii(i)||l0(e,o,i,c)))&&(!yt(c)||(!bc(i)||Yf(e,o,i,c))&&(!la(i)||nh(e,o,i,c))&&(!pa(i)||Vf(e,o,i,c))&&(!fa(i)||ah(e,o,i,c)))&&(!(_t(c)||Nr(c))||(!hc(i)||Uf(e,o,i,c))&&(!ns(i)||Bf(e,o,i,c))&&(!xc(i)||Qf(e,o,i,c))&&(!os(i)||th(e,o,i,c))&&(!Sc(i)||sh(e,o,i,c)))&&(!Ac(i)||JA(e,o,i,c))&&(!kc(i)||WA(e,o,i,c))&&(!dc(i)||mk(e,o,i,c))&&(!Ep(i)||Df(e,o,i,c))&&(!Sp(i)||jf(e,o,i,c))&&(!gc(i)||Qk(e,o,i,c))&&(!wc(i)||ih(e,o,i,c))&&(!uc(i)||BR(e,o,i,c))&&(!mc(i)||HR(e,o,i,c))&&(!Tc(i)||CA(e,o,i,c))&&(!Ai(i)||(!Ge(c)||i0(e,o,i,c)))&&(!$i(i)||(!ut(c)||c0(e,o,i,c)))&&(!ac(i)||OR(e,o,i,c));return e.Pop(i),p}function wo(e,o,i,c,p,g){return o.Push()&&mr(e,o,i,c,p,g)&&o.Pop()}function mr(e,o,i,c,p,g){if(o.AtCapacity())return!1;e.Push(p);let y=Fs(p)?VR(e,o,i,c,p,g):!!(+(!Pc(p)||o0(e,o,i,c,p,g))&+(!(ut(g)&&!Ge(g))||!!(+(!is(p)||ZA(e,o,i,c,p,g))&+(!Po(p)||jR(e,o,i,c,p,g))&+(!pc(p)||rk(e,o,i,c,p,g))&+(!lc(p)||sk(e,o,i,c,p,g))&+(!Va(p)||uk(e,o,i,c,p,g))&+(!Gs(p)||_A(e,o,i,c,p,g))&+(!Ks(p)||UA(e,o,i,c,p,g))&+(!Qa(p)||KA(e,o,i,c,p,g))&+(!da(p)||SA(e,o,i,c,p,g))&+(!Ec(p)||pA(e,o,i,c,p,g))))&+(!Ge(g)||!!(+(!za(p)||DR(e,o,i,c,p,g))&+(!Ps(p)||ZR(e,o,i,c,p,g))&+(!Us(p)||eA(e,o,i,c,p,g))&+(!Ic(p)||nA(e,o,i,c,p,g))&+(!Ja(p)||aA(e,o,i,c,p,g))&+(!Bs(p)||fA(e,o,i,c,p,g))&+(!di(p)||xA(e,o,i,c,p,g))&+(!ss(p)||DA(e,o,i,c,p,g))&+(!Ii(p)||d0(e,o,i,c,p,g))))&+(!yt(g)||!!(+(!bc(p)||cA(e,o,i,c,p,g))&+(!la(p)||bA(e,o,i,c,p,g))&+(!pa(p)||Vk(e,o,i,c,p,g))&+(!fa(p)||vA(e,o,i,c,p,g))))&+(!(_t(g)||Nr(g))||!!(+(!hc(p)||hk(e,o,i,c,p,g))&+(!ns(p)||yk(e,o,i,c,p,g))&+(!xc(p)||sA(e,o,i,c,p,g))&+(!os(p)||gA(e,o,i,c,p,g))&+(!Sc(p)||TA(e,o,i,c,p,g))))&+(!Ac(p)||QA(e,o,i,c,p,g))&+(!kc(p)||zA(e,o,i,c,p,g))&+(!dc(p)||pk(e,o,i,c,p,g))&+(!Ep(p)||QR(e,o,i,c,p,g))&+(!Sp(p)||dk(e,o,i,c,p,g))&+(!gc(p)||Xk(e,o,i,c,p,g))&+(!wc(p)||kA(e,o,i,c,p,g))&+(!uc(p)||GR(e,o,i,c,p,g))&+(!mc(p)||WR(e,o,i,c,p,g))&+(!Tc(p)||PA(e,o,i,c,p,g))&+(!Ai(p)||(!Ge(g)||a0(e,o,i,c,p,g)))&+(!$i(p)||(!ut(g)||m0(e,o,i,c,p,g))))&&(!ac(p)||_R(e,o,i,c,p,g));return e.Pop(p),y}var f0=[0],Yp=new Map,_c=new Map;function w1(){return`${f0[0]++}`}function T1(e,o){if(!Yp.has(e))Yp.set(e,new Map);let i=Yp.get(e);if(i.has(o))return i.get(o);let c=w1();return i.set(o,c),c}function R1(e,o,i,c){return e.UseUnevaluated()?Ir(`check_${i}`,["context",c]):Ir(`check_${i}`,[c])}function k1(e,o,i,c){let p=Nt(e,o,i,"value");return o.UseUnevaluated()?Ns(`check_${c}`,Ys(["context","value"],p)):Ns(`check_${c}`,Ys(["value"],p))}function h0(){f0[0]=0,Yp.clear(),_c.clear()}function g0(){return[..._c.values()]}function Hs(e,o,i,c){let p=T1(i,e.LexicalBaseURL()),g=R1(o,i,p,c);if(_c.has(p))return g;return _c.set(p,""),_c.set(p,k1(e,o,i,p)),g}function A1(e,o){return ut(o)&&!Ru(e)?o[e]:void 0}function C1(e,o){return e.reduce((i,c)=>A1(c,i),o)}function P1(e){if(P(e.length,0))return[];let o=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function $1(e,o){let i=P1(o);return C1(i,e)}var el="https://json-schema.org";function x0(e,o){if(ut(e)&&js(e)&&P(e.$dynamicAnchor,o))return e;if(ut(e))for(let i of Se(e)){let c=x0(e[i],o);if(c)return c}return}function ph(e,o,i){if(P(e,i))return o.href;let c=yn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(Ge(e))for(let p of e){let g=ph(p,c,i);if(!Bt(g))return g}else if(ut(e))for(let p of Se(e)){let g=ph(e[p],c,i);if(!Bt(g))return g}return}function v1(e,o,i){if(P(e.$id,i.hash))return e;let c=new URL(i.href,o.href);if(P(o.pathname,c.pathname))return i.hash.startsWith("#")?I0(e,i):e;return}function M1(e,o,i){let c=new URL(`#${e.$anchor}`,o.href),p=new URL(i.href,o.href);return P(c.href,p.href)?e:void 0}function O1(e,o,i){let c=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(i.href,o.href);return P(c.href,p.href)?e:void 0}function I0(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let i=decodeURIComponent(o.hash.slice(1));if(!i.startsWith("/"))return;return $1(e,i)}function _1(e,o,i){if(Eo(e)){let c=v1(e,o,i);if(!Bt(c))return c}if(cc(e)){let c=M1(e,o,i);if(!Bt(c))return c}if(js(e)){let c=O1(e,o,i);if(!Bt(c))return c}return I0(e,i)}function L1(e,o,i){return e.reduce((c,p)=>{let g=tl(p,o,i);return!Bt(g)?g:c},void 0)}function N1(e){return P(e,"const")||P(e,"enum")}function D1(e,o,i){return Se(e).reduce((c,p)=>{if(N1(p))return c;let g=tl(e[p],o,i);return!Bt(g)?g:c},void 0)}function tl(e,o,i){let c=yn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(yn(e)){let p=_1(e,c,i);if(!Bt(p))return p}if(Ge(e))return L1(e,c,i);if(ut(e))return D1(e,c,i);return}function q1(e,o,i){return ph(e,new URL(o||".",el),i)}function F1(e,o,i,c){let p=rl(e,o,i,c,!1);return yn(p)&&Eo(p)?p:void 0}function y0(e){return e.href.split("#")[0]}function j1(e,o){return me(e,o)?e[o]:void 0}function U1(e,o,i){return tl(e,o,i)}function B1(e,o,i){let c=y0(i);if(P(c,y0(o)))return;if(!me(e,c))return;let p=e[c],g=yn(p)&&Eo(p)?new URL(p.$id,c):new URL(c);return P(i.hash,"")?p:tl(p,g,i)}function G1(e,o,i,c,p){if(!c.$ref.startsWith("#"))return;if(me(e,"$schema"))return;let g=q1(o,i,p);if(Bt(g)||P(g,i))return;return{target:p,base:g,root:o}}function K1(e,o,i){let c=e[o];if(!yn(c))return;return{target:i,base:o,root:c}}function H1(e,o,i,c,p){let g=p?K1(e.context,c,i):void 0;if(!Bt(g))return g;return G1(e.root,e.lexicalSchema,e.referenceBase,o,i)}function W1(e,o,i,c,p,g){if(Eo(p))return;let y=F1(e,o,i,c);if(!y||g.includes(y))return;return{target:p,resource:y}}function rl(e,o,i,c,p=!0){let g=new URL(i||".",el),y=p&&Eo(o)?new URL(o.$id,g):g,b=new URL(c,y.href);return j1(e,c)??U1(o,y,b)??B1(e,y,b)}function z1(e,o,i,c,p,g){let y=new URL(i||".",el),b=p.$dynamicRef.startsWith("#")?c:o,E=rl(e,b,i,p.$dynamicRef,!1);if(Bt(E)){let R=new URL(p.$dynamicRef,y).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let A=decodeURIComponent(R.slice(1));return g.find((L)=>P(L.$dynamicAnchor,A))??x0(o,A)}return}if(!yn(E)||!js(E))return E;if(new URL(p.$dynamicRef,y).hash.startsWith("#/"))return E;return g.find((R)=>P(R.$dynamicAnchor,E.$dynamicAnchor))??E}function V1(e,o){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,c=o.$ref.startsWith("#")?e.lexicalSchema:i,p=rl(e.context,c,e.referenceBase,o.$ref,!1);if(!p||!yn(p))return{schema:p};let g=new URL(o.$ref,e.referenceBase).href.split("#")[0],y=!P(g,e.resourceBase),b=H1(e,o,p,g,y),E=y?W1(e.context,e.root,e.referenceBase,g,p,e.ids):void 0;return{schema:p,retrievedResource:b,resolvedResource:E}}function J1(e,o){let i=Rc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return rl(e.context,i,e.lexicalBase,o.$recursiveRef,!1)}function Q1(e,o){return z1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var _r=function(e,o,i,c){if(i==="a"&&!c)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!c:!o.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:o.get(e)},Sr,ol,R0,hh,nl,b0,E0,S0,w0,dh,fh,gh,yh,T0,k0;class Oi{constructor(e,o){Sr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return _r(this,Sr,"m",hh).call(this,this.ids)}Push(e){if(!yn(e))return;if(Eo(e))_r(this,Sr,"m",gh).call(this,e);if(cc(e))this.anchors.push(e);if(Rc(e))this.recursiveAnchors.push(e);if(js(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!yn(e))return;if(Eo(e))_r(this,Sr,"m",yh).call(this,e);if(cc(e))this.anchors.pop();if(Rc(e))this.recursiveAnchors.pop();if(js(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();_r(this,Sr,"m",k0).call(this,e)}Ref(e){let o=V1(_r(this,Sr,"m",ol).call(this),e);return _r(this,Sr,"m",R0).call(this,o),o.schema}RecursiveRef(e){let o=J1(_r(this,Sr,"m",ol).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=Q1(_r(this,Sr,"m",ol).call(this),e);if(o)this.pendingResource=!0;return o}}Sr=new WeakSet,ol=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:_r(this,Sr,"m",E0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:_r(this,Sr,"m",b0).call(this),resourceBase:_r(this,Sr,"m",nl).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},R0=function(o){if(!Bt(o.schema))this.pendingResource=!0;if(!Bt(o.resolvedResource))_r(this,Sr,"m",T0).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!Bt(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},hh=function(o){let i=this.retrievedFrames[this.retrievedFrames.length-1],c=i?new URL(i.base):new URL(el);return(i?o.slice(i.idDepth):o).reduce((g,y)=>new URL(y.$id,g),c).href},nl=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return _r(this,Sr,"m",hh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((i,c)=>new URL(c.$id,i),new URL(o.base)).href},b0=function(){if(this.retrievedFrames.length>0)return _r(this,Sr,"m",nl).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return _r(this,Sr,"m",nl).call(this)},E0=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(o)return this.ids.length>o.idDepth?this.ids[this.ids.length-1]:o.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},S0=function(o){o.forEach((i)=>_r(this,Sr,"m",dh).call(this,i,!1))},w0=function(o){o.forEach((i)=>_r(this,Sr,"m",fh).call(this,i,!1))},dh=function e(o,i=!0){if(Fs(o))return;if(Ge(o))return _r(this,Sr,"m",S0).call(this,o);if(!yn(o))return;let c=o;if(!i&&Eo(c))return;if(!i&&js(c))this.dynamicAnchors.push(c);for(let p of Se(c))_r(this,Sr,"m",e).call(this,c[p],!1)},fh=function e(o,i=!0){if(Fs(o))return;if(Ge(o))return _r(this,Sr,"m",w0).call(this,o);if(!yn(o))return;let c=o;if(!i&&Eo(c))return;if(!i&&js(c))this.dynamicAnchors.pop();for(let p of Se(c))_r(this,Sr,"m",e).call(this,c[p],!1)},gh=function(o){this.ids.push(o);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(o);_r(this,Sr,"m",dh).call(this,o,!0)},yh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&P(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();_r(this,Sr,"m",fh).call(this,o,!0)},T0=function(o,i){_r(this,Sr,"m",gh).call(this,i),this.resolvedResources.set(o,i)},k0=function(o){if(!this.resolvedResources.has(o))return;let i=this.resolvedResources.get(o);_r(this,Sr,"m",yh).call(this,i),this.resolvedResources.delete(o)};function X1(e){let o=e.Functions().join(`;
|
|
31
|
-
`),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${i.join("; ")} }`}function Y1(e,o){return zy("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Ln,H,tu,Zi,e.External().variables)}function Z1(e){let o=new Oi(e.Context(),e.Schema()),i=new Ln;return(c)=>At(o,i,e.Schema(),c)}function ej(e,o){return Wy()?Y1(e,o):Z1(e)}class A0{constructor(e,o,i){this.isAccelerated=e,this.code=o,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class C0{constructor(e,o,i,c,p,g){this.context=e,this.schema=o,this.external=i,this.functions=c,this.entry=p,this.useUnevaluated=g}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=X1(this),o=ej(this,e);return new A0(Wy(),e,o)}}function sl(...e){let[o,i]=Tn(e,{2:(E,S)=>[E,S],1:(E)=>[{},E]});$R(),h0();let c=new Oi(o,i),p=new Of(PR(o,i)),g=Hs(c,p,i,"value"),y=g0(),b=vR();return new C0(o,i,b,y,g,p.UseUnevaluated())}function il(...e){let[o,i,c]=Tn(e,{3:(w,R,A)=>[w,R,A],2:(w,R)=>[{},w,R]}),p=new Oi(o,i),g=new qn,y=mr(p,g,"#","",i,c),b=g.GetErrors(),E=rx(),S=b.map((w)=>({...w,message:E(w)}));return[y,S]}function Ih(...e){let[o,i,c]=Tn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),p=new Oi(o,i),g=new Ln;return At(p,g,i,c)}function Xt(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Ih(o,i,c)}function $s(...e){let[o,i,c]=Tn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),[p,g]=il(o,i,c);return g}class ha extends Error{constructor(e,o,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:o},writable:!1,configurable:!1,enumerable:!1})}}function P0(e,o,i){if(!Ge(i))return i;return i.map((c)=>xn(e,o.items,c))}function $0(e,o,i){return xn({...e,...o.$defs},cn(o.$ref),i)}function nj(e,o){let i=me(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},c=Ao(e,o),p=kn(c);return Qe(p)?gp(p,i):p}function v0(e,o,i){let c=nj(e,o);return xn(e,c,i)}function al(e){return me(e,"additionalProperties")?e.additionalProperties:void 0}function M0(e,o,i){if(!ut(i)||Ge(i))return i;let c=al(o);for(let p of Se(i)){if(me(o.properties,p)){i[p]=xn(e,o.properties[p],i[p]);continue}if(ln(c)&&P(c,!0)||Pr(c)&&Xt(e,c,i[p])){i[p]=xn(e,c,i[p]);continue}delete i[p]}return i}function O0(e,o,i){if(!ut(i))return i;let c=al(o),[p,g]=[new RegExp(gn(o)),fr(o)];for(let y of Se(i)){if(p.test(y)){i[y]=xn(e,g,i[y]);continue}if(ln(c)&&P(c,!0)||Pr(c)&&Xt(e,c,i[y])){i[y]=xn(e,c,i[y]);continue}delete i[y]}return i}function _0(e,o,i){return me(e,o.$ref)?xn(e,e[o.$ref],i):i}function L0(e,o,i){if(!Ge(i))return i;let c=Math.min(i.length,o.items.length);for(let p=0;p<c;p++)i[p]=xn(e,o.items[p],i[p]);return Hi(i.length,c)?i.slice(0,c):i}function Vr(e){return ka(e)}function N0(e,o,i){for(let c of o.anyOf){let p=xn(e,c,Vr(i));if(Xt(e,c,p))return p}return i}function xn(e,o,i){return wt(o)?P0(e,o,i):Qt(o)?$0(e,o,i):ze(o)?v0(e,o,i):Qe(o)?M0(e,o,i):Gt(o)?O0(e,o,i):jt(o)?_0(e,o,i):mt(o)?L0(e,o,i):xe(o)?N0(e,o,i):i}function oj(e,o){for(let i of Se(e)){if(me(o,i))continue;o[i]=e[i]}return o}function sj(e){let o={};for(let i of Se(e))o[i]=Lc(e[i]);return o}function ij(e){return bh(mR(e))}function bh(e){return e.map((o)=>Lc(o))}function Lc(e){let o=wt(e)?B(Lc(e.items),Aa(e)):ze(e)?$n(bh(e.allOf)):xe(e)?m(ij(e.anyOf)):Qe(e)?l(sj(e.properties)):Gt(e)?Ts(ii(e),Lc(fr(e))):mt(e)?Ur(bh(e.items)):e;return oj(e,o)}function ru(e){return Lc(e)}function _o(...e){let[o,i,c]=Tn(e,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]}),p=Yo().unionPrioritySort?ru(i):i;return xn(o,p,c)}function fo(e){return ut(e)&&me(e,"value")}function We(e){return{value:e}}function wr(){return}function aj(e){return Ge(e)?We(e):We([e])}function uj(e){return P(e,!0)?We(BigInt(1)):We(BigInt(0))}var cj=/^-?(0|[1-9]\d*)n$/,mj=/^-?(0|[1-9]\d*)\.\d+$/,pj=/^-?(0|[1-9]\d*)$/;function lj(e){return cj.test(e)}function dj(e){return mj.test(e)}function fj(e){return pj.test(e)}function hj(e){let o=e.toLowerCase();return lj(e)?We(BigInt(e.slice(0,e.length-1))):dj(e)?We(BigInt(e.split(".")[0])):fj(e)?We(BigInt(e)):P(o,"false")?We(BigInt(0)):P(o,"true")?We(BigInt(1)):wr()}function ul(e){return Nr(e)?We(e):ln(e)?uj(e):_t(e)?We(BigInt(Math.trunc(e))):ho(e)?We(BigInt(0)):yt(e)?hj(e):Bt(e)?We(BigInt(0)):wr()}function gj(e){return P(e,BigInt(0))?We(!1):P(e,BigInt(1))?We(!0):wr()}function yj(e){return P(e,0)?We(!1):P(e,1)?We(!0):wr()}function xj(e){return P(e.toLowerCase(),"false")?We(!1):P(e.toLowerCase(),"true")?We(!0):P(e,"0")?We(!1):P(e,"1")?We(!0):wr()}function D0(e){return Nr(e)?gj(e):ln(e)?We(e):_t(e)?yj(e):ho(e)?We(!1):yt(e)?xj(e):Bt(e)?We(!1):wr()}function Ij(e){return P(e,BigInt(0))?We(null):wr()}function bj(e){return P(e,!1)?We(null):wr()}function Ej(e){return P(e,0)?We(null):wr()}function Sj(e){let o=e.toLowerCase();return P(o,"undefined")||P(o,"null")||P(e,"")||P(e,"0")?We(null):wr()}function wj(e){return Nr(e)?Ij(e):ln(e)?bj(e):_t(e)?Ej(e):ho(e)?We(null):yt(e)?Sj(e):Bt(e)?We(null):wr()}var q0=BigInt(Number.MAX_SAFE_INTEGER),F0=BigInt(Number.MIN_SAFE_INTEGER);function Tj(e){return e<=q0&&e>=F0?We(Number(e)):wr()}function Rj(e){return We(e?1:0)}function kj(e){let o=+e;if(_t(o))return We(o);let i=e.toLowerCase();if(P(i,"false"))return We(0);if(P(i,"true"))return We(1);let c=ul(e);if(fo(c))return c.value<=q0&&c.value>=F0?We(Number(c.value)):wr();return wr()}function Eh(e){return Nr(e)?Tj(e):ln(e)?Rj(e):_t(e)?We(e):ho(e)?We(0):yt(e)?kj(e):Bt(e)?We(0):wr()}function j0(e){return Nr(e)?We(e.toString()):ln(e)?We(e.toString()):_t(e)?We(e.toString()):ho(e)?We("null"):yt(e)?We(e):Bt(e)?We(""):wr()}function Aj(e){return P(e,BigInt(0))?We(void 0):wr()}function Cj(e){return P(e,!1)?We(void 0):wr()}function Pj(e){return P(e,0)?We(void 0):wr()}function $j(e){let o=e.toLowerCase();return P(o,"undefined")||P(o,"null")||P(e,"")||P(e,"0")?We(void 0):wr()}function U0(e){return Nr(e)?Aj(e):ln(e)?Cj(e):_t(e)?Pj(e):ho(e)?We(void 0):yt(e)?$j(e):Bt(e)?We(e):wr()}function B0(e,o,i){return aj(i).value.map((p)=>Yr(e,o.items,p))}function G0(e,o,i){let c=ul(i);return fo(c)?c.value:i}function K0(e,o,i){let c=D0(i);return fo(c)?c.value:i}function H0(e,o,i){return Yr({...e,...o.$defs},cn(o.$ref),i)}function W0(e,o,i){return Yr(e,kn(o),i)}function z0(e,o,i){let c=Eh(i);return fo(c)?Math.trunc(c.value):i}function V0(e,o,i){let c=Ao(e,o),p=kn(c);return Yr(e,p,i)}function vj(e,o,i){let c=ul(i);return fo(c)&&P(o.const,c.value)?c.value:i}function Mj(e,o,i){let c=D0(i);return fo(c)&&P(o.const,c.value)?c.value:i}function Oj(e,o,i){let c=Eh(i);return fo(c)&&P(o.const,c.value)?c.value:i}function _j(e,o,i){let c=j0(i);return fo(c)&&P(o.const,c.value)?c.value:i}function J0(e,o,i){if(P(o.const,i))return i;return lx(o)?vj(e,o,i):dx(o)?Mj(e,o,i):bm(o)?Oj(e,o,i):Em(o)?_j(e,o,i):jr()}function Q0(e,o,i){let c=wj(i);return fo(c)?c.value:i}function X0(e,o,i){let c=Eh(i);return fo(c)?c.value:i}function cl(e,o,i,c){let p=Se(c);for(let[g,y]of o)for(let b of p)if(!g.test(b))c[b]=Yr(e,i,c[b]);return c}function Nc(e,o,i){return mn(e)&&Bt(i[o])}function Lj(e,o,i){let c=ld(o.properties),p=Se(i);for(let[g,y]of c)for(let b of p){if(!g.test(b)||Nc(y,b,i))continue;i[b]=Yr(e,y,i[b])}return me(o,"additionalProperties")&&ut(o.additionalProperties)?cl(e,c,o.additionalProperties,i):i}function Y0(e,o,i){return Xo(i)?Lj(e,o,i):i}function Nj(e,o,i){let c=ld(o.patternProperties),p=Se(i);for(let[g,y]of c)for(let b of p)if(g.test(b))i[b]=Yr(e,y,i[b]);return me(o,"additionalProperties")&&ut(o.additionalProperties)?cl(e,c,o.additionalProperties,i):i}function Z0(e,o,i){return Xo(i)?Nj(e,o,i):i}function eC(e,o,i){return me(e,o.$ref)?Yr(e,e[o.$ref],i):i}function tC(e,o,i){let c=j0(i);return fo(c)?c.value:i}function rC(e,o,i){return Yr(e,kn(o),i)}function nC(e,o,i){if(!Ge(i))return i;for(let c=0;c<Math.min(o.items.length,i.length);c++)i[c]=Yr(e,o.items[c],i[c]);return i}function oC(e,o,i){let c=U0(i);return fo(c)?c.value:i}function sC(e,o,i){if(o.anyOf.some((y)=>Xt(e,y,i)))return i;let g=o.anyOf.map((y)=>Yr(e,y,Vr(i))).find((y)=>Xt(e,o,y));return Bt(g)?i:g}function iC(e,o,i){let c=U0(i);return fo(c)?void 0:i}function Yr(e,o,i){return wt(o)?B0(e,o,i):mo(o)?G0(e,o,i):Wn(o)?K0(e,o,i):Qt(o)?H0(e,o,i):sn(o)?W0(e,o,i):hn(o)?z0(e,o,i):ze(o)?V0(e,o,i):xt(o)?J0(e,o,i):Ss(o)?Q0(e,o,i):kr(o)?X0(e,o,i):Qe(o)?Y0(e,o,i):Gt(o)?Z0(e,o,i):jt(o)?eC(e,o,i):an(o)?tC(e,o,i):ur(o)?rC(e,o,i):mt(o)?nC(e,o,i):rs(o)?oC(e,o,i):xe(o)?sC(e,o,i):po(o)?iC(e,o,i):i}function ms(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Yr(o,i,c)}function aC(e,o,i){if(!Ge(i))return i;for(let c=0;c<i.length;c++)i[c]=In(e,o.items,i[c]);return i}function uC(e,o,i){return In({...e,...o.$defs},cn(o.$ref),i)}function cC(e,o){if(!Bt(o))return o;return fs(e.default)?e.default():Vr(e.default)}function mC(e,o,i){let c=Ao(e,o),p=kn(c);return In(e,p,i)}function pC(e,o,i){if(!ut(i))return i;let c=Se(o.properties);for(let p of c){let g=In(e,o.properties[p],i[p]);if(Bt(g)&&(mn(o.properties[p])||!me(o.properties[p],"default")))continue;i[p]=g}if(!Po(o)||ln(o.additionalProperties))return i;for(let p of Se(i)){if(c.includes(p))continue;i[p]=In(e,o.additionalProperties,i[p])}return i}function lC(e,o,i){if(!ut(i))return i;let[c,p]=[new RegExp(gn(o)),fr(o)];for(let g of Se(i)){if(!(c.test(g)&&bo(p)))continue;i[g]=In(e,p,i[g])}if(!Po(o))return i;for(let g of Se(i)){if(c.test(g))continue;i[g]=In(e,o.additionalProperties,i[g])}return i}function dC(e,o,i){return me(e,o.$ref)?In(e,e[o.$ref],i):i}function fC(e,o,i){if(!Ge(i))return i;let[c,p]=[o.items,Math.max(o.items.length,i.length)];for(let g=0;g<p;g++)if(g<c.length)i[g]=In(e,c[g],i[g]);return i}function hC(e,o,i){for(let c of o.anyOf){let p=In(e,c,Vr(i));if(Xt(e,c,p))return p}return i}function In(e,o,i){let c=bo(o)?cC(o,i):i;return wt(o)?aC(e,o,c):Qt(o)?uC(e,o,c):ze(o)?mC(e,o,c):Qe(o)?pC(e,o,c):Gt(o)?lC(e,o,c):jt(o)?dC(e,o,c):mt(o)?fC(e,o,c):xe(o)?hC(e,o,c):c}function Ws(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return In(o,i,c)}function nu(e){return(...o)=>{let[i,c,p]=Tn(o,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]});return e.reduce((g,y)=>y(i,c,g),p)}}function Dj(e,o,i){return o["~codec"].decode(i)}function qj(e,o,i){return o["~codec"].encode(i)}function Tr(e,o,i,c){if(!Hn(i))return c;return P(e,"Decode")?Dj(o,i,c):qj(o,i,c)}function Fj(e,o,i,c){if(!Ge(c))return c;for(let p=0;p<c.length;p++)c[p]=Cr(e,o,i.items,c[p]);return Tr(e,o,i,c)}function jj(e,o,i,c){let p=Tr(e,o,i,c);if(!Ge(p))return p;for(let g=0;g<p.length;g++)p[g]=Cr(e,o,i.items,p[g]);return p}function gC(e,o,i,c){return P(e,"Decode")?Fj(e,o,i,c):jj(e,o,i,c)}function yC(e,o,i,c){return c=Cr(e,{...o,...i.$defs},cn(i.$ref),c),Tr(e,o,i,c)}function xC(e){return e.reduce((o,i)=>({...o,...i}),{})}function IC(e,o){for(let i of o)if(!Ra(e,i))return i;return e}function Uj(e,o,i,c){if(P(i.allOf.length,0))return Tr(e,o,i,c);let p=i.allOf.map((b)=>Cr(e,o,b,_o(b,Vr(c)))),y=p.every((b)=>ut(b))?xC(p):IC(c,p);return Tr(e,o,i,y)}function Bj(e,o,i,c){if(P(i.allOf.length,0))return Tr(e,o,i,c);let p=Tr(e,o,i,c),g=i.allOf.map((b)=>Cr(e,o,b,_o(b,Vr(p))));if(g.every((b)=>ut(b)))return xC(g);return IC(p,g)}function bC(e,o,i,c){return P(e,"Decode")?Uj(e,o,i,c):Bj(e,o,i,c)}function Gj(e,o,i,c){if(!Xo(c))return c;for(let p of Se(i.properties)){if(!me(c,p)||Nc(i.properties[p],p,c))continue;c[p]=Cr(e,o,i.properties[p],c[p])}return Tr(e,o,i,c)}function Kj(e,o,i,c){let p=Tr(e,o,i,c);if(!Xo(p))return p;for(let g of Se(i.properties)){if(!me(p,g)||Nc(i.properties[g],g,p))continue;p[g]=Cr(e,o,i.properties[g],p[g])}return p}function EC(e,o,i,c){return P(e,"Decode")?Gj(e,o,i,c):Kj(e,o,i,c)}function Hj(e,o,i,c){if(!Xo(c))return c;let p=new RegExp(gn(i));for(let g of Se(c)){if(!p.test(g))continue;c[g]=Cr(e,o,fr(i),c[g])}return Tr(e,o,i,c)}function Wj(e,o,i,c){let p=Tr(e,o,i,c);if(!Xo(p))return p;let g=new RegExp(gn(i));for(let y of Se(p)){if(!g.test(y))continue;p[y]=Cr(e,o,fr(i),p[y])}return p}function SC(e,o,i,c){return P(e,"Decode")?Hj(e,o,i,c):Wj(e,o,i,c)}function wC(e,o,i,c){return me(o,i.$ref)?Cr(e,o,o[i.$ref],c):c}function TC(e,o,i,c){return P(e,"Decode")?Tr(e,o,i,wC(e,o,i,c)):wC(e,o,i,Tr(e,o,i,c))}function zj(e,o,i,c){if(!Ge(c))return c;for(let p=0;p<Math.min(i.items.length,c.length);p++)c[p]=Cr(e,o,i.items[p],c[p]);return Tr(e,o,i,c)}function Vj(e,o,i,c){let p=Tr(e,o,i,c);if(!Ge(p))return c;for(let g=0;g<Math.min(i.items.length,p.length);g++)p[g]=Cr(e,o,i.items[g],p[g]);return p}function RC(e,o,i,c){return P(e,"Decode")?zj(e,o,i,c):Vj(e,o,i,c)}function Jj(e,o,i,c){for(let p of i.anyOf){if(!Xt(o,p,c))continue;let g=Cr(e,o,p,c);return Tr(e,o,i,g)}return c}function Qj(e,o,i,c){let p=Tr(e,o,i,c);for(let g of i.anyOf){let y=Cr(e,o,g,Vr(p));if(!Xt(o,g,y))continue;return y}return p}function kC(e,o,i,c){return P(e,"Decode")?Jj(e,o,i,c):Qj(e,o,i,c)}function Cr(e,o,i,c){return wt(i)?gC(e,o,i,c):Qt(i)?yC(e,o,i,c):ze(i)?bC(e,o,i,c):Qe(i)?EC(e,o,i,c):Gt(i)?SC(e,o,i,c):jt(i)?TC(e,o,i,c):mt(i)?RC(e,o,i,c):xe(i)?kC(e,o,i,c):Tr(e,o,i,c)}class AC extends ha{constructor(e,o){super("Decode",e,o)}}function Xj(e,o,i){if(!Xt(e,o,i))throw new AC(i,$s(e,o,i));return i}function Yj(e,o,i){let c=Yo().unionPrioritySort?ru(o):o;return Cr("Decode",e,c,i)}var Zj=nu([(e,o,i)=>Vr(i),(e,o,i)=>Ws(e,o,i),(e,o,i)=>ms(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>Xj(e,o,i),(e,o,i)=>Yj(e,o,i)]);function Sh(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Zj(o,i,c)}class CC extends ha{constructor(e,o){super("Encode",e,o)}}function eU(e,o,i){if(!Xt(e,o,i))throw new CC(i,$s(e,o,i));return i}function tU(e,o,i){let c=Yo().unionPrioritySort?ru(o):o;return Cr("Encode",e,c,i)}var rU=nu([(e,o,i)=>Vr(i),(e,o,i)=>tU(e,o,i),(e,o,i)=>Ws(e,o,i),(e,o,i)=>ms(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>eU(e,o,i)]);function wh(...e){let[o,i,c]=Tn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return rU(o,i,c)}function nU(e,o){return Hn(o)||Li(e,o.items)}function oU(e,o){return Hn(o)||PC({...e,...o.$defs},cn(o.$ref))}function sU(e,o){return Hn(o)||o.allOf.some((i)=>Li(e,i))}function iU(e,o){return Hn(o)||Se(o.properties).some((i)=>Li(e,o.properties[i]))}function aU(e,o){return Hn(o)||Li(e,fr(o))}function PC(e,o){if(Th.has(o.$ref))return!1;return Th.add(o.$ref),Hn(o)||me(e,o.$ref)&&Li(e,e[o.$ref])}function uU(e,o){return Hn(o)||o.items.some((i)=>Li(e,i))}function cU(e,o){return Hn(o)||o.anyOf.some((i)=>Li(e,i))}function Li(e,o){return wt(o)?nU(e,o):Qt(o)?oU(e,o):ze(o)?sU(e,o):Qe(o)?iU(e,o):Gt(o)?aU(e,o):jt(o)?PC(e,o):mt(o)?uU(e,o):xe(o)?cU(e,o):Hn(o)}var Th=new Set;function Rh(...e){let[o,i]=Tn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return Th.clear(),Li(o,i)}class ps extends Error{constructor(e,o){super(o);this.type=e}}function $C(e,o){return fs(o.default)?o.default(o):ut(o.default)?Vr(o.default):o.default}function vC(e,o){if(Ii(o)&&!bo(o))throw new ps(o,"Arrays with uniqueItems constraints must specify a default annotation");let i=di(o)?o.minItems:0;return Array.from({length:i},()=>en(e,o.items))}function MC(e,o){return ns(o)?BigInt(o.exclusiveMinimum)+BigInt(1):os(o)?BigInt(o.minimum):BigInt(0)}function OC(e,o){return!1}function _C(e,o){let i=en(e,o.instanceType);return class{constructor(){Object.assign(this,i)}}}function LC(e,o){return en({...e,...o.$defs},cn(o.$ref))}function NC(e,o){return en(e,kn(o))}function DC(e,o){let i=en(e,o.returnType);return()=>i}function qC(e,o){return ns(o)&&_t(o.exclusiveMinimum)?o.exclusiveMinimum+1:os(o)?o.minimum:0}function FC(e,o){let i=Ao(e,o),c=kn(i);return en(e,c)}function jC(e,o){return o.const}function UC(e,o){throw new ps(o,"Cannot create TNever types")}function BC(e,o){return null}function GC(e,o){return ns(o)&&_t(o.exclusiveMinimum)?o.exclusiveMinimum+1:os(o)?o.minimum:0}function KC(e,o){return(Bt(o.required)?[]:o.required).reduce((c,p)=>({...c,[p]:en(e,o.properties[p])}),{})}function HC(e,o){if(da(o)&&!bo(o))throw new ps(o,"Record with the minProperties constraint must have a default annotation");return{}}function WC(e,o){return me(e,o.$ref)?en(e,e[o.$ref]):(()=>{throw new ps(o,"Unable to deref Ref")})()}function zC(e,o){if((fa(o)||pa(o))&&!bo(o))throw Error("Strings with format or pattern constraints must specify default");let c=la(o)?o.minLength:0;return"".padEnd(c)}function VC(e,o){return Symbol()}function JC(e,o){let i=_u(o.pattern);if(an(i))throw new ps(o,"Unable to create TemplateLiteral due to infinite type expansion");return en(e,i)}function QC(e,o){return Array.from({length:o.minItems},(i,c)=>en(e,o.items[c]))}function XC(e,o){return}function YC(e,o){if(P(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return en(e,o.anyOf[0])}function ZC(e,o){return}function en(e,o){return bo(o)?$C(e,o):wt(o)?vC(e,o):mo(o)?MC(e,o):Wn(o)?OC(e,o):tn(o)?_C(e,o):Qt(o)?LC(e,o):sn(o)?NC(e,o):rn(o)?DC(e,o):hn(o)?qC(e,o):ze(o)?FC(e,o):xt(o)?jC(e,o):co(o)?UC(e,o):Ss(o)?BC(e,o):kr(o)?GC(e,o):Qe(o)?KC(e,o):Gt(o)?HC(e,o):jt(o)?WC(e,o):an(o)?zC(e,o):ws(o)?VC(e,o):ur(o)?JC(e,o):mt(o)?QC(e,o):rs(o)?XC(e,o):xe(o)?YC(e,o):po(o)?ZC(e,o):void 0}function vs(...e){let[o,i]=Tn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return en(o,i)}class ml extends ha{constructor(e,o){super("Parse",e,o)}}function mU(e,o,i){if(!Xt(e,o,i))throw new ml(i,$s(e,o,i));return i}var eP=nu([(e,o,i)=>Vr(i),(e,o,i)=>Ws(e,o,i),(e,o,i)=>ms(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>mU(e,o,i)]);var lU=l({type:s("insert"),path:a(),value:Rr()}),dU=Object({type:s("update"),path:a(),value:Rr()}),fU=l({type:s("delete"),path:a()}),POe=m([lU,dU,fU]);class pl{constructor(e,o){this.hasCodec=Rh(e,o),this.buildResult=sl(e,o),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(Yo().correctiveParse)return eP(this.Context(),this.Type(),e);throw new ml(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return $s(this.Context(),this.Type(),e)}Clean(e){return _o(this.Context(),this.Type(),e)}Convert(e){return ms(this.Context(),this.Type(),e)}Create(){return vs(this.Context(),this.Type())}Default(e){return Ws(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Sh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?wh(this.Context(),this.Type(),e):this.Parse(e)}}function Ah(...e){let[o,i]=Tn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return new pl(o,i)}var rP=new WeakMap,yU=Symbol.for("TypeBox.Kind");function xU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function IU(e,o){switch(o){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function Ch(e){try{return oP(e)}catch{return}}function bU(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isFinite(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isInteger(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function EU(e,o){let i=o.properties,c=new Set(i?Object.keys(i):[]);if(i)for(let[p,g]of Object.entries(i)){if(!(p in e))continue;e[p]=ya(e[p],g)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[p,g]of Object.entries(e)){if(c.has(p))continue;e[p]=ya(g,o.additionalProperties)}}function SU(e,o){if(Array.isArray(o.items)){for(let i=0;i<e.length;i++){let c=o.items[i];if(!c)continue;e[i]=ya(e[i],c)}return}if(o.items&&typeof o.items==="object")for(let i=0;i<e.length;i++)e[i]=ya(e[i],o.items)}function nP(e,o){for(let i of o)if(Ch(i)?.Check(e))return e;for(let i of o){let c=structuredClone(e),p=ya(c,i);if(Ch(i)?.Check(p))return p}return e}function ya(e,o){let i=e;if(Array.isArray(o.allOf))for(let g of o.allOf)i=ya(i,g);if(Array.isArray(o.anyOf))i=nP(i,o.anyOf);if(Array.isArray(o.oneOf))i=nP(i,o.oneOf);let c=xU(o),p=c.length>1&&c.some((g)=>IU(i,g));if(c.length>0&&!p)for(let g of c){let y=bU(i,g);if(y!==i){i=y;break}}if(c.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))EU(i,o);if(c.includes("array")&&Array.isArray(i))SU(i,o);return i}function ll(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let p=0;p<e.length;p++){let g=o.items[p];if(g)ll(e[p],g)}else if(o.items)for(let p of e)ll(p,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let i=e,c=new Set(o.required??[]);for(let[p,g]of Object.entries(o.properties)){if(!(p in i))continue;if(i[p]===null&&!c.has(p)&&typeof g.$ref!=="string"&&Ch(g)?.Check(null)===!1)delete i[p];else ll(i[p],g)}}function oP(e){let o=e,i=rP.get(o);if(i)return i;let c=Ah(e);return rP.set(o,c),c}function wU(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 TU(e,o){let i=e.find((c)=>c.name===o.name);if(!i)throw Error(`Tool "${o.name}" not found`);return ou(i,o)}function ou(e,o){let i=structuredClone(o.arguments);ll(i,e.parameters),ms(e.parameters,i);let c=oP(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(yU)){let y=ya(i,e.parameters);if(y!==i)if(typeof i==="object"&&i!==null&&typeof y==="object"&&y!==null){for(let b of Object.keys(i))delete i[b];Object.assign(i,y)}else return c.Check(y)?y:i}if(c.Check(i))return i;let p=c.Errors(i).map((y)=>` - ${wU(y)}: ${y.message}`).join(`
|
|
32
|
-
`)||"Unknown validation error",g=`Validation failed for tool "${o.name}":
|
|
33
|
-
${p}
|
|
34
|
-
|
|
35
|
-
Received arguments:
|
|
36
|
-
${JSON.stringify(o.arguments,null,2)}`;throw Error(g)}var sP;function Dc(){if(!sP)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return sP}async function iP(e,o,i,c,p,g){let y=cP(o,e),b=[...y],E={...o,messages:[...o.messages,...y]};await c({type:"agent_start"}),await c({type:"turn_start"});for(let S of y)await c({type:"message_start",message:S}),await c({type:"message_end",message:S});return await uP(E,b,i,p,c,g??Dc()),b}async function aP(e,o,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 g=[],y={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await uP(y,g,o,c,i,p??Dc()),g}async function uP(e,o,i,c,p,g){let y=e,b=i,E,S=!1,w=await b.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||w.length>0){let C=[];if(E){let J=await b.prepareNextTurn?.(E);if(J)y=J.context??y,C=J.messages??[],b={...b,model:J.model??b.model,reasoning:J.thinkingLevel===void 0?b.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(w.length===0)w=await b.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let J of cP(y,[...C,...w]))await p({type:"message_start",message:J}),await p({type:"message_end",message:J}),y.messages.push(J),o.push(J);w=[];let L=await b.prepareRequest?.({context:y,model:b.model,thinkingLevel:b.reasoning??"off"},c);if(L)y=L.context??y,b={...b,model:L.model??b.model,reasoning:L.thinkingLevel===void 0?b.reasoning:L.thinkingLevel==="off"?void 0:L.thinkingLevel};let q=await kU(y,b,c,p,g);if(o.push(q),q.stopReason==="error"||q.stopReason==="aborted"){E={message:q,toolResults:[],context:y,newMessages:o},await b.finishTurn?.(E,c),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:o});return}let X=q.content.filter((J)=>J.type==="toolCall"),j=[];if(R=!1,X.length>0){let J=q.stopReason==="length"?await AU(X,p):await CU(y,q,b,c,p);j.push(...J.messages),R=!J.terminate;for(let ee of j)y.messages.push(ee),o.push(ee)}E={message:q,toolResults:j,context:y,newMessages:o};let V=await b.finishTurn?.(E,c);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:o});return}if(S=V?.action==="continue",w=await b.getSteeringMessages?.()||[],R||w.length>0)S=!1}let A=await b.getFollowUpMessages?.()||[];if(A.length>0){S=!1,w=A;continue}if(S){S=!1;continue}break}await p({type:"agent_end",messages:o})}function cP(e,o){let i=-1;for(let w=o.length-1;w>=0;w--)if(o[w].role==="system"){i=w;break}let c=o[i],p=c?o.map((w,R)=>R===i?Ph(c,RU):w):o,g=qo(oe([...e.messages,...p]),(e.tools??[]).map(ot)),y=g.toolsAdded.length===0&&g.toolsRemoved.length===0;if(c){if(y&&!c.toolsAdded?.length&&!c.toolsRemoved?.length)return o;return p.map((w,R)=>R===i?Ph(c,g):w)}if(y)return o;let b=Ph({role:"system",content:"",timestamp:Date.now()},g),E=o.findIndex((w)=>w.role!=="system"),S=E===-1?o.length:E;return[...o.slice(0,S),b,...o.slice(S)]}var RU={toolsAdded:[],toolsRemoved:[]};function Ph(e,{toolsAdded:o,toolsRemoved:i}){let{toolsAdded:c,toolsRemoved:p,...g}=e;return{...g,...o.length>0?{toolsAdded:o}:{},...i.length>0?{toolsRemoved:i}:{}}}async function kU(e,o,i,c,p){let g=e.messages;if(o.transformContext)g=await o.transformContext(g,i);let y=await o.convertToLlm(g),b=ft({messages:y}),E=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,S=await p(o.model,b,{...o,apiKey:E,signal:i}),w=async()=>Object.assign(await S.result(),{thinkingLevel:o.reasoning??"off"}),R=null,A=!1;for await(let L of S)switch(L.type){case"start":R=L.partial,e.messages.push(R),A=!0,await c({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=L.partial,e.messages[e.messages.length-1]=R,await c({type:"message_update",assistantMessageEvent:L,message:{...R}});break;case"done":case"error":{let q=await w();if(A)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!A)await c({type:"message_start",message:{...q}});return await c({type:"message_end",message:q}),q}}let C=await w();if(A)e.messages[e.messages.length-1]=C;else e.messages.push(C),await c({type:"message_start",message:{...C}});return await c({type:"message_end",message:C}),C}async function AU(e,o){let i=[];for(let c of e){await o({type:"tool_execution_start",toolCallId:c.id,toolName:c.name,args:c.arguments});let p={toolCall:c,result:Vs(`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 qc(p,o);let g=$h(p);await vh(g,o),i.push(g)}return{messages:i,terminate:!1}}async function CU(e,o,i,c,p){let g=o.content.filter((b)=>b.type==="toolCall"),y=g.some((b)=>e.tools?.find((E)=>E.name===b.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||y)return PU(e,o,g,i,c,p);return $U(e,o,g,i,c,p)}async function PU(e,o,i,c,p,g){let y=[],b=[];for(let E of i){await g({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await pP(e,o,E,c,p),w;if(S.kind==="immediate")w={toolCall:E,result:S.result,isError:S.isError};else{let A=await dP(S,p,lP(E,g));w=await fP(e,o,S,A,c,p)}await qc(w,g);let R=$h(w);if(await vh(R,g),y.push(w),b.push(R),p?.aborted)break}return{messages:b,terminate:mP(y)}}async function $U(e,o,i,c,p,g){let y=[];for(let S of i){await g({type:"tool_execution_start",toolCallId:S.id,toolName:S.name,args:S.arguments});let w=await pP(e,o,S,c,p);if(w.kind==="immediate"){let R={toolCall:S,result:w.result,isError:w.isError};if(await qc(R,g),y.push(R),p?.aborted)break;continue}if(y.push(async()=>{if(p?.aborted){let C={toolCall:S,result:Vs("Operation aborted"),isError:!0};return await qc(C,g),C}let R=await dP(w,p,lP(S,g)),A=await fP(e,o,w,R,c,p);return await qc(A,g),A}),p?.aborted)break}let b=await Promise.all(y.map((S)=>typeof S==="function"?S():Promise.resolve(S))),E=[];for(let S of b){let w=$h(S);await vh(w,g),E.push(w)}return{messages:E,terminate:mP(b)}}function mP(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function vU(e,o){if(!e.prepareArguments)return o;let i=e.prepareArguments(o.arguments);if(i===o.arguments)return o;return{...o,arguments:i}}async function pP(e,o,i,c,p,g=e.tools??[]){let y=g.find((b)=>b.name===i.name);if(!y)return{kind:"immediate",result:Vs(`Tool ${i.name} not found`),isError:!0};try{let b=vU(y,i),E=ou(y,b);if(c.beforeToolCall){let S=await c.beforeToolCall({assistantMessage:o,toolCall:i,args:E,context:e},p);if(p?.aborted)return{kind:"immediate",result:Vs("Operation aborted"),isError:!0};if(S?.block){let w=Vs(S.reason||"Tool execution was blocked");if(S.terminate===!0)w.terminate=!0;return{kind:"immediate",result:w,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Vs("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:y,args:E}}catch(b){return{kind:"immediate",result:Vs(b instanceof Error?b.message:String(b)),isError:!0}}}function lP(e,o){return(i)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function dP(e,o,i){let c=[],p=!0,g=performance.now(),y=()=>Math.round(performance.now()-g);try{let b=await e.tool.execute(e.toolCall.id,e.args,o,(S)=>{if(!p)return;c.push(Promise.resolve(i(S)))}),E=y();return p=!1,await Promise.all(c),{result:b,isError:b.isError===!0,durationMs:E}}catch(b){let E=y();return p=!1,await Promise.all(c),{result:Vs(b instanceof Error?b.message:String(b)),isError:!0,durationMs:E}}finally{p=!1}}async function fP(e,o,i,c,p,g){let{result:y,isError:b}=c;if(p.afterToolCall)try{let E=await p.afterToolCall({assistantMessage:o,toolCall:i.toolCall,args:i.args,result:y,isError:b,context:e},g);if(E){let S=E.structuredContent??(E.content?void 0:y.structuredContent);if(y={...y,content:E.content??y.content,details:E.details??y.details,usage:E.usage??y.usage,terminate:E.terminate??y.terminate},S===void 0)delete y.structuredContent;else y.structuredContent=S;b=E.isError??b}}catch(E){y=Vs(E instanceof Error?E.message:String(E)),b=!0}return{toolCall:i.toolCall,result:y,isError:b,durationMs:c.durationMs}}function Vs(e){return{content:[{type:"text",text:e}],details:{}}}async function qc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function $h(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs},timestamp:Date.now()}}async function vh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function MU(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var OU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},_U={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 LU(e){let o=e?.tools?.slice()??[],i=e?.messages?.slice()??[],c=Kn(e?.systemPrompt,o.map(ot));if(i[0]?.role!=="system"&&c)i.unshift(c);return{get systemPrompt(){return Ho(i)},model:e?.model??_U,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(p){o=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Mh{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class Oh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let o=e??{};this._state=LU(o.initialState),this.convertToLlm=o.convertToLlm??MU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Dc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new Mh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Mh(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=Xr(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let i=this.normalizePromptInput(e,o);await this.runPromptMessages(i)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(o&&o.length>0)i.push(...o);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(i)=>{await iP(e,this.createContextSnapshot(),this.createLoopConfig(o),(c)=>this.processEvents(c),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await aP(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,i=()=>{},c=new Promise((p)=>{i=p});this.activeRun={promise:c,resolve:i,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(p){await this.handleRunFailure(p,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:OU,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,o)}}function ve(e,...o){return Object.assign(e,{aliases:o})}function xa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function NU(e){let o=[],i="";for(let c of e){if(!/[a-zA-Z0-9]/.test(c)){if(i)o.push(i);i="";continue}if(c>="A"&&c<="Z"&&i&&!/[A-Z]$/.test(i))o.push(i),i="";i+=c}if(i)o.push(i);return o}function hP(e,o){if(e.some((L)=>L.name===o))return o;let i=e.map((L)=>L.name),c=(L)=>i.filter((q)=>xa(q)===L),p=c(xa(o));if(p.length===1&&p[0])return p[0];if(p.length>1)return o;let g=o.split(/[.:/]/).pop()??o,y=g===o?[]:c(xa(g));if(y.length===1&&y[0])return y[0];let b=new Map;for(let L of e)for(let q of L.aliases??[]){let X=xa(q);b.set(X,(b.get(X)??new Set).add(L.name))}let E=(L)=>[...new Set([...c(L),...b.get(L)??[]])],S=E(xa(g));if(S.length===1&&S[0])return S[0];if(S.length>1)return o;let w=NU(g),R=new Set;w.forEach((L,q)=>{R.add(xa(L));let X=w[q+1];if(X)R.add(xa(L+X))});let A=new Set;for(let L of R)for(let q of E(L))A.add(q);let C=[...A];return C.length===1&&C[0]?C[0]:o}function x(e){return e}function Sn(e,o){let i=o.indexOf("/");if(i<=0)return;return e.getModel(o.slice(0,i),o.slice(i+1))}function rt(e){return`${e.provider}/${e.id}`}function DU(e,o,i){let c=async(g,y)=>{try{if(o){let E=g instanceof Request?g:void 0;o({at:Date.now(),method:y?.method??E?.method??"GET",url:typeof g==="string"?g:g instanceof URL?g.toString():g.url,headers:gP(y?.headers??E?.headers),body:qU(y?.body!==void 0?y.body:E?.body??void 0)})}}catch{}let b=await e(g,y);if(i)try{let E=Date.now(),{status:S,statusText:w}=b,R=gP(b.headers);if(!b.body)return i({at:E,status:S,statusText:w,headers:R,body:""}),b;let A="",C=new TextDecoder,L=new TransformStream({transform(j,V){V.enqueue(j),A+=C.decode(j,{stream:!0}),i({at:E,status:S,statusText:w,headers:R,body:A})},flush(){A+=C.decode(),i({at:E,status:S,statusText:w,headers:R,body:A})}}),q=b.body.pipeThrough(L),X=new Response(q,b);try{Object.defineProperty(X,"url",{value:b.url})}catch{}return X}catch{}return b},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(c,{preconnect:p})}function gP(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((c,p)=>{o[p]=c}),o;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")o[c[0]]=c[1];return o}function qU(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 FU(e,o){return hP(e,o)}function jU(e,o,i){let c=Date.now(),p=new WeakSet,g=(E)=>{if(!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;let S=Date.now(),w=Math.max(10,S-c);E.generationMs=w},y=async(E)=>{if(!i||!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;if(g(E),p.has(E))return;p.add(E),Object.assign(E,await i(E))},b=(E)=>{let S=E?.content;if(!Array.isArray(S))return;for(let w of S)if(w&&w.type==="toolCall"&&typeof w.name==="string")w.name=FU(o(),w.name)};return{async*[Symbol.asyncIterator](){for await(let E of e){let{partial:S,message:w}=E;b(S),await y(w),b(w),yield E}},result:async()=>{let E=await e.result();return g(E),await y(E),b(E),E}}}function Fc(e,o){let i=(o??[]).filter((b)=>b.kind==="path").map((b)=>`<file path=${JSON.stringify(b.data)} />`),c=(o??[]).filter((b)=>b.kind==="text").map((b)=>`<file name=${JSON.stringify(b.name)}>
|
|
37
|
-
${b.data}
|
|
38
|
-
</file>`),p=(o??[]).filter((b)=>b.kind==="image").map((b)=>({type:"image",data:b.data,mimeType:b.mimeType})),g=(o??[]).filter((b)=>b.kind==="image"&&b.id).map((b)=>`<image id=${JSON.stringify(b.id)} name=${JSON.stringify(b.name)} />`);return{merged:[...i,...c,...g,...e.trim()?[e]:[]].join(`
|
|
39
|
-
|
|
40
|
-
`),images:p}}function _h(e,o){let{merged:i,images:c}=Fc(e,o);return{role:"user",content:c.length>0?[{type:"text",text:i},...c]:i,timestamp:Date.now()}}function yP(e){let o=new Set;for(let b of e.tools){let E=b.name.toLowerCase();if(o.has(E))throw Error(`Tool names collide ignoring case: ${b.name}`);o.add(E)}let i=new Oh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(b,E,S)=>{let{captureRequest:w,captureResponse:R}=e,A=w||R?{...S,fetch:DU(S?.fetch??globalThis.fetch,w?(L)=>w({...L,model:rt(b)}):void 0,R?(L)=>R({...L,model:rt(b)}):void 0)}:S,C=b.api==="openai-completions"||b.api==="openai-responses"?{...b,compat:{...b.compat,supportsDeveloperRole:!1}}:b;return jU(e.models.streamSimple(C,E,A),()=>i.state.tools,e.hooks.response)},convertToLlm:(b)=>b,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:b,model:E})=>{let S=b.messages.findIndex((C)=>C.role!=="system"),w=b.messages.slice(0,S===-1?b.messages.length:S),R=e.hooks.prepare,A=e.hooks.tools?.()??b.tools;if(A){i.state.tools=A;let C=w[0];if(C?.role==="system")w[0]={...C,toolsAdded:A.map(ot),toolsRemoved:void 0}}return{context:{...b,tools:A,messages:await R(w,A,E)}}}:void 0}),c=new Map,p=new Map,g=new WeakSet,y;return i.subscribe((b)=>{if(b.type==="message_update"&&b.message.role==="assistant"){p.clear(),e.hooks.draft(IP(b.message));return}if(b.type==="tool_execution_update"){let S=c.get(b.toolCallId)??Pe(b.toolName,b.args),w=Array.isArray(b.partialResult?.content)?b.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";p.set(b.toolCallId,{type:"tool_call",id:b.toolCallId,name:S.name,input:S.input,...S.source?{source:S.source}:{},output:w}),e.hooks.draft([...p.values()]);return}if(b.type==="tool_execution_end"){if(p.delete(b.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(b.type!=="message_end")return;if(g.has(b.message)){e.steerConsumed?.(b.message);return}let E=b.message.role==="user"&&y?{type:"user",text:y.text,...y.attachments?.length?{attachments:y.attachments}:{}}:UU(b.message);if(b.message.role==="user")y=void 0;if(E?.type==="assistant"){for(let S of E.parts)if(S.type==="tool_call")c.set(S.id,S)}if(E?.type==="tool_result"){let S=c.get(E.callID);if(S?.source)Object.assign(E,{name:S.name,source:S.source})}if(E)e.hooks.message(E,b.message);if(b.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(b,E)=>{y={text:b,attachments:E};let{merged:S,images:w}=Fc(b,E);return i.prompt(S,w.length>0?w:void 0)},retry:async()=>{let b=i.state.messages;if(b.at(-1)?.role==="assistant")i.state.messages=b.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(b)=>{g.add(b),i.steer(b)},unsteer:(b)=>{let S=i.steeringQueue?.messages;if(!S)return!1;let w=S.indexOf(b);if(w<0){let A=JSON.stringify(b);w=S.findIndex((C)=>JSON.stringify(C)===A)}if(w<0)return!1;let[R]=S.splice(w,1);if(R)g.delete(R);return!0},abort:()=>i.abort()}}function Lh(e){if(e?.role!=="assistant")return{reason:"done"};if(e.stopReason==="aborted")return{reason:"aborted"};if(e.stopReason==="error")return{reason:"error",error:e.errorMessage};return{reason:"done"}}function xP(e){let{name:i,source:c}=Pe(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 IP(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...Pe(o.name,o.arguments)}})}function UU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:IP(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class pt extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function k(e){return e}import{createHash as bP}from"crypto";import{existsSync as BU}from"fs";import{readFile as EP,realpath as dl}from"fs/promises";import{dirname as GU,isAbsolute as SP,relative as wP,resolve as TP,sep as RP}from"path";var kP=[...jg];class fl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class hl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let i=GU(TP(e)),c=TP(i,o??"web.tsx");if(!o&&!BU(c))return;let p=wP(await dl(i),await dl(c));if(SP(p)||p===".."||p.startsWith(`..${RP}`))throw Error("Plugin web entry must stay inside its plugin directory");return c}async build(e,o){let i=this.pending.get(e);if(i)return i;let c=this.compile(e,o);this.pending.set(e,c);try{return await c}finally{this.pending.delete(e)}}async compile(e,o){let i=this.cache.get(e);if(i){let S=!0;for(let[w,R]of i.inputs){let A=await EP(w).catch(()=>{return});if(!A||bP("sha256").update(A).digest("hex")!==R){S=!1;break}}if(S)return i.source;this.cache.delete(e)}let c=await dl(o),p=new Map,g=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:kP,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(S){S.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(w)=>{if(!kP.includes(w.path))throw Error(`Unsupported shared web import: ${w.path}`);return{path:w.path,external:!0}}),S.onLoad({filter:/.*/},async(w)=>{let R=wP(c,await dl(w.path));if(SP(R)||R===".."||R.startsWith(`..${RP}`))throw Error("Plugin web imports must stay inside its plugin directory");let A=await EP(w.path);p.set(w.path,bP("sha256").update(A).digest("hex"));return})}}]}).catch((S)=>{let R=(S instanceof AggregateError?S.errors:[S]).map((A)=>A instanceof Error?A.message:String(A));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:S})});if(!g.success)throw new fl(g.logs.filter((S)=>S.level==="error").map((S)=>({file:S.position?.file??null,line:S.position?.line??null,message:S.message})));let y=g.outputs.find((S)=>S.kind==="entry-point"&&S.path.endsWith(".js")),b=g.outputs.find((S)=>S.path.endsWith(".css"));if(!y||g.outputs.some((S)=>S!==y&&S!==b))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let E=await y.text();return this.cache.set(e,{source:E,css:await b?.text(),inputs:p}),E}}function Ko(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Ms(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function gl(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
|
|
41
|
-
|
|
42
|
-
`)}function su(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function iu(e){return e.role==="assistant"&&e.content.length>0}function ls(e){let o=[],i=new Map,c=0;for(let p of e){let g=p.raw;if(g.role==="assistant"){if(iu(g))c++;for(let y of g.content){if(y.type!=="toolCall")continue;let b={call:y,step:c,message:g};o.push(b),i.set(y.id,b)}}else if(g.role==="toolResult"){let y=i.get(g.toolCallId);if(y)y.result=g}}return o}var yl=new Set(["edit","write"]),AP=new Set(["grep","glob"]);function ao(e,o){let i=Pe(e.name,e.arguments).input?.[o];return typeof i==="string"?i:void 0}function CP(e){return[...new Set(ls(e).flatMap((o)=>yl.has(Pe(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&ao(o.call,"path")?[ao(o.call,"path")]:[]))]}function Nh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function xl(e){let o=[{source:"ASSISTANT_TOOL",text:`${Pe(e.call.name,e.call.arguments).name}(${Ko(Pe(e.call.name,e.call.arguments).input)}) [${Nh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:su(e.result)});return o}function D(e){let o=0,i=0,c=0;for(let p of e){let g=p.codePointAt(0);if(g<=127)o++;else if(g>=19968&&g<=40959||g>=12288&&g<=12351||g>=65280&&g<=65519||g>=131072&&g<=173791)i++;else c++}return Math.max(0,Math.ceil(o/4+i+c/2))}var Dh=8192;function F(e){let o=e,i=0,c="";if(o.role==="system")c=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")c=o.content;else for(let p of o.content)if(p.type==="text")c+=p.text;else i++;else if(o.role==="assistant")for(let p of o.content)if(p.type==="text")c+=p.text;else if(p.type==="thinking")c+=p.thinking;else c+=`${p.name}${Ko(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")c+=p.text;else i++;else c=Ko(e);return D(c)+16+i*Dh}function Ni(e=[]){return e.reduce((o,i)=>o+D(i.name+i.description+Ko(i.parameters))+16,0)}function Fn(e,o){let i=e.replace(/\s+/g," ").trim();if(D(i)<=o)return i;let c=Math.min(i.length,o*4);while(c>0&&D(i.slice(0,c))>o-1)c=Math.floor(c*0.8);return`${i.slice(0,c).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function To(e,o,i=Number.POSITIVE_INFINITY){if(D(e)<=o&&e.length<=i)return e;let c=`
|
|
43
|
-
[... omitted; use history tools for the full text ...]
|
|
44
|
-
`,p=Math.floor((o-D(c))/2);if(p<=0)return"";let g=(y)=>{let b=0,E=Math.max(0,Math.min(e.length,p*4,Math.floor((i-c.length)/2)));while(b<E){let S=Math.ceil((b+E)/2),w=y?e.slice(-S):e.slice(0,S);if(D(w)<=p)b=S;else E=S-1}if(!b)return"";return y?e.slice(-b).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,b).replace(/[\uD800-\uDBFF]$/,"")};return`${g(!1)}${c}${g(!0)}`}function Il(e,o){if(D(e.join(`
|
|
45
|
-
`))<=o)return e;let i=(w)=>`- [... ${w} steps omitted; use history tools for the full text ...]`,c=o-D(i(e.length)),p=[],g=[],y=0,b=0,E=e.length-1;while(b<=E){let w=p.length<=g.length,R=w?e[b]:e[E],A=D(`${R}
|
|
46
|
-
`);if(y+A>c)break;if(y+=A,w)p.push(e[b++]);else g.unshift(e[E--])}let S=E-b+1;return[...p,...S>0?[i(S)]:[],...g]}function Os(e){let o=[],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:[]},o.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=KU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!c.raw)continue;if(!i&&p.type==="user"&&p.notices&&o.length){o.at(-1)?.records.push(c);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);i.records.push(c)}for(let c of o)c.records=qh(c.records);return o}function qh(e){if(e.length<=1)return[...e];let o=[],i=[],c=new Set;for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;let y=g.raw?.role;if(y==="assistant"){let E=g.raw.content?.filter((S)=>S.type==="toolCall")??[];if(E.length>0)for(let S of E)c.add(S.id);if(o.push(g),c.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="toolResult"){let b=g.raw;if(b.toolCallId)c.delete(b.toolCallId);if(o.push(g),c.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="user"){if(o.length===0){o.push(g);continue}let b=e.slice(p+1).some((E)=>E.raw?.role==="assistant");if(c.size>0||b){i.push(g);continue}o.push(g);continue}o.push(g)}if(i.length>0)o.push(...i);return o}function KU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=o.findLast((c)=>c.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&ma(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ma(i)?"interrupted":"failed";default:return"interrupted"}}function Ia(e){for(let o=e.length-1;o>=0;o--){let i=e[o]?.entry;if(i?.type==="compaction")return i.through}return 0}function bl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((i)=>i.entry.seq<=o)}function Fh(e,o){return e.find((i)=>i.start<o&&!bl(i,o)&&i.records.some((c)=>c.entry.seq<=o))}function au(e){let o=Ia(e),c=Os(e).findLast((p)=>p.end!==void 0);if(!c?.end||c.end<=o)return;return c.end}function El(e){let o=Ia(e);return Fh(Os(e),o)?.end}function jc(e,o){let i=Ia(e),c=Os(e).at(-1);if(!c||c.end!==void 0)return;let p=c.records.filter((w)=>w.entry.seq>i),g=[],y=new Set;for(let w of p){let R=w.raw,A=F(w.raw);if(R.role==="assistant"){for(let C of R.content)if(C.type==="toolCall")y.add(C.id)}else if(R.role==="toolResult")y.delete(R.toolCallId);if(iu(R)||!g.length||R.role==="user"&&g.at(-1)?.assistant)g.push({end:w.entry.seq,tokens:A,assistant:iu(R),pending:y.size});else{let C=g.at(-1);C.end=w.entry.seq,C.tokens+=A,C.pending=y.size}}let b=g.findLastIndex((w)=>w.assistant),E=0,S;for(let w=g.length-1;w>=0;w--){let R=g[w];if(w<b&&R.assistant&&R.pending===0&&(E<=o||S===void 0))S=R.end;if(E+=R.tokens,E>o&&S!==void 0)break}if(E<=o)return;return S}var PP=2000;function Di(e,o){let i=D(o);if(i<=PP)return o;let c=new TextEncoder().encode(o).length,p=o.split(`
|
|
47
|
-
`).length,g=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${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(`
|
|
48
|
-
`),y="</user-text-reference>",b=PP-D(`${g}
|
|
49
|
-
|
|
50
|
-
${y}`);if(b<=0)return o;let E=`${g}
|
|
51
|
-
${To(o,b,o.length-g.length-y.length-3)}
|
|
52
|
-
${y}`;return E.length<o.length&&D(E)<i?E:o}function $P(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let p=Di(e.entry.seq,o.content);return p===o.content?o:{...o,content:p}}let i=!1,c=o.content.map((p)=>{if(p.type!=="text")return p;let g=Di(e.entry.seq,p.text);if(g!==p.text)i=!0;return g===p.text?p:{...p,text:g}});return i?{...o,content:c}:o}function jh(e,o=!1){let i=e.records.filter((C)=>C.entry.type==="user"&&!C.entry.notices&&C.raw.role==="user"),c=i.flatMap((C)=>{let L=C.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.`,g=e.status==="open"?"interrupted":e.status,y="";if(i.length){let C=o?To(i.map((L)=>Ms(L.raw)).join(`
|
|
53
|
-
|
|
54
|
-
`),600):i.map((L,q)=>`<user-message sequence="${q+1}">
|
|
55
|
-
${Di(L.entry.seq,Ms(L.raw))}
|
|
56
|
-
</user-message>`).join(`
|
|
57
|
-
|
|
58
|
-
`);y=[`<chunk-input id="${e.id}" status="${g}"${o?' excerpt="true"':""}>`,C,...o?[p]:[],"</chunk-input>"].join(`
|
|
59
|
-
`)}let E=e.records.filter((C)=>C.raw.role==="assistant").at(-1)?.raw,S=E?gl(E):"",w=[];if(g!=="completed"){let C=ls(e.records),L=new Map(C.map((J)=>[J.call,J])),q=C.slice(-3),X=new Set(q.map((J)=>J.message)),j=[],V=[];for(let J of e.records){let ee=J.raw;if(ee.role!=="assistant")continue;let ae=X.has(ee);for(let K of ee.content)if(K.type==="text"&&ee!==E&&K.text.trim())if(ae)V.push(`ASSISTANT: ${Fn(K.text,50)}`);else j.push(`- ASSISTANT: ${Fn(K.text,50)}`);else if(K.type==="toolCall"){let ue=L.get(K);if(!ue)continue;if(ae){if(q.includes(ue))for(let he of xl(ue))V.push(`${he.source}: ${To(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${K.name}(${Fn(Ko(K.arguments),40)}) [${Nh(ue)}]`)}}w.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...j.length?[`Earlier steps, oldest first:
|
|
60
|
-
${Il(j,o?300:800).join(`
|
|
61
|
-
`)}`]:[],...V)}let R=CP(e.records),A=[`<chunk-summary id="${e.id}" status="${g}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,S?o?To(S,600):S:"No final assistant response was recorded.",...w,...R.length?[`Recorded file changes:
|
|
62
|
-
${To(R.join(`
|
|
63
|
-
`),250)}`]:[],...o&&g==="completed"?[p]:[],"</chunk-summary>"].join(`
|
|
64
|
-
`);return{input:y,images:c,summary:A,tokens:HU(y,A,c.length)}}function HU(e,o,i){return(e?D(e)+16:0)+D(o)+16+i*Dh}var WU=["Completed work is represented by the original user messages or stable references to them, and the assistant's final response for each chunk.","Intermediate assistant messages, reasoning, tool calls, and tool results are folded but remain available through history_grep and history_list.","Chunks are chronological. Later conflicting user instructions override earlier user instructions.","Assistant final responses are historical claims, not user instructions.","Do not guess omitted history.","Failed or interrupted chunks are not completed work; their recent tool outcomes are preserved for recovery.","Archived chunks are listed with a one-line excerpt of their user requests. Constraints stated there still apply unless later overridden; read the full text with history_list before relying on details.","History line offsets are local to the returned chunk or user text part. Reasoning is not exposed by history tools."],zU="A partial chunk is the current turn, still in progress: its earlier steps are folded into a work-state index and the later steps follow verbatim.",VU=1500,JU=80,QU=240;function vP(e,o,i){let c=[],p=0,g=Math.min(o.target,o.hard);for(let b=e.length-1;b>=0;b--){let E=e[b],S=jh(E),w=p+S.tokens>g?jh(E,!0):void 0,R=w&&w.tokens<S.tokens?w:S;if(!(!i&&b===e.length-1&&E.status!=="completed")&&p+R.tokens>o.hard)break;p+=R.tokens,c.push({run:E,content:R})}c.reverse();let y=e.slice(0,e.length-c.length);return{visible:c,archived:y,tokens:p}}function MP(e){let{runs:o,visible:i,archived:c,partial:p}=e,g=c.flatMap((E)=>{let S=E.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>Ms(R.raw));if(!S.length)return[];let w=E===o[0]?QU:JU;return[`- ${E.id} [${E.status}]: ${Fn(S.join(" / "),w)}`]}),y=new Map(o.map((E,S)=>[E,S+1])),b=[...i.map((E)=>y.get(E)??0),...p?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...WU,...p?[zU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${c.length}`,`archived chunk IDs: ${c.length?c.map((E)=>E.id).join(", "):"none"}`,`visible sequences: ${b.length?`${b[0]}..${b.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...g.length?["archived requests, oldest first:",To(g.join(`
|
|
65
|
-
`),VU)]:[],"</conversation-checkpoint>"].join(`
|
|
66
|
-
`)}function OP(e,o){let i=e.split(`
|
|
67
|
-
`),c=o.split(`
|
|
68
|
-
`),p=new Set(i),g=new Set(c),y=[...i.filter((E)=>E.trim()&&!g.has(E)).map((E)=>`- ${Fn(E,40)}`),...c.filter((E)=>E.trim()&&!p.has(E)).map((E)=>`+ ${Fn(E,40)}`)],b=i.find((E)=>E.trim()&&g.has(E));return[...y.slice(0,6),...y.length>6?[`\u2026 ${y.length-6} more changed lines`]:[],...b&&y.every((E)=>E.startsWith("+"))?[`@ ${Fn(b,40)}`]:[]]}function Sl(e,o){if(!o)return e;let i=o.endsWith("/")?o:`${o}/`;return e.startsWith(i)?e.slice(i.length):e}function XU(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((i)=>{let c=i&&typeof i==="object"?i.path:void 0;return typeof c==="string"?[c]:[]})}function YU(e,o){let i=ao(e,"path");if(yl.has(e.name)&&i)return`file:${Sl(i,o)}`;let c=ao(e,"command");if(c)return`command:${c}`;return`${e.name}:${Ko(e.arguments)}`}function ZU(e,o){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},c=new Map;for(let g of ls(e)){let y=c.get(g.step)??[];y.push(g),c.set(g.step,y)}let p=new Map;for(let g of e){let y=g.raw;if(!iu(y))continue;let b=++i.steps,E=gl(y);if(E)i.narration.push({step:b,text:Fn(E,60)});for(let{call:S,result:w}of c.get(b)??[]){if(!w)continue;let R=Pe(S.name,S.arguments),A={...S,name:R.name,arguments:R.input},C=YU(A,o),L=su(w);if(w.isError){let ee=ao(A,"command"),ae=ee?`${A.name} \`${Fn(ee,40)}\``:`${A.name} ${C.startsWith("file:")?C.slice(5):Fn(Ko(A.arguments),40)}`,K={step:b,key:C,what:ae,detail:To(L.trim().split(`
|
|
69
|
-
`).slice(0,8).join(`
|
|
70
|
-
`),200)};i.errors.push(K);let ue=p.get(C)??[];ue.push(K),p.set(C,ue);continue}for(let ee of p.get(C)??[])ee.resolved=b;p.delete(C);let q=ao(A,"path");if(yl.has(A.name)&&q){let ee=Sl(q,o),ae=i.files.get(ee)??{count:0,first:b,last:b,diffs:[]};if(ae.count++,ae.last=b,ae.diffs.push({step:b,lines:A.name==="edit"?ao(A,"old_string")!==void 0?OP(ao(A,"old_string")??"",ao(A,"new_string")??""):[]:OP("",ao(A,"content")??"")}),ae.diffs.length>3)ae.diffs.shift();i.files.set(ee,ae);continue}let X=A.name==="read"?[...q?[q]:[],...XU(A)]:[];if(X.length){for(let ee of X){let ae=Sl(ee,o),K=i.reads.get(ae)??[];K.push(b),i.reads.set(ae,K)}continue}if(AP.has(A.name)){let ee=q?` in ${Sl(q,o)}`:"",ae=A.name==="grep"&&ao(A,"glob")?` (${ao(A,"glob")})`:"",K=`${A.name} ${ao(A,"pattern")??""}${ee}${ae}`.replace(/\s+/g," "),ue=i.searches.get(K)??{steps:[],head:""};ue.steps.push(b),ue.head=Fn(L.trim().split(`
|
|
71
|
-
`)[0]??"",25),i.searches.set(K,ue);continue}let j=ao(A,"command");if(j){let ee=L.trim().split(`
|
|
72
|
-
`);i.commands.push({step:b,command:Fn(j,40),exit:"0",lines:ee.length,tail:ee.slice(-3).map((ae)=>Fn(ae,40))});continue}let V=`${A.name} ${Fn(Ko(A.arguments),40)}`,J=i.other.get(V)??[];J.push(b),i.other.set(V,J)}}return i}function _P(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Uc(e,o,i){let c=(S,w)=>w===void 0||!S.length?S:Il(S,w),p=[`<work-state chunk="${o.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${o.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],g=[...e.files];p.push("",`## Modified files (${g.length})`),g.forEach(([S,w],R)=>{if(p.push(`- ${S}: ${w.count} change${w.count>1?"s":""} (step ${w.first}${w.last!==w.first?`-${w.last}`:""})`),R<g.length-i.diffFiles)return;for(let A of w.diffs)p.push(` step ${A.step}:`,...A.lines.map((C)=>` ${C}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((S)=>S.resolved?`- step ${S.step} ${S.what} (resolved at step ${S.resolved})${i.lists===void 0?`: ${S.detail.replace(/\n/g,`
|
|
73
|
-
`)}`:""}`:`- step ${S.step} ${S.what} (UNRESOLVED): ${S.detail.replace(/\n/g,`
|
|
74
|
-
`)}`)),p.push("","## Steps",...c(e.narration.map((S)=>`- ${S.step}. ${S.text}`),i.narration));let y=[...e.reads].map(([S,w])=>`- ${S} @ ${w.join(",")}`);p.push("",`## Files read (${y.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...c(y,i.lists));let b=[...e.searches].map(([S,w])=>`- ${S} \u2192 ${w.head||"(no output)"} (${_P(w.steps)})`);p.push("",`## Searches (${b.length})`,...c(b,i.lists));let E=e.commands.map((S)=>[`- ${S.step}. \`${S.command}\` exit=${S.exit}, ${S.lines} output lines, last ${S.tail.length}:`,...S.tail.map((w)=>` ${w}`)].join(`
|
|
75
|
-
`));if(p.push("",`## Commands (${E.length})`,...c(E,i.lists)),e.other.size){let S=[...e.other].map(([w,R])=>`- ${w} (${_P(R)})`);p.push("",`## Other tool calls (${S.length})`,...c(S,i.lists))}return p.push("</work-state>"),p.join(`
|
|
76
|
-
`)}function wl(e,o,i,c){let p=ZU(e,c),g=Uc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(D(g)<=i)return g;let y={...p,narration:[]};for(let S of[Number.POSITIVE_INFINITY,20,10,5]){let w=D(Uc(y,o,{diffFiles:S}));if(w>i*0.7)continue;return Uc(p,o,{narration:Math.max(500,i-w),diffFiles:S})}let b=Math.max(300,Math.floor(i*0.1)),E=D(Uc(y,o,{diffFiles:0,lists:b}));return Uc(p,o,{narration:Math.max(500,i-E),diffFiles:0,lists:b})}function Tl(e){return{role:"user",content:e,timestamp:0}}function Uh(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function LP(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:Tl(e.input)}function uu(e){let o=[];for(let i of e){let c=o.at(-1),p=i;if(c?.role==="user"&&p.role==="user"){let g=(y)=>typeof y.content==="string"?[{type:"text",text:y.content}]:y.content;o[o.length-1]={...p,content:[...g(c),{type:"text",text:`
|
|
77
|
-
|
|
78
|
-
`},...g(p)]};continue}o.push(i)}return o}function eB(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Re(e,o,i,c={}){let p=Ia(e),g=Os(e),y=g.filter((Ee)=>bl(Ee,p)),b=Fh(g,p),E=[],S=[],w=0;for(let Ee of g){if(bl(Ee,p))continue;let se=[];for(let ce of Ee.records){if(Ee===b&&ce.entry.seq<=p)continue;let Fe=ce.raw.role==="user"?$P(ce):ce.raw;w+=F(Fe),E.push(Fe),se.push(Fe)}if(c.inspect&&se.length)S.push({id:`recent-${Ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Ee.id}`,tokens:se.reduce((ce,Fe)=>ce+F(Fe),0),detail:JSON.stringify(se,eB,2)})}if(!y.length&&!b)return{items:S,messages:uu(E),visible:0,archived:0,open:w,tokens:w,untrimmed:w};let R=vP(y,i,!!b),{visible:A,archived:C}=R,L=R.tokens,q=[],X="",j="";if(b){let Ee=b.records.filter((ce)=>ce.entry.seq<=p),se=Ee.filter((ce)=>ce.entry.type==="user"&&!ce.entry.notices&&ce.raw.role==="user");if(se.length){X=[`<chunk-input id="${b.id}" status="partial">`,...se.map((Fe,It)=>`<user-message sequence="${It+1}">
|
|
79
|
-
${Di(Fe.entry.seq,Ms(Fe.raw))}
|
|
80
|
-
</user-message>`),"</chunk-input>"].join(`
|
|
81
|
-
`);let ce=se.flatMap((Fe)=>{let It=Fe.raw.content;return typeof It==="string"?[]:It.filter((Je)=>Je.type==="image")});q.push(ce.length?{role:"user",content:[{type:"text",text:X},...ce],timestamp:0}:Tl(X))}j=wl(Ee,b,i.index,c.cwd),q.push(Uh(j,o))}let V=e.flatMap((Ee)=>{let se=Ee.raw;if(Ee.entry.seq>p||se?.role!=="toolResult"||se.toolName!=="skill")return[];return[Tl(se.content.filter((ce)=>ce.type==="text").map((ce)=>ce.text).join(`
|
|
82
|
-
`))]}),J="",ee=()=>{J=MP({runs:y,visible:A.map((se)=>se.run),archived:C,partial:!!b,tokens:L,budget:i});let Ee=[Tl(J)];for(let{content:se}of A){if(se.input)Ee.push(LP(se));Ee.push(Uh(se.summary,o))}return[...Ee,...V,...q]},ae=(Ee)=>Ee.reduce((se,ce)=>se+F(ce),0),K=ee(),ue=ae(K)+w,he=ue,{trim:_e}=c;while(_e&&_e.fixed+ue>_e.limit){let Ee=b||A.at(-1)?.run.status==="completed"?A:A.slice(0,-1);if(!Ee.length)break;let se=0,ce=0;for(let Fe of Ee)if(ce++,se+=Fe.content.tokens,se>=_e.fixed+ue-_e.limit)break;C=[...C,...A.slice(0,ce).map((Fe)=>Fe.run)],A=A.slice(ce),L-=se,K=ee(),ue=ae(K)+w}return{items:c.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:F(K[0]),detail:J},...A.map(({run:Ee,content:se})=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"sealed",tokens:(se.input?F(LP(se)):0)+F(Uh(se.summary,o)),detail:[se.input,se.summary].filter(Boolean).join(`
|
|
83
|
-
|
|
84
|
-
`)})),...C.map((Ee)=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...b?[{id:b.id,label:`Chunk ${b.id}`,state:"folded",tokens:ae(q),detail:[X,j].filter(Boolean).join(`
|
|
85
|
-
|
|
86
|
-
`)}]:[],...S]:[],messages:uu([...K,...E]),visible:A.length,archived:C.length,open:w,tokens:ue,untrimmed:he}}function cu(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Bh=0.97,tB=0.97,NP=0.5,rB=0.05,nB=20000,oB=24000;function Bc(e){return{target:nB,hard:oB,index:Math.floor(cu(e)*rB)}}function Gh(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class Gc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,i=()=>{return}){this.records=e;this.fold=o;this.cwd=i}budget(e){return Bc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(cu(e)*Bh/this.ratio)}prepare(e,o,i,c){let p=cu(i),g=Bc(i),y=e.reduce((K,ue)=>K+F(ue),0)+Ni(o),b=this.records().at(-1)?.entry.seq??0,E=()=>c?[...c,...this.records().filter((K)=>K.entry.seq>b)]:this.records(),S=()=>Re(E(),i,g,{cwd:this.cwd(),trim:{fixed:y,limit:Math.floor(p*Bh/this.ratio)}}),w=E().findLast((K)=>K.raw?.role==="assistant"),R=w?E().filter((K)=>K.entry.seq>w.entry.seq&&K.raw):[],A=w?.raw,C=()=>w!==void 0&&(w.entry.seq===this.reshapedAfter||E().some((K)=>K.entry.type==="compaction"&&K.entry.seq>w.entry.seq)),L=this.dueSeal(i);if(L!==void 0)this.fold(L,!1),this.reshapedAfter=w?.entry.seq??-1;let q=S(),X=R.reduce((K,ue)=>K+F(ue.raw),0);if(this.lastEstimate===0&&w&&A&&!C()){let K=A.usage.input+A.usage.cacheRead+A.usage.cacheWrite,ue=y+q.untrimmed-F(A)-X;if(K>0&&ue>0)this.ratio=Math.min(2,Math.max(0.5,K/ue))}let V=((K)=>{let ue=y+K.untrimmed,he=y+K.tokens;return((w&&A&&!C()&&Gh(A)>0?Gh(A)+Math.round(this.ratio*X):void 0)??Math.round(ue*this.ratio))-Math.round((ue-he)*this.ratio)})(q);if(V>p*tB){let K=V-q.open*this.ratio,ue=Math.max(1000,Math.floor((p*NP-K-g.index)/this.ratio)),he=w?.entry.seq??-1,_e=E().findLast((Fe)=>Fe.entry.type==="compaction"&&Fe.entry.partial)?.entry.seq??-1,Ee=Math.max(this.lastFoldSeq,_e),ce=(Ee>0?E().filter((Fe)=>Fe.entry.seq>Ee&&Fe.raw?.role==="assistant").length:999)<=1;if(!ce||this.consecutivePartialFolds<2){let Fe=jc(E(),ue);if(Fe!==void 0)this.fold(Fe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=ce?this.consecutivePartialFolds+1:1,q=S()}}else this.consecutivePartialFolds=0;this.lastEstimate=y+q.tokens;let J=q.messages,ee=y+q.tokens;if(Math.round(ee*this.ratio)>p)J=sB(J,Math.floor((p-y)/this.ratio)),ee=y+J.reduce((K,ue)=>K+F(ue),0);return this.lastEstimate=ee,{messages:uu([...e,...J]),estimate:ee}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(El(o)===void 0){let i=o.findLast((b)=>b.raw?.role==="assistant"),c=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||o.some((b)=>b.entry.type==="compaction"&&b.entry.seq>i.entry.seq)),y=(i?o.filter((b)=>b.entry.seq>i.entry.seq&&b.raw):[]).reduce((b,E)=>b+F(E.raw),0);if(p||!c||Gh(c)+y<Math.floor(cu(e)*Bh))return}return au(o)}recover(e){let o=cu(e),i=Bc(e),c=Re(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((o*NP-(o-c.open*this.ratio)-i.index)/this.ratio),g=jc(this.records(),p);if(g===void 0)return!1;return this.fold(g,!0),this.reshapedAfter=this.records().findLast((y)=>y.raw?.role==="assistant")?.entry.seq??-1,!0}}function sB(e,o){let i=e.reduce((p,g)=>p+F(g),0);if(i<=o)return e;let c=[];for(let p of e){let g=p;if(g.role!=="toolResult"||i<=o){c.push(p);continue}let y=F(p);if(y<=1500){c.push(p);continue}let b=Math.max(500,Math.floor(y/2)),E=g.content.map((R)=>{if(R.type!=="text")return R;return{...R,text:To(R.text,b)}}),S={...g,content:E},w=F(S);i-=y-w,c.push(S)}return c}var iB=2000;function mu(e,o){let i=[];for(let c of o.replace(/\r\n/g,`
|
|
87
|
-
`).split(`
|
|
88
|
-
`))for(let p=0;p<Math.max(c.length,1);){let g=Math.min(c.length,p+iB);if(g<c.length&&/[\uD800-\uDBFF]/.test(c.charAt(g-1)))g--;i.push({source:e,text:c.slice(p,g)}),p=g>p?g:p+1}return i}function pu(e){let o=[],i=ls(e.records),c=new Map(i.map((g)=>[g.call,g])),p=new Set(i.flatMap((g)=>g.result?[g.result]:[]));for(let g of e.records){let y=g.raw;if(y.role==="user")o.push(...mu(g.entry.type==="user"&&g.entry.notices?"NOTICE":"USER",Ms(y)));else if(y.role==="assistant"){for(let b of y.content)if(b.type==="text"&&b.text.trim())o.push(...mu("ASSISTANT",b.text));else if(b.type==="toolCall"){let E=c.get(b);if(E)for(let S of xl(E))o.push(...mu(S.source,S.text))}}else if(y.role==="toolResult"&&!p.has(y))o.push(...mu(y.isError?"TOOL_ERROR":"TOOL_OUTPUT",su(y)))}return o.map((g,y)=>({chunk:e.id,line:y,...g}))}function Kc(e,o){let i=e.find((c)=>c.entry.seq===o);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return mu("USER",Ms(i.raw)).map((c,p)=>({chunk:`seq ${o}`,line:p,...c}))}function Hc(e,o){let i=e.find((c)=>c.entry.seq===o)?.entry;if(i?.type!=="extension"||!i.display)return;return mu("EXTENSION",i.display.text).map((c,p)=>({chunk:`seq ${o}`,line:p,...c}))}function Wc(e,o=""){return e.map((i,c)=>{let p=e[c-1],g=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${o}${g?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
|
|
89
|
-
`)}import{join as vg}from"path";import{existsSync as t$}from"fs";import{realpath as r$}from"fs/promises";import{dirname as n$,isAbsolute as wB,join as o$,relative as TB,resolve as Qh,sep as RB}from"path";import{existsSync as aB,watch as uB}from"fs";import{readdir as cB,stat as mB}from"fs/promises";import{basename as Kh,dirname as pB,join as DP,resolve as lB}from"path";class Hh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,i,c=150){this.host=e;this.slots=o;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,o=[]){let i=[],c=[];for(let b of[...new Set(e)]){let E;try{E=await cB(b)}catch(S){if(S instanceof Error&&"code"in S&&S.code==="ENOENT")continue;throw S}for(let S of E.sort()){let w=DP(b,S),R=(await mB(w)).isDirectory()?DP(w,"index.ts"):w;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{c.push({definition:await this.read(R),path:R})}catch(A){let C=Kh(R)==="index.ts"?Kh(pB(R)):Kh(R,".ts");if(this.slots.has(C))throw Error(`Duplicate plugin: ${C}`);let L={id:C,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${C}; repair the file and reload`)}};i.push({definition:L,path:R}),this.slots.set(C,{definition:L,path:R,enabled:!0,discoveryFailed:!0,error:A instanceof Error?A.message:String(A)})}}}let p=o.filter((b)=>![...c,...i].some((E)=>E.definition.id===b.definition.id)),g=[...p,...c],y=this.order(g.map(({definition:b})=>b));for(let b of y){let E=g.find((w)=>w.definition===b)?.path,S=p.some((w)=>w.definition===b);try{await this.host.install(b,E,S)}catch(w){this.slots.set(b.id,{definition:b,path:E,builtin:S,enabled:!0,error:w instanceof Error?w.message:String(w)})}}if(this.watching())for(let b of[...g,...i]){if(!aB(b.path))continue;let E=uB(b.path,()=>{let S=b.definition.id,w=this.debounceTimers.get(S);if(w)clearTimeout(w);let R=setTimeout(()=>{this.debounceTimers.delete(S),this.host.reload(S).catch((A)=>{let C=this.slots.get(S);if(C)C.error=A instanceof Error?A.message:String(A)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(S,R)});E.on("error",(S)=>{let w=this.slots.get(b.definition.id);if(w)w.error=S.message,this.host.changed()}),this.watchers.push(E)}}order(e,o=!1){let i=new Map;for(let b of e){if(this.validate(b),i.has(b.id)||!o&&this.slots.has(b.id))throw Error(`Duplicate plugin: ${b.id}`);i.set(b.id,b)}let c=[],p=new Set,g=new Set,y=(b)=>{if(g.has(b.id))return;if(p.has(b.id))throw Error(`Plugin dependency cycle: ${b.id}`);p.add(b.id);for(let E of b.deps??[]){let S=i.get(E);if(S)y(S);else if(!this.slots.has(E))throw Error(`Missing plugin dependency: ${E}`)}p.delete(b.id),g.add(b.id),c.push(b)};for(let b of e)y(b);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((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${lB(e)}?v=${++this.revision}`);if(!o.default)throw Error("Plugin module must export a default definition");return this.validate(o.default),o.default}}async function qP(e,o,i=!1){if(!Number.isSafeInteger(o)||o<1||o>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((g,y)=>{p=setTimeout(()=>{c.abort(),y(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as dB}from"async_hooks";import{isDeepStrictEqual as FP}from"util";var ba=new dB;function _s(){let e=ba.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function lu(e){let o=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(o),o}function jP(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let E of["seq","time","session_id","raw"])if(E in o)throw Error(`Entry replacement contains protected field: ${E}`);let i=JSON.parse(JSON.stringify(o,(E,S)=>{if(typeof S==="function"||typeof S==="symbol"||typeof S==="number"&&!Number.isFinite(S))throw Error("Entry replacement must contain JSON values");return S}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let 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 g={...e};for(let E of new Set([...Object.keys(e),...Object.keys(c)])){if(!p.includes(E)&&!FP(g[E],c[E]))throw Error(`Entry replacement changed protected field: ${E}`);if(["seq","time","session_id","raw"].includes(E))throw Error(`Entry replacement contains protected field: ${E}`)}let y=(E)=>E===void 0||typeof E==="string",b=!0;switch(e.type){case"user":b=typeof c.text==="string"&&(c.attachments===void 0||Array.isArray(c.attachments)&&c.attachments.every((E)=>E&&typeof E.name==="string"&&typeof E.mimeType==="string"&&em.includes(E.kind)&&typeof E.data==="string"));break;case"assistant":b=y(c.error)&&Array.isArray(c.parts)&&c.parts.every((E)=>E&&(["text","thinking"].includes(E.type)&&typeof E.text==="string"||E.type==="tool_call"&&typeof E.id==="string"&&typeof E.name==="string"&&("input"in E)));break;case"tool_result":b=typeof c.output==="string"&&(c.images===void 0||Array.isArray(c.images)&&c.images.every((E)=>E&&typeof E.mimeType==="string"&&typeof E.data==="string"));break;case"extension":{let E=c.display;b="payload"in c&&(E===void 0||E!==null&&typeof E==="object"&&("text"in E)&&typeof E.text==="string"&&(!("title"in E)||y(E.title)));break}case"notice_pending":{let S=["text"],w=g.notice,R=c.notice;if(b=!!R&&typeof R==="object"&&!Array.isArray(R),!b)break;let A=R;for(let C of new Set([...Object.keys(w),...Object.keys(A)]))if(S.includes(C)){if(typeof A[C]!=="string")b=!1}else if(!FP(w[C],A[C]))b=!1;break}case"run":b=y(c.error);break;case"compaction":break}if(!b)throw Error("Invalid entry replacement content");return i}function UP(e,o,i,c,p,g){let y=c;for(let b of i.generations)for(let E of b.hooks.get("entry.before_append")??[]){if(b.disabled)break;let S={phase:"before",violated:!1};try{let w=ba.run(S,()=>{let R=lu(y),A=performance.now(),C=E(R,{sessionID:p,seq:g});if(C&&(typeof C==="object"||typeof C==="function")&&"then"in C&&typeof C.then==="function")throw Promise.resolve(C).catch(()=>{}),Error("entry.before_append must be synchronous");let L=C===void 0?void 0:jP(y,C);if(S.violated)throw Error("entry.before_append attempted a database write");if(performance.now()-A>e)throw Error("entry.before_append exceeded budget");return L});if(w&&JSON.stringify(w)!==JSON.stringify(y))y=w;b.beforeFailures=0,b.failures=0}catch(w){b.failures=b.beforeFailures++,o(b,w)}}return y}function fB(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return lu(o);return structuredClone(o)}async function BP(e,o,i,c,p,g,y,b,E="end"){let S=g;for(let w of c){if(w.disabled)continue;let R=w.hooks.get(p)??[];for(let A of R){if(w.disabled)break;let C=w.hookOptions.get(A);if(p==="prompt.fragments"&&(C?.promptPosition??"end")!==E)continue;let L=p==="prompt.fragments"?JSON.stringify([y?.id,S]):void 0,q=L===void 0?void 0:w.promptCache.get(A)?.get(L);try{let X=fB(p,S),j=C?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:y,connection:b}):j,J=await o((ee)=>A(X,{runtime:e.runtime,session:y,connection:b,signal:ee}),V);if(L!==void 0){let ee=J===void 0?S:J;if(!Array.isArray(ee)||ee.some((K)=>typeof K!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(ee))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let ae=w.promptCache.get(A)??new Map;ae.set(L,[...ee]),w.promptCache.set(A,ae)}if(w.failures=0,J!==void 0&&p!=="entry.after_append")S=J}catch(X){if(q)S=structuredClone(q);if(i(w,X),C?.errorMode==="propagate")throw X}}}return S}class zc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,i,c,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,i,c,p)}has(e,o){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((c)=>o===void 0||(i.hookOptions.get(c)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...i)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((i)=>i(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let c of i.historyResolvers){let p=c(e,o);if(p)return p}}}policy(e){return this.generations.findLast((o)=>!o.disabled&&o.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as hB}from"fs";import{dirname as gB,resolve as GP}from"path";var Wh=new WeakMap;function KP(e){return[...e].map((o)=>{let i=Boolean(o.path&&(Boolean(o.definition.webEntry)||hB(GP(gB(GP(o.path)),"web.tsx"))));if(o.current&&!Wh.has(o.current))Wh.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:i,webRevision:o.current?Wh.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((c)=>({kind:"hook",name:c})),...o.current.tools.map((c)=>({kind:"tool",name:c.name})),...o.current.routes.map((c)=>({kind:"route",method:c.method,path:c.path})),...o.current.websockets.map((c)=>({kind:"websocket",path:c.path})),...o.current.commands.map((c)=>({kind:"command",id:c.id})),...o.current.web.map((c)=>({kind:"web",id:c.id})),...[...o.current.policies.keys()].map((c)=>({kind:"policy",id:c})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class zh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,i){this.host=e;this.deadline=o;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,i){let c=this.host.pin(),p=(async()=>{try{let g=[];for(let y of c.generations){if(y.disabled)continue;for(let b of y.hooks.get(e)??[]){let E=y.hookOptions.get(b)?.timeoutMs,S=typeof E==="function"?E({runtime:this.host.runtime,session:o,connection:i}):E;g.push(this.deadline((w)=>b(o,{runtime:this.host.runtime,session:o,connection:i,signal:w}),S,!0).catch((w)=>this.fail(y,w)))}}await Promise.all(g)}finally{await c.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,o,i){let c=i===void 0?void 0:lu(i),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(c)await ba.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",c,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,p),this.pending.add(p);let g=()=>{if(this.pending.delete(p),this.entryQueues.get(o)===p)this.entryQueues.delete(o)};p.then(g,g)}}function HP(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 yB(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 xB(e,o){let i=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!i)throw Error("Completion session not found");let c=o.model??i?.model??e.options.defaultModel;if(typeof c!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=Sn(e.options.models,c);if(!p&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!p){let g=(await e.models()).models.filter((b)=>b.available===!0),y=p?rt(p):c;if(!g.some((b)=>b.id===y)){let b=g[0];if(b)p=Sn(e.options.models,b.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function WP(e,o){yB(o);let i=await xB(e,o),c=o.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(o.signal?.aborted)throw Error("Completion cancelled");let p="",g=!1;try{let y=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],b=e.options.models.streamSimple(i,{messages:y},{maxTokens:c,signal:o.signal});for await(let E of b){if(o.signal?.aborted)throw Error("cancelled");if(E.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${HP(E.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(E.type==="text_delta")p+=E.delta;if(E.type==="done"){if(E.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(E.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${E.reason}\uFF09`);g=!0}}}catch(y){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${HP(y instanceof Error?y.message:String(y))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!g)throw Error("Model completion ended without a stop response; retry");return{text:p,model:rt(i)}}var IB=["active","archived","all"];function zP(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function bB(e){let{projectID:o,children:i,archive:c,since:p}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(c!==void 0&&!IB.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 EB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function VP(e){function o(i,c={}){let{types:p,bodies:g}=c;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let y=zP(c.limit),b=c.after??0;if(!Number.isSafeInteger(b)||b<0)throw Error("sessions after must be a non-negative integer");let E=(e.get(i)?.entries(b)??[]).filter((S)=>p===void 0||p.includes(S.type)).slice(0,y);return structuredClone(g===!1?E.map(EB):E)}return{list(i={}){bB(i);let c=i.limit===void 0?void 0:zP(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((g)=>i.projectID===void 0||g.projectID===i.projectID).filter((g)=>i.since===void 0||g.created>=i.since);return structuredClone(c===void 0?p:p.slice(0,c))},get(i){return structuredClone(e.get(i)?.info())},entries:o}}async function JP(e,o,i,c,p,g){let y={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},b=e.runtime.store.db,E=new Map,S=!1,w=!0,R=()=>{if(!w||y.disposed)throw Error("Plugin registration scope is closed")},A=(j,V)=>{if(R(),!S){E.set(j,V);return}if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)},C={get:(j)=>{R();let V=E.has(j)?E.get(j):b.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");A(j,J)},delete:(j)=>A(j,null)},L=()=>{if(R(),S)throw Error("Register resources during setup only")},q=[...o.migrations??[]].sort((j,V)=>j.version-V.version),X=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||X.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(X.add(j.version),b.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,j.version))continue;b.transaction(()=>{if(j.sql!==void 0)b.run(j.sql);else j.up({...C,db:b});for(let[V,J]of E)if(J===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,J);b.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,j.version)})(),e.runtime.store.invalidateEntryCache(),E.clear()}return await c(async()=>o.setup({runtime:e.runtime,sessions:VP(e.runtime),complete:(j)=>WP(e.runtime,j),kv:C,database:b,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{L(),y.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");y.noticeSources.set(j,{...V})},provide:(j,V)=>{if(L(),j.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(y.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);y.services.set(j.name,V)},on:(j,V,J)=>{if(L(),J?.promptPosition&&j!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let ee=y.hooks.get(j)??[];if(ee.push(V),y.hooks.set(j,ee),J)y.hookOptions.set(V,J)},registerHistoryResolver:(j)=>{L(),y.historyResolvers.push(j)},registerTool:(j,V)=>{if(L(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||SB(e,p,o.id).has(j.name.toLowerCase())||y.tools.some((ee)=>ee.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let J=i?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;y.tools.push({...j,defer:J,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(L(),!(j.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>j.path===V||j.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(j.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(y.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");y.routes.push(j)},registerWebSocket:(j)=>{if(L(),!j.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(y.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");y.websockets.push(j)},registerCommand:(j)=>{L(),y.commands.push(j)},registerWebContribution:(j)=>{L(),y.web.push(j)},registerToolPolicy:(j,V)=>{L(),y.policies.set(j,V)},appendExtension:(j,V)=>{if(_s(),R(),!S)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{L(),y.deactivators.push(j)},onDispose:(j)=>{L(),y.disposers.push(j)}})),b.transaction(()=>{for(let[j,V]of E)if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)})(),E.clear(),S=!0,y}catch(j){throw w=!1,await g(y),j}}function SB(e,o,i){let c=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,g]of o){if(p===i)continue;for(let y of g.current?.tools??[])c.add(y.name.toLowerCase())}return c}class Vh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(i){e.error=i instanceof Error?i.message:String(i)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(i){e.error=i instanceof Error?i.message:String(i)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function QP(e,o,i,c){for(let p of o){let g=p.current;if(!g||g.disabled||g.retired)continue;let y=g.websockets.find((b)=>b.path===c);if(!y)continue;return{connect:(b)=>{let E=!1;g.references++,g.connections.add(b);let S={send:(R)=>{if(E||g.retired||g.disabled)return;b.send(R)},close:(R,A)=>b.close(R,A)},w=async(R)=>{if(E||g.retired||g.disabled){b.close(1012,"Plugin unavailable");return}try{await i(R),g.failures=0}catch(A){if(g.failures++,g.error=A instanceof Error?A.message:String(A),b.close(1011,"Plugin callback failed"),g.failures>=e.failureThreshold){g.disabled=!0;for(let C of g.connections)C.close(1011,"Plugin disabled")}}};return{open:()=>w(()=>y.open?.(S)),message:(R)=>w(()=>y.message(S,R)),close:async()=>{if(E)return;E=!0,g.connections.delete(b);try{await i(()=>y.close?.(S))}catch(R){g.error=R instanceof Error?R.message:String(R)}finally{g.references--,await e.collect(g)}}}}}}return}function Jh(e,o){let i=e.split("/"),c=new URL(o.url).pathname.split("/");if(i.length!==c.length)return;let p={};return i.every((y,b)=>{let E=c[b];if(E===void 0)return!1;if(!y.startsWith(":"))return E===y;try{p[y.slice(1)]=decodeURIComponent(E)}catch{return!1}return E.length>0})?p:void 0}async function XP(e,o,i,c,p){let g=e.pin();try{let y=g.generations.find((b)=>b.definition.id===i)?.commands.find((b)=>b.id===c);if(!y)throw new f("Plugin command is unavailable");return await o(()=>y.execute(p))}finally{await g.release()}}function YP(e,o){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.method===o.method&&Jh(p.path,o)!==void 0))}finally{i.release()}}function ZP(e,o){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.public===!0&&p.method===o.method&&Jh(p.path,o)!==void 0))}finally{i.release()}}async function e$(e,o,i){let c=e.pin(),p=!0;try{for(let g of c.generations)for(let y of g.routes){if(y.method!==i.method)continue;let b=Jh(y.path,i);if(b){let E=await o(()=>y.handler(i,b),y.timeoutMs);if(!E)return;if(E.body&&E.body instanceof ReadableStream){p=!1;let S=!1,w=()=>{if(S)return;S=!0,c.release()},R=E.body.getReader(),A=new ReadableStream({async pull(C){try{let{done:L,value:q}=await R.read();if(L)C.close(),w();else C.enqueue(q)}catch(L){C.error(L),w()}},async cancel(C){try{await R.cancel(C)}finally{w()}}});return new Response(A,{status:E.status,statusText:E.statusText,headers:E.headers})}return E}}return}finally{if(p)await c.release()}}class Xh{runtime;options;slots=new Map;retirement=new Vh(this.deadline.bind(this));observers=new zh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new hl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,o={}){this.runtime=e;this.options=o;if(o.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(o.beforeAppendBudgetMs)||o.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new Hh(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=o.current.services.get(e.name);if(!e.validate(i))throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let i of e)this.directories.add(Qh(i));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await r$(e),i=[...this.directories,o$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((c)=>o$(c.directory,".basalt","plugins"))];for(let c of i){if(!t$(c))continue;let p=TB(await r$(c),o);if(p&&p!==".."&&!p.startsWith(`..${RB}`)&&!wB(p)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),i=await this.checkEntry(o);if(!i.ok)throw new pt(i.errors);let c=await this.catalog.read(o);return await this.installDefinition(c,o,!1),c.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,i)})}async installDefinition(e,o,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let c=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:o,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 o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let b=await this.checkEntry(o.path);if(!b.ok)throw new pt(b.errors)}let i=o.builtin&&!t$(o.path)?o.definition:await this.catalog.read(o.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let c=this.order([...this.slots.values()].map((b)=>b.definition.id===e?i:b.definition),!0),p=await this.stage(i),g=o.current;o.definition=i,o.current=p,o.error=void 0,o.discoveryFailed=!1;let y=new Map(this.slots);this.slots.clear();for(let b of c){let E=y.get(b.id);if(E)this.slots.set(b.id,E)}if(g)await this.retirement.retire(g)}catch(i){throw o.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,o){return this.exclusive(async()=>{let i=this.require(e);if(o===i.enabled&&(!o||i.current&&!i.current.disabled))return;if(!o){for(let y of this.slots.values())if(y.enabled&&y.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${y.definition.id}`)}let c=o&&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=o?await this.stage(c):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let g=i.current;if(i.definition=c,o)i.discoveryFailed=!1;if(i.enabled=o,i.current=p,i.error=void 0,g)await this.retirement.retire(g)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let i of e.deps??[])if(i===e.id||!this.slots.get(i)?.current||this.slots.get(i)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${i}`);return JP(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,i){this.observers.notify(e,o,i)}resolveHistory(e,o){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let c of i.current.historyResolvers){let p=c(e,o);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new zc(this,e)}async invoke(e,o,i,c,p,g="end"){return BP(this,this.deadline.bind(this),this.fail.bind(this),e,o,i,c,p,g)}pinEntry(e){if(ba.getStore()?.phase==="after")return;let o;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;o??=[],o.push(c),c.references++}if(!o)return;return new zc(this,o)}beforeEntry(e,o,i,c){return UP(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,i,c)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,i){this.observers.finishEntry(e,o,i)}deadline(e,o=this.timeoutMs,i=!1){return qP(e,o,i)}appendExtension(e,o){return _s(),new Promise((i)=>{let c=this.runtime.get(e);if(!c)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});c.refreshEntries(),i(p)})}list(){return KP(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(i&&o.path)await this.webBuilder.build(i,n$(Qh(o.path)));return{ok:!0}}catch(o){if(o instanceof fl)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!i)return;return this.webBuilder.build(i,n$(Qh(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let i=await this.webBuilder.entry(o.path,o.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,o,i){return XP(this,this.deadline.bind(this),e,o,i)}hasRoute(e){return YP(this,e)}isPublicRoute(e){return ZP(this,e)}route(e){return e$(this,this.deadline.bind(this),e)}websocket(e){return QP(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 s$}from"fs";import{join as kB}from"path";var AB=500,CB=1000,PB=3600000,$B=5000,vB=2000,MB=3,OB=1073741824;class Yh{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;constructor(e){this.options=e;if(this.indexPath=kB(e.dataDir,Go),this.features={...zo(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,i=o?.backfill;if(!o||!i)return{...e,state:"backfilling"};if(i.state==="done"){let c=o.entries;return{...e,state:"ready",lag:o.lag,total:c,indexed:Math.max(0,c-o.lag)}}return{...e,lag:o.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=s$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=s$(this.options.store.path).size}catch{}return Math.max(OB,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(),Zn(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.worker;if(!o)return e();Atomics.store(this.flags,He,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Tt,0,$B);try{return e()}finally{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=jo(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,He,0),Atomics.store(this.flags,Tt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<MB&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He);let o=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(vB)]),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,AB-(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)Zn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),PB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,CB-(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(o===0)i();else this.statusTimer=setTimeout(i,o),this.statusTimer.unref?.()}}import{existsSync as hu,mkdirSync as FB,readdirSync as d$,readFileSync as c$,realpathSync as Zh,statSync as Pl,writeFileSync as eg}from"fs";import{dirname as Cl,isAbsolute as tg,relative as f$,resolve as jB}from"path";import{existsSync as Vc}from"fs";import{dirname as qB,join as fu}from"path";import{mkdirSync as _B,writeFileSync as LB}from"fs";import{tmpdir as NB}from"os";import{join as i$}from"path";var Rl=2000,Te=30000;function u(e){return{content:[{type:"text",text:e}],details:void 0}}function du(e,o){return e.map((i,c)=>{let p=i.length>Rl?`${i.slice(0,Rl)}\u2026 [line truncated]`:i;return`${String(o+c).padStart(6)} ${p}`}).join(`
|
|
90
|
-
`)}function pe(e,o){if(e.length<=o)return e;let i=Math.floor(o*0.4),c=o-i,p=e.length-i-c,g=e.slice(i,e.length-c).split(`
|
|
91
|
-
`).length-1;return`${e.slice(0,i)}
|
|
92
|
-
|
|
93
|
-
\u2026 [${p} characters, ~${g} lines omitted] \u2026
|
|
94
|
-
|
|
95
|
-
${e.slice(-c)}`}var DB=0;function nt(e,o,i){if(e.length<=o)return e;let c=pe(e,o);try{let p=i?ad(i):i$(NB(),"basalt-output");_B(p,{recursive:!0});let g=i$(p,`${process.pid}-${Date.now().toString(36)}-${DB++}.txt`);return LB(g,e),`${c}
|
|
96
|
-
[Full output saved to ${g}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return c}}var a$=120000,u$=600000,Ea;function tr(){if(Ea!==void 0)return Ea||void 0;let o=(process.env.PATH??"").split(";").map((c)=>c.trim()).filter(Boolean);for(let c of o){let p=fu(c,"bash.exe");if(Vc(p))return Ea=p,p}for(let c of o){let p=fu(c,"git.exe");if(Vc(p)){let g=qB(c),y=fu(g,"bin","bash.exe");if(Vc(y))return Ea=y,y;let b=fu(g,"usr","bin","bash.exe");if(Vc(b))return Ea=b,b}}let i=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?fu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?fu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let c of i)if(Vc(c))return Ea=c,c;Ea="";return}class kl{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 o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let i=0;while(i<o.length){if(o[i]<128){i+=1;continue}let p=o[i+1];if(p===void 0)break;let g=p>=48&&p<=57?4:2;if(i+g>o.length)break;i+=g}return this.gbkPending=o.slice(i),this.gbk.decode(o.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});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 Sa(e,o){let i=process.platform==="win32",c=o??"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:[tr()??"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=tr();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,o){let i=await je(e,o.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:c,isWindows:p}=Sa(e,o.shell),g=Bun.spawn(c,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,...om(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((ee)=>ee.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),y=!1,b=()=>{try{if(p)g.kill();else process.kill(-g.pid,"SIGKILL")}catch{}},E=setTimeout(()=>{y=!0,b()},o.timeout);o.signal?.addEventListener("abort",b,{once:!0});let S=Te*2,w="",R="",A=0,C=0,L="",q=(ee=!1)=>{let ae=A-w.length-R.length,K=ae>0?`${w}
|
|
97
|
-
\u2026 [${ae} characters omitted] \u2026
|
|
98
|
-
${R}`:w+R;if(!ee)return pe(K,Te);return nt(L.length===A?L:K,Te,o.cwd)},X=()=>{let ee=new kl;return async(ae)=>{for await(let ue of ae){let he=ee.decode(ue);if(A+=he.length,L.length<4000000)L+=he;if(w.length<S)w+=he;else R=(R+he).slice(-S);if(o.onOutput){let _e=performance.now();if(_e-C>=80)C=_e,o.onOutput(q())}}let K=ee.flush();if(K){if(A+=K.length,L.length<4000000)L+=K;if(w.length<S)w+=K;else R=(R+K).slice(-S)}}},j=Promise.all([X()(g.stdout),X()(g.stderr)]),V=await g.exited;if(clearTimeout(E),o.signal?.removeEventListener("abort",b),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
|
|
99
|
-
[background processes are still running; their later output is not captured]`;return{output:q(!0),code:y?null:V,timedOut:y}}class rg{seen=new Map;mark(e,o=Pl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Pl(e).mtimeMs!==o?"changed":void 0}}var m$=2000,UB=500,BB=10485760,Al=20,GB=6,KB=40000,HB=80000;function WB(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 h$(e,o,i=[],c){let p=(L)=>tg(L)?L:jB(e,L),g=(L)=>{let q=f$(e,L);return q&&!q.startsWith("..")&&!tg(q)?q:L},y=(L)=>{let q=L;while(!hu(q)&&Cl(q)!==q)q=Cl(q);let X=Zh(q);if(i.some((j)=>hu(j)&&l$(Zh(j),X))&&!l$(Zh(e),X))throw Error("External directories are read-only")},b=(L,q,X)=>{let j=p(L);if(!hu(j))throw Error(`No such file or directory: ${j}${QB(j)}`);let V=Pl(j);if(V.isDirectory()){let ce=d$(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),Fe=ce.slice(0,UB),It=ce.length-Fe.length;return u(`${Fe.join(`
|
|
100
|
-
`)}${It>0?`
|
|
101
|
-
\u2026 and ${It} more entries`:""}`||"(empty directory)").content}let J=c$(j),ee=WB(J);if(ee){if(V.size>BB)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return o.mark(j),[{type:"text",text:`Read image ${g(j)} (${ee}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:ee}]}if(J.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);o.mark(j);let ae=J.toString("utf8");if(!ae)return u("(empty file)").content;let K=ae.replace(/\r?\n$/,"").split(/\r?\n/),ue=(q??1)-1;if(ue>=K.length)throw Error(`offset ${q} is past the end of the file (${K.length} lines)`);let he=Math.min(K.length,ue+(X??m$)),_e=0,Ee=ue;while(Ee<he){let ce=K[Ee]?.length??0;if(Ee>ue&&_e+ce>KB)break;_e+=ce,Ee++}let se=du(K.slice(ue,Ee),ue+1);if(Ee<he)se+=`
|
|
102
|
-
|
|
103
|
-
(Showing lines ${ue+1}-${Ee} of ${K.length} (truncated at line ${Ee} due to safety budget). Use offset/limit to read specific windows.)`;else if(ue>0||Ee<K.length)se+=`
|
|
104
|
-
|
|
105
|
-
(Showing lines ${ue+1}-${Ee} of ${K.length}. Use offset/limit to read other parts.)`;return u(se).content},E=x({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
|
|
106
|
-
- path may be absolute or relative to the working directory.
|
|
107
|
-
- By default reads up to ${m$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
|
|
108
|
-
- Lines longer than ${Rl} characters are truncated.
|
|
109
|
-
- Reading a directory lists its entries (directories end with /).
|
|
110
|
-
- Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
|
|
111
|
-
- To read several files at once, give paths instead of path (up to ${Al}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
|
|
112
|
-
- Always read a file before editing or overwriting it.`,parameters:l({path:n(a({description:"File or directory path"})),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"})),paths:n(B(l({path:a({description:"File or directory path"}),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:Al,description:"Several files or directories to read in one call, instead of path"}))}),async execute(L,q){let X=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(X.length===0)throw Error("Give path, or paths to read several files");if(X.length===1){let ae=X[0];return{content:b(ae.path,ae.offset,ae.limit),details:void 0}}if(X.length>Al)throw Error(`Read at most ${Al} paths per call`);let j=[],V=[],J=0,ee=(ae)=>{let K=j.at(-1);if(ae.type==="text"&&K?.type==="text")K.text+=`
|
|
113
|
-
|
|
114
|
-
${ae.text}`;else j.push(ae)};for(let ae of X){let K=`==> ${g(p(ae.path))} <==`;if(J>=HB){ee({type:"text",text:`${K}
|
|
115
|
-
(Skipped due to total read safety budget; read in separate calls)`});continue}try{let ue=b(ae.path,ae.offset,ae.limit);for(let he=0;he<ue.length;he++){let _e=ue[he];if(!_e)continue;if(_e.type==="text")J+=_e.text.length,ee(he===0?{..._e,text:`${K}
|
|
116
|
-
${_e.text}`}:_e);else ee(_e)}}catch(ue){let he=ue instanceof Error?ue.message:String(ue);V.push(he),ee({type:"text",text:`${K}
|
|
117
|
-
Error: ${he}`})}}if(V.length===X.length)throw Error(V.join(`
|
|
118
|
-
`));return{content:j,details:void 0}}}),S=async(L,q,X,j)=>{let V=j?.update,J=await rr(L,{cwd:e,timeout:120000,signal:X,extraPath:c?.extraPath,shell:typeof c?.shell==="function"?c.shell():c?.shell,onOutput:V?(he)=>V(u(`${j.prefix}
|
|
119
|
-
|
|
120
|
-
$ ${L}
|
|
121
|
-
${he.trimEnd()}`)):void 0}),ee=J.output.trimEnd()||"(no output)",ae=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,K=J.timedOut||J.code!==0,ue=K?`
|
|
122
|
-
${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
|
|
123
|
-
|
|
124
|
-
$ ${L}
|
|
125
|
-
${ee}
|
|
126
|
-
[${ae}]${ue}`,failed:K}},w=(L,q=!1)=>{let X=o.check(L);if(X==="changed")return`Note: ${g(L)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(X==="unread"&&q)return`Note: ${g(L)} existed and had not been read; it was replaced whole.`;return},R=x({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
|
|
127
|
-
- An existing file is replaced whole, including changes made since you last read it.
|
|
128
|
-
- Prefer the edit tool for changing existing files; use write for new files or full rewrites.
|
|
129
|
-
- then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
|
|
130
|
-
- Do not create documentation or README files unless asked.`,parameters:l({path:a({description:"File path"}),content:a({description:"The full file content"}),then_run:n(a({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(L,q,X,j){let V=p(q.path);y(V);let J=hu(V),ee;if(J){if(Pl(V).isDirectory())throw Error(`${V} is a directory`);ee=w(V,!0)}FB(Cl(V),{recursive:!0}),eg(V,q.content),o.mark(V);let ae=q.content?q.content.split(`
|
|
131
|
-
`).length:0,K=`${J?"Overwrote":"Created"} ${g(V)} (${ae} lines)${ee?`
|
|
132
|
-
${ee}`:""}`;if(q.then_run){let ue=await S(q.then_run,`${g(V)} was written as given`,X,{prefix:K,update:j});if(K+=ue.out,ue.failed)return{...u(K),isError:!0}}return u(K)}}),A=(L,q,X,j)=>{let V=p(L);if(!hu(V))throw Error(`File not found: ${V} (use write to create it)`);y(V);let J=w(V),ee=c$(V,"utf8"),ae=ee,K=ae.includes(`\r
|
|
133
|
-
`),ue=[],he=[],_e=0,Ee=0;return q.forEach((se,ce)=>{let Fe=j?`edits[${X+ce}]: `:"";try{if(se.old_string===se.new_string)throw Error(`${Fe}old_string and new_string are identical`);if(!se.old_string)throw Error(`${Fe}old_string is empty (use write to create or replace a whole file)`);let It=K&&!se.old_string.includes(`\r
|
|
134
|
-
`),Je=It?se.old_string.replace(/\n/g,`\r
|
|
135
|
-
`):se.old_string,Yt=It?se.new_string.replace(/\n/g,`\r
|
|
136
|
-
`):se.new_string,Ue=zB(ae,Je).map((Ct)=>[Ct,Ct+Je.length]);if(Ue.length===0)Ue=VB(ae,Je);if(Ue.length===0)throw Error(`${Fe}old_string not found in ${g(V)}; read the relevant lines and copy the exact text.${JB(ae,Je)}`);if(Ue.length>1&&!se.replace_all){let Ct=Ue.map(([it])=>p$(ae,it)).join(", ");throw Error(`${Fe}old_string occurs ${Ue.length} times (lines ${Ct}); add surrounding lines to make it unique, or set replace_all.`)}let Be=p$(ae,Ue[0][0]),qt=se.replace_all?Ue:[Ue[0]],lt="",Ot=0;for(let[Ct,it]of qt)lt+=ae.slice(Ot,Ct)+Yt,Ot=it;ae=lt+ae.slice(Ot),_e++,Ee+=qt.length;let yr=ae.split(/\r?\n/),pr=Be+Yt.split(/\r?\n/).length-1,Ut=Math.max(1,Be-1),st=Math.min(yr.length,pr+1);if(st-Ut+1<=GB+2)ue.push(du(yr.slice(Ut-1,st),Ut));else ue.push(`${du(yr.slice(Ut-1,Be+1),Ut)}
|
|
137
|
-
\u2026 (${pr-Be-3} lines as given)
|
|
138
|
-
${du(yr.slice(pr-2,st),pr-1)}`)}catch(It){he.push(It instanceof Error?It.message:String(It))}}),{path:V,original:ee,content:ae,echoes:ue,applied:_e,total:Ee,count:q.length,note:J,failed:he}},C=x({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
|
|
139
|
-
- No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
|
|
140
|
-
- For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
|
|
141
|
-
- Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
|
|
142
|
-
- Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
|
|
143
|
-
- To create a file use write; to delete or move files use bash.
|
|
144
|
-
- then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
|
|
145
|
-
- Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(a({description:"File path (the default for edits items without their own path)"})),old_string:n(a({description:"The exact text to replace (only when edits is absent)"})),new_string:n(a({description:"The replacement text (only when edits is absent)"})),replace_all:n(O({description:"Replace every occurrence (default false)"})),edits:n(B(l({path:n(a({description:"The file of this replacement, when it is not path"})),old_string:a({description:"The exact text to replace"}),new_string:a({description:"The replacement text"}),replace_all:n(O({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(a({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(L,q,X,j){let V=q.edits&&q.edits.length>0?q.edits.map((se)=>({path:se.path??q.path,step:se})):q.old_string!==void 0&&q.new_string!==void 0?[{path:q.path,step:{old_string:q.old_string,new_string:q.new_string,replace_all:q.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,ee=new Map;V.forEach((se,ce)=>{if(!se.path)throw Error(`${J?`edits[${ce}]: `:""}path is required`);let Fe=p(se.path),It=ee.get(Fe)??{raw:se.path,steps:[],offset:ce};It.steps.push(se.step),ee.set(Fe,It)});let ae=[],K=[];for(let se of ee.values())try{let ce=A(se.raw,se.steps,se.offset,J);if(ce.applied>0)ae.push(ce);K.push(...ce.failed)}catch(ce){let Fe=ce instanceof Error?ce.message:String(ce);K.push(`${J?`edits[${se.offset}]: `:""}${Fe}`)}if(ae.length===0)throw Error(K.join(`
|
|
146
|
-
`));let ue=[];try{for(let se of ae)eg(se.path,se.content),ue.push(se)}catch(se){for(let ce of ue)eg(ce.path,ce.original);throw se}for(let se of ae)o.mark(se.path);let _e=ae.map((se)=>{let ce=se.total===1?"1 occurrence":`${se.total} occurrences`,Fe=se.note?`
|
|
147
|
-
${se.note}`:"";if(!J)return`Edited ${g(se.path)} (${ce}).${Fe}
|
|
148
|
-
${se.echoes[0]}`;let It=se.failed.length>0?`, ${se.failed.length} failed`:"";return`Edited ${g(se.path)} (${se.applied} edits${It}, ${ce}). Regions are shown as they were right after each edit; later edits may shift line numbers.${Fe}
|
|
149
|
-
${se.echoes.map((Je,Yt)=>`--- edit ${Yt+1}
|
|
150
|
-
${Je}`).join(`
|
|
151
|
-
`)}`}).join(`
|
|
152
|
-
|
|
153
|
-
`),Ee=!1;if(q.then_run){let se=await S(q.then_run,"The edits above were applied",X,{prefix:_e,update:j});if(_e+=se.out,se.failed)Ee=!0}if(K.length>0)_e+=`
|
|
154
|
-
|
|
155
|
-
${K.length===1?"1 edit":`${K.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
|
|
156
|
-
- ${K.join(`
|
|
157
|
-
- `)}`,Ee=!0;return Ee?{...u(_e),isError:!0}:u(_e)}});return[ve(E,"cat","view","read_file","view_file","open_file","open"),ve(R,"write_file","create_file","new_file","save_file"),ve(C,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function zB(e,o){let i=[];for(let c=e.indexOf(o);c!==-1;c=e.indexOf(o,c+o.length))i.push(c);return i}function p$(e,o){let i=1;for(let c=0;c<o;c++)if(e.charCodeAt(c)===10)i++;return i}function VB(e,o){let i=o.replace(/\r?\n$/,"").split(/\r?\n/).map((E)=>E.trimEnd()),c=[],p=e.split(`
|
|
158
|
-
`),g=0;for(let E of p)c.push(g),g+=E.length+1;let y=p.map((E)=>E.replace(/\r$/,"").trimEnd()),b=[];for(let E=0;E+i.length<=y.length;E++)if(i.every((S,w)=>y[E+w]===S)){let S=E+i.length-1,w=c[S]+p[S].replace(/\r$/,"").length,R=o.endsWith(`
|
|
159
|
-
`)&&w<e.length?e[w]==="\r"?2:1:0;b.push([c[E],w+R]),E+=i.length-1}return b}function JB(e,o){let i=(b)=>b.replace(/\s+/g," ").trim(),c=i(o);if(!c)return"";let p=e.split(/\r?\n/),g=o.split(/\r?\n/).length;for(let b=0;b+g<=p.length;b++)if(i(p.slice(b,b+g).join(`
|
|
160
|
-
`))===c)return` A match ignoring whitespace exists at line ${b+1}; copy the exact indentation and line breaks from the read output:
|
|
161
|
-
${pe(du(p.slice(b,b+g),b+1),4000)}`;let y=o.split(/\r?\n/).find((b)=>b.trim())?.trim();if(y){let b=p.findIndex((E)=>E.includes(y));if(b!==-1)return` Its first line appears at line ${b+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function QB(e){let o=Cl(e);if(!hu(o))return"";let c=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!c)return"";let p=d$(o).filter((g)=>{let y=g.toLowerCase().replace(/\.[^.]*$/,"");return y&&(y.includes(c)||c.includes(y))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function l$(e,o){let i=f$(e,o);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!tg(i)}var ng=20,og=80,XB=5,g$=(e)=>e!==void 0&&e>0?e:void 0;function $l(e,o){let i=(g)=>{if(o)return o(g);if(g.source&&g.source!=="self"||g.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},c=x({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
|
|
162
|
-
- 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).
|
|
163
|
-
- Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),pattern:a({minLength:1,description:"Text to search for"}),also:n(B(a({minLength:1}),{maxItems:XB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(a({description:"Only search this chunk"})),seq:n(_({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(O({description:"Default false"})),head_limit:n(_({minimum:1,maximum:ng,description:`Hits to return (default ${ng})`})),offset:n(_({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(g,y){let b=i(y),E=g$(y.seq),S=()=>Os(b.records),w=`session_id=${b.sessionID}`,R=E!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
164
|
-
`:"",A;if(E!==void 0){let K=Kc(b.records,E)??Hc(b.records,E);if(!K)throw Error(`No user message with seq ${E}`);A=[K]}else{let K=S(),ue=y.chunk_id?K.filter((he)=>he.id===y.chunk_id):K;if(y.chunk_id&&!ue.length)throw Error(`No chunk ${y.chunk_id}. Chunk IDs look like r12.`);A=ue.map(pu)}let C=(K)=>y.case_sensitive?K:K.toLowerCase(),L=[y.pattern,...(y.also??[]).filter(Boolean)].map(C),q=y.head_limit??ng,X=y.offset??0,j=[],V=new Map,J=0;for(let K of A)K.forEach((ue,he)=>{let _e=C(ue.text);if(!L.every((se)=>_e.includes(se)))return;if(V.set(ue.chunk,(V.get(ue.chunk)??0)+1),J++,J<=X||j.length>=q)return;let Ee=K.slice(Math.max(0,he-2),he+3);j.push(`${w} chunk ${ue.chunk} line ${ue.line}:
|
|
165
|
-
${Wc(Ee," ")}`)});if(!J)return u(`${R}No matches`);if(!j.length)return u(`${R}No matches at offset ${X} (total ${J})`);let ee=J-X-j.length,ae=V.size>1?` (all matches by chunk: ${[...V].map(([K,ue])=>`${K} ${ue}`).join(", ")})`:"";return u(`${R}${j.join(`
|
|
166
|
-
|
|
167
|
-
`)}${ee>0?`
|
|
168
|
-
|
|
169
|
-
\u2026 ${ee} more matches${ae}; continue with offset=${X+j.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=x({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),chunk_id:n(a({description:"Chunk to read"})),seq:n(_({description:"User message to read (from a user-text-reference)"})),offset:n(_({minimum:0,description:"First line (default 0)"})),limit:n(_({minimum:1,maximum:og,description:`Lines to return (default ${og})`}))}),async execute(g,y){let b=i(y),E=g$(y.seq),S=()=>Os(b.records),w=`session_id=${b.sessionID}`,R=E!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
|
|
170
|
-
`:"",A;if(E!==void 0){if(A=Kc(b.records,E)??Hc(b.records,E),!A)throw Error(`No user message with seq ${E}`)}else if(y.chunk_id){let X=S().find((j)=>j.id===y.chunk_id);if(!X)throw Error(`No chunk ${y.chunk_id}. Chunk IDs look like r12.`);A=pu(X)}else{let X=S().map((j)=>`${w} ${j.id} (${j.status}, ${pu(j).length} lines)`);return u(X.length?`Pass chunk_id or seq. Chunks in this session:
|
|
171
|
-
${X.join(`
|
|
172
|
-
`)}`:"This session has no history yet")}let C=y.offset??0,L=A.slice(C,C+(y.limit??og));if(!L.length)return u(`No lines at offset ${C} (total ${A.length})`);let q=A.length-C-L.length;return u(`${R}${w} ${E!==void 0?`seq=${E}`:y.chunk_id}
|
|
173
|
-
${Wc(L)}${q>0?`
|
|
174
|
-
|
|
175
|
-
\u2026 ${q} more lines; continue with offset=${C+L.length}`:""}`)}});return[c,p]}import{statSync as YB}from"fs";import{isAbsolute as y$,relative as ZB,resolve as x$}from"path";var vl=200,eG=30000,Ml=Bun.which("rg");async function sg(e,o,i){let c=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,g,y]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(y>1)throw Error(g.trim()||`${e[0]} exited with ${y}`);return p}function I$(e){let o=(g)=>g?y$(g)?g:x$(e,g):e,i=(g)=>{let y=ZB(e,g);return y&&!y.startsWith("..")&&!y$(y)?y:g},c=x({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
|
|
176
|
-
- Respects .gitignore and skips .git. Use it instead of find or ls -R.
|
|
177
|
-
- To search file contents, use grep.`,parameters:l({pattern:a({description:"Glob pattern, matched relative to path"}),path:n(a({description:"Directory to search (default: working directory)"}))}),async execute(g,y,b){let E=o(y.path),S;if(Ml)S=(await sg([Ml,"--files","--hidden","--glob","!.git","--glob",y.pattern],E,b)).split(`
|
|
178
|
-
`).filter(Boolean);else{S=[];for await(let C of new Bun.Glob(y.pattern).scan({cwd:E,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(C))S.push(C)}if(!S.length)return u("No files found");let w=S.map((C)=>{let L=x$(E,C);try{return{path:L,time:YB(L).mtimeMs}}catch{return{path:L,time:0}}});w.sort((C,L)=>L.time-C.time);let R=w.slice(0,vl).map((C)=>i(C.path)),A=S.length-R.length;return u(`${R.join(`
|
|
179
|
-
`)}${A>0?`
|
|
180
|
-
\u2026 ${A} more files; narrow the pattern`:""}`)}}),p=x({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
|
|
181
|
-
- output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
|
|
182
|
-
- Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
|
|
183
|
-
- Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
|
|
184
|
-
- Use this instead of running grep or rg through bash.`,parameters:l({pattern:a({description:"Regular expression"}),path:n(a({description:"File or directory to search (default: working directory)"})),glob:n(a({description:"Only search files matching this glob"})),output:n(m([s("files"),s("content"),s("count")],{description:"Output mode (default files)"})),ignore_case:n(O()),context:n(_({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(g,y,b){let E=o(y.path),S=y.output??"files",w;if(Ml){let C=[Ml,"--hidden","--glob","!.git","--max-columns","400","--max-columns-preview"];if(y.ignore_case)C.push("-i");if(y.glob)C.push("--glob",y.glob);if(S==="files")C.push("-l");else if(S==="count")C.push("-c");else if(C.push("-n","--no-heading"),y.context)C.push("-C",String(y.context));C.push("--",y.pattern,E),w=await sg(C,e,b)}else{let C=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(y.ignore_case)C.push("-i");if(y.glob)C.push(`--include=${y.glob}`);if(S==="files")C.push("-l");else if(S==="count")C.push("-c");else if(C.push("-n"),y.context)C.push(`-C${y.context}`);C.push("--",y.pattern,E),w=await sg(C,e,b)}let R=`${e}/`,A=w.split(`
|
|
185
|
-
`).filter(Boolean).map((C)=>C.startsWith(R)?C.slice(R.length):C).filter((C)=>S!=="count"||!C.endsWith(":0"));if(!A.length)return u("No matches");if(S==="files"&&A.length>vl)return u(`${A.slice(0,vl).join(`
|
|
186
|
-
`)}
|
|
187
|
-
\u2026 ${A.length-vl} more files; narrow the search`);return u(nt(A.join(`
|
|
188
|
-
`),eG,e))}});return[ve(c,"find","find_files","list_files","file_search","ls","list","list_dir"),ve(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function b$(e){return ve(x({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
|
|
189
|
-
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.
|
|
190
|
-
- Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
|
|
191
|
-
- 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.
|
|
192
|
-
- Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:B(l({content:a({minLength:1,description:"What to do, in imperative form"}),status:m(Ug.map((o)=>s(o)))}))}),async execute(o,i){let c=i.todos.map((y)=>({content:y.content,status:y.status}));e(c);let p=c.filter((y)=>y.status==="completed").length,g=c.find((y)=>y.status==="in_progress");return u(`Todo list updated (${p}/${c.length} completed${g?`; in progress: ${g.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function $e(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}function E$(e){let o=$e(e);return{target:o,hard:o,index:o}}class Ol{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},i){this.records=e;this.cwd=o;if(i)this.defaultPolicy=new Gc(e,i,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??E$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??$e(e)}prepare(e,o,i,c,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,i,c);let g=e.reduce((S,w)=>S+F(w),0)+Ni(o),y=Math.max(0,$e(i)*this.recoveryRatio-g),b=Re(c??this.records(),i,E$(i),{cwd:this.cwd()}).messages,E=b.reduce((S,w)=>S+F(w),0);if(p&&E>y)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(E>y&&b.length>1){let S=b.shift();if(S)E-=F(S);while(b[0]?.role==="toolResult"){let w=b.shift();if(w)E-=F(w)}}if(E>y){let S=b.at(-1),w=S&&"content"in S&&typeof S.content==="string"?S.content:"[Context omitted: use history tools to retrieve earlier messages.]";b.length=0;let R=w;while(R&&F({role:"user",content:R,timestamp:0})>y)R=R.slice(Math.ceil(R.length/2));if(R)b.push({role:"user",content:R,timestamp:0});E=b.reduce((A,C)=>A+F(C),0)}return this.lastMessageCount=b.length,{messages:[...e,...b],estimate:g+E}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as S$,readFileSync as tG}from"fs";import{homedir as rG}from"os";import{dirname as nG,join as w$}from"path";var oG=`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.
|
|
193
|
-
|
|
194
|
-
# How to work
|
|
195
|
-
|
|
196
|
-
- 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.
|
|
197
|
-
- 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.
|
|
198
|
-
- 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.
|
|
199
|
-
- 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.
|
|
200
|
-
|
|
201
|
-
# Making changes
|
|
202
|
-
|
|
203
|
-
- 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.
|
|
204
|
-
- 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.
|
|
205
|
-
- 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.
|
|
206
|
-
- 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).
|
|
207
|
-
- Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
|
|
208
|
-
- 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.
|
|
209
|
-
|
|
210
|
-
# Verifying
|
|
211
|
-
|
|
212
|
-
- 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.
|
|
213
|
-
- 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.
|
|
214
|
-
- 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.
|
|
215
|
-
- 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.
|
|
216
|
-
- 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.
|
|
217
|
-
|
|
218
|
-
# Tools
|
|
219
|
-
|
|
220
|
-
- Tool calls are the only way to act; describing an action does not perform it.
|
|
221
|
-
- 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.
|
|
222
|
-
- 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.
|
|
223
|
-
- 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.
|
|
224
|
-
- 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.
|
|
225
|
-
- 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.
|
|
226
|
-
- 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 &&.
|
|
227
|
-
- 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.
|
|
228
|
-
|
|
229
|
-
# Honesty
|
|
230
|
-
|
|
231
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
232
|
-
- Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
|
|
233
|
-
- When the user asks you to run something, run it, even when you can predict the result.
|
|
234
|
-
- If a step failed, was skipped or could not be verified, say which one and why.
|
|
235
|
-
|
|
236
|
-
# Safety
|
|
237
|
-
|
|
238
|
-
- 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.
|
|
239
|
-
- 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.
|
|
240
|
-
- 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.
|
|
241
|
-
- Never print, log or commit secrets such as API keys, tokens or passwords.
|
|
242
|
-
|
|
243
|
-
# Communication
|
|
244
|
-
|
|
245
|
-
- Reply in the same language the user writes in.
|
|
246
|
-
- 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.
|
|
247
|
-
- 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.
|
|
248
|
-
- Do not use emojis unless the user does or asks for them.
|
|
249
|
-
- 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.
|
|
250
|
-
- Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,sG=`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.
|
|
251
|
-
|
|
252
|
-
# Tools
|
|
253
|
-
|
|
254
|
-
- 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.
|
|
255
|
-
- 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.
|
|
256
|
-
- Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
|
|
257
|
-
- Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
|
|
258
|
-
- Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
|
|
259
|
-
|
|
260
|
-
# Communication
|
|
261
|
-
|
|
262
|
-
- Reply in the same language the user writes in.
|
|
263
|
-
- Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
|
|
264
|
-
- Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,iG=["AGENTS.md","CLAUDE.md"],aG=20000;function T$(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?oG:sG}],i=[];if(e.globalInstructions?.trim())i.push(ig("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let c of uG(e.project.directory))i.push(ig(c.path,c.content));if(e.project.instructions.trim())i.push(ig(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
|
|
265
|
-
|
|
266
|
-
# Instructions from the user and project
|
|
267
|
-
|
|
268
|
-
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.
|
|
269
|
-
|
|
270
|
-
${i.join(`
|
|
271
|
-
|
|
272
|
-
`)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
|
|
273
|
-
|
|
274
|
-
${cG(e)}`}),o}function ig(e,o){return`<instructions source="${e}">
|
|
275
|
-
${pe(o.trim(),aG)}
|
|
276
|
-
</instructions>`}function uG(e){let o=[],i=e;for(let c=0;c<20;c++){for(let g of iG){let y=w$(i,g);if(S$(y)){try{o.unshift({path:y,content:tG(y,"utf8")})}catch{}break}}if(S$(w$(i,".git"))||i===rG())break;let p=nG(i);if(p===i)break;i=p}return o}function cG(e){let o=e.now??new Date,i=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),c=o.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:g}=Sa("",e.shell),y=[`Working directory: ${p}`,`Shell: ${g}`,`Date: ${i} (${c})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project){let b=mG(e.project.directory);y.push(b??"Git: not a git repository")}return`<environment>
|
|
277
|
-
${y.join(`
|
|
278
|
-
`)}
|
|
279
|
-
</environment>`}function mG(e){let o=(...b)=>{try{let E=Bun.spawnSync(["git",...b],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0});return E.exitCode===0?E.stdout.toString().trim():void 0}catch{return}},i=o("rev-parse","--abbrev-ref","HEAD");if(i===void 0)return;let c=o("status","--short")??"",p=c?c.split(`
|
|
280
|
-
`):[],g=p.length>30?[...p.slice(0,30),`\u2026 ${p.length-30} more`]:p,y=o("log","--oneline","-5")??"";return[`Git branch: ${i}`,`Git status at session start:${g.length?`
|
|
281
|
-
${g.join(`
|
|
282
|
-
`)}`:" clean"}`,y?`Recent commits:
|
|
283
|
-
${y}`:"Recent commits: none"].join(`
|
|
284
|
-
`)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?$l(e.records,e.history):[],c=e.directory??process.cwd();return[...h$(c,new rg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...I$(c),b$(e.onTodos),...i]}class qi{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!Gg.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Bg.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let i=e.scope==="tool"?o.tools:o.sources,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(o)),o}partition(e){let o=this.settings();return e.map((c)=>{let p=c,g=p.source??"core",y=c.name.toLowerCase(),b=p.defer??"always",E="suggestion";if(o.global)b=o.global,E="global";if(Object.hasOwn(o.sources,g))b=o.sources[g]??b,E="source";if(Object.hasOwn(o.tools,y))b=o.tools[y]??b,E="tool";if(g==="core"||p.builtin&&p.defer!=="defer")b="always",E="suggestion";return{name:c.name,source:g,mode:b,origin:E,deferred:b==="defer"}})}}function ag(e){return{name:e.name,description:e.description,parameters:e.parameters}}function ug(e,o){if(!o)return e;let i=Array.isArray(o.type)?o.type:[o.type],c=e;if(i.includes("number")||i.includes("integer")){let p=typeof c==="string"&&c.trim()?Number(c):c;if(typeof p!=="number"||!Number.isFinite(p))return c;let g=p;if(typeof o.maximum==="number"&&g>o.maximum)g=o.maximum;if(typeof o.minimum==="number"&&g<o.minimum)g=o.minimum;return g===p?c:g}if(typeof c==="string"&&(i.includes("object")||i.includes("array")))try{let p=JSON.parse(c),g=Array.isArray(p);if(typeof p==="object"&&p!==null&&!g&&i.includes("object")||g&&i.includes("array"))c=p}catch{}if(Array.isArray(c)){let p=o.items;if(!p||typeof p!=="object"||Array.isArray(p))return c;return c.map((g)=>ug(g,p))}if(typeof c==="object"&&c!==null&&o.properties){let p={...c};for(let[g,y]of Object.entries(o.properties))if(g in p)p[g]=ug(p[g],y);return p}return c}function pG(e){let o=e.prepareArguments;return{...e,prepareArguments:(i)=>{let c=ug(i,e.parameters);return o?o(c):c}}}function lG(e,o,i){let c=e.prepareArguments?e.prepareArguments(i):i;return ou(e,{type:"toolCall",id:o,name:e.name,arguments:c})}class cg{retrieved=new Map;stub(e,o){let i=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${i}
|
|
285
|
-
(Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(c,p,g,y)=>{let b=JSON.stringify(ag(e)),E;try{E=lG(e,c,p??{})}catch(R){return{...u(`Invalid arguments for ${e.name}: ${String(R)}
|
|
286
|
-
Schema: ${b}`),isError:!0}}let S=await e.execute(c,E,g,y),w=S.content.map((R)=>R.type==="text"?{...R,text:nt(R.text,Te,o)}:R);return{...S,content:w}}}}assemble(e,o,i,c){let p=e.map(pG),g=new Set(o.filter((b)=>b.deferred).map((b)=>b.name));if(!g.size)return p;let y=p.filter((b)=>g.has(b.name)&&i(b.name)).sort((b,E)=>b.name<E.name?-1:b.name>E.name?1:0);return[...p.filter((b)=>!g.has(b.name)),...y.map((b)=>this.stub(b,c)),ve(x({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:a(),max_results:n(_({minimum:1,maximum:100}))}),execute:async(b,E)=>{let S=E.query.trim().toLowerCase(),w=S.startsWith("select:")?S.slice(7).split(",").map((A)=>A.trim()):void 0,R=y.filter((A)=>i(A.name)&&(w?w.includes(A.name.toLowerCase()):`${A.name} ${A.description}`.toLowerCase().includes(S))).slice(0,E.max_results??5);return u(JSON.stringify(R.map((A)=>{let C=JSON.stringify(ag(A)),L=this.retrieved.get(A.name);if(L?.schema===C)return{name:A.name,status:"\u5DF2\u53D6\u56DE",callID:L.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(A.name,{schema:C,callID:b}),ag(A)})))}}),"tool_search")]}}async function _l(e,o,i){let c=await o.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 g=c.systemPrompt,y=c.systemParts?.at(-1);if(y?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let w=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),R=g.length-y.detail.length;g=g.slice(0,R)+w.join("")+y.detail}let b=await i.invoke("prompt.fragments",[],e),E=[...c.tools,...i.tools()],S=i.has("tools.visible")?await i.invoke("tools.visible",E,e):E;return{...c,systemPrompt:g+b.join(""),tools:S}}var dG=3,R$={attempts:1/0,delayMs:2000},fG=/\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 hG(e,o){if(e.stopReason!=="error")return!1;if(ma(e,o))return!1;return!fG.test(e.errorMessage??"")}function k$(e,o,i){if(ma(e,o))return!0;if(i?.preserveHistory!==!0)return!1;return e.errorMessage===(i.overflowError??"Context exceeds the request budget")}function gG(e,o){return new Promise((i,c)=>{if(o.aborted)return c(o.reason);let p=setTimeout(()=>{o.removeEventListener("abort",g),i()},e),g=()=>{clearTimeout(p),c(o.reason)};o.addEventListener("abort",g,{once:!0})})}async function A$(e,o,i,c,p,g,y,b,E=!1){let S=E?void 0:await o?.invoke("run.start",{text:g},e);if(S)g=S.text;if(b.throwIfAborted(),g===void 0)await c.resume();else await c.prompt(g,y);let w=0,R=0;while(w<dG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!k$(q,p.contextWindow,i)){if(!hG(q,p.contextWindow)||R>=R$.attempts)return;R++,await gG(R$.delayMs,b),await c.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}b.throwIfAborted(),w++,await c.retry()}let C=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&C?.stopReason==="error"&&k$(C,p.contextWindow,i))throw Error(i.overflowError??"Context exceeds the request budget")}async function C$(e,o,i,c,p,g){g.throwIfAborted();let y,b;try{b=await Promise.race([_l(e,o,i()),new Promise((A,C)=>{y=()=>C(g.reason),g.addEventListener("abort",y,{once:!0})})])}finally{if(y)g.removeEventListener("abort",y)}g.throwIfAborted();let E=i(),S=(A)=>{if(!E)return A;return{...A,execute:async(C,L,q,X)=>{let j=c()??b.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?E.policy(j):void 0;if(j&&!V?.(A.name,e))throw Error(`Tool ${A.name} is unavailable under tool policy ${j}`);let J=await E.invoke("tool.before_call",{name:A.name,callID:C,args:L},e);if(J.block)throw Error(J.block);let ee=await z.run(e,()=>A.execute(C,J.args,q,X));return E.invoke("tool.after_result",ee,e)}}};if(E)b.tools=b.tools.map(S);let w=b.tools,R=()=>{if(!w.some((C)=>C.name==="history_grep")){if(e.records.some((L)=>L.entry.type==="compaction")){let q=$l(()=>e.records,(X)=>o.runtime?.resolveHistory?.(e.id,X)).map(S);for(let X of q)if(!w.some((j)=>j.name===X.name))w.push(X)}}let A=new qi(o.store).partition(w);return b.tools=p.assemble(w,A,(C)=>e.permitsTool(C),b.cwd),b.tools};return b.tools=R(),{setup:b,executionTools:w,assemble:R}}function P$(e,o,i,c,p,g,y){return{response:async(b)=>{let E=await o()?.invoke("model.after_response",b,e)??b;if(E.role==="assistant")for(let S of E.content){if(S.type!=="toolCall"||S.name.toLowerCase()!=="tool_call")continue;let w=S.arguments.name;if(typeof w==="string"){let R=y.find((A)=>A.name.toLowerCase()===w.toLowerCase());S.arguments.name=R?.name??w}}return E},payload:(b)=>o()?.invoke("model.before_request",b,e)??Promise.resolve(b),transformContext:(b)=>o()?.invoke("transformContext",b,e)??Promise.resolve(b),boundary:async()=>{if(c())return!0;let b=await o()?.invoke("step.after",{notices:[]},e);for(let S of b?.notices??[])e.notice(S);await g.work;let E=await g.flushNotices();if(E&&!p())e.agent?.steer(E)},prepare:async(b,E,S)=>{if(c())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let w=await o()?.invoke("model.check",{},e);if(w?.error)throw Error(w.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let j of R?.notices??[])e.notice(j);await g.work,await g.flushNotices();let A=await o()?.invoke("projection.before",e.records,e),C=await o()?.invoke("projection.prefix",[],e)??[],L=e.context.prepare([...b,...C],E,S,A,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&L.estimate>$e(S))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=L.messages,X=await o()?.invoke("projection.after",q,e)??q;return uu(X)}}}async function $$(e,o,i){let c=o.store.pendingNotices(e.id);if(!c.length)return;let p=c,g=o.plugins?.pin();try{if(g){let C=await g.invoke("notice.deliver",c,e);p=c.map((L,q)=>({...L,text:C[q]?.text??L.text}))}}finally{await g?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let y=p.map((C)=>C.text).join(`
|
|
287
|
-
`),b=p.map((C)=>o.plugins?.noticeSource(C.sourceKind)),E=Math.max(800,...b.map((C)=>C?.summaryLimit??800)),S=y.length>E?`
|
|
288
|
-
[\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${b.find((C)=>C?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
|
|
289
|
-
${y.slice(0,E)}${S}`,A={role:"user",content:R,timestamp:Date.now()};return i({type:"user",text:R,notices:c.map(({text:C,...L})=>L)},A),A}class mg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,i,c,p,g,y,b){this.session=e;this.context=o;this.isStopped=i;this.isRunning=c;this.waiting=p;this.start=g;this.invalidateAgent=y;this.append=b}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let i of e){if(i.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:i.dedupeKey,sourceKind:i.sourceKind,sourceID:i.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((i)=>i.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((i)=>{this.failure=i}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=$$(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((o)=>o.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var yG=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 pg(e){let o={};for(let[i,c]of Object.entries(e)){if(!yG.has(i.toLowerCase())){o[i]=c;continue}let p=/^bearer\s+/i.exec(c)?.[0];o[i]=p?`${p}***`:"***"}return o}function v$(e,o,i,c){let g=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((K,ue)=>({id:`system-${ue}`,label:K.label,detail:K.detail,tokens:D(K.detail)+(ue===0?16:0)})),y=i.tools.map((K)=>{let ue=K,he=ue.defer==="defer"||K.description.includes("(Parameters not inlined: use toolsearch");return{name:K.name,description:K.description,group:ue.group??"\u5185\u7F6E",schema:K.parameters,deferred:he}});g.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Ni(i.tools),detail:JSON.stringify(y,null,2)});let b=g.reduce((K,ue)=>K+ue.tokens,0),E=c!==void 0?e.records.filter((K)=>K.entry.seq<=c):e.records,S=Re(E,o,e.context.budget(o),{inspect:!0,cwd:i.cwd,trim:{fixed:b,limit:e.context.previewLimit(o)}}),w,R=0,A=0;for(let K of E){if(K.raw?.role!=="assistant")continue;let ue=K.raw.usage;w??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},w.input+=ue.input,w.output+=ue.output,w.cacheRead+=ue.cacheRead,w.cacheWrite+=ue.cacheWrite,w.cost+=ue.cost.total;let he=K.entry.generationMs??K.raw.generationMs;if(typeof he==="number"&&he>0&&ue.output>0)R+=he,A+=ue.output}if(w){let K=w.input+w.cacheRead+w.cacheWrite;if(K>0)w.cacheHitRate=w.cacheRead/K}if(w&&R>0&&A>0)w.generationMs=R,w.tps=Number((A/(R/1000)).toFixed(1));let C=b+S.tokens,L=e.context.calibrationRatio??1,q=Math.round(C*L),X=E.findLast((K)=>K.raw?.role==="assistant"),j=X?.raw,J=(X?E.filter((K)=>K.entry.seq>X.entry.seq&&K.raw):E.filter((K)=>K.raw)).length>0,ee,ae;if(j){let K=j.usage,ue=K.input+K.cacheRead+K.cacheWrite;if(ue>0)ee=ue,ae=K.cacheRead/ue}return{contextWindow:o.contextWindow,usableWindow:$e(o),items:[...g,...S.items],calibratedTokens:q,calibrationRatio:L,lastInputTokens:ee,lastCacheHitRate:ae,hasPendingOutput:J,tools:y,usage:w}}class dt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class ie extends Error{constructor(e="session"){super(`${e} is busy`)}}var lg="medium";class Ll{row;ctx;events;notices;lease;policyID;discovery=new cg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await _l(this,this.ctx,e);return new qi(this.ctx.store).partition(o.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new ie;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 o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,i){this.row=e;this.ctx=o;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new mg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let c=o.store.lastEntry(e.id,"run");this.stopped=c?.type==="run"&&c.state==="end"&&c.reason==="aborted";let p=this.entries(0,["extension","run"]),g=p.findLast((b)=>b.type==="extension"&&b.namespace==="session"&&b.kind==="stop_requested"),y=p.findLast((b)=>b.type==="run"&&b.state==="start");if(g&&g.seq>(y?.seq??0))this.stopped=!0;if(c?.type==="run"&&c.state==="start"){let b=this.records.some((S)=>S.entry.seq>c.seq&&S.entry.type==="user"),E=o.store.pendingNotices(e.id).some((S)=>S.wake&&S.recovery!=="discard");if(!this.stopped&&(b||E))this.recoveryStart=c.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new Ol(()=>this.records,()=>this.cwd,(b,E)=>this.appendCompaction(b,E)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=Sn(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:pg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:pg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??lg}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:o,projectID:i,model:c,thinking:p,metadata:g,created:y,updated:b,todos:E}=this.row;return{id:e,title:o,projectID:i,model:c,thinking:p??lg,metadata:g,created:y,updated:b,archivedAt:this.row.archivedAt,status:this.status,todos:E,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,o,i){return this.ctx.store.entriesAround(this.row.id,e,o,i)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,i=!0){return this.ctx.store.entries(this.row.id,e,o,i)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let i=Sn(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 _l(this,this.ctx,c)}finally{await c?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new qi(this.ctx.store).partition(p.tools),(y)=>this.permitsTool(y),p.cwd);let g=v$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:g};return g})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new dt}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!Sn(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,Zl(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let i=Zl(o),c=_h(e,i),p=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},c);if(this.recallableSteers.set(p.seq,c),this.events.changed(),this.agent)this.agent.steer(c);else this.pendingSteers.push(c)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((g)=>g.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let i=o.raw,c=this.pendingSteers.indexOf(i);if(c<0){let g=JSON.stringify(i);c=this.pendingSteers.findIndex((y)=>JSON.stringify(y)===g)}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[o,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new ie;if(e!==void 0)this.stopped=!1;let c=Sn(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:xG(e,o)},this.ctx.store.updateSession(this.row);let g=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let y=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=y.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let b=this.records.filter((R)=>R.entry.seq>g),E=b.filter((R)=>R.entry.type==="user"&&!R.raw);if(E.length>1)return{reason:"interrupted"};let S=E[0];if(S?.entry.type==="user"){if(b.some((R)=>R.entry.seq>S.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=S.entry.text,o=S.entry.attachments,this.pendingUserSeq=S.entry.seq}for(let R of ls(b.filter((A)=>A.raw))){if(R.result)continue;let{body:A,raw:C}=xP(R.call);this.append(A,C)}if(!S&&this.waitingForInput())return{reason:"waiting_user"};let w=this.records.findLast((R)=>R.entry.seq>g&&R.raw)?.raw;if(!S&&w?.role==="assistant")return Lh(w);if(!S&&!w&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!c)throw Error(`unknown model ${this.row.model}`);let y=await this.prepareAgent(c,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let b=this.pendingSteers.shift();if(b)y.steer(b)}return await A$(this,this.lease,this.setup,y,c,e,o,p.signal,i!==void 0&&e===void 0),Lh(this.records.findLast((b)=>b.entry.seq>g&&b.raw?.role==="assistant")?.raw)}).then((y)=>p.signal.aborted?{reason:"aborted"}:y,(y)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(y)}).then(async(y)=>{try{if(!this.suspended&&y.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())y={reason:"waiting_user"};if(y.reason!=="interrupted")y=await this.lease?.invoke("run.end",{reason:y.reason,error:y.error},this)??y}}catch(b){y={reason:"error",error:String(b)}}finally{try{await this.lease?.release()}catch(b){y={reason:"error",error:String(b)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...y});let b=Sn(this.ctx.models,this.row.model);if(b)this.context.settle(b)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:i,executionTools:c,assemble:p}=await C$(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=i,this.row.parentID&&(!i.toolPolicy||!this.lease?.policy(i.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=i.cwd,this.agent=yP({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((g)=>!this.pendingSteers.includes(g.raw)).flatMap((g)=>g.raw?[g.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??lg,captureRequest:(g)=>{this.lastRequestSnapshot=g},captureResponse:(g)=>{this.lastResponseSnapshot=g},steerConsumed:(g)=>this.markSteerConsumed(g),hooks:{tools:p,...P$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,c),message:(g,y)=>{if(this.suspended&&y.role==="assistant"&&(y.stopReason==="aborted"||y.stopReason==="error"))return;if(y.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,y);let b=this.loaded?.find((E)=>E.entry.seq===this.pendingUserSeq);if(b)b.raw=y;this.pendingUserSeq=void 0;return}if(y.role==="assistant")this.context.calibrate(y);this.append(g,y)},draft:(g)=>{this.draftParts=g,this.events.draft(g)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let i=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...i?{saved:i}:{}})}measureCompactionSavings(e,o){let i=Sn(this.ctx.models,this.row.model);if(!i)return;let c=this.context.budget(i),p=Re(this.records,i,c,{cwd:this.cwd}).tokens,g={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},y=Re([...this.records,g],i,c,{cwd:this.cwd}).tokens;return{before:p,after:y}}compact(){this.assertWritable();let e=au(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function xG(e,o){let c=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
|
|
290
|
-
`)[0]?.trim()??"";return c.length>40?`${c.slice(0,40)}\u2026`:c}var O$=new Set(["user","assistant","tool_result","run","compaction"]),IG=new Set(["user","assistant","toolResult"]);function _$(e,o,i){return{format:Yl,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...i?{project:i}:{},records:o.filter((c)=>O$.has(c.entry.type)).map((c)=>c.raw===void 0?{entry:c.entry}:{entry:c.entry,raw:c.raw})}}function Uo(e){if(!gr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Yl)return bG(e);if(gr(e.info)&&Array.isArray(e.messages))return SG(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 bG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!gr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let i=0,c=e.records.flatMap((p,g)=>{let y=`records[${g}]`;if(!gr(p)||!gr(p.entry))throw new t(`${y} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let b=p.entry;if(b.type==="notice_pending"||b.type==="extension")return[];if(typeof b.type!=="string"||!O$.has(b.type))throw new t(`${y} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(b.type)}`);let{seq:E,time:S}=b;if(typeof E!=="number"||!Number.isSafeInteger(E)||E<=i)throw new t(`${y} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof S!=="number"||!Number.isFinite(S))throw new t(`${y} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=E,EG(b,y);let w=p.raw;if(w!==void 0&&!(gr(w)&&typeof w.role==="string"&&IG.has(w.role)))throw new t(`${y} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:b,...w===void 0?{}:{raw:w}}]});return{title:Lr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(N$):[],created:Js(o.created)??Date.now(),updated:Js(o.updated)??Date.now(),needsRaw:!1,records:c}}function EG(e,o){let i=(c)=>new t(`${o}\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"&&Ng.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 SG(e){let o=e.info,i=gr(o.time)?o.time:{},c=gr(o.model)?o.model:void 0,p=e.messages.filter(gr).sort(wG),g=[],y=0,b=0,E=(X,j)=>{b=Math.max(b,j??b),y+=1,g.push({entry:{...X,seq:y,time:b}})},S=!1,w=(X,j)=>{if(!S)return;S=!1,E({type:"run",state:"end",reason:X,...j?{error:j}:{}},void 0)};for(let X of p){let j=gr(X.info)?X.info:{},V=Array.isArray(X.parts)?X.parts.filter(gr):[],J=Js(gr(j.time)?j.time.created:void 0);if(j.role==="user"){w("done");let ee=TG(V);if(!ee)continue;E({type:"run",state:"start"},J),E(ee,J),S=!0}else if(j.role==="assistant"){if(!S)E({type:"run",state:"start"},J),S=!0;AG(j,V,E);let ee=L$(j.error);if(ee)w(ee.aborted?"aborted":"error",ee.aborted?void 0:ee.message)}}w("done");let R=p.findLast((X)=>gr(X.info)&&X.info.role==="assistant"),A=gr(R?.info)?R.info:void 0,C=Lr(c?.providerID)||Lr(A?.providerID),L=Lr(c?.id)||Lr(A?.modelID),q=C&&L?`${C}/${L}`:void 0;return{title:Lr(o.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(N$):[],created:Js(i.created)??g[0]?.entry.time??Date.now(),updated:Js(i.updated)??g.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:g}}function wG(e,o){let i=(p)=>(gr(p.info)&&gr(p.info.time)?Js(p.info.time.created):void 0)??0,c=(p)=>gr(p.info)?Lr(p.info.id):"";return i(e)-i(o)||c(e).localeCompare(c(o))}function TG(e){let o=e.filter((c)=>c.type==="text"&&c.synthetic!==!0&&c.ignored!==!0).map((c)=>Lr(c.text)).join(`
|
|
291
|
-
|
|
292
|
-
`),i=e.flatMap((c)=>c.type==="file"?RG(c):[]);if(!o.trim()&&i.length===0)return;return{type:"user",text:o,...i.length?{attachments:i}:{}}}function RG(e){let o=Lr(e.mime)||"application/octet-stream",i=Lr(e.filename)||"file",c=Lr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(c);if(p){let g=p[3]??"";if(o.startsWith("image/"))return[{name:i,mimeType:o,kind:"image",data:p[2]?g:btoa(g)}];if(o.startsWith("text/")||o==="application/json"){let y=p[2]?new TextDecoder().decode(Uint8Array.from(atob(g),(b)=>b.charCodeAt(0))):g;return[{name:i,mimeType:o,kind:"text",data:y}]}return[]}if(c.startsWith("file://"))try{return[{name:i,mimeType:o,kind:"path",data:decodeURIComponent(new URL(c).pathname)}]}catch{return[]}return[]}function kG(e){let o=[[]];for(let i of e){if(i.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")o.at(-1)?.push(i)}return o.filter((i)=>i.length>0)}function AG(e,o,i){let c=`${Lr(e.providerID)}/${Lr(e.modelID)}`,p=L$(e.error),g=kG(o);g.forEach((y,b)=>{let E=y.flatMap((R)=>{if(R.type==="reasoning")return Lr(R.text).trim()?[{type:"thinking",text:Lr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Lr(R.text).trim()?[{type:"text",text:Lr(R.text)}]:[];return[{type:"tool_call",id:M$(R.callID),name:Lr(R.tool),input:gr(R.state)&&gr(R.state.input)?R.state.input:{}}]}),S=b===g.length-1,w=CG(y);i({type:"assistant",parts:E,model:c,...S&&p&&!p.aborted?{error:p.message}:{}},w);for(let R of y){if(R.type!=="tool")continue;let A=gr(R.state)?R.state:{},C=A.status==="error",L=A.status==="pending"||A.status==="running",q=C?[Lr(A.output),Lr(A.error)].filter(Boolean).join(`
|
|
293
|
-
`):L?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Lr(A.output);i({type:"tool_result",callID:M$(R.callID),name:Lr(R.tool),output:q,isError:C||L},Js(gr(A.time)?A.time.end:void 0))}})}function M$(e){return Lr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function L$(e){if(!gr(e))return;let o=gr(e.data)?e.data:{};return{message:Lr(o.message)||Lr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function CG(e){for(let o of e){let i=gr(o.time)?Js(o.time.start):gr(o.state)?PG(o.state):void 0;if(i!==void 0)return i}return}function PG(e){return gr(e.time)?Js(e.time.start):void 0}function N$(e){if(!gr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function D$(e,o){let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:c})=>{let p=c.time;switch(c.type){case"user":return{entry:c,raw:$G(c,p)};case"assistant":{let g=c.parts.flatMap((b)=>{if(b.type==="text")return[{type:"text",text:b.text}];if(b.type==="thinking")return[];return[{type:"toolCall",id:b.id,name:b.name,arguments:vG(b.input)}]}),y=g.some((b)=>b.type==="toolCall");return{entry:c,raw:{role:"assistant",content:g,api:o.api,provider:o.provider,model:o.id,usage:i,stopReason:c.error?"error":y?"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 $G(e,o){let i=(e.attachments??[]).flatMap((g)=>g.kind==="path"?[`<file path=${JSON.stringify(g.data)} />`]:g.kind==="text"?[`<file name=${JSON.stringify(g.name)}>
|
|
294
|
-
${g.data}
|
|
295
|
-
</file>`]:[]),c=(e.attachments??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),p=[...i,...e.text.trim()?[e.text]:[]].join(`
|
|
296
|
-
|
|
297
|
-
`);return{role:"user",content:c.length?[{type:"text",text:p},...c]:p,timestamp:o}}function gr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e==="string"?e:""}function Js(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function vG(e){return gr(e)?e:{}}function or(e,o){let i=e.at(-1)?.entry.seq??0,c,p,g;for(let{entry:S}of e){if(S.type==="run"&&S.state==="start")c=S.seq;if(S.seq===o)if(S.type==="user"&&!S.notices)i=(c??S.seq)-1;else p=c;if(S.type==="run"&&S.state==="end"){if(p!==void 0&&c===p)g=S.seq;c=void 0}}let y=e.find((S)=>S.entry.seq===o)?.entry;if(o!==void 0&&!y)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(y&&!(y.type==="user"&&!y.notices)){if(p!==void 0&&g===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=g??y.seq}else if(o===void 0&&c!==void 0)i=e.findLast(({entry:S})=>S.type==="run"&&S.state==="end")?.entry.seq??0;let b=e.filter(({entry:S})=>S.seq<=i&&(S.type!=="compaction"||S.through<=i)),E=new Map(b.map(({entry:S},w)=>[S.seq,w+1]));return b.map((S,w)=>{let R=structuredClone(S);if(R.entry.seq=w+1,R.entry.type==="compaction"){let A=R.entry.through,C=b.findLast(({entry:L})=>L.seq<=A);R.entry.through=C?E.get(C.entry.seq)??0:0}return R})}function ir(e){let o=new Map,i=[];for(let c of e){if(c.type==="assistant"){for(let y of c.parts)if(y.type==="tool_call"&&y.name==="todo")o.set(y.id,y.input)}if(c.type!=="tool_result"||c.name!=="todo"||c.isError)continue;let p=o.get(c.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let g=[];for(let y of p.todos){if(!y||typeof y!=="object"||!("content"in y)||typeof y.content!=="string"||!("status"in y)||y.status!=="pending"&&y.status!=="in_progress"&&y.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");g.push({content:y.content,status:y.status})}i=g}return i}import{Buffer as Dl}from"buffer";import{createHash as q$}from"crypto";import{isDeepStrictEqual as Nl}from"util";var Fi="@blob:";function gu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function ql(e,o){if(!o)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(Fi)){let g=Dl.from(p.data,"base64");if(g.byteLength>0&&g.toString("base64")===p.data){let y=q$("sha256").update(g).digest("hex");return o.put(y,p.mimeType,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),i=!0,{...p,data:`${Fi}${y}`}}}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(Fi)){let g=Dl.from(p.data,"base64");if(g.byteLength>0&&g.toString("base64")===p.data){let y=q$("sha256").update(g).digest("hex");return o.put(y,p.mimeType,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),i=!0,{...p,data:`${Fi}${y}`}}}return p});if(!i)return e;return{...e,images:c}}return e}function ji(e,o){if(!o)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(Fi)){let g=p.data.slice(Fi.length),y=o.get(g);if(y!==void 0)return i=!0,{...p,data:Dl.from(y.buffer,y.byteOffset,y.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(Fi)){let g=p.data.slice(Fi.length),y=o.get(g);if(y!==void 0)return i=!0,{...p,data:Dl.from(y.buffer,y.byteOffset,y.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,images:c}}return e}function Jc(e,o){if(!gu(o))return o;if(e.type==="user"){let{merged:i,images:c}=Fc(e.text,e.attachments),p=c.length>0?[{type:"text",text:i},...c]:i,g=Object.keys(o),{role:y,timestamp:b,content:E}=o;if(g.length===3&&y==="user"&&typeof b==="number"&&"content"in o&&Nl(E,p))return{role:"user",timestamp:b};return o}if(e.type==="tool_result"){let{role:i,toolCallId:c,toolName:p,isError:g,timestamp:y,content:b}=o;if(i!=="toolResult"||c!==e.callID||typeof p!=="string"||g!==e.isError||typeof y!=="number")return o;let E=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!Nl(o.details,e.meta):e.meta!==void 0)return o;let{role:w,toolCallId:R,toolName:A,content:C,details:L,isError:q,timestamp:X,...j}=o;if(Nl(b,E))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:y};if(Array.isArray(b)){let V=e.images??[],J=0,ee=!0,ae=b.map((K)=>{if(gu(K)&&K.type==="image"){let ue=V[J++],he=Object.keys(K);if(ue&&he.length===3&&K.mimeType===ue.mimeType&&K.data===ue.data)return{type:"image",mimeType:K.mimeType};ee=!1}return K});if(ee&&J===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:ae,...j,timestamp:y}}return o}if(e.type==="assistant"){let{role:i,content:c}=o;if(i!=="assistant"||!Array.isArray(c)||c.length!==e.parts.length)return o;let p=!1,g=c.map((y,b)=>{let E=e.parts[b];if(gu(y)){if(y.type==="text"&&E?.type==="text"&&y.text===E.text){p=!0;let S={...y};return delete S.text,S}if(y.type==="thinking"&&E?.type==="thinking"&&y.thinking===E.text){p=!0;let S={...y};return delete S.thinking,S}if(y.type==="toolCall"&&E?.type==="tool_call"&&y.id===E.id&&y.name===E.name&&"arguments"in y&&Nl(y.arguments,E.input)){p=!0;let S={...y};return delete S.id,delete S.name,delete S.arguments,S}}return y});if(!p)return o;return{...o,content:g}}return o}function dg(e,o){if(!gu(o))return o;if(e.type==="user"){let{role:i,timestamp:c}=o;if(i==="user"&&!("content"in o)&&typeof c==="number"&&Object.keys(o).length===2){let{merged:p,images:g}=Fc(e.text,e.attachments);return{role:"user",content:g.length>0?[{type:"text",text:p},...g]:p,timestamp:c}}return o}if(e.type==="tool_result"){let{role:i,timestamp:c}=o;if(i==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof c==="number"){let{role:g,toolName:y,content:b,timestamp:E,...S}=o,w;if(Array.isArray(b)){let R=e.images??[],A=0;w=b.map((C)=>{if(gu(C)&&C.type==="image"&&!("data"in C)){let L=R[A++];if(L)return{type:"image",mimeType:C.mimeType,data:L.data}}return C})}else w=[{type:"text",text:e.output},...(e.images??[]).map((R)=>({type:"image",mimeType:R.mimeType,data:R.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof y==="string"?y:e.name,content:w,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...S,timestamp:c}}return o}if(e.type==="assistant"){let{role:i,content:c}=o;if(i!=="assistant"||!Array.isArray(c))return o;let p=!1,g=c.map((y,b)=>{let E=e.parts[b];if(gu(y)){if(y.type==="text"&&!("text"in y)&&E?.type==="text"){p=!0;let{type:S,...w}=y;return{type:S,text:E.text,...w}}if(y.type==="thinking"&&!("thinking"in y)&&E?.type==="thinking"){p=!0;let{type:S,...w}=y;return{type:S,thinking:E.text,...w}}if(y.type==="toolCall"&&!("arguments"in y)&&E?.type==="tool_call"){p=!0;let{type:S,...w}=y;return{type:S,id:E.id,name:E.name,arguments:structuredClone(E.input),...w}}}return y});if(!p)return o;return{...o,content:g}}return o}function F$(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),c={put(E,S,w){o.run(E,S,w)},get(E){return i.get(E)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),g=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),y=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),b=0;return e.transaction(()=>{for(let E of p){let S;try{S=JSON.parse(E.body)}catch{continue}let w=ji(S,c),R=ql(w,c),A=R===S?E.body:JSON.stringify(R),C=E.raw;if(E.raw!==null)try{let L=JSON.parse(E.raw),q=dg(w,L),X=Jc(w,q);C=JSON.stringify(X)}catch{C=E.raw}if(A!==E.body)g.run(A,C,E.session_id,E.seq),b++;else if(C!==E.raw)y.run(C,E.session_id,E.seq),b++}})(),b}import{Database as MG}from"bun:sqlite";import{chmodSync as j$,existsSync as OG,mkdirSync as _G}from"fs";import{dirname as LG}from"path";var fg=[`
|
|
298
|
-
CREATE TABLE projects (
|
|
299
|
-
id TEXT PRIMARY KEY,
|
|
300
|
-
name TEXT NOT NULL,
|
|
301
|
-
directory TEXT NOT NULL UNIQUE,
|
|
302
|
-
instructions TEXT NOT NULL DEFAULT '',
|
|
303
|
-
created INTEGER NOT NULL,
|
|
304
|
-
updated INTEGER NOT NULL
|
|
305
|
-
);
|
|
306
|
-
CREATE TABLE automations (
|
|
307
|
-
id TEXT PRIMARY KEY,
|
|
308
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
309
|
-
name TEXT NOT NULL,
|
|
310
|
-
prompt TEXT NOT NULL,
|
|
311
|
-
schedule TEXT NOT NULL,
|
|
312
|
-
model TEXT NOT NULL,
|
|
313
|
-
enabled INTEGER NOT NULL,
|
|
314
|
-
created INTEGER NOT NULL,
|
|
315
|
-
updated INTEGER NOT NULL,
|
|
316
|
-
next_run INTEGER,
|
|
317
|
-
last_run INTEGER,
|
|
318
|
-
last_session_id TEXT
|
|
319
|
-
);
|
|
320
|
-
CREATE TABLE sessions (
|
|
321
|
-
id TEXT PRIMARY KEY,
|
|
322
|
-
project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
|
|
323
|
-
automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
|
|
324
|
-
title TEXT NOT NULL DEFAULT '',
|
|
325
|
-
model TEXT NOT NULL,
|
|
326
|
-
todos TEXT NOT NULL DEFAULT '[]',
|
|
327
|
-
created INTEGER NOT NULL,
|
|
328
|
-
updated INTEGER NOT NULL
|
|
329
|
-
);
|
|
330
|
-
CREATE INDEX sessions_project ON sessions(project_id);
|
|
331
|
-
CREATE TABLE entries (
|
|
332
|
-
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
333
|
-
seq INTEGER NOT NULL,
|
|
334
|
-
time INTEGER NOT NULL,
|
|
335
|
-
body TEXT NOT NULL,
|
|
336
|
-
raw TEXT,
|
|
337
|
-
PRIMARY KEY (session_id, seq)
|
|
338
|
-
) WITHOUT ROWID;
|
|
339
|
-
`,"","","",`
|
|
340
|
-
ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
|
|
341
|
-
ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
|
|
342
|
-
ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
|
|
343
|
-
CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
|
|
344
|
-
ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
|
|
345
|
-
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,
|
|
346
|
-
PRIMARY KEY (namespace, key));
|
|
347
|
-
CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
|
|
348
|
-
PRIMARY KEY (namespace, version));
|
|
349
|
-
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);
|
|
350
|
-
CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
|
|
351
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
352
|
-
END;
|
|
353
|
-
CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
|
|
354
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
|
|
355
|
-
END;
|
|
356
|
-
CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
|
|
357
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
|
|
358
|
-
END;
|
|
359
|
-
CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
|
|
360
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
361
|
-
END;
|
|
362
|
-
CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
|
|
363
|
-
INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
|
|
364
|
-
END;
|
|
365
|
-
CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
|
|
366
|
-
INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
|
|
367
|
-
END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
|
|
368
|
-
WHERE json_extract(body,'$.type')='compaction';
|
|
369
|
-
CREATE TABLE IF NOT EXISTS blobs (
|
|
370
|
-
hash TEXT PRIMARY KEY,
|
|
371
|
-
mime TEXT NOT NULL,
|
|
372
|
-
data BLOB NOT NULL
|
|
373
|
-
) WITHOUT ROWID;
|
|
374
|
-
CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`,"ALTER TABLE projects ADD COLUMN position INTEGER NOT NULL DEFAULT 0;","ALTER TABLE projects ADD COLUMN closed_at INTEGER;"];var NG=[20,50,100,200,400,800];function DG(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let c="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(c)}function hg(e){let o=0;while(!0)try{return e()}catch(i){let c=NG[o];if(c===void 0||!DG(i))throw i;o++,Bun.sleepSync(c)}}function U$(e,o){if(e!==":memory:")_G(LG(e),{recursive:!0});let i=new MG(e,{create:!0,strict:!0}),c=(g,y=!0)=>new Proxy(function(...b){return Reflect.apply(g,this,b)},{apply(b,E,S){_s();let w=o.length===0&&!i.inTransaction,R=y?Reflect.get(g,"immediate"):void 0,A=()=>{let C=[];o.push(C);let L=!1;try{let q=typeof R==="function"?Reflect.apply(R,g,S):Reflect.apply(b,E,S);return L=!0,q}finally{o.pop();let q=o.at(-1);if(L&&q)q.push(...C);else for(let X of C)if(L)X.commit();else X.rollback()}};return w?hg(A):A()},get(b,E){let S=Reflect.get(g,E);if(["deferred","immediate","exclusive"].includes(String(E))&&typeof S==="function")return c(S,!1);return S}}),p=new Proxy(i,{get(g,y){let b=Reflect.get(g,y,g);if(typeof b!=="function")return b;return(...E)=>{_s();let R=(y==="run"||y==="exec")&&o.length===0&&!i.inTransaction?hg(()=>Reflect.apply(b,g,E)):Reflect.apply(b,g,E);if(y==="transaction"&&typeof R==="function")return c(R,!0);if(y!=="query"&&y!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(A,C,L){let q=Reflect.get(A,C,A);if(typeof q!=="function")return q;return(...X)=>{_s();let J=(C==="run"||C==="get"||C==="all"||C==="values")&&o.length===0&&!i.inTransaction?hg(()=>Reflect.apply(q,A,X)):Reflect.apply(q,A,X);return J===A?L:J}}})}}});if(e!==":memory:")j$(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"),qG(p),p.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),p.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let g of["-wal","-shm"]){let y=e+g;if(OG(y))j$(y,384)}return p}function qG(e,o=fg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let c=i;c<o.length;c++)e.transaction(()=>{let p=o[c]??"",g=Array.isArray(p)?p:c>=4?FG(p):[p];for(let y of g)try{if(y.trim())e.run(y)}catch(b){if(!(b instanceof Error)||!/already exists|duplicate column name/i.test(b.message))throw b}e.run(`PRAGMA user_version = ${c+1}`)})()}function FG(e){let o=[],i=0,c=0,p=[],g=!1,y=0,b=(E)=>{let S=e.slice(i,E).trim();if(S)o.push(S);i=E+1,p=[],g=!1,y=0};while(c<e.length){let E=e[c];if(E==="'"||E==='"'||E==="`"||E==="["){let S=E==="["?"]":E;c++;while(c<e.length)if(e[c]===S)if(S!=="]"&&e[c+1]===S)c+=2;else break;else c++;c++;continue}if(E==="-"&&e[c+1]==="-"){let S=e.indexOf(`
|
|
375
|
-
`,c);c=S===-1?e.length:S+1;continue}if(E==="/"&&e[c+1]==="*"){let S=e.indexOf("*/",c+2);c=S===-1?e.length:S+2;continue}if(/[A-Za-z_]/.test(E)){let S=c+1;while(S<e.length&&/[A-Za-z0-9_$]/.test(e[S]))S++;let w=e.slice(c,S).toUpperCase();if(p.length<3)p.push(w),g=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(g){if(w==="BEGIN"||w==="CASE"&&y>0)y++;else if(w==="END"&&y>0)y--}c=S;continue}if(E===";"&&y===0)b(c);c++}return b(e.length),o}var Fl=({position:e,closed_at:o,...i})=>({...i,closedAt:o??null}),jl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var gg=new Set(["user","run","extension","notice_pending","compaction"]);class Ul{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=U$(e,this.entryTransactions),this.blobs={put:(o,i,c)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,i,c)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Fl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Fl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Fl(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[i,c]of e.entries())o.run(i,c)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){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(jl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(jl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(jl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,i){this.insertSessionWithRecords(o,or(this.records(e),i))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:c,raw:p}of o){let{seq:g,time:y,...b}=c,E=b,S=ql(E,this.blobs),w=p===void 0?null:JSON.stringify(Jc(E,p));i.run(e.id,g,y,JSON.stringify(S),w)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let c of e)i.run(o,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.invalidateEntryCache(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,o,i,c){_s();let p=this.plugins,g=p?.pinEntry(i),y;try{return y=this.db.transaction(()=>{let b=Math.max(o??0,this.lastSeq(e)+1),S=(g&&p?p.beforeEntry(g,i,e,b):void 0)??i,w=JSON.stringify(S),R=g?JSON.parse(w):S,A={...R,seq:b,time:Date.now()},C=ql(R,this.blobs),L=C===R&&!g?w:JSON.stringify(C),q=c===void 0?null:JSON.stringify(Jc(R,c));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,b,A.time,L,q),A.type==="user"&&!(("notices"in A)&&A.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(A.time,e);return this.cacheAppended(e,A,L),A})(),y}finally{if(g&&p){let b={commit:()=>p.finishEntry(g,e,y),rollback:()=>p.finishEntry(g,e)},E=this.entryTransactions.at(-1);if(E)E.push(b);else b.commit()}}}setEntryRaw(e,o,i){let c=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!c)throw Error("pending message entry is missing or already completed");let p=ji(JSON.parse(c.body),this.blobs),g=Jc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(g),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,i,c=!0){let p=i?.every((y)=>gg.has(y))?this.cachedEntries(e):void 0;if(p&&i)return p.filter((b)=>b.seq>o&&i.includes(b.type)).map((b)=>({...c?ji(b,this.blobs):b}));return(i?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...i):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((y)=>({...ji(JSON.parse(y.body),c?this.blobs:void 0),seq:y.seq,time:y.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let i=[...gg],c=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...i).map((p)=>({...JSON.parse(p.body),seq:p.seq,time:p.time}));return this.smallEntries.set(e,c),c}cacheAppended(e,o,i){let c=this.smallEntries.get(e);if(!c||!gg.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}c.push({...JSON.parse(i),seq:o.seq,time:o.time})}entriesRange(e,o,i=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,i).map((c)=>({...ji(JSON.parse(c.body),this.blobs),seq:c.seq,time:c.time}))}alignToUser(e,o){if(o<=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,o)?.seq??1}alignToTurnEnd(e,o){let i=this.lastSeq(e),c=(E)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,E),p=c(o),g=p?.type==="run"&&p.state==="start"?o+1:o;if(g>=i)return i;let y=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,g,g);if(!y)return i;if(y.end)return y.seq;let b=c(y.seq-1);return b?.type==="run"&&b.state==="start"&&y.seq-1>g?y.seq-2:y.seq-1}entriesAround(e,o,i,c){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let g=Math.min(Math.max(1,o),p),y=this.alignToUser(e,Math.max(1,g-i)),b=this.alignToTurnEnd(e,Math.min(p,g+c));return this.window(e,y,b,p)}entriesFrom(e,o,i){let c=this.lastSeq(e),p=Math.max(1,o);if(p>c)return{entries:[],from:p,to:c,hasBefore:c>0,hasAfter:!1};let g=this.alignToTurnEnd(e,Math.min(c,p+i-1));return this.window(e,p,g,c)}window(e,o,i,c){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,i+1),from:o,to:i,hasBefore:p!==null,hasAfter:i<c}}replayStart(e,o,i){let c=this.lastSeq(e),p=this.lastEntry(e,"compaction"),g=p?.type==="compaction"?p.through+1:1,y=Math.max(1,c-i+1,Math.min(g,c-o+1));return this.alignToUser(e,y)}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((i)=>{let c=ji(JSON.parse(i.body),this.blobs);return{entry:{...c,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:dg(c,JSON.parse(i.raw))}}})}lastEntry(e,o){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,o);return i?{...ji(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,o){let i=this.truncationEpoch(e),c=o;if(this.plugins){let p=this.plugins.pin();try{let g=await p.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(g===null)return!1;o={...g,dedupeKey:c.dedupeKey,wake:c.wake&&g.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,0,["user","notice_pending"],!1).some((b)=>b.type==="notice_pending"&&b.notice.dedupeKey===o.dedupeKey||b.type==="user"&&b.notices?.some((E)=>E.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,o,["user","extension","notice_pending"],!1),c=new Set;for(let g of i)if(g.type==="user"&&g.notices)for(let y of g.notices)c.add(y.dedupeKey);else if(g.type==="extension"&&g.namespace==="basalt.notice"&&g.kind==="discarded"&&g.payload&&typeof g.payload==="object"&&"dedupeKey"in g.payload&&typeof g.payload.dedupeKey==="string")c.add(g.payload.dedupeKey);let p=[];for(let g of i)if(g.type==="notice_pending"&&!c.has(g.notice.dedupeKey))p.push(g.notice);return p}}function ne(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as jG,readdirSync as G$,statSync as K$}from"fs";import{join as H$}from"path";function Qc(e){try{return K$(e).size}catch{return 0}}function W$(e){try{return Math.round(K$(e).mtimeMs)}catch{return}}function z$(e){let o=0,i=0;try{let c=G$(e,{withFileTypes:!0});for(let p of c){let g=H$(e,p.name);if(p.isDirectory()){let y=z$(g);o+=y.bytes,i+=y.files}else if(p.isFile())o+=Qc(g),i+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:i}}function UG(e){if(!jG(e))return[];try{return G$(e,{withFileTypes:!0}).flatMap((o)=>{let i=H$(BG(e),o.name),c=W$(i);if(o.isDirectory()){let p=z$(i);return[{name:o.name,kind:"directory",bytes:p.bytes,files:p.files,...c!==void 0?{modified:c}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Qc(i),...c!==void 0?{modified:c}:{}}];return[]}).sort((o,i)=>i.bytes-o.bytes||o.name.localeCompare(i.name))}catch{return[]}}function BG(e){return e}function Qs(e,o){let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return 0;let c=Object.values(i)[0];return typeof c==="number"?c:0}function B$(e,o){try{let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return;let c=Object.values(i)[0];return c!==void 0&&c!==null?String(c):void 0}catch{return}}var GG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},KG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function HG(e){let o=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 g of c)i.set(g.name,g.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let g of p){let y=i.get(g.name)??g.name;if(y.startsWith("sqlite_autoindex_")){let E=y.slice(17),S=E.lastIndexOf("_");if(S>0)y=E.slice(0,S)}let b=o.get(y)??{bytes:0,pages:0};o.set(y,{bytes:b.bytes+(Number(g.bytes)||0),pages:b.pages+(Number(g.pages)||0)})}}catch{}return o}function WG(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
|
|
376
|
-
count(*) AS total,
|
|
377
|
-
sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
|
|
378
|
-
sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
|
|
379
|
-
sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
|
|
380
|
-
sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
|
|
381
|
-
FROM sessions`).get(),c=e.db.query(`SELECT
|
|
382
|
-
count(*) AS total,
|
|
383
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
384
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
|
|
385
|
-
min(time) AS oldest_time,
|
|
386
|
-
max(time) AS newest_time
|
|
387
|
-
FROM entries`).get(),g=e.db.query(`SELECT
|
|
388
|
-
coalesce(json_extract(body, '$.type'), 'unknown') AS type,
|
|
389
|
-
count(*) AS count,
|
|
390
|
-
coalesce(sum(octet_length(body)), 0) AS body_bytes,
|
|
391
|
-
coalesce(sum(octet_length(raw)), 0) AS raw_bytes
|
|
392
|
-
FROM entries
|
|
393
|
-
GROUP BY type
|
|
394
|
-
ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((E)=>({type:String(E.type||"unknown"),count:Number(E.count)||0,bodyBytes:Number(E.body_bytes)||0,rawBytes:Number(E.raw_bytes)||0})),y=g.find((E)=>E.type==="compaction")?.count??0,b=[];try{let E=new Map,S=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let A of S)E.set(A.namespace,Number(A.max_ver)||0);let w=e.db.query(`SELECT
|
|
395
|
-
namespace,
|
|
396
|
-
count(*) AS keys,
|
|
397
|
-
coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
|
|
398
|
-
FROM plugin_kv
|
|
399
|
-
GROUP BY namespace
|
|
400
|
-
ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let A of w){R.add(A.namespace);let C=E.get(A.namespace);b.push({namespace:A.namespace,keys:Number(A.keys)||0,bytes:Number(A.bytes)||0,...C!==void 0?{migrationVersion:C}:{}})}for(let[A,C]of E.entries())if(!R.has(A))b.push({namespace:A,keys:0,bytes:0,migrationVersion:C})}catch{}return{projectCount:o,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(c?.total)||0,totalBodyBytes:Number(c?.body_bytes)||0,totalRawBytes:Number(c?.raw_bytes)||0,compactionCount:y,...c?.oldest_time?{oldestEntryTime:Number(c.oldest_time)}:{},...c?.newest_time?{newestEntryTime:Number(c.newest_time)}:{},entryTypes:g,pluginNamespaces:b}}function Bl(e,o){let i=Qs(e,"page_size"),c=Qs(e,"page_count"),p=Qs(e,"freelist_count"),g=e.db.query("PRAGMA journal_mode").get(),y=e.db.query("SELECT sqlite_version() AS v").get(),b=Qs(e,"synchronous"),E=Qs(e,"auto_vacuum"),S=Qs(e,"cache_size"),w=S<0?Math.abs(S)*1024:S*i,R=Qs(e,"foreign_keys")===1,A=Qs(e,"busy_timeout"),C=B$(e,"encoding")??"UTF-8",L=B$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?W$(e.path):void 0,X=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),j=HG(e),V=UG(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((J,ee)=>J+ee.bytes,0),database:{size:Qc(e.path),walSize:Qc(`${e.path}-wal`),shmSize:Qc(`${e.path}-shm`),sqliteVersion:y?.v??"unknown",journalMode:g?.journal_mode??"unknown",synchronous:GG[b]??String(b),foreignKeys:R,busyTimeout:A,encoding:C,autoVacuum:KG[E]??String(E),cacheSizeBytes:w,pageSize:i,pageCount:c,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Qs(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:L},analytics:WG(e),entries:V,tables:X.map(({name:J,sql:ee})=>{let ae=J.replaceAll('"','""'),K=e.db.query(`SELECT count(*) AS count FROM "${ae}"`).get().count,ue=e.db.query(`PRAGMA table_info("${ae}")`).all().map((se)=>se.name),he=e.db.query(`PRAGMA index_list("${ae}")`).all().length,_e=Boolean(ee&&/WITHOUT\s+ROWID/i.test(ee)),Ee=j.get(J);return{name:J,rows:K,...Ee?{bytes:Ee.bytes,pages:Ee.pages}:{},indexes:he,columns:ue,withoutRowid:_e}})}}function zG(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),c=new Set;for(let g of i)for(let y of g.body.matchAll(/@blob:([0-9a-f]{64})/g)){let b=y[1];if(b)c.add(b)}let p=[];for(let g of o)if(!c.has(g.hash))p.push(g.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let g=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let y of p)g.run(y)})()}catch{return 0}return p.length}function V$(e,o,i){let c=Bl(e,o);if(i.vacuum)F$(e.db),e.invalidateEntryCache(),zG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:c,after:Bl(e,o)}}var VG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Gl{plugins;builtinNames;registered=new Map;constructor(e,o){this.plugins=e;this.builtinNames=o}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let o=e.name.trim().toLowerCase();if(!o)throw Error("Tool name cannot be empty");if(VG.has(o))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(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function J$(e,o){let i=Jr(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function Q$(e,o){let c=(await e.options.models.getAvailable().catch(()=>[])).map((g)=>({...J$(rt(g),g),available:!0})),p=new Set(c.map((g)=>g.id));for(let g of[o,...e.list(!0,{archive:"all"}).map((y)=>y.model)]){if(p.has(g))continue;let y=Sn(e.options.models,g);if(!y)continue;p.add(g),c.push({...J$(g,y),available:!1})}return{models:c}}function X$(e,o){if(typeof o!=="string"||!Sn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as JG,statSync as QG}from"fs";import{basename as XG,resolve as YG}from"path";class yg{runtime;sessions;emit;arm;constructor(e,o,i,c){this.runtime=e;this.sessions=o;this.emit=i;this.arm=c}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new f("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=YG(e.directory.trim());if(!JG(o)||!QG(o).isDirectory())throw new t(`${o} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(o);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let c=Date.now(),p={id:ne("p"),name:e.name?.trim()||XG(o)||o,directory:o,instructions:e.instructions??"",created:c,updated:c,closedAt:null};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,o){let c={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(c);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:c}),c}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((p)=>p.id)),i=new Set(e);if(!(i.size===e.length&&i.size===o.size&&e.every((p)=>o.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new ie("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let p of i)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as IK,readFileSync as bK}from"fs";import{homedir as EK}from"os";import{join as yu}from"path";var ov=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),ZG={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"]},eK=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),bg={'"':['"'],"\u201C":["\u201D",'"']},xg=(e)=>e!==void 0&&/\s/.test(e),sv=(e)=>[...new Set(e)],Xc=(e)=>[...e].length;var tK={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function rK(e,o){let i=e.trim().toLowerCase(),c=new Date(o),p=c.getFullYear(),g=c.getMonth(),y=c.getDate();if(i==="today")return{start:new Date(p,g,y).getTime(),end:new Date(p,g,y+1).getTime()};if(i==="yesterday")return{start:new Date(p,g,y-1).getTime(),end:new Date(p,g,y).getTime()};let b=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(b)return{start:o-Number(b[1])*tK[b[2]]};if(/^\d{4}$/.test(i))return{start:new Date(Number(i),0,1).getTime(),end:new Date(Number(i)+1,0,1).getTime()};let E=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!E)return null;let S=Number(E[1]),w=Number(E[3]);if(w<1||w>12)return null;if(E[4]===void 0){if(E[5]!==void 0)return null;return{start:new Date(S,w-1,1).getTime(),end:new Date(S,w,1).getTime()}}let R=Number(E[4]),A=Number(E[5]??0),C=Number(E[6]??0),L=Number(E[7]??0);if(A>23||C>59||L>59)return null;let q=new Date(S,w-1,R,A,C,L);if(q.getMonth()!==w-1||q.getDate()!==R)return null;if(E[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(S,w-1,R+1).getTime()}}var nK=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Eg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),Sg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function Ig(e,o,i,c,p,g){let y=i.trim(),b=(S,w)=>e.diagnostics.push({code:S,message:w,filter:o});if(!y)return b("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(c&&o!=="is")return b("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let E=p?[y]:y.split(",").map((S)=>S.trim()).filter(Boolean);switch(o){case"in":case"project":for(let S of E){let w=S.toLowerCase();if(o==="in"&&w==="this")e.currentSession=!0;else if(o==="in"&&w==="title")e.fields.push("title");else e.projectID.push(S)}return;case"session":for(let S of E)if(S.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(S);return;case"from":case"role":for(let S of E){let w=ZG[S.toLowerCase()];if(w)e.fields.push(...w);else b("bad_filter_value",`${o}:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...E);return;case"model":e.model.push(...E);return;case"is":for(let S of E){let w=S.toLowerCase();if(w==="error")e.isError=!c;else if(w==="archived")e.archived=!c;else if(w==="compacted")e.compacted=!c;else b("bad_filter_value",`is:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let S=rK(y,g);if(!S)return b("bad_filter_value",`${o}:${y} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=Eg(e.after,S.start);else if(o==="before")e.before=Sg(e.before,S.start);else if(e.after=Eg(e.after,S.start),S.end!==void 0)e.before=Sg(e.before,S.end)}}}function oK(e,o){let i={},c=(L,q)=>{let X=sv([...L??[],...q]);return X.length?X:void 0},p=c(e?.projectID,o.projectID),g=c(e?.sessionID,o.sessionID),y=c(e?.fields,o.fields),b=c(e?.tools,o.tools),E=c(e?.model,o.model);if(p)i.projectID=p;if(g)i.sessionID=g;if(y)i.fields=y;if(b)i.tools=b;if(E)i.model=E;let S=o.isError??e?.isError,w=o.archived??e?.archived,R=o.compacted??e?.compacted;if(S!==void 0)i.isError=S;if(w!==void 0)i.archived=w;if(R!==void 0)i.compacted=R;let A=Eg(e?.after,o.after),C=Sg(e?.before,o.before);if(A!==void 0)i.after=A;if(C!==void 0)i.before=C;if(A!==void 0&&C!==void 0&&A>=C)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function Y$(e,o){let i=bg[e[o]]??['"'],c="",p=o+1;while(p<e.length){let g=e[p],y=e[p+1];if(g==="\\"&&y!==void 0&&(y==="\\"||y==='"'||y==="\u201C"||y==="\u201D")){c+=y,p+=2;continue}if(i.includes(g))return{text:c,next:p+1,closed:!0};c+=g,p++}return{text:c,next:p,closed:!1}}function Z$(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let i=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(i.length!==e.length-1)return;let c=i.toLowerCase();return ov.has(c)?c:void 0}function ev(e,o,i){let c=e==="word"&&!i&&Xc(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:i,fuzzy:c}}function sK(e,o){let i=[],c=e.length,p=0;while(p<c){if(xg(e[p])){p++;continue}let g=!1;if(e[p]==="-"){if(p+1>=c||xg(e[p+1])){p++;continue}g=!0,p++}if(bg[e[p]]){let C=Y$(e,p);if(p=C.next,!C.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let L=C.text.trim();if(L)i.push({kind:"term",negated:g,term:ev("phrase",L,!1)});continue}let y=[],b;while(p<c&&!xg(e[p])){let C=e[p],L=e[p+1];if(C==="\\"&&L!==void 0&&eK.has(L)){y.push({c:L,esc:!0}),p+=2;continue}let q=bg[C]?Z$(y):void 0;if(q){let X=Y$(e,p);if(p=X.next,!X.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});b={key:q,value:X.text,quoted:!0};break}y.push({c:C,esc:!1}),p++}if(b){i.push({kind:"filter",negated:g,...b});continue}let E=y.findIndex((C,L)=>L>0&&!C.esc&&(C.c===":"||C.c==="\uFF1A")),S=E>0?Z$(y.slice(0,E+1)):void 0;if(S){i.push({kind:"filter",negated:g,key:S,value:y.slice(E+1).map((C)=>C.c).join(""),quoted:!1});continue}if(!g&&y.length===2&&y.every((C)=>!C.esc)&&y[0]?.c==="O"&&y[1]?.c==="R"){i.push({kind:"or"});continue}let w=y[y.length-1],R=y.length>1&&w!==void 0&&!w.esc&&w.c==="*",A=(R?y.slice(0,-1):y).map((C)=>C.c).join("");if(A)i.push({kind:"term",negated:g,term:ev("word",A,R)})}return i}var iK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function tv(e){let o=[];return{rest:e.replace(iK,(c,p,g,y,b)=>{let E=y.toLowerCase();if(!ov.has(E))return c;let S=b.startsWith('"')&&b.length>=2;return o.push({key:E,value:S?b.slice(1,-1).replace(/\\(["\\])/g,"$1"):b,negated:g==="-",quoted:S}),p}).trim(),filters:o}}var rv={n:`
|
|
401
|
-
`,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function aK(e){let o=[...e],i=0,c=(w)=>{let R=o.slice(i,i+w).join("");if(R.length!==w||!/^[0-9a-fA-F]+$/.test(R))return;return i+=w,String.fromCodePoint(Number.parseInt(R,16))},p=()=>{let w=o[i++];if(w===void 0)return{kind:"lit",ch:"\\"};if(w in rv)return{kind:"lit",ch:rv[w]};if("dDwWsS".includes(w))return{kind:"any"};if(w==="b"||w==="B")return{kind:"zero"};if(w>="1"&&w<="9"){while(o[i]!==void 0&&/\d/.test(o[i]))i++;return{kind:"any"}}if(w==="k"||w==="p"||w==="P"){let R=o[i];if(R==="<"||R==="{"){let A=R==="<"?">":"}",C=o.indexOf(A,i);i=C<0?o.length:C+1}return{kind:"any"}}if(w==="c")return i++,{kind:"any"};if(w==="x"){let R=c(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(w==="u"){if(o[i]==="{"){let A=o.indexOf("}",i),C=A<0?"":o.slice(i+1,A).join("");if(/^[0-9a-fA-F]{1,6}$/.test(C)&&Number.parseInt(C,16)<=1114111)return i=A+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(C,16))};return{kind:"lit",ch:"u"}}let R=c(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:w}},g=()=>{if(o[i]==="^")i++;while(i<o.length&&o[i]!=="]")i+=o[i]==="\\"?2:1;return i++,{kind:"any"}},y=()=>{let w="capture";if(o[i]==="?"){let A=o[i+1],C=o[i+2];if(A===":")w="plain",i+=2;else if(A==="="||A==="!")w="look",i+=2;else if(A==="<"&&(C==="="||C==="!"))w="look",i+=3;else if(A==="<"){let L=o.indexOf(">",i);i=L<0?o.length:L+1}else{w="opaque";while(i<o.length&&o[i]!==":"&&o[i]!==")")i++;if(o[i]===":")i++}}let R=S();if(o[i]===")")i++;if(w==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:w==="opaque"}},b=()=>{let w=o[i],R=1,A=!0;if(w==="*"||w==="?")R=0,i++;else if(w==="+")i++;else if(w==="{"){let C=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(i,i+24).join(""));if(!C)return{quantified:!1,min:1};R=Number(C[1]),i+=C[0].length}else return{quantified:!1,min:1};if(o[i]==="?")i++;return{quantified:A,min:R}},E=()=>{let w=[];while(i<o.length){let R=o[i];if(R==="|"||R===")")break;i++;let A;if(R==="(")A=y();else if(R==="[")A=g();else if(R==="\\")A=p();else if(R===".")A={kind:"any"};else if(R==="^"||R==="$")A={kind:"zero"};else if(R==="*"||R==="+"||R==="?")A={kind:"zero"};else A={kind:"lit",ch:R};w.push({atom:A,...b()})}return w};function S(){let w=[E()];while(o[i]==="|")i++,w.push(E());return w}return S()}function nv(e){let o=[],i="",c=()=>{if(i)o.push([i]);i=""},p=(g)=>{for(let y of g){let b=y.atom;if(b.kind==="lit")if(y.min>=1){if(i+=b.ch,y.quantified)c()}else c();else if(b.kind==="group"&&!b.opaque&&y.min>=1)if(b.alts.length===1&&!y.quantified)p(b.alts[0]);else c(),o.push(...iv(b.alts));else c()}};return p(e),c(),o}function iv(e){if(e.length===1)return nv(e[0]);let o=[];for(let i of e){let c=nv(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!c.length)return[];o.push(c.reduce((p,g)=>Xc(g)>Xc(p)?g:p))}return[sv(o)]}var uK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function cK(e){return!/^\s*$/.test(e)&&(Xc(e)>=2||uK.test(e))}function mK(e){let o;try{o=iv(aK(e))}catch{return[]}let i=o.filter((E)=>E.every(cK)),c=i.filter((E)=>E.length===1).map((E)=>E[0]),p=i.filter((E)=>{if(E.length!==1)return!0;let S=E[0];return!c.some((w)=>w!==S&&w.includes(S))}),g=new Set,y=p.filter((E)=>{let S=JSON.stringify(E);if(g.has(S))return!1;return g.add(S),!0}),b=(E)=>Math.min(...E.map(Xc));return y.sort((E,S)=>b(S)-b(E))}function pK(e){let o=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(o)}function lK(e,o){let i=`m${o?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(c){let p=c instanceof Error?c.message:String(c),g="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))g="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))g="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))g="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))g="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${g}`}}}function Kl(e,o={}){let i=o.now??Date.now(),c=e.q??"",p=nK(),g=p.diagnostics,y,b=[];if(e.mode==="regex"){let q=tv(c);for(let X of q.filters)Ig(p,X.key,X.value,X.negated,X.quoted,i);y=q.rest}else{let q=tv(c),X=/^\/([\s\S]+)\/$/.exec(q.rest);if(X){for(let j of q.filters)Ig(p,j.key,j.value,j.negated,j.quoted,i);y=X[1]}else{b=[{include:[],exclude:[]}];for(let j of sK(c,g)){let V=b[b.length-1];if(j.kind==="or")b.push({include:[],exclude:[]});else if(j.kind==="filter")Ig(p,j.key,j.value,j.negated,j.quoted,i);else(j.negated?V.exclude:V.include).push(j.term)}b=b.filter((j)=>j.include.length||j.exclude.length)}}let E=b.flatMap((q)=>[...q.include,...q.exclude]),S=y!==void 0?pK(y):E.some((q)=>/\p{Lu}/u.test(q.text)),w=e.caseSensitive??S,R=e.caseSensitive===void 0&&S,A,C;if(y){let q=lK(y,w);if("message"in q)C={code:"bad_regex",message:q.message};else{let X=mK(y);A={source:y,flags:q.flags,literals:X,deepScan:X.length===0}}}let L=oK(e.filters,p);return{mode:y!==void 0?"regex":"text",branches:b,...A?{regex:A}:{},filters:L,currentSession:p.currentSession,caseSensitive:w,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:b.some((q)=>q.include.some((X)=>X.fuzzy)),hasPositive:A!==void 0||b.some((q)=>q.include.length>0),hasFilters:Object.keys(L).length>0||p.currentSession,...C?{error:C}:{},diagnostics:g}}var Tg={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},av=new WeakMap;function uv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,i=av.get(e);if(i?.version===o)return i.terms;let c=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return av.set(e,{version:o,terms:c}),c}var wg=32,dK=1024,Yc=(e)=>`"${e.replaceAll('"','""')}"`;function fK(e,o){let i=Array.from({length:o.length+1},(c,p)=>p);for(let c=0;c<e.length;c++){let p=[c+1];for(let g=0;g<o.length;g++)p.push(Math.min((p[g]??0)+1,(i[g+1]??0)+1,(i[g]??0)+Number(e[c]!==o[g])));i=p}return i[o.length]??e.length}function Rg(e,o){let i=gt(o.trim());if(!i||i.length>64)return[];let c=uv(e),p=c.filter((b)=>b.t.startsWith(i)).slice(0,8).map((b)=>b.t);if(p.length>=8||i.length<4)return p;let g=i.length>=8?2:1,y=[];for(let b of c){if(Math.abs(b.t.length-i.length)>g)continue;if(fK(i,b.t)<=g)y.push(b.t);if(y.length>=8)break}return[...new Set([...p,...y])].slice(0,8)}function cv(e,o){let i=!1,c=[],p=[],g=o.filters,y=(X,j)=>{if(!j?.length)return;p.push(`${X} IN (${j.map(()=>"?").join(",")})`),c.push(...j)};if(y("s.project_id",g.projectID),g.sessionID?.length){p.push(`(${g.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let X of g.sessionID)c.push(X,X)}if(g.archived!==void 0)p.push(`s.archived_at IS ${g.archived?"NOT ":""}NULL`);let b=p.length?p.join(" AND "):"1",E=[...c];if(y("r.kind",g.fields?.map((X)=>Ne[X])),y("r.tool",g.tools),g.model?.length){p.push(`(${g.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let X of g.model)c.push(X,X)}if(g.isError!==void 0)p.push("r.err = ?"),c.push(Number(g.isError));if(g.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
|
|
402
|
-
SELECT max(json_extract(body,'$.through')) FROM store.entries
|
|
403
|
-
WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
|
|
404
|
-
),0)) = ?`),c.push(Number(g.compacted));if(g.after!==void 0)p.push("r.time >= ?"),c.push(g.after);if(g.before!==void 0)p.push("r.time < ?"),c.push(g.before);let S=e.query("SELECT v FROM meta WHERE k='layout'").get(),w=S&&JSON.parse(S.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),A=(X)=>{let j=(ee)=>{let ae=gt(ee);if(!X&&w){if([...ae].length<3){let se=[...ae].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ae,`${ae}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ae);if([...ae].length===1&&se.length>wg)se.length=wg,i=!0;if(!se.length)return Yc("__basalt_no_short_match__");return`(${se.map((ce)=>Yc(ce.term)).join(" OR ")})`}return Yc(ae)}let K=/^[\p{Script=Latin}\p{N}]+$/u.test(ee)?[ae]:Vo(ee),ue=K.filter((se)=>!/^[a-z0-9]{1,2}$/.test(se)),he=ue.length?ue:K;if(!he.length){R=!0;return}let _e=he.map((se,ce)=>{let Fe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(se),It=he.length>2&&ce>0&&ce<he.length-1;if(Fe||It){let Ue=e.query("SELECT n FROM term WHERE t=?").get(se)?.n??0;return{expression:Yc(se),frequency:Ue}}let Je=[se],Yt=0;for(let Ue of uv(e)){if(!Ue.t.includes(se))continue;if(Yt+=Ue.n,Ue.t!==se)Je.push(Ue.t);if(Je.length>=wg){i=!0;break}}return{expression:`(${Je.map(Yc).join(" OR ")})`,frequency:Yt}});return _e.sort((se,ce)=>se.frequency-ce.frequency),`(${_e.slice(0,(_e[0]?.frequency??1/0)<=dK?1:2).map((se)=>se.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((ee)=>ee.include.map((ae)=>ae.text));if(o.regex){let ee=V.map((ae)=>ae.map(j));if(ee.some((ae)=>ae.some((K)=>!K)))return;return ee.map((ae)=>`(${ae.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((ee)=>{let ae=ee.filter((K)=>!/^[a-z0-9]{1,2}$/i.test(K));return(ae.length?ae:ee).map(j)});if(J.some((ee)=>!ee.length||ee.some((ae)=>!ae)))return;return J.map((ee)=>`(${ee.join(" AND ")})`).join(" OR ")||void 0},C=A(!1),L=A(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:C,out:L,scan:R,where:p.length?p.join(" AND "):"1",bindings:c,forks:q,sessionWhere:b,sessionBindings:E,partial:i,candidateLimit:o.branches.some((X)=>X.include.length>0&&X.include.every((j)=>[...j.text].length<2))?512:void 0}}function mv(e){let o=1/0,i=-1/0;for(let c of e)o=Math.min(o,c.relevance),i=Math.max(i,c.relevance);return e.map((c)=>({...c,relevance:o===i?-1:-(0.5+0.5*(i-c.relevance)/(i-o))}))}function Hl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(Tg).map(([i,c])=>`WHEN ${Ne[i]} THEN ${c}`).join(" ")} ELSE 1 END) *
|
|
405
|
-
(0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function pv(e,o,i,c){let p=Math.max(0,c-i)/86400000;return Math.max(0.000000001,-e)*Tg[o]*(0.3+0.7/(1+p/30))}function kg(e,o){return e.sort((i,c)=>(o==="best"?c.score-i.score:0)||(o==="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 Cg=512;function lv(e,o,i){let c=performance.now(),p=o.partial;Pg(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[g,y]of[["fts",o.msg],["fts_out",o.out]]){if(!y)continue;let b=o.candidateLimit??2000,E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
|
|
406
|
-
ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(y,o.candidateLimit?b+1:b);if(o.candidateLimit&&E.length>b)E.length=b,p=!0;else if(!o.candidateLimit&&E.length===b){let w=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
|
|
407
|
-
AND rowid NOT IN (SELECT value FROM json_each(?))`).all(y,JSON.stringify(E.map((R)=>R.doc)));for(let R of w)E.push(R)}let S=mv(E);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
|
|
408
|
-
FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(S))}return i?.("match",performance.now()-c),p}function dv(e,o,i,c,p){let g=performance.now();if(o.candidateLimit){let b=e.query(`
|
|
409
|
-
SELECT r.session_id,r.seq,${Hl(c)} AS score
|
|
410
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
411
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
412
|
-
WHERE ${o.where} LIMIT ${o.candidateLimit+1}
|
|
413
|
-
`).all(...o.bindings);if(b.length>o.candidateLimit)b.length=o.candidateLimit,o.partial=!0;let E=new Map;for(let S of b){let w=i?S.seq:0,R=JSON.stringify([S.session_id,w]),A=E.get(R);if(!A||S.score>A.score)E.set(R,{...S,seq:w})}return p?.("filter",performance.now()-g),[...E.values()].sort((S,w)=>w.score-S.score||(S.session_id<w.session_id?-1:Number(S.session_id>w.session_id))||w.seq-S.seq)}let y=e.query(`
|
|
414
|
-
SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Hl(c)}) AS score
|
|
415
|
-
FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
|
|
416
|
-
${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
417
|
-
WHERE ${o.where}
|
|
418
|
-
GROUP BY r.session_id${i?",r.seq":""}
|
|
419
|
-
ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
|
|
420
|
-
`).all(...o.bindings);return p?.("filter",performance.now()-g),y}var fv=new WeakMap,hK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
|
|
421
|
-
SELECT id,forked_from_id,forked_from_seq FROM store.sessions
|
|
422
|
-
WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
|
|
423
|
-
UNION
|
|
424
|
-
SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
|
|
425
|
-
FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
|
|
426
|
-
WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
|
|
427
|
-
)`;function Pg(e,o){if(!o.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${hK} 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();fv.set(e,new Map(i.map((c)=>[c.ancestor,c.through])))}function Ag(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
|
|
428
|
-
SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
|
|
429
|
-
JOIN store.sessions ps ON ps.id=pr.session_id
|
|
430
|
-
WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
|
|
431
|
-
AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
|
|
432
|
-
AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
|
|
433
|
-
SELECT 1 FROM store.entries original JOIN store.entries copied
|
|
434
|
-
ON copied.session_id=r.session_id AND copied.seq=r.seq
|
|
435
|
-
WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
|
|
436
|
-
))
|
|
437
|
-
))`}function hv(e,o,i,c,p){let g=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let y=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,b=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
|
|
438
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${y>4000?"INDEXED BY ref_time":""}
|
|
439
|
-
${b} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${Ag(o)}
|
|
440
|
-
ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${c} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],i);let E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(E===c){let S=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(S)e.query(`
|
|
441
|
-
INSERT INTO temp.search_window SELECT r.* FROM ref r ${b}
|
|
442
|
-
WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
|
|
443
|
-
AND ${o.where} AND ${Ag(o)} AND NOT EXISTS (
|
|
444
|
-
SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
|
|
445
|
-
)`).run(S.session_id,S.seq,...o.bindings,...o.forks?o.bindings:[]),E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-g),E}function gv(e,o,i,c,p,g,y){let b=performance.now(),E=o.group==="none",S=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",w=e.query(`
|
|
446
|
-
SELECT r.session_id,${E?"r.seq":"0"} AS seq,
|
|
447
|
-
max(${Hl(p)}) AS relevance,max(r.time) AS time
|
|
448
|
-
FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
|
|
449
|
-
WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
|
|
450
|
-
GROUP BY r.session_id${E?",r.seq":""}
|
|
451
|
-
ORDER BY ${S},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(g),c,i);return y?.("group",performance.now()-b),w}function yv(e,o,i,c,p,g){let y=performance.now(),b=p?o:{...o,forks:!1},E=e.query(`
|
|
452
|
-
SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
|
|
453
|
-
${b.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
|
|
454
|
-
WHERE r.session_id=? ${c?"AND r.seq=?":""}
|
|
455
|
-
AND ${o.where} AND ${Ag(b)}
|
|
456
|
-
${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(i.session_id,...c?[i.seq]:[],...o.bindings,...b.forks?o.bindings:[]);return g?.("filter",performance.now()-y),E}function $g(e,o,i,c){if(!o.forks)return[];let p=fv.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
|
|
457
|
-
SELECT DISTINCT r.session_id,s.title,e.body
|
|
458
|
-
FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
|
|
459
|
-
CROSS JOIN ref r ON r.session_id=l.child
|
|
460
|
-
JOIN store.sessions s ON s.id=r.session_id
|
|
461
|
-
LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
|
|
462
|
-
WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...o.bindings).filter((g)=>{if(i.seq===0)return g.title===c;if(!g.body)return!1;let y=JSON.parse(g.body);return Ke(y,!0).some((b)=>b.part===i.part&&b.kind===Zr[i.kind]&&b.text===c)}).map((g)=>g.session_id)}function gK(e,o){let i=o?e:gt(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let c="",p=[],g=[],y=0;for(let b of e){let E=o?b:gt(b);c+=E;for(let S=0;S<E.length;S++)p.push(y),g.push(y+b.length);y+=b.length}return{normalized:c,starts:p,ends:g}}function Wl(e,o){if(o.regex){let E=new RegExp(o.regex.source,`${o.regex.flags}g`),S=[];for(let w of e.matchAll(E)){if(o.wholeWord&&!xv(e,w.index,w.index+w[0].length))continue;S.push([w.index,w.index+w[0].length])}return S.length?S:void 0}let{normalized:i,starts:c,ends:p}=gK(e,o.caseSensitive),g=(E)=>{let S=o.caseSensitive?E.text:gt(E.text),w=[],R=i.indexOf(S);while(R>=0&&S){let A=c?c[R]:R,C=p?p[R+S.length-1]:R+S.length,L=A===0||A!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(A-1,A))||/[a-z0-9][A-Z]/.test(e.slice(A-1,A+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(E.text));if(A!==void 0&&C!==void 0&&(!E.prefix||L)&&(!o.wholeWord||xv(e,A,C)))w.push([A,C]);R=i.indexOf(S,R+Math.max(1,S.length))}return w};if(!o.branches.length)return[];let y=[],b=!1;for(let E of o.branches){if(E.exclude.some((w)=>g(w).length))continue;let S=E.include.map(g);if(S.some((w)=>!w.length))continue;b=!0,y.push(...S.flat())}return b?y:void 0}function xv(e,o,i){let c=/[\p{L}\p{N}_]/u;return(o===0||!c.test(e.slice(o-1,o)))&&(i===e.length||!c.test(e.slice(i,i+1)))}function zl(e,o){let i=e.split(`
|
|
463
|
-
`),c=new Set,p=0,g=i.map((y,b)=>{let E=p;if(o.some(([S,w])=>S<=E+y.length&&w>=E))for(let S=Math.max(0,b-1);S<=Math.min(i.length-1,b+1);S++)c.add(S);return p+=y.length+1,E});if(!c.size)c.add(0);return[...c].sort((y,b)=>y-b).slice(0,5).map((y)=>{let b=i[y]??"",E=g[y]??0,S=o.filter(([C,L])=>L>E&&C<E+b.length),w=Math.max(0,(S[0]?.[0]??E)-E-100),R=b.slice(w,w+300),A=S.map(([C,L])=>[Math.max(0,C-E-w),Math.min(R.length,L-E-w)]);return{text:R,line:y+1,ranges:A.filter(([C,L])=>C<L)}})}var Iv=3;function yK(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 bv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function xK(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===o&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let c="window"in i?i.window:0,p="seen"in i?i.seen:[],g="emitted"in i?i.emitted:[],y="after"in i?i.after:void 0;if(y!==void 0&&!yK(y))throw Error("invalid best cursor");let b=(E)=>Array.isArray(E)&&E.every((S)=>typeof S==="string"&&S.length<=1024);if(typeof c==="number"&&Number.isSafeInteger(c)&&c>=0&&b(p)&&b(g))return{offset:i.offset,key:o,now:i.now,window:c,seen:p,emitted:g,after:y}}}catch{}throw Error("invalid search cursor")}function Dn(e,o){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return xK(e.cursor,i)}async function Gr(e,o,i){let c="search"in e?e.search:e,p=performance.now(),g=(Ue)=>{if(!i.signal?.aborted)i.onEvent(Ue)};if(i.signal?.aborted)return;let y=Dn(o,i.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let b=Kl(o,{now:y.now});if(b.error){g({type:"error",...b.error});return}if(b.currentSession){if(!i.sessionID){g({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}b.filters.sessionID=[i.sessionID]}if(!o.deep&&b.regex?.deepScan){g({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let E=performance.now(),S=c.withIndex((Ue)=>cv(Ue,b));if(!S){g({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()-E);let w=S.partial,R=y.after,A=new Map,C=new Map,L=[],q=!1,X=new Map,j=new WeakMap,V=new Map,J=new Map,{offset:ee,window:ae}=y,K=[...y.seen],ue=[...y.emitted],he=!1,_e=Math.max(1,Math.min(200,o.limit??30)),Ee=Math.min(S.candidateLimit??2000,o.group==="none"?Cg:Math.min(2000,Math.max(Cg,_e*32))),se=(Ue,Be)=>{let qt=A.get(Be);if(qt)return qt;let lt=Ue.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Be);if(lt)A.set(Be,lt);return lt??void 0},ce=(Ue,Be,qt)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(Be.session_id))return;if(i.excludeEntry?.sessionID===Be.session_id&&i.excludeEntry.seq===Be.seq)return;let lt=se(Ue,Be.session_id);if(!lt)return;let Ot=Zr[Be.kind];if(!Ot)return;let yr=lt.title;if(Be.seq!==0){let it=`${Be.session_id}:${Be.seq}`,Jt=J.get(it);if(!Jt){let pn=qt?void 0:Ue.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Be.session_id,Be.seq);if(!qt&&!pn)return;let Kt=qt??JSON.parse(pn?.body??"null");Jt=Ke(Kt,!0),J.set(it,Jt)}let Zt=Jt.find((pn)=>pn.part===Be.part&&pn.kind===Ot);if(!Zt)return;yr=Zt.text}let pr=Wl(yr,b);if(!pr)return;let Ut=C.get(lt.id);if(Ut===void 0)Ut=Ue.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(lt.id)?.through??0,C.set(lt.id,Ut);let st=Be.seq>0&&Be.seq<=Ut;if(b.filters.compacted!==void 0&&st!==b.filters.compacted)return;let Ct={sessionID:lt.id,seq:Be.seq,time:Be.time,field:Ot,tool:Be.tool??void 0,isError:Boolean(Be.err),model:Be.model??void 0,snippet:[],score:pv(Be.relevance,Ot,Be.time,y.now),flags:{archived:lt.archived_at!==null,compacted:st,partial:yr.length>Ei+Pi}};return X.set(Ct,{text:yr,ranges:pr}),L.push(Ct),q=!0,V.set(Ct,{doc:Be.doc,part:Be.part}),Ct},Fe=(Ue)=>{let Be=performance.now(),qt=[...Ue].sort((st,Ct)=>st.time-Ct.time||st.sessionID.localeCompare(Ct.sessionID)),lt=[],Ot=new Map;for(let st of qt){let Ct=V.get(st),Jt=A.get(st.sessionID),Zt=new Set;while(Jt?.forked_from_id&&Jt.forked_from_seq!==null&&st.seq<=Jt.forked_from_seq&&!Zt.has(Jt.id))Zt.add(Jt.id),Jt=A.get(Jt.forked_from_id)??c.withIndex((Ro)=>se(Ro,Jt?.forked_from_id??""));let pn=`${Jt?.id??st.sessionID}:${st.seq}:${Ct?.part}:${Ct?.doc}`,Kt=Ot.get(pn);if(Kt){if(Kt.sessionID!==st.sessionID)Kt.forks=[...new Set([...Kt.forks??[],st.sessionID])]}else Ot.set(pn,st),lt.push(st)}let yr=[],pr=new Map,Ut=new Map;for(let st of lt){let Ct=`${st.sessionID}:${st.seq}`,it=Ut.get(Ct);if(!it){Ut.set(Ct,st),j.set(st,[st]);continue}let Jt=[...j.get(it)??[it],st],Zt=st.score>it.score?st:it;if(Zt.forks=[...new Set([...it.forks??[],...st.forks??[]])],!Zt.forks.length)Zt.forks=void 0;Zt.flags={archived:it.flags.archived||st.flags.archived,compacted:it.flags.compacted||st.flags.compacted,partial:it.flags.partial||st.flags.partial},Ut.set(Ct,Zt),j.set(Zt,Jt)}for(let st of kg([...Ut.values()],o.sort??"best")){let Ct=A.get(st.sessionID);if(!Ct)continue;let it=o.group==="none"?void 0:pr.get(Ct.id);if(!it)it={session:{id:Ct.id,title:Ct.title,projectID:Ct.project_id,updated:Ct.updated},hits:[],more:0,...w&&o.group!=="none"?{moreIsLowerBound:!0}:{}},yr.push(it),pr.set(Ct.id,it);if(it.hits.length<Iv||o.group==="none")it.hits.push(st);else it.more++}return i.onTiming?.("group",performance.now()-Be),yr},It=(Ue)=>{for(let Be of Ue)for(let qt of Be.hits){if(i.allowedSessionIDs&&qt.forks)qt.forks=qt.forks.filter((yr)=>i.allowedSessionIDs?.has(yr));let lt=performance.now(),Ot=new Map;for(let yr of j.get(qt)??[qt]){let pr=X.get(yr);if(!pr)continue;for(let Ut of zl(pr.text,pr.ranges)){let st=`${Ut.line}:${Ut.text}`,Ct=Ot.get(st);if(!Ct)Ot.set(st,Ut);else Ct.ranges=[...new Map([...Ct.ranges,...Ut.ranges].map((it)=>[it.join(":"),it])).values()]}}qt.snippet=[...Ot.values()],i.onTiming?.("snippet",performance.now()-lt)}},Je=o.deep||S.scan,Yt=(Ue,Be)=>{let qt=se(Ue,Be.session_id);if(!qt)return[];let lt=yv(Ue,S,Be,o.group==="none",qt.forked_from_id!==null,i.onTiming);if(S.candidateLimit&<.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Ot=L.length,yr=performance.now();for(let pr of lt){if(i.signal?.aborted)break;let Ut=ce(Ue,pr);if(!Ut)continue;let st=$g(Ue,S,pr,X.get(Ut)?.text??"");if(st.length)Ut.forks=st}return i.onTiming?.("body",performance.now()-yr),L.slice(Ot)};if(Je){w=!1;let Ue=[],Be=new Set,qt=c.withIndex((it)=>{Pg(it,S);for(let Kt of it.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())A.set(Kt.id,Kt);let Jt=new Set(it.query(`SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}`).all(...S.sessionBindings).map((Kt)=>Kt.id)),Zt=(Kt)=>{if(Be.has(Kt.id))return;Be.add(Kt.id);let Ro=Kt.forked_from_id?A.get(Kt.forked_from_id):void 0;if(Ro)Zt(Ro);if(Jt.has(Kt.id))Ue.push(Kt)};for(let Kt of A.values())Zt(Kt);return(it.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
|
|
464
|
-
SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}
|
|
465
|
-
)`).get(...S.sessionBindings)?.n??0)+Jt.size})??0,lt=0,Ot=0,yr=0;if(b.regex?.deepScan)g({type:"groups",groups:[]});let pr=new Set,Ut=new Set,st=new Map,Ct=()=>{let it=Fe(L),Jt=[];for(let Zt of it){let pn=Zt.session.id,Kt=o.group==="none"?void 0:st.get(pn);if(o.group!=="none"&&Ut.has(pn)&&!Kt)continue;if(!Kt){if(Ut.add(pn),Ot<y.offset){Ot++;continue}if(yr>=_e){he=!0;break}yr++,ee++}if(o.group!=="none"){let Ro=(Kt?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,Iv-(Kt?.shown??0));let xu=(Kt?.shown??0)+Zt.hits.length;Zt.more=Ro-xu,st.set(pn,{shown:xu,count:Ro})}Jt.push(Zt)}if(Jt.length)It(Jt),g({type:"groups",groups:Jt});L.length=0,X.clear(),V.clear(),J.clear()};for(let it of Ue){if(i.signal?.aborted||he)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||he)break;let pn=c.withIndex((Kt)=>{let Ro=Kt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(it.id,Math.max(0,Jt));if(Jt<0)Ro.unshift({seq:0,time:it.updated,body:null});for(let Ui of Ro){if(i.signal?.aborted)break;let Iu=Ui.body?JSON.parse(Ui.body):void 0;if(Iu?.type==="assistant")Zt=Iu.model;let kv=Iu?Ke(Iu,!0):[{part:0,kind:"title",text:it.title}];for(let Jo of kv){if(i.signal?.aborted)break;let Ls={session_id:it.id,seq:Ui.seq,part:Jo.part,doc:Number(BigInt(Bun.hash(Jo.text))&0x1fffffffffffffn),kind:Ne[Jo.kind],tool:Jo.tool??null,err:Number(Jo.err??!1),model:Jo.model??(Jo.tool?Zt:void 0)??null,time:Ui.time,relevance:-1};if(!Kt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
|
|
466
|
-
JOIN store.sessions s ON s.id=r.session_id WHERE ${S.where}`).get(Ls.session_id,Ls.seq,Ls.kind,Ls.tool,Ls.err,Ls.model,Ls.time,...S.bindings))continue;let Xs=it,Mg=new Set;while(Xs.forked_from_id&&Xs.forked_from_seq!==null&&Ui.seq<=Xs.forked_from_seq&&!Mg.has(Xs.id)){Mg.add(Xs.id);let bu=A.get(Xs.forked_from_id);if(!bu)break;Xs=bu}let Og=`${Xs.id}:${Ui.seq}:${Jo.part}:${Bun.hash(Jo.text)}`;if(pr.has(Og))continue;let _g=ce(Kt,Ls,Iu);if(_g){if(pr.add(Og),S.forks){let bu=Kt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(it.id,Ui.seq,Jo.part);if(bu){let Lg=$g(Kt,S,{...Ls,doc:bu.doc},Jo.text);if(Lg.length)_g.forks=Lg}}}}}let xu=Ro.at(-1);if(xu)Jt=xu.seq;return Ro.length});if(pn===void 0){g({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=pn,g({type:"progress",scanned:lt,total:qt}),i.signal?.aborted)return;if(Ct(),!pn||he)break;await Bun.sleep(0)}}}else c.withIndex((Ue)=>{if(w=lv(Ue,S,i.onTiming)||w,b.regex?b.regex.literals.every((lt)=>lt.some((Ot)=>[...Ot].length<3)):b.branches.some((lt)=>lt.include.length>0&<.include.every((Ot)=>[...Ot.text].length<3)))Ue.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let lt=dv(Ue,S,o.group==="none",y.now,i.onTiming);if(w||=S.partial,S.candidateLimit&<.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Ot=[];for(let pr of lt){if(i.signal?.aborted)return;let Ut=Ot[_e]?.key.score;if(Ut!==void 0&&pr.score+0.000000000001<Ut)break;let st=L.length,Ct=Yt(Ue,pr);L.splice(st);let it=kg([...Ct],"best")[0];if(!it)continue;let Jt={score:it.score,sessionID:it.sessionID,seq:o.group==="none"?it.seq:0};if(y.after&&bv(Jt,y.after)<=0)continue;if(Ot.push({key:Jt,hits:Ct}),Ot.sort((Zt,pn)=>bv(Zt.key,pn.key)),Ot.length>_e+1)Ot.length=_e+1}he=Ot.length>_e;let yr=Ot.slice(0,_e);for(let pr of yr)L.push(...pr.hits);R=yr.at(-1)?.key;return}let qt=0;for(;;){if(i.signal?.aborted)return;let lt=hv(Ue,S,ae,Ee,i.onTiming),Ot=S.candidateLimit!==void 0&&ae+lt>=S.candidateLimit;w||=Ot;let yr=gv(Ue,o,ee,_e-qt+1,y.now,K,i.onTiming);he=yr.length>_e-qt;let pr=yr.slice(0,_e-qt);if(!pr.length){if(lt<Ee||Ot){he=!1;break}ae+=lt,ee=0,K=[...new Set([...K,...ue])],ue=[];continue}for(let Ut of pr)if(ee++,Yt(Ue,Ut).length){if(qt++,o.group!=="none")ue.push(Ut.session_id)}if(qt>=_e){he||=!Ot&<>=Ee;break}if(!he){if(lt<Ee||Ot)break;ae+=lt,ee=0,K=[...new Set([...K,...ue])],ue=[]}}});if(i.signal?.aborted)return;if(!Je){let Ue=Fe(L);It(Ue),g({type:"groups",groups:Ue})}if(!q){let Ue=b.branches.flatMap((Be)=>Be.include).find((Be)=>Be.fuzzy)?.text;if(Ue)g({type:"suggest",terms:c.withIndex((Be)=>Rg(Be,Ue))??[]})}g({type:"done",cursor:he?Buffer.from(JSON.stringify(!Je&&o.sort!=="recent"?{...y,offset:0,window:0,seen:[],emitted:[],after:R}:{...y,offset:ee,window:ae,seen:K,emitted:ue})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:w,index:c.status()})}function Bo(e,o){return e.withIndex((i)=>Rg(i,o))??[]}function Ev(e,o,i){let c=x({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(m([a({maxLength:2000}),vn()])),scope:n(m([s("session"),s("project"),s("all"),s(""),vn()])),fields:n(m([B(qr({type:"string",enum:[...On]})),vn()])),tool:n(m([a(),vn()])),isError:n(m([O(),vn()])),after:n(m([a(),Y(),vn()])),before:n(m([a(),Y(),vn()])),limit:n(m([_(),vn()])),session:n(m([a(),vn()])),seq:n(m([_(),vn()])),around:n(m([_(),vn()]))}),async execute(p,g,y){let b={query:g.query?.trim(),scope:g.scope||void 0,fields:g.fields?.length?g.fields:void 0,tool:g.tool?.trim(),isError:g.isError??void 0,after:g.after??void 0,before:g.before??void 0,limit:g.limit||void 0,session:g.session?.trim(),seq:g.seq??void 0,around:g.around??void 0},E=b.query?.trim(),S=!E&&Boolean(b.session?.trim())&&Number.isSafeInteger(b.seq)&&(b.seq??0)>=1;if(S&&b.around!==void 0&&(!Number.isInteger(b.around)||b.around<0||b.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(b.scope&&!["session","project","all"].includes(b.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(y?.aborted)throw Error("History search cancelled");let w=e.sessions().find((se)=>se.id===i);if(!w)throw Error("History session is unavailable");let R=(se)=>{if(se===void 0||se===0||typeof se==="string"&&!se.trim())return;if(typeof se==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(se))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let ce=typeof se==="number"?se:Date.parse(se);if(!Number.isFinite(ce)||Math.abs(ce)>8640000000000000){if(typeof se==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return ce},A=S?void 0:R(b.after),C=S?void 0:R(b.before);if(A!==void 0&&C!==void 0&&A>=C)throw Error("after must precede before");let L=[];if(S&&b.session&&b.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===b.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let ce=b.around??3,Fe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(b.session,Math.max(1,b.seq-ce),b.seq+ce);if(!Fe.some((Je)=>Je.seq===b.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:Fe.map((Je)=>{let Yt={...JSON.parse(Je.body),seq:Je.seq,time:Je.time};return`[seq=${Je.seq}]
|
|
467
|
-
${Ke(Yt,!0).map((Ue)=>`${Ue.kind}: ${Ue.kind==="error"?Ue.text.replace(/^(?:error:\s*)+/i,""):Ue.text}`).join(`
|
|
468
|
-
`).slice(0,4000)}`}).join(`
|
|
469
|
-
|
|
470
|
-
`)||"No history content"}],details:{groups:L,count:Fe.length}}}if(!E)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(b.limit)?Math.max(1,Math.min(30,Math.trunc(b.limit??10))):10,X=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,j=new Set(e.sessions().filter((se)=>{if(b.scope==="session")return se.id===i;if((b.scope??"project")==="project"&&w.projectID)return se.projectID===w.projectID;return!0}).map((se)=>se.id)),V={q:E,filters:{tools:b.tool?.trim()?[b.tool.trim()]:void 0,isError:b.isError,after:A,before:C},group:"none",limit:q},J=Kl(V);if(J.error)throw Error(J.error.message);if(b.fields?.length){if(J.filters.fields=b.fields.filter((se)=>(se in Ne)),J.filters.fields.length!==b.fields.length)throw Error("Unknown search field")}if((b.scope??"project")==="session")J.filters.sessionID=[i];else if((b.scope??"project")==="project"&&w.projectID)J.filters.projectID=[w.projectID];let ee=o.status().state!=="ready",ae=!1;if(!ee){let se=J.filters.fields??Object.keys(Ne).filter((It)=>(It in Ne)),ce=se.filter((It)=>It!=="title"),Fe=ce.length?[ce]:[];if(se.includes("title"))Fe.push(["title"]);for(let It of Fe){if(L.length>=q&&ae)break;if(await Gr(o,{...V,limit:Math.max(1,q-L.length),filters:{...J.filters,fields:It}},{signal:y,excludeEntry:X===void 0?void 0:{sessionID:i,seq:X},sessionID:i,allowedSessionIDs:j,onEvent(Je){if(Je.type==="groups")L.push(...Je.groups);if(Je.type==="done")ae||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")ee=!0;else throw Error(Je.message)}}),ee)break}}let K=[],ue=0;if(ee){L.length=0;let se=performance.now()+2000;e:for(let ce of e.sessions()){if(!j.has(ce.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(ce.id))continue;if(J.filters.projectID&&(!ce.projectID||!J.filters.projectID.includes(ce.projectID)))continue;let Fe=Number.MAX_SAFE_INTEGER,It=!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(ce.id,Fe);if(It)Je.push({body:"null",seq:0,time:ce.updated}),It=!1;if(!Je.length)break;for(let Yt of Je){if(Yt.seq>0)Fe=Yt.seq;if(y?.aborted)throw Error("History search cancelled");if(ue>=1e4||performance.now()>se){ae=!0;break e}if(ue++,ce.id===i&&Yt.seq===X)continue;if(J.filters.after!==void 0&&Yt.time<J.filters.after||J.filters.before!==void 0&&Yt.time>=J.filters.before)continue;let Ue=Yt.seq===0?[{part:0,kind:"title",text:ce.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Be of Ue){if(J.filters.fields&&!J.filters.fields.includes(Be.kind))continue;if(J.filters.tools&&(!Be.tool||!J.filters.tools.includes(Be.tool)))continue;if(J.filters.isError!==void 0&&Boolean(Be.err)!==J.filters.isError)continue;let qt=Wl(Be.text,J);if(!qt)continue;if(L.length>=q&&Be.kind!=="title"){ae=!0;break e}(Be.kind==="title"?K:L).push({session:{id:ce.id,title:ce.title,projectID:ce.projectID,updated:ce.updated},more:0,hits:[{sessionID:ce.id,seq:Yt.seq,time:Yt.time,field:Be.kind,tool:Be.tool,isError:Boolean(Be.err),snippet:zl(Be.text,qt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(y?.aborted)throw Error("History search cancelled");if(K.length>Math.max(0,q-L.length))ae=!0;if(L.push(...K.slice(0,q)),L.sort((se,ce)=>Number(se.hits[0]?.field==="title")-Number(ce.hits[0]?.field==="title")),L.length>q)ae=!0;L.length=Math.min(L.length,q);let he=new Map;for(let se of L)for(let ce of se.hits){let Fe=he.get(se.session.id)??[];Fe.push(`[${se.session.title.replace(/[\r\n]/g," ")} \xB7 ${ce.sessionID} \xB7 ${ce.seq} \xB7 ${new Date(ce.time).toISOString()} \xB7 ${ce.field}${ce.tool?`/${ce.tool}`:""}]
|
|
471
|
-
${ce.snippet.slice(0,3).map((It)=>{let Je=It.text;for(let[Yt,Ue]of[...It.ranges].sort((Be,qt)=>qt[0]-Be[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Ue)}\u3011${Je.slice(Ue)}`;return Je}).join(`
|
|
472
|
-
`)}`),he.set(se.session.id,Fe)}let _e="";if(ee){if(_e="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")_e="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let Ee=L.reduce((se,ce)=>se+ce.hits.length,0);return{content:[{type:"text",text:[_e,ee&&ae?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ue} \u6761`:"",[...he.values()].map((se)=>se.join(`
|
|
473
|
-
|
|
474
|
-
`)).join(`
|
|
475
|
-
|
|
476
|
-
`),Ee===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${Ee} \u6761\uFF1B${ae?"\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(`
|
|
477
|
-
`)}],details:{groups:L,count:Ee}}}});return Object.assign(c,{source:"history",builtin:!0,defer:"defer"})}async function Sv(e,o){let i=o.projectID?e.store.project(o.projectID):void 0,c=i?.directory??process.cwd(),g=o.info().kind==="sub",y=()=>g||o.records.some((S)=>S.entry.type==="compaction"),b=e.options.tools??nr({directory:i?.directory,records:()=>o.records,history:(S)=>e.resolveHistory(o.id,S),onTodos:(S)=>o.setTodos(S),shell:()=>e.serverShell(),hasCompacted:y});if(e.options.tools===void 0)b.push(Ev(e.store,e.search,o.id));let E=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:T$({project:i,globalInstructions:wK(e),shell:e.serverShell()});return{systemPrompt:E.map((S)=>S.detail).join(""),systemParts:E,tools:[...b,...e.tools.snapshot()],cwd:c}}var SK=[yu(".basalt","AGENTS.md"),yu(".agents","AGENTS.md"),yu(".opencode","AGENTS.md"),yu(".claude","CLAUDE.md"),yu(".codex","AGENTS.md")];function wK(e){let o=e.options.homeDir??EK();for(let i of SK){let c=yu(o,i);try{if(IK(c))return bK(c,"utf8")}catch{return}}return}class zr{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new yg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Ul(vg(e.dataDir,"basalt.db")),this.plugins=new Xh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Gl(this.plugins,()=>this.builtinToolNames()),this.search=new Yh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let i=this.open(o,"restore");this.sessions.set(o.id,i),this.restored.add(i)}}static async create(e){let o=new zr(e);try{return await o.initialize(),o}catch(i){throw await o.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[vg(this.options.dataDir,"plugins"),...this.projects().map((e)=>vg(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 Q$(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 o=[...this.sessions.values()];if(await Promise.all(o.map((c)=>c.noticesIdle())),o.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{...Bl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>V$(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let c=o.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((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let i=this.get(e);if(!i)throw new t("History session is unavailable");let c=i.historyScope(o);if(c)return c;if(o.source&&o.source!=="self"||o.session_id&&o.session_id!==i.id)throw new t("History source is unavailable");return{sessionID:i.id,records:i.records}}openStoredSession(e,o="restore"){let i=this.open(e,o);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let o=e.model??this.defaultModel;if(!Sn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),c={id:ne("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(c);let p=this.open(c);return this.sessions.set(c.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,o,i){o={...o,archivedAt:null},this.store.copySession(e,o,i);let c=this.open(o);return this.sessions.set(o.id,c),this.plugins.notify("session.fork",c),this.emit({type:"session",session:c.info()}),c}exportSession(e){let o=this.get(e);if(!o)throw new f("no such session");let i=o.info(),c=i.projectID?this.store.project(i.projectID):void 0;return _$(i,this.store.records(e),c?{name:c.name,directory:c.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let i=[o.model,e.model,this.defaultModel].find((y)=>y!==void 0&&Sn(this.options.models,y)!==void 0),c=i?Sn(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:ne("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:i,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?D$(e.records,c):e.records);let g=this.open(p);return this.sessions.set(p.id,g),this.emit({type:"session",session:g.info()}),g}truncateHistory(e,o){let i=this.sessions.get(e.id);if(!i)throw new f("no such session");if(i.assertWritable(),i.status==="busy")throw new ie;if(!Sn(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,o);let c=this.open(e,"replay");return this.sessions.set(e.id,c),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)}),c}setArchived(e,o){let i=this.sessions.get(e);if(!i)throw new f("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 ie;if(i.isArchived===o)return i.info();this.store.setArchived(c.map((p)=>p.id),o?Date.now():null);for(let p of c)p.refreshArchive();for(let p of c)p.archiveChanged();return i.info()}sessionTree(e){let o=[e];for(let i=0;i<o.length;i++){let c=o[i];if(!c)continue;for(let p of this.sessions.values())if(p.info().parentID===c.id)o.push(p)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new f("no such session");if(o.status==="busy")throw new ie;let i=this.sessionTree(o).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});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return c();o.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(c)}open(e,o="create"){let i=e.id,c=new Ll(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>Sv(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(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",c);return c}get toolLoading(){return new qi(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!Xl.includes(e))throw new t(`Invalid shell type; must be ${Xl.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return X$(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(i){console.error("runtime listener failed",i)}}}var Ce={now:()=>Date.now(),after(e,o){let i=setTimeout(o,e);return()=>clearTimeout(i)}};var wv=1048576,Tv=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,i,c){this.cwd=e;this.outputLimit=o;this.terminal=i;this.shellPreference=c}setTerminalObserver(e){this.terminal=e}start(e,o,i){let c=i?.observer,p=i?.clock??Ce;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let X=sd(e);if(X.length>0)throw Error(id(X))}if(this.list().filter((X)=>X.state==="running").length>=Tv)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${Tv}\uFF09`);let y=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:b,isWindows:E}=Sa(e,y),S=Bun.spawn(b,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!E,windowsHide:!0,env:{...process.env,...om(this.cwd)}}),w={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:S,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(w.id,w);let R=()=>{for(let X of w.waiters.splice(0))X()},A=async(X,j)=>{let V=new kl;for await(let ee of X){let ae=V.decode(ee);w.output+=ae,c?.output(ae,j);let K=Buffer.from(w.output);if(K.length>wv){let ue=K.length-wv;while(ue<K.length&&(K[ue]??0)>>6===2)ue++;let he=K.subarray(ue).toString(),_e=w.output.length-he.length;w.unreadDroppedBytes+=Buffer.byteLength(w.output.slice(Math.max(0,w.readAt-w.dropped),_e)),w.output=he,w.dropped+=_e}R()}let J=V.flush();if(w.output+=J,J)c?.output(J,j)},C,L=Promise.all([A(S.stdout,"stdout"),A(S.stderr,"stderr")]).catch((X)=>{C=X,this.kill(w)}),q=!1;if(w.done=(async()=>{if(w.code=await S.exited,w.timer?.(),this.kill(w),await L,C)throw C;if(w.state==="running")w.state="exited";if(q=!0,c?.end(w.state,w.code),!c&&w.state!=="killed")this.terminal?.(w);R()})().catch((X)=>{if(w.state="exited",w.output+=`
|
|
478
|
-
[\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(X)}]`,!q)c?.end(w.state,w.code);if(c)throw X;if(!c)this.terminal?.(w,X);R()}),o!==void 0)w.timer=p.after(o,()=>{if(w.state==="running")w.state="timeout",this.kill(w)});return w}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128&&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(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,o,i=0,c=!1,p){let g=this.find(e),y=o?new RegExp(o):void 0,b=Date.now()+i;p?.throwIfAborted();while(g.state==="running"){p?.throwIfAborted();let A=g.output.slice(Math.max(0,g.readAt-g.dropped));if((y?y.test(A):!c)||Date.now()>=b)break;await new Promise((C,L)=>{let q=()=>{clearTimeout(j);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);L(p?.reason)},X=()=>{clearTimeout(j),p?.removeEventListener("abort",q);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);C()},j=setTimeout(X,Math.max(0,b-Date.now()));g.waiters.push(X),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let E=g.unreadDroppedBytes;g.unreadDroppedBytes=0;let S=g.output.slice(Math.max(0,g.readAt-g.dropped));g.readAt=g.dropped+g.output.length;let w=S.slice(-this.outputLimit),R=E+Buffer.byteLength(S.slice(0,S.length-w.length));return{job:g,output:`${R?`[truncated ${R} bytes]
|
|
479
|
-
`:""}${w}`}}async write(e,o,i=!1,c){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let g=p.proc.stdin;if(!g||typeof g==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let y=await je(o,c);if(y)throw Error(y);g.write(o)}if(i)await g.end();else await g.flush()}async stop(e){let o=this.find(e);if(o.state==="running")o.state="killed",this.kill(o);return await o.done,{id:o.id,state:o.state,code:o.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var Vl=new WeakMap,Jl=new WeakMap;function sr(e,o){let i=Vl.get(e);if(!i)i=o(),Vl.set(e,i);return i}function ar(e){Jl.set(e,(Jl.get(e)??0)+1)}function lr(e,o){let i=(Jl.get(o)??1)-1;if(Jl.set(o,i),i>0)return!1;if(o.close(),Vl.get(e)===o)Vl.delete(e);return!0}async function N(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function v(e,o){let i=e[o];if(!i)throw new t(`${o} is required`);return i}var Un=100,cr=1e4,TK=60000,RK=200,An=()=>a(),Rv=()=>n(_({minimum:1,maximum:cr})),Zc=()=>n(a({minLength:1,maxLength:128})),kK=m([l({click:m([An(),l({selector:An()})])}),l({type:l({label:An(),text:An()})}),l({waitText:An(),timeoutMs:Rv()}),l({expectText:An(),within:n(An())}),l({waitSelector:An(),timeoutMs:Rv()}),l({expectCount:l({selector:An(),n:_({minimum:0})})}),l({snapshot:l({selector:An(),depth:n(_({minimum:0,maximum:RK}))})}),l({expectCalls:l({onOpen:n(B(An())),onClose:n(_({minimum:0}))})}),l({expectValue:l({label:An(),value:An()})})]),AK=l({status:_({minimum:100,maximum:599}),body:Rr(),delayMs:n(_({minimum:0,maximum:cr}))}),CK=m([s("paths"),s("request"),s("verify"),s("ui_test"),s("list"),s("docs"),s("check"),s("load"),s("reload"),s("enable"),s("disable")]),PK=m([s("page"),s("tab"),s("card"),s("sidebar")]),xi=l({action:CK,path:n(a({minLength:1,maxLength:4096})),method:n(An()),body:n(Ts(An(),Rr())),importTimeoutMs:n(_({minimum:1,maximum:cr})),timeoutMs:n(_({minimum:1,maximum:TK})),sessionID:Zc(),scope:n(m([s("user"),s("all")])),id:Zc(),slot:Zc(),view:Zc(),codeBlock:Zc(),kind:n(PK),props:n(Ts(An(),Rr())),context:n(Ts(An(),Rr())),steps:n(B(kK,{maxItems:Un})),mockRoutes:n(Ts(An(),AK)),topic:n(a({maxLength:100})),grep:n(a({minLength:1,maxLength:200}))});
|
|
480
|
-
export{t,f,Fr,Wr,mi,$r,er,Co,On,hi,fi,gi,Ft,yi,bi,Hr,Io,Si,Pe,wi,et,Pt,z,Mo,je,tt,B,n,l,qr,O,_,s,Y,a,m,h,le,Nn,Lo,Oo,No,Do,ve,x,rt,pt,k,D,F,Re,Te,u,pe,nt,tr,rr,$e,nr,dt,ie,Uo,or,ir,ne,Dn,Gr,Bo,zr,Ce,Wt,sr,ar,lr,N,v,Fo,Un,cr,xi};
|