@bkm016/basalt 0.1.14 → 0.1.16

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.
Files changed (181) hide show
  1. package/{chunk-mfb3dgs8.js → chunk-1c9nr9rs.js} +1 -1
  2. package/{chunk-z9p6s986.js → chunk-4hf0r9hv.js} +3 -3
  3. package/{chunk-p886jr17.js → chunk-6ae9810t.js} +2 -2
  4. package/{chunk-6hx9y86d.js → chunk-6exa9fp7.js} +1 -1
  5. package/{chunk-xk3t5ves.js → chunk-8jn0yax5.js} +132 -132
  6. package/{chunk-xq74x4gc.js → chunk-8r4baw9e.js} +1 -1
  7. package/{chunk-nysatg77.js → chunk-9ymm1gge.js} +167 -156
  8. package/{chunk-qjnx4fsn.js → chunk-b350b01x.js} +3 -3
  9. package/{chunk-59hg9a84.js → chunk-bv96b8q7.js} +1 -1
  10. package/{chunk-343jsm46.js → chunk-e8x8zwkg.js} +1 -1
  11. package/{chunk-k38jaz6c.js → chunk-ehnc8g6v.js} +2 -2
  12. package/{chunk-kcn05erf.js → chunk-fzftb4n2.js} +3 -3
  13. package/{chunk-0rasqm8y.js → chunk-nrdszs0g.js} +2 -2
  14. package/{chunk-qs161f2q.js → chunk-p78wde92.js} +1 -1
  15. package/{chunk-39mh7h58.js → chunk-pna1wh02.js} +1 -1
  16. package/{chunk-edcf97ka.js → chunk-q6tgpaf3.js} +1 -1
  17. package/{chunk-qe76naq9.js → chunk-rqn67tm8.js} +1 -1
  18. package/{chunk-en7z6ne5.js → chunk-v9ttcf6r.js} +1 -1
  19. package/{chunk-9v3b7jjv.js → chunk-vv9csar7.js} +1 -1
  20. package/{chunk-81x8r8w4.js → chunk-xba6fr5v.js} +1 -1
  21. package/{chunk-03wzwnn6.js → chunk-ypxs8djn.js} +1 -1
  22. package/compiled.js +4 -4
  23. package/package.json +1 -1
  24. package/ui-test-worker.js +2 -2
  25. package/web/{chunk-kpmd893m.js → chunk-0qnetvsc.js} +4 -4
  26. package/web/{chunk-mvm68qtt.js → chunk-0zb330w3.js} +4 -4
  27. package/web/{chunk-78m018ya.js → chunk-0zyekjym.js} +1 -1
  28. package/web/chunk-11byy7vm.js +1 -0
  29. package/web/chunk-160x5pv7.js +1 -0
  30. package/web/{chunk-ysw5fs45.js → chunk-19g09ekr.js} +5 -5
  31. package/web/chunk-1gzprnyd.js +1 -0
  32. package/web/{chunk-7wzszsf5.js → chunk-1hx4xtdk.js} +2 -2
  33. package/web/{chunk-wspk8qbg.js → chunk-1je4p601.js} +4 -4
  34. package/web/{chunk-3haw3wcw.js → chunk-1np2aamb.js} +3 -3
  35. package/web/{chunk-qftcdcps.js → chunk-1rjtqf8h.js} +2 -2
  36. package/web/{chunk-54mgncq3.js → chunk-23258z1r.js} +1 -1
  37. package/web/{chunk-y3tb6410.js → chunk-27592nd8.js} +3 -3
  38. package/web/chunk-27tchdxd.js +2 -0
  39. package/web/{chunk-7hpqrfgg.js → chunk-2hqmdqn3.js} +1 -1
  40. package/web/chunk-2q79n966.js +2 -0
  41. package/web/{chunk-nfpff7yf.js → chunk-2ws74tfa.js} +10 -10
  42. package/web/{chunk-9vr6hpmk.js → chunk-2z8epr8f.js} +7 -7
  43. package/web/{chunk-k4qrqmdk.js → chunk-36e78034.js} +2 -2
  44. package/web/{chunk-vpegzgzb.js → chunk-3gj2t10x.js} +8 -8
  45. package/web/{chunk-2gsf89vs.js → chunk-444xfger.js} +4 -4
  46. package/web/{chunk-988e9wx6.js → chunk-4k62e61g.js} +5 -5
  47. package/web/{chunk-8sr9w61v.js → chunk-4z6wma3s.js} +2 -2
  48. package/web/{chunk-qcdej581.js → chunk-5sss3r97.js} +1 -1
  49. package/web/chunk-5wkqqa59.js +1 -0
  50. package/web/{chunk-s2ps0ct5.js → chunk-5yczs6sb.js} +1 -1
  51. package/web/chunk-5yn7mwvt.js +1 -0
  52. package/web/{chunk-mv7jgmnb.js → chunk-6ty9vw27.js} +3 -3
  53. package/web/chunk-705tkt2r.js +1 -0
  54. package/web/{chunk-j6wcszxq.js → chunk-753qp8sa.js} +2 -2
  55. package/web/{chunk-3rxhs9qm.js → chunk-75kzvpf3.js} +8 -8
  56. package/web/{chunk-hdtvrh0f.js → chunk-75meb0dh.js} +2 -2
  57. package/web/{chunk-y6mcxfm0.js → chunk-76e3npmd.js} +1 -1
  58. package/web/chunk-7p04dn0k.js +1 -0
  59. package/web/chunk-7rb3v8gy.js +1 -0
  60. package/web/{chunk-797bh7z6.js → chunk-7yz88k97.js} +3 -3
  61. package/web/{chunk-p79c7aak.js → chunk-85d7jkp0.js} +1 -1
  62. package/web/chunk-90kgn35s.js +1 -0
  63. package/web/chunk-931y1g0h.js +1 -0
  64. package/web/chunk-bcp6na49.js +1145 -0
  65. package/web/chunk-bz1q7qdd.js +8 -0
  66. package/web/chunk-c0evk1xy.js +1 -0
  67. package/web/{chunk-ahn2frbt.js → chunk-c0hdp2zj.js} +1 -1
  68. package/web/{chunk-25sn840r.js → chunk-c1z290wm.js} +2 -2
  69. package/web/{chunk-vg346gxc.js → chunk-cge0cjfm.js} +1 -1
  70. package/web/{chunk-ffywf5w5.js → chunk-chh8bg2h.js} +11 -11
  71. package/web/{chunk-7zfqppsx.js → chunk-ctmxm4qd.js} +2 -2
  72. package/web/{chunk-hbwxtbq3.js → chunk-e229cr90.js} +1 -1
  73. package/web/{chunk-xhqvzmfj.js → chunk-e9mmkrc3.js} +5 -5
  74. package/web/{chunk-s70aj1v5.js → chunk-ef03t1mb.js} +5 -5
  75. package/web/{chunk-783s8jds.js → chunk-f8nnrk6y.js} +4 -4
  76. package/web/{chunk-8ttp8fh3.js → chunk-fcrswzgm.js} +3 -3
  77. package/web/{chunk-w5q7978e.js → chunk-ffn1a0zw.js} +1 -1
  78. package/web/chunk-fw4fa7j6.js +1 -0
  79. package/web/chunk-fx8hheqz.js +1 -0
  80. package/web/{chunk-vxm7n7w6.js → chunk-g8wy9sa6.js} +11 -11
  81. package/web/{chunk-pafw34vg.js → chunk-gaf9brzv.js} +2 -2
  82. package/web/{chunk-npw1s1h2.js → chunk-gj16e7z0.js} +1 -1
  83. package/web/{chunk-tjd8qp87.js → chunk-gjchc4kg.js} +1 -1
  84. package/web/chunk-h1y8y203.js +1 -0
  85. package/web/{chunk-sgkevxdf.js → chunk-h6vy008x.js} +1 -1
  86. package/web/{chunk-zsat72qd.js → chunk-h8mhnze5.js} +55 -55
  87. package/web/{chunk-7kywe73f.js → chunk-hhnhgthx.js} +2 -2
  88. package/web/{chunk-jzge034r.js → chunk-j27mtdr2.js} +1 -1
  89. package/web/chunk-jys02310.js +1 -0
  90. package/web/chunk-kew13yzg.js +1 -0
  91. package/web/{chunk-zx3h7v72.js → chunk-kx5r8nf2.js} +1 -1
  92. package/web/{chunk-d3hyf9yd.js → chunk-m7c0xk69.js} +1 -1
  93. package/web/{chunk-59g6rrew.js → chunk-madrcnm1.js} +2 -2
  94. package/web/{chunk-vwv6pqy7.js → chunk-mcm3t5wr.js} +1 -1
  95. package/web/{chunk-mn2wv9ye.js → chunk-mrnx4f74.js} +2 -2
  96. package/web/chunk-mtdsrtc5.js +1 -0
  97. package/web/{chunk-aknsydan.js → chunk-mv5axm2y.js} +4 -4
  98. package/web/{chunk-ya696bfe.js → chunk-n3f5a91k.js} +1 -1
  99. package/web/{chunk-dwtatme7.js → chunk-n3spc397.js} +1 -1
  100. package/web/{chunk-feanedhx.js → chunk-nhc280n0.js} +1 -1
  101. package/web/chunk-nx1bcekh.js +2 -0
  102. package/web/{chunk-wfgrdabk.js → chunk-p0jghn6b.js} +1 -1
  103. package/web/chunk-p8t7s4z4.js +1 -0
  104. package/web/chunk-pgh1cx6w.js +1 -0
  105. package/web/{chunk-g3szt4c4.js → chunk-ps489yjy.js} +1 -1
  106. package/web/{chunk-kk5rw81s.js → chunk-qbhv18t0.js} +2 -2
  107. package/web/{chunk-c7fqrs8j.js → chunk-qgzn0ha5.js} +1 -1
  108. package/web/{chunk-faskbfjf.js → chunk-qtwxq6hj.js} +3 -3
  109. package/web/chunk-qwp3dhmf.js +1 -0
  110. package/web/{chunk-bahccwb9.js → chunk-qwwqdmhv.js} +1 -1
  111. package/web/{chunk-9h0f3gar.js → chunk-rjh54ygb.js} +5 -5
  112. package/web/chunk-ryh8jdzy.js +1 -0
  113. package/web/chunk-s3t8dkkz.js +1 -0
  114. package/web/chunk-sk1w7f7h.js +1 -0
  115. package/web/chunk-smkrxjm5.js +1 -0
  116. package/web/{chunk-s45g7fp6.js → chunk-sv5ph7fa.js} +1 -1
  117. package/web/{chunk-2gvz70wr.js → chunk-t89tfrpj.js} +8 -8
  118. package/web/{chunk-qv1w36ja.js → chunk-t9pg7qf8.js} +2 -2
  119. package/web/{chunk-xf1hnpme.js → chunk-t9twxmsg.js} +1 -1
  120. package/web/{chunk-ptpkv0te.js → chunk-tfdchqn4.js} +1 -1
  121. package/web/{chunk-p4pqtybm.js → chunk-tfsrk2rc.js} +24 -24
  122. package/web/{chunk-we4mhfmq.js → chunk-tvvggvjt.js} +8 -8
  123. package/web/chunk-ty87gdvr.js +1 -0
  124. package/web/{chunk-ppa21760.js → chunk-v16s0x7c.js} +1 -1
  125. package/web/{chunk-zpzvz973.js → chunk-vb2z2azk.js} +10 -10
  126. package/web/{chunk-snaepr87.js → chunk-vcnsvj49.js} +9 -9
  127. package/web/{chunk-2c7kxr4v.js → chunk-vgyp8wa2.js} +2 -2
  128. package/web/chunk-vh8pkcem.css +1 -0
  129. package/web/{chunk-17wwzrp4.js → chunk-vjnvfb8z.js} +1 -1
  130. package/web/{chunk-32dh0hft.js → chunk-vphzndz8.js} +1 -1
  131. package/web/{chunk-r8p741qj.js → chunk-w60dxtyz.js} +1 -1
  132. package/web/{chunk-1zwc09e8.js → chunk-wcj3bxdf.js} +2 -2
  133. package/web/{chunk-ex8rmqn1.js → chunk-wgmwgaw4.js} +5 -5
  134. package/web/{chunk-51b8n5e1.js → chunk-wvt76598.js} +1 -1
  135. package/web/chunk-y0mef85j.js +1 -0
  136. package/web/{chunk-410qdvmv.js → chunk-y2ykn1gm.js} +1 -1
  137. package/web/{chunk-jdx7qp2w.js → chunk-ybqt106a.js} +2 -2
  138. package/web/{chunk-wkhj4hsw.js → chunk-ym9qfsjs.js} +4 -4
  139. package/web/{chunk-fx3d48e6.js → chunk-ypdptddq.js} +1 -1
  140. package/web/{chunk-tdzh6nsz.js → chunk-z08c63ph.js} +2 -2
  141. package/web/{chunk-k9fyqrhp.js → chunk-z2hvvkf5.js} +2 -2
  142. package/web/chunk-z6x74qfh.js +1 -0
  143. package/web/{chunk-zkq1xknc.js → chunk-z86pjpqp.js} +1 -1
  144. package/web/{chunk-rjakb64x.js → chunk-zh0vjc6g.js} +1 -1
  145. package/web/chunk-zns9wmab.js +1 -0
  146. package/web/index.html +1 -1
  147. package/web/sw.js +17 -1
  148. package/web/chunk-15g9pnzy.js +0 -1
  149. package/web/chunk-19tkjg9w.js +0 -1
  150. package/web/chunk-26sp6jre.js +0 -1
  151. package/web/chunk-2s3my1jn.js +0 -1
  152. package/web/chunk-4qehf2xx.js +0 -2
  153. package/web/chunk-6481wt3t.js +0 -1
  154. package/web/chunk-6ehecat3.js +0 -1
  155. package/web/chunk-6m8hq6ph.js +0 -1
  156. package/web/chunk-73941p08.js +0 -1
  157. package/web/chunk-8zg89764.js +0 -1
  158. package/web/chunk-9vrp249f.js +0 -2
  159. package/web/chunk-dcegr80c.js +0 -1
  160. package/web/chunk-g7bcntpm.js +0 -1
  161. package/web/chunk-gr1tjqbd.js +0 -1
  162. package/web/chunk-j031r08w.js +0 -1
  163. package/web/chunk-jge7nn3s.js +0 -1
  164. package/web/chunk-jy8zat04.js +0 -1
  165. package/web/chunk-k8s7kye3.js +0 -1
  166. package/web/chunk-k9zn1n6d.js +0 -1
  167. package/web/chunk-kg3tksv7.js +0 -1
  168. package/web/chunk-md9j949p.js +0 -1
  169. package/web/chunk-nk7jkpam.js +0 -1
  170. package/web/chunk-nmvt1rn3.js +0 -1
  171. package/web/chunk-npyrdsf8.css +0 -1
  172. package/web/chunk-nzzxv84v.js +0 -8
  173. package/web/chunk-rcexbkjj.js +0 -1
  174. package/web/chunk-say8bvkc.js +0 -1
  175. package/web/chunk-sjffrcq9.js +0 -1
  176. package/web/chunk-tncc9e57.js +0 -1
  177. package/web/chunk-ty2rmwda.js +0 -1142
  178. package/web/chunk-v22hp18w.js +0 -1
  179. package/web/chunk-ve9dz857.js +0 -2
  180. package/web/chunk-xq70hgre.js +0 -1
  181. package/web/chunk-zkv025s5.js +0 -1
@@ -1,57 +1,57 @@
1
1
  // @bun
2
- import{ei,nn,G}from"./chunk-38g4jd6v.js";import{Gi,ze,Rt,zi,lo,Vi,Ki,Qi,Ct,Yi,Be,uo,Je}from"./chunk-44a7f5ta.js";import{eo,ts,rn}from"./chunk-g5p9mj1r.js";import{Oe,ie,ti,to,D,ro,yt,Ne,Sr,W,De,no,bt,ge,zt,ae,on,ri,Ue,se,st,oo,ni,xe,rs,Hi,ve,io,d,ns,Y,sn,K,os}from"./chunk-z9p6s986.js";import{so,U,ao,Xe,qi,jt,Ie}from"./chunk-4yxd2kg1.js";import{r,Ze}from"./chunk-qd2enpr2.js";var xy=r(function(f2,yy){var IM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],pd=/[\n\r\u2028\u2029]/,bM=/[\s#!"$&'():;<=>@\\^`|~]/g;yy.exports=function(o){var a=!1;return o.map(function(u){if(a&&typeof u==="string"&&pd.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(pd.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(bM,"\\$&")}if("op"in u&&typeof u.op==="string"){if(IM.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(pd.test(u.comment))throw TypeError("`comment` must not contain line terminators");return a=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var ky=r(function(h2,Ry){var wy="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Iy=new RegExp("^"+wy+"$"),by="|&;()<> \\t",EM="'([^']*?)'",Ty="(?:\\\\[\\s\\S]|[^\\\\'])*?",Ey="\\$'"+Ty+"'",sm=new RegExp("\\$'"+Ty+"(?:(')|\\\\?$)","g"),SM="abeEfnrtv",wM=`\x07\b\x1B\x1B\f
3
- \r \v`,TM=/^#$/,ld="'",Sy='"',ku="$",vi="",RM=4294967296;for(om=0;om<4;om++)vi+=(RM*Math.random()).toString(16);var om,kM=new RegExp("^"+vi);function AM(e,o){var a=o.lastIndex,u=[],m;while(m=o.exec(e))if(u[u.length]=m,o.lastIndex===m.index)o.lastIndex+=1;return o.lastIndex=a,u}function PM(e,o,a){var u=typeof e==="function"?e(a):e[a];if(typeof u>"u"&&a!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+vi+JSON.stringify(u)+vi;return o+u}var CM=/\\([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 $M(e,o){var a=o.charAt(0);if(a==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(a==="x"||a==="u"||a==="U"){var m=parseInt(o.slice(1),16);if(m>1114111)return e;return String.fromCharCode.apply(null,m>65535?[55232+(m>>10),56320+(m&1023)]:[m])}if(a>="0"&&a<="7")return String.fromCharCode(parseInt(o,8)&255);var p=SM.indexOf(o);return p<0?o:wM.charAt(p)}function vM(e){return e.replace(CM,$M).split("\x00")[0]}function MM(e,o){return sm.lastIndex=o,!!sm.exec(e)[1]}function OM(e,o,a){if(!a)a={};var u=a.escape||"\\",m=a.splitUnquoted===!0?`
4
- `:typeof a.splitUnquoted==="string"?a.splitUnquoted:"",p="(\\"+u+`['"$\\`+u+by+"]|\\$\\$|\\$(?!"+Ey.slice(2)+`)|[^\\s'"$`+by+"])+",f='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',h=new RegExp(["("+wy+")","("+Ey+"|"+p+"|"+f+"|"+EM+")+"].join("|"),"g"),I=AM(e,h);if(I.length===0)return[];if(!o)o={};var E=!1;return I.map(function(S){var R=S[0];if(!R||E)return;if(Iy.test(R))return{op:R};var k=!1,P=!1,v="",_=[],Q=!1,L=null,V=!1,J;function Z(){J+=1;var ue,$e,gt=R.charAt(J);if(gt==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var Ke=1;ue=J;while(Ke>0&&ue<R.length){if(R.charAt(ue)==="{"&&R.charAt(ue-1)==="$")Ke+=1;else if(R.charAt(ue)==="}")Ke-=1;ue+=1}if(Ke!==0)throw Error("Bad substitution: "+R.slice(J));ue-=1,$e=R.slice(J,ue),J=ue}else if(/[*@#?$!-]/.test(gt))$e=gt;else{var Zt=R.slice(J);if(ue=Zt.match(/[^\w\d_]/),!ue)$e=Zt,J=R.length;else $e=Zt.slice(0,ue.index),J+=ue.index-1}return PM(o,"",$e)}function ne(){if(L===null)return;if(L===0){if(v!=="")_[_.length]=v,v=""}else{_[_.length]=v,v="";for(var ue=1;ue<L;ue+=1)_[_.length]=""}L=null}for(J=0;J<R.length;J++){var z=R.charAt(J);if(m&&z!==ku)ne();if(V=V||!k&&(z==="*"||z==="?"),P)v+=z,P=!1;else if(k)if(z===k)k=!1;else if(k==ld)v+=z;else if(z===u)if(J+=1,z=R.charAt(J),z===Sy||z===u||z===ku)v+=z;else v+=u+z;else if(z===ku)v+=Z();else v+=z;else if(z===Sy||z===ld)k=z,Q=!0;else if(Iy.test(z))return{op:R};else if(TM.test(z)){E=!0;var oe={comment:e.slice(S.index+J+1)};if(v.length)return[v,oe];return[oe]}else if(z===u)P=!0;else if(z===ku&&R.charAt(J+1)===ld&&MM(R,J))ne(),Q=!0,v+=vM(R.slice(J+2,sm.lastIndex-1)),J=sm.lastIndex-1;else if(z===ku){var fe=Z();if(!m)v+=fe;else for(var ke=0;ke<fe.length;ke+=1){var Ee=fe.charAt(ke);if(m.indexOf(Ee)<0)ne(),v+=Ee;else if(L===null)L=Ee===" "||Ee==="\t"||Ee===`
5
- `?0:1;else if(Ee!==" "&&Ee!=="\t"&&Ee!==`
6
- `)L+=1}}else v+=z}if(V)return{op:"glob",pattern:v};if(m){if(L!==null&&L>0){_[_.length]=v,v="";for(var ee=1;ee<L;ee+=1)_[_.length]=""}if(v!==""||Q&&_.length===0)_[_.length]=v;return _}return v}).reduce(function(S,R){if(typeof R>"u")return S;return[].concat(R).forEach(function(k){S[S.length]=k}),S},[])}Ry.exports=function(o,a,u){var m=OM(o,a,u);if(typeof a!=="function")return m;return m.reduce(function(p,f){if(typeof f==="object")return p[p.length]=f,p;var h=f.split(RegExp("("+vi+".*?"+vi+")","g"));if(h.length===1)return p[p.length]=h[0],p;return h.filter(Boolean).forEach(function(I){p[p.length]=kM.test(I)?JSON.parse(I.split(vi)[1]):I}),p},[])}});var Zo={};Ze(Zo,{ArchivedError:()=>ft,BadRequestError:()=>t,BusyError:()=>ce,DEFAULT_TIMEOUT:()=>B$,FoldingPolicy:()=>zc,MAX_ATTACHMENTS:()=>mt,MAX_TIMEOUT:()=>G$,MAX_TOOL_OUTPUT:()=>Ce,NotFoundError:()=>y,PluginCheckError:()=>ht,ProcessRegistry:()=>Gt,Type:()=>mo,aliased:()=>Te,budget:()=>Wc,calls:()=>Po,clip:()=>le,clipSaved:()=>it,dataDir:()=>nt,definePlugin:()=>C,estimateMessage:()=>q,estimateTokens:()=>F,estimateTools:()=>ki,extensionTranscript:()=>vl,findWindowsBash:()=>lr,foldPoint:()=>Kc,foldedThrough:()=>Ta,formatLines:()=>Vc,gateShellCommand:()=>Qe,groupRuns:()=>Qs,historyTodos:()=>dr,newID:()=>re,normalizeRunRecords:()=>Jh,processRegistry:()=>mr,project:()=>Me,projectUserText:()=>Ai,releaseProcesses:()=>fr,requestBody:()=>O,resolveShellCommand:()=>Aa,retainProcesses:()=>hr,routeParam:()=>A,runShell:()=>cr,sealPoint:()=>lu,selectHistory:()=>pr,sessionTools:()=>ur,staleFold:()=>kl,text:()=>c,timerClock:()=>Le,tool:()=>T,toolSession:()=>j,transcript:()=>hu,usable:()=>me,userTranscript:()=>$l,validAttachment:()=>qt,workState:()=>Pl});var Qo={};Ze(Qo,{AssistantMessageEventStream:()=>U,AssistantMessageFrameEncoder:()=>QR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>ZR,EventStream:()=>so,InMemoryCredentialStore:()=>to,InMemoryModelsStore:()=>ro,ModelsError:()=>D,StringEnum:()=>AF,Type:()=>mo,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>Y,clampThinkingLevel:()=>K,cleanupSessionResources:()=>ts,collapseSystemMessages:()=>Ue,contentText:()=>Sr,createAssistantMessageDiagnostic:()=>jt,createAssistantMessageEventStream:()=>ao,createFauxCore:()=>JR,createInitialSystemMessage:()=>no,createModels:()=>io,createProvider:()=>d,declarationsEqual:()=>oo,defaultProviderAuthContext:()=>ti,envApiKeyAuth:()=>b,extractDiagnosticError:()=>qi,fauxAssistantMessage:()=>Vo,fauxProvider:()=>Ko,fauxText:()=>qn,fauxThinking:()=>jo,fauxToolCall:()=>iF,formatThrownValue:()=>Xe,getCurrentSystemMessage:()=>on,getCurrentSystemPrompt:()=>ri,getCurrentTools:()=>ae,getDeclaredTools:()=>xe,getInitialSystemMessage:()=>ge,getModelType:()=>yt,getOverflowPatterns:()=>SF,getSupportedThinkingLevels:()=>sn,getSystemMessageText:()=>W,getToolStateChanges:()=>ni,hasApi:()=>ns,hasNonAdditiveToolChanges:()=>Hi,hasToolRedefinitions:()=>rs,isContextOverflow:()=>ha,isModelType:()=>Ne,isRecoverableLength:()=>EF,isRetryableAssistantError:()=>tk,lazyApi:()=>ie,lazyOAuth:()=>de,lazyStream:()=>Oe,modelsAreEqual:()=>os,normalizeContext:()=>bt,parseJsonWithRepair:()=>nn,parseStreamingJson:()=>G,reduceAssistantMessageFrames:()=>xF,registerSessionResourceCleanup:()=>eo,renderSystemMessageUpdate:()=>De,repairJson:()=>ei,resolveTranscript:()=>se,resolveTranscriptTools:()=>ve,retryAssistantCall:()=>kF,retryDelayMs:()=>ek,toToolDeclaration:()=>st,uuidv7:()=>rn,validateToolArguments:()=>cu,validateToolCall:()=>lB,withoutInitialSystemMessage:()=>zt});var B={};Ze(B,{Counted:()=>Sd,Entries:()=>hn,EntriesRegExp:()=>wd,Every:()=>mn,EveryAll:()=>$n,GraphemeCount:()=>cO,HasPropertyKey:()=>pe,IsArray:()=>Fe,IsBigInt:()=>qr,IsBoolean:()=>fn,IsClassInstance:()=>Gy,IsConstructor:()=>bd,IsDeepEqual:()=>$a,IsEqual:()=>M,IsFunction:()=>gs,IsGreaterEqualThan:()=>Pa,IsGreaterThan:()=>ji,IsInteger:()=>cm,IsLessEqualThan:()=>ys,IsLessThan:()=>Pu,IsMaxLength:()=>Ky,IsMinLength:()=>Hy,IsMultipleOf:()=>By,IsNull:()=>bo,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>Uo,IsString:()=>lt,IsSymbol:()=>Ed,IsUndefined:()=>Bt,IsUnsafePropertyKey:()=>Cu,IsValueLike:()=>Ji,Keys:()=>Se,ShiftLeft:()=>xt,Some:()=>Ca,SomeAll:()=>Wy,Symbols:()=>zy,Values:()=>Td});var oa={};Ze(oa,{Hash:()=>vd,HashCode:()=>Ax});var _t={};Ze(_t,{ExtendsFalse:()=>Ye,ExtendsTrue:()=>we,ExtendsUnion:()=>Zd,IsExtendsFalse:()=>rf,IsExtendsTrue:()=>tf,IsExtendsTrueLike:()=>co,IsExtendsUnion:()=>ef,Match:()=>wr});var mo={};Ze(mo,{Any:()=>_a,Array:()=>H,BigInt:()=>Lu,Boolean:()=>N,Call:()=>jw,Capitalize:()=>zw,Codec:()=>Im,Conditional:()=>tT,Constructor:()=>Is,ConstructorParameters:()=>nT,Cyclic:()=>Ss,Decode:()=>vx,DecodeBuilder:()=>xm,Dependent:()=>na,Encode:()=>Mx,EncodeBuilder:()=>ym,Enum:()=>yx,Evaluate:()=>Pn,Exclude:()=>sT,Extends:()=>An,ExtendsResult:()=>_t,Extract:()=>aT,Function:()=>bs,Generic:()=>ui,Identifier:()=>Nu,Immutable:()=>Ox,Index:()=>pT,Infer:()=>_u,InstanceType:()=>NT,Instantiate:()=>Mo,Integer:()=>x,Interface:()=>Ew,Intersect:()=>Mn,IsAny:()=>Or,IsArray:()=>St,IsBigInt:()=>go,IsBoolean:()=>Vn,IsCall:()=>Wa,IsCodec:()=>Kn,IsConstructor:()=>zr,IsCyclic:()=>Xt,IsDependent:()=>Fr,IsEnum:()=>un,IsEnumValue:()=>gx,IsFunction:()=>en,IsGeneric:()=>Oa,IsIdentifier:()=>Dx,IsImmutable:()=>sa,IsInfer:()=>an,IsInteger:()=>yn,IsIntersect:()=>Ge,IsKind:()=>Re,IsLiteral:()=>dt,IsNever:()=>ho,IsNull:()=>Ts,IsNumber:()=>Cr,IsObject:()=>He,IsOptional:()=>ln,IsParameter:()=>Ux,IsReadonly:()=>aa,IsRecord:()=>Kt,IsRef:()=>Ft,IsRefine:()=>bm,IsRest:()=>fi,IsSchema:()=>Mr,IsString:()=>cn,IsSymbol:()=>Rs,IsTemplateLiteral:()=>tr,IsThis:()=>_m,IsTuple:()=>ct,IsUndefined:()=>ss,IsUnion:()=>be,IsUnknown:()=>tn,IsUnsafe:()=>gm,IsVoid:()=>yo,KeyOf:()=>qT,Literal:()=>i,Lowercase:()=>Vw,Mapped:()=>WT,Module:()=>_R,Never:()=>Vt,NonNullable:()=>QT,Null:()=>On,Number:()=>te,Object:()=>l,Omit:()=>YT,Optional:()=>n,Parameter:()=>ua,Parameters:()=>tR,Partial:()=>nR,Pick:()=>mR,Readonly:()=>_x,ReadonlyObject:()=>Mf,ReadonlyType:()=>dR,Record:()=>ks,RecordKey:()=>di,RecordPattern:()=>xn,RecordValue:()=>or,Ref:()=>pn,Refine:()=>Lx,Required:()=>PR,Rest:()=>ma,ReturnType:()=>$R,Script:()=>qR,String:()=>s,Symbol:()=>Da,TemplateLiteral:()=>BS,This:()=>Om,Tuple:()=>Ur,Uncapitalize:()=>Jw,Undefined:()=>ja,Union:()=>g,Unknown:()=>Pr,Unsafe:()=>sr,Uppercase:()=>Qw,Void:()=>Lm,With:()=>Ip});var iu={};Ze(iu,{Clear:()=>yA,Entries:()=>_1,Get:()=>D1,Has:()=>N1,IsDate:()=>nu,IsDateTime:()=>Pp,IsDuration:()=>Cp,IsEmail:()=>$p,IsHostname:()=>qp,IsIPv4:()=>Up,IsIPv6:()=>Bp,IsIdnEmail:()=>Fp,IsIdnHostname:()=>jp,IsIri:()=>Kp,IsIriReference:()=>Gp,IsJsonPointer:()=>Wp,IsJsonPointerUriFragment:()=>Hp,IsRegex:()=>zp,IsRelativeJsonPointer:()=>Vp,IsTime:()=>ou,IsUri:()=>Xp,IsUriReference:()=>Jp,IsUriTemplate:()=>Qp,IsUrl:()=>Yp,IsUuid:()=>Zp,Reset:()=>IA,Set:()=>L1,Test:()=>xA});var Ru="shell-guard",Xg=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class y extends Error{constructor(e){super(e);this.name="NotFoundError"}}var kt="chatgpt:subscription";function Yg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Zg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function lM(e,o){if(e===o)return 0;let a=Array.from({length:o.length+1},(u,m)=>m);for(let u=1;u<=e.length;u++){let m=a[0]??0;a[0]=u;for(let p=1;p<=o.length;p++){let f=a[p]??0;a[p]=Math.min((a[p]??0)+1,(a[p-1]??0)+1,m+(e[u-1]===o[p-1]?0:1)),m=f}}return a[o.length]??0}function ey(e,o){let a=Yg(e);if(!a)return[];let u=Zg(e),m=[];for(let p of o){let f=p.id.indexOf("/"),h=f>=0?p.id.slice(f+1):"",E=[p.id,p.name,h].filter(Boolean).map((R)=>({compact:Yg(R),tokens:Zg(R)})).filter((R)=>R.compact.length>0),S=Number.POSITIVE_INFINITY;for(let R of E)if(R.compact===a)S=Math.min(S,0);else if(R.compact.includes(a)||a.includes(R.compact)){let k=Math.abs(R.compact.length-a.length);S=Math.min(S,1+k/Math.max(R.compact.length,a.length))}else{let k=0;for(let P of u)if(R.tokens.has(P))k++;if(k>0){let P=k/Math.max(u.size,R.tokens.size);S=Math.min(S,10+(1-P)*10)}}if(!Number.isFinite(S)&&a.length>=4){let R=Math.max(2,Math.floor(a.length*0.34));for(let k of E){if(Math.abs(k.compact.length-a.length)>R)continue;let P=lM(a,k.compact);if(P<=R)S=Math.min(S,100+P)}}if(Number.isFinite(S))m.push({model:p,score:S})}return m.sort((p,f)=>p.score-f.score||p.model.id.localeCompare(f.model.id))}function dM(e,o,a=5){return ey(e,o).slice(0,Math.max(1,a)).map((u)=>u.model)}function Vr(e,o){let a=ey(e,o);if(a.length===0)return;let u=a.filter((p)=>p.score===0);if(u.length===1&&u[0])return u[0].model;if(u.length>1)return;let m=a.filter((p)=>p.score<10);if(m.length===1&&m[0])return m[0].model;return}function Kr(e,o){let a=[...o].sort((f,h)=>f.id.localeCompare(h.id)),u=(f)=>f.name===f.id?f.id:`${f.id} (${f.name})`,m=dM(e,a).map(u),p=a.map(u);return[`unknown model ${e}`,`closest matches: ${m.length>0?m.join(", "):"none"}`,`available models (${p.length}): ${p.length>0?p.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
- `)}var Li=["openai-completions","openai-responses","anthropic-messages"];function Qr(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 a=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!a)return;let u=Number.parseFloat(a[1]??"");if(!Number.isFinite(u)||u<=0)return;let m=a[2];if(m==="k")return Math.round(u*1000);if(m==="m")return Math.round(u*1e6);return Math.round(u)}function od(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 fM(e){let o=e.trim();if(!o)return;let a,u,m=o,p=m.match(/\s*\[(.*?)\]\s*$/);if(p&&p.index!==void 0){m=m.slice(0,p.index).trim();let S=p[1]?.split(",").map((k)=>k.trim()).filter(Boolean)??[],R=0;for(let k of S){let P=k.indexOf("=");if(P>=0){let v=k.slice(0,P).trim().toLowerCase(),_=Qr(k.slice(P+1).trim());if(v==="context"||v==="ctx"||v==="window"||v==="contextwindow")a=_;else if(v==="max"||v==="output"||v==="maxtokens")u=_}else{let v=Qr(k);if(R===0)a=v;else if(R===1)u=v;R++}}}else{let S=m.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(S?.[1]&&S[2])m=S[1].trim(),a=Qr(S[2])}let f=m.indexOf("="),h,I;if(f<0)h=m.trim(),I=h;else h=m.slice(0,f).trim(),I=m.slice(f+1).trim()||h;if(!h)return;let E={id:h,name:I};if(a!==void 0)E.contextWindow=a;if(u!==void 0)E.maxTokens=u;return E}function ir(e){return e.split(/\r?\n/).map(fM).filter((o)=>o!==void 0)}function qo(e){return e.map((o)=>{let a=o.name===o.id?o.id:`${o.id}=${o.name}`,u=[];if(o.contextWindow!==void 0)u.push(od(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)u.push(od(o.maxTokens));else u.push(`max=${od(o.maxTokens)}`);return u.length>0?`${a} [${u.join(", ")}]`:a}).join(`
8
- `)}var ty=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var hM=["http","https"];var ry="provider:",ny="oauth:openai",Xr="update:registry";function sd(e){let o=e.trim();if(!o)throw Error("\u8BF7\u8F93\u5165\u4EE3\u7406\u4E3B\u673A\u6216\u5B8C\u6574\u5730\u5740");let a;try{a=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(o)?o:`http://${o}`)}catch{throw Error("\u4EE3\u7406\u5730\u5740\u65E0\u6548")}if(!gM(a.protocol))throw Error("\u4EC5\u652F\u6301 http:// \u6216 https:// \u4EE3\u7406");if(a.username||a.password||a.pathname!=="/"||a.search||a.hash)throw Error("\u4EE3\u7406\u5730\u5740\u53EA\u80FD\u5305\u542B\u534F\u8BAE\u3001\u4E3B\u673A\u548C\u7AEF\u53E3\uFF1B\u8D26\u53F7\u5BC6\u7801\u8BF7\u5355\u72EC\u586B\u5199");return{protocol:a.protocol==="https:"?"https":"http",hostname:a.hostname.replace(/^\[|\]$/g,""),port:a.port?Number(a.port):a.protocol==="https:"?443:8080}}function gM(e){return hM.some((o)=>`${o}:`===e)}function oy(e){return e.startsWith("provider:")&&e.length>9}var Wn=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],Oi=["text","regex"],Ni=["best","recent"],Di=["session","none"];var Ht=4,Ui="https://basalt.work",Bi=["https://basalt.work","https://www.basalt.work"],Jr=7420;var id=["auto","bash","powershell","cmd"];var Go=["active","archived","all"],Fi="session.group";var sy=["pending","in_progress","completed"],ad="basalt-session",nm=["image","text","path"];var iy=["defer","always"],ay=["global","tool","source"];function We(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let a=o;if(typeof a.name!=="string"||!a.name.trim())return{name:e,input:o};if(a.arguments===void 0)return{name:a.name,input:{},source:{name:"tool_call",input:o}};if(!a.arguments||typeof a.arguments!=="object"||Array.isArray(a.arguments))return{name:e,input:o};return{name:a.name,input:a.arguments,source:{name:"tool_call",input:o}}}function $i(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var mt=10,yM=15000000;function qt(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"&&nm.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=yM}function ud(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as uy,existsSync as cy,fsyncSync as my,mkdirSync as py,openSync as ly,readFileSync as dy,renameSync as fy,writeFileSync as hy}from"fs";import{dirname as cd,join as gy}from"path";class Hn{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=gy(e,"auth.json"),this.deviceIdPath=gy(e,"device-id")}load(){if(!cy(this.path))return;let e;try{e=JSON.parse(dy(this.path,"utf8"))}catch{this.quarantine();return}let o=md(e);if(o?.version!==1){this.quarantine();return}let a=md(o.providers);if(!a){this.quarantine();return}for(let[u,m]of Object.entries(a)){if(!xM(m))continue;this.providers[u]=m}}deviceId(){if(cy(this.deviceIdPath)){let o=dy(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return py(cd(this.deviceIdPath),{recursive:!0}),hy(this.deviceIdPath,`${e}
9
- `),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[kt]??=e,delete o.openai;try{this.persist(o)}catch(a){throw Error("\u8F6C\u79FB ChatGPT \u8BA2\u9605\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u65B0\u542F\u52A8",{cause:a})}this.providers=o,this.dirty=!1}async read(e,o){return o?.signal?.throwIfAborted(),this.flush(),this.providers[e]?structuredClone(this.providers[e]):void 0}async list(e){return e?.signal?.throwIfAborted(),this.flush(),Object.entries(this.providers).map(([o,a])=>({providerId:o,type:a.type}))}modify(e,o,a){return this.enqueue(e,()=>this.applyModify(e,o),a)}delete(e,o){return this.enqueue(e,()=>{if(!(e in this.providers)){this.flush();return}let a={...this.providers};delete a[e],this.persist(a),this.providers=a,this.dirty=!1},o)}async close(){this.closed=!0;try{while(this.chains.size)await Promise.all(this.chains.values());this.flush()}catch(e){throw this.closed=!1,e}}enqueue(e,o,a){if(this.closed)return Promise.reject(Error("\u51ED\u636E\u5B58\u50A8\u6B63\u5728\u5173\u95ED"));let u=a?.signal;if(u?.aborted)return Promise.reject(u.reason);let m=this.chains.get(e)??Promise.resolve(),p,f=m.then(()=>{if(u?.throwIfAborted(),p)u?.removeEventListener("abort",p);return o()}),h=f.then(()=>{return},()=>{return});if(this.chains.set(e,h),h.then(()=>{if(this.chains.get(e)===h)this.chains.delete(e)}),!u)return f;return new Promise((I,E)=>{let S=()=>E(u.reason);if(p=S,u.addEventListener("abort",S,{once:!0}),f.then((R)=>{u.removeEventListener("abort",S),I(R)},(R)=>{u.removeEventListener("abort",S),E(R)}),u.aborted)S()})}async applyModify(e,o){this.flush();let a=this.providers[e]?structuredClone(this.providers[e]):void 0,u=await o(a);if(u===void 0)return a?structuredClone(a):void 0;return this.providers[e]=structuredClone(u),this.dirty=!0,this.flush(),structuredClone(u)}flush(){if(!this.dirty)return;this.persist(this.providers),this.dirty=!1}persist(e){py(cd(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,a=ly(o,"w",384);try{hy(a,`${JSON.stringify({version:1,providers:e},null,2)}
10
- `),my(a)}finally{uy(a)}if(fy(o,this.path),process.platform==="win32")return;let u=ly(cd(this.path),"r");try{my(u)}catch(m){if(!(m instanceof Error&&("code"in m)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(m.code))))throw m}finally{uy(u)}}quarantine(){try{fy(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function md(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function xM(e){let o=md(e);if(!o)return!1;if(o.type==="api_key")return o.key===void 0||typeof o.key==="string";if(o.type!=="oauth")return!1;return typeof o.refresh==="string"&&typeof o.access==="string"&&typeof o.expires==="number"}var _M=xy(),dd=ky();import{AsyncLocalStorage as LM}from"async_hooks";var j=new LM;var NM=3,Ay=160,DM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),qM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),$y=/^[A-Za-z_][A-Za-z0-9_]*=/,FM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),jM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),UM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,BM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),GM=new Set(["command","builtin","nohup","time","exec"]),KM=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 im(e){return{out:e.out,depth:e.depth+1}}function Py(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function fd(e,o,a,u){let m=e.length,p=0,f=o;while(f<m){let h=e.charAt(f);if(h==="\\"){f+=2;continue}if(h==="'"||h==='"'||h==="`"){let I=f+1;while(I<m){let E=e.charAt(I);if(E==="\\"){I+=2;continue}if(E===h)break;I++}f=I+1;continue}if(h===a)p++;else if(h===u){if(p--,p===0)return f+1}f++}return m}function HM(e){let o={text:"",subs:[],heredocs:[]},a=[],u=[],m=e.length,p=0,f=0,h=null,I=(E)=>{if(e.charAt(E)==="`"){let P=E+1;while(P<m){let v=e.charAt(P);if(v==="\\"){P+=2;continue}if(v==="`")break;P++}return o.subs.push(e.slice(E+1,P)),P<m?P+1:m}if(e.charAt(E+1)==="("){let P=fd(e,E+1,"(",")");if(e.charAt(E+2)==="(")return a.push(e.slice(E,P)),P;return o.subs.push(e.slice(E+2,P-1)),P}let R=fd(e,E+1,"{","}"),k=e.slice(E+2,R-1);for(let P=0;P<k.length;P++){let v=k.charAt(P);if(v==="\\"){P++;continue}if(v==="`"){let _=k.indexOf("`",P+1);o.subs.push(_<0?k.slice(P+1):k.slice(P+1,_)),P=_<0?k.length:_;continue}if(v==="$"&&k.charAt(P+1)==="("){let _=fd(k,P+1,"(",")");o.subs.push(k.slice(P+2,_-1)),P=_-1}}return R};while(p<m){let E=e.charAt(p);if(h==="'"){if(E==="'")h=null;a.push(E),p++;continue}if(h==='"'){if(E==="\\"){if(!'$`"\\\n'.includes(e.charAt(p+1)))a.push("\\");a.push(E,e.charAt(p+1)),p+=2;continue}if(E==='"'){h=null,a.push(E),p++;continue}if(E==="`"||E==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=I(p);continue}a.push(E),p++;continue}if(E==="'"||E==='"'){h=E,a.push(E),p++;continue}if(E==="\\"){a.push(E,e.charAt(p+1)),p+=2;continue}if(E==="`"||E==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=I(p);continue}if(E==="#"){let S=a.at(-1);if(S===void 0||`
2
+ import{ei,nn,G}from"./chunk-38g4jd6v.js";import{Gi,ze,Rt,zi,lo,Vi,Ki,Qi,Ct,Yi,Be,uo,Je}from"./chunk-44a7f5ta.js";import{eo,ts,rn}from"./chunk-g5p9mj1r.js";import{Oe,ie,ti,to,D,ro,yt,Ne,Sr,H,De,no,bt,ge,zt,ae,on,ri,Ue,se,st,oo,ni,xe,rs,Hi,ve,io,d,ns,Y,sn,K,os}from"./chunk-4hf0r9hv.js";import{so,U,ao,Xe,qi,jt,Ie}from"./chunk-4yxd2kg1.js";import{r,Ze}from"./chunk-qd2enpr2.js";var Iy=r(function(y2,xy){var SM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],pd=/[\n\r\u2028\u2029]/,wM=/[\s#!"$&'():;<=>@\\^`|~]/g;xy.exports=function(o){var a=!1;return o.map(function(u){if(a&&typeof u==="string"&&pd.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(pd.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(wM,"\\$&")}if("op"in u&&typeof u.op==="string"){if(SM.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(pd.test(u.comment))throw TypeError("`comment` must not contain line terminators");return a=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var Ay=r(function(x2,ky){var Ty="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",by=new RegExp("^"+Ty+"$"),Ey="|&;()<> \\t",TM="'([^']*?)'",Ry="(?:\\\\[\\s\\S]|[^\\\\'])*?",Sy="\\$'"+Ry+"'",sm=new RegExp("\\$'"+Ry+"(?:(')|\\\\?$)","g"),RM="abeEfnrtv",kM=`\x07\b\x1B\x1B\f
3
+ \r \v`,AM=/^#$/,ld="'",wy='"',ku="$",vi="",PM=4294967296;for(om=0;om<4;om++)vi+=(PM*Math.random()).toString(16);var om,CM=new RegExp("^"+vi);function $M(e,o){var a=o.lastIndex,u=[],m;while(m=o.exec(e))if(u[u.length]=m,o.lastIndex===m.index)o.lastIndex+=1;return o.lastIndex=a,u}function vM(e,o,a){var u=typeof e==="function"?e(a):e[a];if(typeof u>"u"&&a!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+vi+JSON.stringify(u)+vi;return o+u}var MM=/\\([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 OM(e,o){var a=o.charAt(0);if(a==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(a==="x"||a==="u"||a==="U"){var m=parseInt(o.slice(1),16);if(m>1114111)return e;return String.fromCharCode.apply(null,m>65535?[55232+(m>>10),56320+(m&1023)]:[m])}if(a>="0"&&a<="7")return String.fromCharCode(parseInt(o,8)&255);var p=RM.indexOf(o);return p<0?o:kM.charAt(p)}function _M(e){return e.replace(MM,OM).split("\x00")[0]}function LM(e,o){return sm.lastIndex=o,!!sm.exec(e)[1]}function NM(e,o,a){if(!a)a={};var u=a.escape||"\\",m=a.splitUnquoted===!0?`
4
+ `:typeof a.splitUnquoted==="string"?a.splitUnquoted:"",p="(\\"+u+`['"$\\`+u+Ey+"]|\\$\\$|\\$(?!"+Sy.slice(2)+`)|[^\\s'"$`+Ey+"])+",f='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',h=new RegExp(["("+Ty+")","("+Sy+"|"+p+"|"+f+"|"+TM+")+"].join("|"),"g"),I=$M(e,h);if(I.length===0)return[];if(!o)o={};var E=!1;return I.map(function(S){var R=S[0];if(!R||E)return;if(by.test(R))return{op:R};var k=!1,P=!1,v="",_=[],Q=!1,L=null,V=!1,J;function Z(){J+=1;var ue,we,Ve=R.charAt(J);if(Ve==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var je=1;ue=J;while(je>0&&ue<R.length){if(R.charAt(ue)==="{"&&R.charAt(ue-1)==="$")je+=1;else if(R.charAt(ue)==="}")je-=1;ue+=1}if(je!==0)throw Error("Bad substitution: "+R.slice(J));ue-=1,we=R.slice(J,ue),J=ue}else if(/[*@#?$!-]/.test(Ve))we=Ve;else{var Qt=R.slice(J);if(ue=Qt.match(/[^\w\d_]/),!ue)we=Qt,J=R.length;else we=Qt.slice(0,ue.index),J+=ue.index-1}return vM(o,"",we)}function ne(){if(L===null)return;if(L===0){if(v!=="")_[_.length]=v,v=""}else{_[_.length]=v,v="";for(var ue=1;ue<L;ue+=1)_[_.length]=""}L=null}for(J=0;J<R.length;J++){var z=R.charAt(J);if(m&&z!==ku)ne();if(V=V||!k&&(z==="*"||z==="?"),P)v+=z,P=!1;else if(k)if(z===k)k=!1;else if(k==ld)v+=z;else if(z===u)if(J+=1,z=R.charAt(J),z===wy||z===u||z===ku)v+=z;else v+=u+z;else if(z===ku)v+=Z();else v+=z;else if(z===wy||z===ld)k=z,Q=!0;else if(by.test(z))return{op:R};else if(AM.test(z)){E=!0;var oe={comment:e.slice(S.index+J+1)};if(v.length)return[v,oe];return[oe]}else if(z===u)P=!0;else if(z===ku&&R.charAt(J+1)===ld&&LM(R,J))ne(),Q=!0,v+=_M(R.slice(J+2,sm.lastIndex-1)),J=sm.lastIndex-1;else if(z===ku){var fe=Z();if(!m)v+=fe;else for(var Ae=0;Ae<fe.length;Ae+=1){var Ge=fe.charAt(Ae);if(m.indexOf(Ge)<0)ne(),v+=Ge;else if(L===null)L=Ge===" "||Ge==="\t"||Ge===`
5
+ `?0:1;else if(Ge!==" "&&Ge!=="\t"&&Ge!==`
6
+ `)L+=1}}else v+=z}if(V)return{op:"glob",pattern:v};if(m){if(L!==null&&L>0){_[_.length]=v,v="";for(var ee=1;ee<L;ee+=1)_[_.length]=""}if(v!==""||Q&&_.length===0)_[_.length]=v;return _}return v}).reduce(function(S,R){if(typeof R>"u")return S;return[].concat(R).forEach(function(k){S[S.length]=k}),S},[])}ky.exports=function(o,a,u){var m=NM(o,a,u);if(typeof a!=="function")return m;return m.reduce(function(p,f){if(typeof f==="object")return p[p.length]=f,p;var h=f.split(RegExp("("+vi+".*?"+vi+")","g"));if(h.length===1)return p[p.length]=h[0],p;return h.filter(Boolean).forEach(function(I){p[p.length]=CM.test(I)?JSON.parse(I.split(vi)[1]):I}),p},[])}});var Zo={};Ze(Zo,{ArchivedError:()=>ft,BadRequestError:()=>t,BusyError:()=>ce,DEFAULT_TIMEOUT:()=>G$,FoldingPolicy:()=>zc,MAX_ATTACHMENTS:()=>mt,MAX_TIMEOUT:()=>K$,MAX_TOOL_OUTPUT:()=>Ce,NotFoundError:()=>y,PluginCheckError:()=>ht,ProcessRegistry:()=>Gt,Type:()=>mo,aliased:()=>Te,budget:()=>Wc,calls:()=>Po,clip:()=>le,clipSaved:()=>it,dataDir:()=>nt,definePlugin:()=>C,estimateMessage:()=>j,estimateTokens:()=>W,estimateTools:()=>ki,extensionTranscript:()=>vl,findWindowsBash:()=>lr,foldPoint:()=>Kc,foldedThrough:()=>Ta,formatLines:()=>Vc,gateShellCommand:()=>Qe,groupRuns:()=>Qs,historyTodos:()=>dr,newID:()=>re,normalizeRunRecords:()=>Jh,processRegistry:()=>mr,project:()=>Me,projectUserText:()=>Ai,releaseProcesses:()=>fr,requestBody:()=>O,resolveShellCommand:()=>Aa,retainProcesses:()=>hr,routeParam:()=>A,runShell:()=>cr,sealPoint:()=>lu,selectHistory:()=>pr,sessionTools:()=>ur,staleFold:()=>kl,text:()=>c,timerClock:()=>Le,tool:()=>T,toolSession:()=>q,transcript:()=>hu,usable:()=>me,userTranscript:()=>$l,validAttachment:()=>qt,workState:()=>Pl});var Qo={};Ze(Qo,{AssistantMessageEventStream:()=>U,AssistantMessageFrameEncoder:()=>XR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>ek,EventStream:()=>so,InMemoryCredentialStore:()=>to,InMemoryModelsStore:()=>ro,ModelsError:()=>D,StringEnum:()=>$F,Type:()=>mo,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>Y,clampThinkingLevel:()=>K,cleanupSessionResources:()=>ts,collapseSystemMessages:()=>Ue,contentText:()=>Sr,createAssistantMessageDiagnostic:()=>jt,createAssistantMessageEventStream:()=>ao,createFauxCore:()=>QR,createInitialSystemMessage:()=>no,createModels:()=>io,createProvider:()=>d,declarationsEqual:()=>oo,defaultProviderAuthContext:()=>ti,envApiKeyAuth:()=>b,extractDiagnosticError:()=>qi,fauxAssistantMessage:()=>Vo,fauxProvider:()=>Ko,fauxText:()=>qn,fauxThinking:()=>jo,fauxToolCall:()=>cF,formatThrownValue:()=>Xe,getCurrentSystemMessage:()=>on,getCurrentSystemPrompt:()=>ri,getCurrentTools:()=>ae,getDeclaredTools:()=>xe,getInitialSystemMessage:()=>ge,getModelType:()=>yt,getOverflowPatterns:()=>RF,getSupportedThinkingLevels:()=>sn,getSystemMessageText:()=>H,getToolStateChanges:()=>ni,hasApi:()=>ns,hasNonAdditiveToolChanges:()=>Hi,hasToolRedefinitions:()=>rs,isContextOverflow:()=>ha,isModelType:()=>Ne,isRecoverableLength:()=>TF,isRetryableAssistantError:()=>rk,lazyApi:()=>ie,lazyOAuth:()=>de,lazyStream:()=>Oe,modelsAreEqual:()=>os,normalizeContext:()=>bt,parseJsonWithRepair:()=>nn,parseStreamingJson:()=>G,reduceAssistantMessageFrames:()=>EF,registerSessionResourceCleanup:()=>eo,renderSystemMessageUpdate:()=>De,repairJson:()=>ei,resolveTranscript:()=>se,resolveTranscriptTools:()=>ve,retryAssistantCall:()=>CF,retryDelayMs:()=>tk,toToolDeclaration:()=>st,uuidv7:()=>rn,validateToolArguments:()=>cu,validateToolCall:()=>hB,withoutInitialSystemMessage:()=>zt});var B={};Ze(B,{Counted:()=>Sd,Entries:()=>hn,EntriesRegExp:()=>wd,Every:()=>mn,EveryAll:()=>$n,GraphemeCount:()=>lO,HasPropertyKey:()=>pe,IsArray:()=>qe,IsBigInt:()=>qr,IsBoolean:()=>fn,IsClassInstance:()=>Ky,IsConstructor:()=>bd,IsDeepEqual:()=>$a,IsEqual:()=>M,IsFunction:()=>gs,IsGreaterEqualThan:()=>Pa,IsGreaterThan:()=>ji,IsInteger:()=>cm,IsLessEqualThan:()=>ys,IsLessThan:()=>Pu,IsMaxLength:()=>Hy,IsMinLength:()=>Wy,IsMultipleOf:()=>Gy,IsNull:()=>bo,IsNumber:()=>Ot,IsObject:()=>ut,IsObjectNotArray:()=>Uo,IsString:()=>dt,IsSymbol:()=>Ed,IsUndefined:()=>Bt,IsUnsafePropertyKey:()=>Cu,IsValueLike:()=>Ji,Keys:()=>Ee,ShiftLeft:()=>xt,Some:()=>Ca,SomeAll:()=>zy,Symbols:()=>Vy,Values:()=>Td});var oa={};Ze(oa,{Hash:()=>vd,HashCode:()=>Px});var _t={};Ze(_t,{ExtendsFalse:()=>et,ExtendsTrue:()=>Se,ExtendsUnion:()=>Zd,IsExtendsFalse:()=>rf,IsExtendsTrue:()=>tf,IsExtendsTrueLike:()=>co,IsExtendsUnion:()=>ef,Match:()=>wr});var mo={};Ze(mo,{Any:()=>_a,Array:()=>F,BigInt:()=>Lu,Boolean:()=>N,Call:()=>Uw,Capitalize:()=>Vw,Codec:()=>Im,Conditional:()=>rT,Constructor:()=>Is,ConstructorParameters:()=>oT,Cyclic:()=>Ss,Decode:()=>Mx,DecodeBuilder:()=>xm,Dependent:()=>na,Encode:()=>Ox,EncodeBuilder:()=>ym,Enum:()=>xx,Evaluate:()=>Pn,Exclude:()=>iT,Extends:()=>An,ExtendsResult:()=>_t,Extract:()=>uT,Function:()=>bs,Generic:()=>ui,Identifier:()=>Nu,Immutable:()=>_x,Index:()=>lT,Infer:()=>_u,InstanceType:()=>DT,Instantiate:()=>Mo,Integer:()=>x,Interface:()=>Sw,Intersect:()=>Mn,IsAny:()=>Or,IsArray:()=>St,IsBigInt:()=>go,IsBoolean:()=>Vn,IsCall:()=>Wa,IsCodec:()=>Kn,IsConstructor:()=>zr,IsCyclic:()=>Yt,IsDependent:()=>Fr,IsEnum:()=>un,IsEnumValue:()=>yx,IsFunction:()=>en,IsGeneric:()=>Oa,IsIdentifier:()=>qx,IsImmutable:()=>sa,IsInfer:()=>an,IsInteger:()=>yn,IsIntersect:()=>Ke,IsKind:()=>Re,IsLiteral:()=>gt,IsNever:()=>ho,IsNull:()=>Ts,IsNumber:()=>Cr,IsObject:()=>He,IsOptional:()=>ln,IsParameter:()=>Bx,IsReadonly:()=>aa,IsRecord:()=>Kt,IsRef:()=>Ft,IsRefine:()=>bm,IsRest:()=>fi,IsSchema:()=>Mr,IsString:()=>cn,IsSymbol:()=>Rs,IsTemplateLiteral:()=>tr,IsThis:()=>_m,IsTuple:()=>pt,IsUndefined:()=>ss,IsUnion:()=>be,IsUnknown:()=>tn,IsUnsafe:()=>gm,IsVoid:()=>yo,KeyOf:()=>FT,Literal:()=>i,Lowercase:()=>Jw,Mapped:()=>zT,Module:()=>LR,Never:()=>Vt,NonNullable:()=>XT,Null:()=>On,Number:()=>te,Object:()=>l,Omit:()=>ZT,Optional:()=>n,Parameter:()=>ua,Parameters:()=>rR,Partial:()=>oR,Pick:()=>pR,Readonly:()=>Lx,ReadonlyObject:()=>Mf,ReadonlyType:()=>fR,Record:()=>ks,RecordKey:()=>di,RecordPattern:()=>xn,RecordValue:()=>or,Ref:()=>pn,Refine:()=>Nx,Required:()=>CR,Rest:()=>ma,ReturnType:()=>vR,Script:()=>FR,String:()=>s,Symbol:()=>Da,TemplateLiteral:()=>GS,This:()=>Om,Tuple:()=>Ur,Uncapitalize:()=>Qw,Undefined:()=>ja,Union:()=>g,Unknown:()=>Pr,Unsafe:()=>sr,Uppercase:()=>Xw,Void:()=>Lm,With:()=>Ip});var iu={};Ze(iu,{Clear:()=>xA,Entries:()=>D1,Get:()=>j1,Has:()=>F1,IsDate:()=>nu,IsDateTime:()=>Pp,IsDuration:()=>Cp,IsEmail:()=>$p,IsHostname:()=>qp,IsIPv4:()=>Up,IsIPv6:()=>Bp,IsIdnEmail:()=>Fp,IsIdnHostname:()=>jp,IsIri:()=>Kp,IsIriReference:()=>Gp,IsJsonPointer:()=>Wp,IsJsonPointerUriFragment:()=>Hp,IsRegex:()=>zp,IsRelativeJsonPointer:()=>Vp,IsTime:()=>ou,IsUri:()=>Xp,IsUriReference:()=>Jp,IsUriTemplate:()=>Qp,IsUrl:()=>Yp,IsUuid:()=>Zp,Reset:()=>bA,Set:()=>q1,Test:()=>IA});var Ru="shell-guard",Yg=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class y extends Error{constructor(e){super(e);this.name="NotFoundError"}}var kt="chatgpt:subscription";function Zg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function ey(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function hM(e,o){if(e===o)return 0;let a=Array.from({length:o.length+1},(u,m)=>m);for(let u=1;u<=e.length;u++){let m=a[0]??0;a[0]=u;for(let p=1;p<=o.length;p++){let f=a[p]??0;a[p]=Math.min((a[p]??0)+1,(a[p-1]??0)+1,m+(e[u-1]===o[p-1]?0:1)),m=f}}return a[o.length]??0}function ty(e,o){let a=Zg(e);if(!a)return[];let u=ey(e),m=[];for(let p of o){let f=p.id.indexOf("/"),h=f>=0?p.id.slice(f+1):"",E=[p.id,p.name,h].filter(Boolean).map((R)=>({compact:Zg(R),tokens:ey(R)})).filter((R)=>R.compact.length>0),S=Number.POSITIVE_INFINITY;for(let R of E)if(R.compact===a)S=Math.min(S,0);else if(R.compact.includes(a)||a.includes(R.compact)){let k=Math.abs(R.compact.length-a.length);S=Math.min(S,1+k/Math.max(R.compact.length,a.length))}else{let k=0;for(let P of u)if(R.tokens.has(P))k++;if(k>0){let P=k/Math.max(u.size,R.tokens.size);S=Math.min(S,10+(1-P)*10)}}if(!Number.isFinite(S)&&a.length>=4){let R=Math.max(2,Math.floor(a.length*0.34));for(let k of E){if(Math.abs(k.compact.length-a.length)>R)continue;let P=hM(a,k.compact);if(P<=R)S=Math.min(S,100+P)}}if(Number.isFinite(S))m.push({model:p,score:S})}return m.sort((p,f)=>p.score-f.score||p.model.id.localeCompare(f.model.id))}function gM(e,o,a=5){return ty(e,o).slice(0,Math.max(1,a)).map((u)=>u.model)}function Vr(e,o){let a=ty(e,o);if(a.length===0)return;let u=a.filter((p)=>p.score===0);if(u.length===1&&u[0])return u[0].model;if(u.length>1)return;let m=a.filter((p)=>p.score<10);if(m.length===1&&m[0])return m[0].model;return}function Kr(e,o){let a=[...o].sort((f,h)=>f.id.localeCompare(h.id)),u=(f)=>f.name===f.id?f.id:`${f.id} (${f.name})`,m=gM(e,a).map(u),p=a.map(u);return[`unknown model ${e}`,`closest matches: ${m.length>0?m.join(", "):"none"}`,`available models (${p.length}): ${p.length>0?p.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
+ `)}var Li=["openai-completions","openai-responses","anthropic-messages"];function Qr(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 a=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!a)return;let u=Number.parseFloat(a[1]??"");if(!Number.isFinite(u)||u<=0)return;let m=a[2];if(m==="k")return Math.round(u*1000);if(m==="m")return Math.round(u*1e6);return Math.round(u)}function od(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 yM(e){let o=e.trim();if(!o)return;let a,u,m=o,p=m.match(/\s*\[(.*?)\]\s*$/);if(p&&p.index!==void 0){m=m.slice(0,p.index).trim();let S=p[1]?.split(",").map((k)=>k.trim()).filter(Boolean)??[],R=0;for(let k of S){let P=k.indexOf("=");if(P>=0){let v=k.slice(0,P).trim().toLowerCase(),_=Qr(k.slice(P+1).trim());if(v==="context"||v==="ctx"||v==="window"||v==="contextwindow")a=_;else if(v==="max"||v==="output"||v==="maxtokens")u=_}else{let v=Qr(k);if(R===0)a=v;else if(R===1)u=v;R++}}}else{let S=m.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(S?.[1]&&S[2])m=S[1].trim(),a=Qr(S[2])}let f=m.indexOf("="),h,I;if(f<0)h=m.trim(),I=h;else h=m.slice(0,f).trim(),I=m.slice(f+1).trim()||h;if(!h)return;let E={id:h,name:I};if(a!==void 0)E.contextWindow=a;if(u!==void 0)E.maxTokens=u;return E}function ir(e){return e.split(/\r?\n/).map(yM).filter((o)=>o!==void 0)}function qo(e){return e.map((o)=>{let a=o.name===o.id?o.id:`${o.id}=${o.name}`,u=[];if(o.contextWindow!==void 0)u.push(od(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)u.push(od(o.maxTokens));else u.push(`max=${od(o.maxTokens)}`);return u.length>0?`${a} [${u.join(", ")}]`:a}).join(`
8
+ `)}var ry=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var xM=["http","https"];var ny="provider:",oy="oauth:openai",Xr="update:registry";function sd(e){let o=e.trim();if(!o)throw Error("\u8BF7\u8F93\u5165\u4EE3\u7406\u4E3B\u673A\u6216\u5B8C\u6574\u5730\u5740");let a;try{a=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(o)?o:`http://${o}`)}catch{throw Error("\u4EE3\u7406\u5730\u5740\u65E0\u6548")}if(!IM(a.protocol))throw Error("\u4EC5\u652F\u6301 http:// \u6216 https:// \u4EE3\u7406");if(a.username||a.password||a.pathname!=="/"||a.search||a.hash)throw Error("\u4EE3\u7406\u5730\u5740\u53EA\u80FD\u5305\u542B\u534F\u8BAE\u3001\u4E3B\u673A\u548C\u7AEF\u53E3\uFF1B\u8D26\u53F7\u5BC6\u7801\u8BF7\u5355\u72EC\u586B\u5199");return{protocol:a.protocol==="https:"?"https":"http",hostname:a.hostname.replace(/^\[|\]$/g,""),port:a.port?Number(a.port):a.protocol==="https:"?443:8080}}function IM(e){return xM.some((o)=>`${o}:`===e)}function sy(e){return e.startsWith("provider:")&&e.length>9}var Wn=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],Oi=["text","regex"],Ni=["best","recent"],Di=["session","none"];var Ht=4,Ui="https://basalt.work",Bi=["https://basalt.work","https://www.basalt.work"],Jr=7420;var id=["auto","bash","powershell","cmd"];var Go=["active","archived","all"],Fi="session.group";var iy=["pending","in_progress","completed"],ad="basalt-session",nm=["image","text","path"];var ay=["defer","always"],uy=["global","tool","source"];function We(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let a=o;if(typeof a.name!=="string"||!a.name.trim())return{name:e,input:o};if(a.arguments===void 0)return{name:a.name,input:{},source:{name:"tool_call",input:o}};if(!a.arguments||typeof a.arguments!=="object"||Array.isArray(a.arguments))return{name:e,input:o};return{name:a.name,input:a.arguments,source:{name:"tool_call",input:o}}}function $i(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var mt=10,bM=15000000;function qt(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"&&nm.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=bM}function ud(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as cy,existsSync as my,fsyncSync as py,mkdirSync as ly,openSync as dy,readFileSync as fy,renameSync as hy,writeFileSync as gy}from"fs";import{dirname as cd,join as yy}from"path";class Hn{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=yy(e,"auth.json"),this.deviceIdPath=yy(e,"device-id")}load(){if(!my(this.path))return;let e;try{e=JSON.parse(fy(this.path,"utf8"))}catch{this.quarantine();return}let o=md(e);if(o?.version!==1){this.quarantine();return}let a=md(o.providers);if(!a){this.quarantine();return}for(let[u,m]of Object.entries(a)){if(!EM(m))continue;this.providers[u]=m}}deviceId(){if(my(this.deviceIdPath)){let o=fy(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return ly(cd(this.deviceIdPath),{recursive:!0}),gy(this.deviceIdPath,`${e}
9
+ `),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[kt]??=e,delete o.openai;try{this.persist(o)}catch(a){throw Error("\u8F6C\u79FB ChatGPT \u8BA2\u9605\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u65B0\u542F\u52A8",{cause:a})}this.providers=o,this.dirty=!1}async read(e,o){return o?.signal?.throwIfAborted(),this.flush(),this.providers[e]?structuredClone(this.providers[e]):void 0}async list(e){return e?.signal?.throwIfAborted(),this.flush(),Object.entries(this.providers).map(([o,a])=>({providerId:o,type:a.type}))}modify(e,o,a){return this.enqueue(e,()=>this.applyModify(e,o),a)}delete(e,o){return this.enqueue(e,()=>{if(!(e in this.providers)){this.flush();return}let a={...this.providers};delete a[e],this.persist(a),this.providers=a,this.dirty=!1},o)}async close(){this.closed=!0;try{while(this.chains.size)await Promise.all(this.chains.values());this.flush()}catch(e){throw this.closed=!1,e}}enqueue(e,o,a){if(this.closed)return Promise.reject(Error("\u51ED\u636E\u5B58\u50A8\u6B63\u5728\u5173\u95ED"));let u=a?.signal;if(u?.aborted)return Promise.reject(u.reason);let m=this.chains.get(e)??Promise.resolve(),p,f=m.then(()=>{if(u?.throwIfAborted(),p)u?.removeEventListener("abort",p);return o()}),h=f.then(()=>{return},()=>{return});if(this.chains.set(e,h),h.then(()=>{if(this.chains.get(e)===h)this.chains.delete(e)}),!u)return f;return new Promise((I,E)=>{let S=()=>E(u.reason);if(p=S,u.addEventListener("abort",S,{once:!0}),f.then((R)=>{u.removeEventListener("abort",S),I(R)},(R)=>{u.removeEventListener("abort",S),E(R)}),u.aborted)S()})}async applyModify(e,o){this.flush();let a=this.providers[e]?structuredClone(this.providers[e]):void 0,u=await o(a);if(u===void 0)return a?structuredClone(a):void 0;return this.providers[e]=structuredClone(u),this.dirty=!0,this.flush(),structuredClone(u)}flush(){if(!this.dirty)return;this.persist(this.providers),this.dirty=!1}persist(e){ly(cd(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,a=dy(o,"w",384);try{gy(a,`${JSON.stringify({version:1,providers:e},null,2)}
10
+ `),py(a)}finally{cy(a)}if(hy(o,this.path),process.platform==="win32")return;let u=dy(cd(this.path),"r");try{py(u)}catch(m){if(!(m instanceof Error&&("code"in m)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(m.code))))throw m}finally{cy(u)}}quarantine(){try{hy(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function md(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function EM(e){let o=md(e);if(!o)return!1;if(o.type==="api_key")return o.key===void 0||typeof o.key==="string";if(o.type!=="oauth")return!1;return typeof o.refresh==="string"&&typeof o.access==="string"&&typeof o.expires==="number"}var DM=Iy(),dd=Ay();import{AsyncLocalStorage as qM}from"async_hooks";var q=new qM;var FM=3,Py=160,jM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),UM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),vy=/^[A-Za-z_][A-Za-z0-9_]*=/,BM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),GM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),KM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,HM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),WM=new Set(["command","builtin","nohup","time","exec"]),zM=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 im(e){return{out:e.out,depth:e.depth+1}}function Cy(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function fd(e,o,a,u){let m=e.length,p=0,f=o;while(f<m){let h=e.charAt(f);if(h==="\\"){f+=2;continue}if(h==="'"||h==='"'||h==="`"){let I=f+1;while(I<m){let E=e.charAt(I);if(E==="\\"){I+=2;continue}if(E===h)break;I++}f=I+1;continue}if(h===a)p++;else if(h===u){if(p--,p===0)return f+1}f++}return m}function VM(e){let o={text:"",subs:[],heredocs:[]},a=[],u=[],m=e.length,p=0,f=0,h=null,I=(E)=>{if(e.charAt(E)==="`"){let P=E+1;while(P<m){let v=e.charAt(P);if(v==="\\"){P+=2;continue}if(v==="`")break;P++}return o.subs.push(e.slice(E+1,P)),P<m?P+1:m}if(e.charAt(E+1)==="("){let P=fd(e,E+1,"(",")");if(e.charAt(E+2)==="(")return a.push(e.slice(E,P)),P;return o.subs.push(e.slice(E+2,P-1)),P}let R=fd(e,E+1,"{","}"),k=e.slice(E+2,R-1);for(let P=0;P<k.length;P++){let v=k.charAt(P);if(v==="\\"){P++;continue}if(v==="`"){let _=k.indexOf("`",P+1);o.subs.push(_<0?k.slice(P+1):k.slice(P+1,_)),P=_<0?k.length:_;continue}if(v==="$"&&k.charAt(P+1)==="("){let _=fd(k,P+1,"(",")");o.subs.push(k.slice(P+2,_-1)),P=_-1}}return R};while(p<m){let E=e.charAt(p);if(h==="'"){if(E==="'")h=null;a.push(E),p++;continue}if(h==='"'){if(E==="\\"){if(!'$`"\\\n'.includes(e.charAt(p+1)))a.push("\\");a.push(E,e.charAt(p+1)),p+=2;continue}if(E==='"'){h=null,a.push(E),p++;continue}if(E==="`"||E==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=I(p);continue}a.push(E),p++;continue}if(E==="'"||E==='"'){h=E,a.push(E),p++;continue}if(E==="\\"){a.push(E,e.charAt(p+1)),p+=2;continue}if(E==="`"||E==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=I(p);continue}if(E==="#"){let S=a.at(-1);if(S===void 0||`
11
11
  ;&|()`.includes(S)){while(p<m&&e.charAt(p)!==`
12
12
  `)p++;continue}a.push(E),p++;continue}if(E==="<"&&e.charAt(p+1)==="<"&&e.charAt(p+2)!=="<"){let S=p+2;if(e.charAt(S)==="-")S++;a.push(e.slice(p,S));let R=S;while(R<m&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let k="";while(R<m){let P=e.charAt(R);if(P==="'"||P==='"'){let v=e.indexOf(P,R+1);if(v<0)break;k+=e.slice(R+1,v),R=v+1;continue}if(P==="\\"){k+=e.charAt(R+1),R+=2;continue}if(` \r
13
13
  ;&|()<>`.includes(P))break;k+=P,R++}if(k)u.push(k);p=S;continue}if(E===`
14
- `){if(u.length>0){let S=UM.test(a.slice(f).join(""));p++;for(let R of u.splice(0)){let k=p,P=m;while(p<m){let v=e.indexOf(`
14
+ `){if(u.length>0){let S=KM.test(a.slice(f).join(""));p++;for(let R of u.splice(0)){let k=p,P=m;while(p<m){let v=e.indexOf(`
15
15
  `,p),_=v<0?m:v;if(e.slice(p,_).trim()===R){P=p,p=v<0?m:v+1;break}p=v<0?m:v+1}if(S&&P>k)o.heredocs.push(e.slice(k,P))}}else p++;a.push(";",`
16
- `),f=a.length;continue}a.push(E),p++}return o.text=a.join(""),o}function Au(e,o){if(o.depth>NM)return;let a=HM(e),u;try{u=dd(a.text)}catch{return}let m=[];for(let p of u){if(typeof p==="string"){m.push({kind:"word",text:p});continue}if("pattern"in p){m.push({kind:"word",text:p.pattern});continue}if("op"in p)m.push({kind:"op",text:p.op})}WM(m,o);for(let p of a.subs)Au(p,im(o));for(let p of a.heredocs)Au(p,im(o))}function WM(e,o){let a=[],u=()=>{if(a.length>0)zM(a,o);a=[]};for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;if(p.kind==="op"){if(FM.has(p.text)){u();continue}if(jM.has(p.text)){if(/^\d+$/.test(a.at(-1)??""))a.pop();m++}continue}a.push(p.text)}u()}function zM(e,o){let a=0;for(;;){let f=e[a];if(f===void 0)return;if(qM.has(f)||$y.test(f)){a++;continue}let h=JM(Py(f),e,a);if(h===a)break;a=h}let u=e[a];if(u===void 0)return;let m=Py(u),p=e.slice(a+1);if(m==="git"){XM(u,p,o);return}if(DM.has(m)){VM(p,o);return}if(m==="powershell"||m==="pwsh")Cy(p,/^-(command|c)$/i,o);if(m==="cmd")Cy(p,/^\/[ck]$/i,o)}function Cy(e,o,a){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let m=e.slice(u+1).join(" ");if(m.trim())Au(m,im(a));return}}function VM(e,o){for(let a=0;a<e.length;a++){let u=e[a]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){a++;continue}if(u.startsWith("--"))continue;let m=/^-[a-zA-Z]*c(.*)$/.exec(u);if(m){let p=m[1]||e[a+1];if(p)Au(p,im(o));return}if(u.startsWith("-")||u==="")continue;return}}function JM(e,o,a){if(GM.has(e)){let p=a+1;while(o[p]?.startsWith("-"))p++;return p}let u=KM.get(e);if(!u)return a;let m=a+1;for(;;){let p=o[m];if(p===void 0)return m;if(u.includes(p)){m+=2;continue}if($y.test(p)||p.startsWith("-")){m++;continue}return m}}function Fo(e,o){return e.some((a)=>a.length>1&&a.startsWith("-")&&!a.startsWith("--")&&a.slice(1).includes(o))}function Xn(e,o){return e.some((a)=>a===`--${o}`||a.startsWith(`--${o}=`))}var QM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Fo(e,"f")||Fo(e,"i")||Xn(e,"force")||Xn(e,"interactive"))&&!(Fo(e,"n")||Xn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Fo(e,"f")||Xn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Fo(e,"f")||Xn(e,"force")||Fo(e,"C")||Xn(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)=>Fo(e,"f")||Xn(e,"force")||Xn(e,"force-with-lease")||Xn(e,"force-if-includes")||Xn(e,"delete")||Xn(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)=>Xn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Fo(e,"D")||Fo(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)=>Xn(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)=>Fo(e,"f")||Xn(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"&&(Fo(e,"f")||Xn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function XM(e,o,a){let u=0;for(;;){let I=o[u];if(I===void 0)break;if(BM.has(I)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(I)||/^-[Cc].+/.test(I)||I.startsWith("-")){u++;continue}break}let m=o[u]?.toLowerCase();if(!m)return;let p=QM[m];if(!p)return;let f=p(o.slice(u+1));if(!f)return;let h=[e,...o.slice(u)].join(" ");a.out.push({rule:m,fragment:h.length>Ay?`${h.slice(0,Ay)}\u2026`:h,reason:f})}function gd(e){let o={out:[],depth:0};return Au(e,o),o.out}function vy(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),a=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${a}`}var hd=new Map;function YM(e,o,a,u,m){let p=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((f)=>{let h=(E)=>{if(!hd.delete(p))return;m?.removeEventListener("abort",I),f(E)},I=()=>{My(e,p),h("aborted")};if(hd.set(p,{session:e,finish:h}),e.appendExtension({namespace:Ru,kind:"requested",schemaVersion:1,payload:{id:p,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:E,reason:S})=>({fragment:E,reason:S})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${a}`}}),m?.aborted)I();else m?.addEventListener("abort",I,{once:!0})})}function My(e,o){try{e.appendExtension({namespace:Ru,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function zo(e,o,a){let u=hd.get(o);if(!u||u.session!==e){if(!ZM(e,o))return"unknown";return My(e,o),"expired"}return e.appendExtension({namespace:Ru,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:a,resolvedAt:Date.now()},display:{text:a?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(a?"approved":"denied"),"answered"}function ZM(e,o){let a=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==Ru)continue;let m=u.payload;if(!m||typeof m!=="object"||!("id"in m)||m.id!==o)continue;if(u.kind==="requested")a=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return a}function yd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${vy(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function Qe(e,o){let a=gd(e);if(!a.at(0))return;let m=vy(a),p=j.getStore();if(p?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${m}\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`${yd(a)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let f=await YM(p,e,m,a,o);if(f==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${m} \u672A\u6267\u884C\uFF1A${f==="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 eO,mkdirSync as tO,writeFileSync as rO}from"fs";import{homedir as nO}from"os";import{join as Mi}from"path";function nt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=nO();if(process.platform==="win32")return Mi(e.LOCALAPPDATA??Mi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Mi(o,"Library","Application Support","basalt");return Mi(e.XDG_DATA_HOME??Mi(o,".local","share"),"basalt")}function oO(e){return Mi(e,".basalt","tmp")}function xd(e){let o=oO(e);tO(o,{recursive:!0});let a=Mi(o,".gitignore");if(!eO(a))rO(a,`*
16
+ `),f=a.length;continue}a.push(E),p++}return o.text=a.join(""),o}function Au(e,o){if(o.depth>FM)return;let a=VM(e),u;try{u=dd(a.text)}catch{return}let m=[];for(let p of u){if(typeof p==="string"){m.push({kind:"word",text:p});continue}if("pattern"in p){m.push({kind:"word",text:p.pattern});continue}if("op"in p)m.push({kind:"op",text:p.op})}JM(m,o);for(let p of a.subs)Au(p,im(o));for(let p of a.heredocs)Au(p,im(o))}function JM(e,o){let a=[],u=()=>{if(a.length>0)QM(a,o);a=[]};for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;if(p.kind==="op"){if(BM.has(p.text)){u();continue}if(GM.has(p.text)){if(/^\d+$/.test(a.at(-1)??""))a.pop();m++}continue}a.push(p.text)}u()}function QM(e,o){let a=0;for(;;){let f=e[a];if(f===void 0)return;if(UM.has(f)||vy.test(f)){a++;continue}let h=YM(Cy(f),e,a);if(h===a)break;a=h}let u=e[a];if(u===void 0)return;let m=Cy(u),p=e.slice(a+1);if(m==="git"){eO(u,p,o);return}if(jM.has(m)){XM(p,o);return}if(m==="powershell"||m==="pwsh")$y(p,/^-(command|c)$/i,o);if(m==="cmd")$y(p,/^\/[ck]$/i,o)}function $y(e,o,a){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let m=e.slice(u+1).join(" ");if(m.trim())Au(m,im(a));return}}function XM(e,o){for(let a=0;a<e.length;a++){let u=e[a]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){a++;continue}if(u.startsWith("--"))continue;let m=/^-[a-zA-Z]*c(.*)$/.exec(u);if(m){let p=m[1]||e[a+1];if(p)Au(p,im(o));return}if(u.startsWith("-")||u==="")continue;return}}function YM(e,o,a){if(WM.has(e)){let p=a+1;while(o[p]?.startsWith("-"))p++;return p}let u=zM.get(e);if(!u)return a;let m=a+1;for(;;){let p=o[m];if(p===void 0)return m;if(u.includes(p)){m+=2;continue}if(vy.test(p)||p.startsWith("-")){m++;continue}return m}}function Fo(e,o){return e.some((a)=>a.length>1&&a.startsWith("-")&&!a.startsWith("--")&&a.slice(1).includes(o))}function Xn(e,o){return e.some((a)=>a===`--${o}`||a.startsWith(`--${o}=`))}var ZM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Fo(e,"f")||Fo(e,"i")||Xn(e,"force")||Xn(e,"interactive"))&&!(Fo(e,"n")||Xn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Fo(e,"f")||Xn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Fo(e,"f")||Xn(e,"force")||Fo(e,"C")||Xn(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)=>Fo(e,"f")||Xn(e,"force")||Xn(e,"force-with-lease")||Xn(e,"force-if-includes")||Xn(e,"delete")||Xn(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)=>Xn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Fo(e,"D")||Fo(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)=>Xn(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)=>Fo(e,"f")||Xn(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"&&(Fo(e,"f")||Xn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function eO(e,o,a){let u=0;for(;;){let I=o[u];if(I===void 0)break;if(HM.has(I)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(I)||/^-[Cc].+/.test(I)||I.startsWith("-")){u++;continue}break}let m=o[u]?.toLowerCase();if(!m)return;let p=ZM[m];if(!p)return;let f=p(o.slice(u+1));if(!f)return;let h=[e,...o.slice(u)].join(" ");a.out.push({rule:m,fragment:h.length>Py?`${h.slice(0,Py)}\u2026`:h,reason:f})}function gd(e){let o={out:[],depth:0};return Au(e,o),o.out}function My(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),a=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${a}`}var hd=new Map;function tO(e,o,a,u,m){let p=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((f)=>{let h=(E)=>{if(!hd.delete(p))return;m?.removeEventListener("abort",I),f(E)},I=()=>{Oy(e,p),h("aborted")};if(hd.set(p,{session:e,finish:h}),e.appendExtension({namespace:Ru,kind:"requested",schemaVersion:1,payload:{id:p,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:E,reason:S})=>({fragment:E,reason:S})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${a}`}}),m?.aborted)I();else m?.addEventListener("abort",I,{once:!0})})}function Oy(e,o){try{e.appendExtension({namespace:Ru,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function zo(e,o,a){let u=hd.get(o);if(!u||u.session!==e){if(!rO(e,o))return"unknown";return Oy(e,o),"expired"}return e.appendExtension({namespace:Ru,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:a,resolvedAt:Date.now()},display:{text:a?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(a?"approved":"denied"),"answered"}function rO(e,o){let a=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==Ru)continue;let m=u.payload;if(!m||typeof m!=="object"||!("id"in m)||m.id!==o)continue;if(u.kind==="requested")a=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return a}function yd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${My(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function Qe(e,o){let a=gd(e);if(!a.at(0))return;let m=My(a),p=q.getStore();if(p?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${m}\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`${yd(a)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let f=await tO(p,e,m,a,o);if(f==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${m} \u672A\u6267\u884C\uFF1A${f==="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 nO,mkdirSync as oO,writeFileSync as sO}from"fs";import{homedir as iO}from"os";import{join as Mi}from"path";function nt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=iO();if(process.platform==="win32")return Mi(e.LOCALAPPDATA??Mi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Mi(o,"Library","Application Support","basalt");return Mi(e.XDG_DATA_HOME??Mi(o,".local","share"),"basalt")}function aO(e){return Mi(e,".basalt","tmp")}function xd(e){let o=aO(e);oO(o,{recursive:!0});let a=Mi(o,".gitignore");if(!nO(a))sO(a,`*
17
17
  !.gitignore
18
- `);return o}function am(e){try{let o=xd(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var hs={assign:0,create:0,clone:0,discard:0,update:0};function _i(e,o,a){return e>=o&&e<=a}function Ly(e){return e===8205}function sO(e){return _i(e,55296,56319)}function Oy(e){return _i(e,127462,127487)}function Ny(e){return _i(e,65024,65039)}function Dy(e){return _i(e,768,879)||_i(e,6832,6911)||_i(e,7616,7679)||_i(e,65056,65071)}function um(e){return e>65535?2:1}function _y(e,o){while(o<e.length){let a=e.codePointAt(o);if(Dy(a)||Ny(a))o+=um(a);else break}return o}function Id(e,o){let a=e.codePointAt(o),u=o+um(a);u=_y(e,u);while(u<e.length-1&&Ly(e.codePointAt(u))){let m=e.codePointAt(u+1);u+=1+um(m),u=_y(e,u)}if(Oy(a)&&u<e.length&&Oy(e.codePointAt(u)))u+=um(e.codePointAt(u));return u}function qy(e){return e>=768&&(sO(e)||Dy(e)||Ny(e)||Ly(e))}function Fy(e){let o=0,a=0;while(a<e.length)a=Id(e,a),o++;return o}function iO(e,o){let a=0,u=0;while(u<e.length)if(u=Id(e,u),++a>=o)return!0;return!1}function aO(e,o){let a=0,u=0;while(u<e.length)if(u=Id(e,u),++a>o)return!1;return!0}function jy(e,o){if(o===0)return!0;if(e.length<o)return!1;let a=0;while(!0){if(qy(e.charCodeAt(a)))return iO(e,o);if(++a>=o)return!0}}function Uy(e,o){if(e.length<=o)return!0;let a=0;while(!0){if(qy(e.charCodeAt(a)))return aO(e,o);if(++a>o)return!1}}function Fe(e){return Array.isArray(e)}function qr(e){return M(typeof e,"bigint")}function fn(e){return M(typeof e,"boolean")}function bd(e){if(Bt(e)||!gs(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 gs(e){return M(typeof e,"function")}function cm(e){return Number.isInteger(e)}function bo(e){return M(e,null)}function Ot(e){return Number.isFinite(e)}function Uo(e){return at(e)&&!Fe(e)}function at(e){return M(typeof e,"object")&&!bo(e)}function lt(e){return M(typeof e,"string")}function Ed(e){return M(typeof e,"symbol")}function Bt(e){return M(e,void 0)}function M(e,o){return e===o}function ji(e,o){return e>o}function Pu(e,o){return e<o}function ys(e,o){return e<=o}function Pa(e,o){return e>=o}function By(e,o){if(qr(e)||qr(o))return BigInt(e)%BigInt(o)===0n;let a=0.0000000001;if(!Ot(e))return!0;if(cm(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<a}function Gy(e){if(!at(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(bo(o))return!1;return M(typeof o.constructor,"function")&&!(M(o.constructor,globalThis.Object)||M(o.constructor.name,"Object"))}function Ji(e){return qr(e)||fn(e)||bo(e)||Ot(e)||lt(e)||Bt(e)}function cO(e){return Fy(e)}function Ky(e,o){return Uy(e,o)}function Hy(e,o){return jy(e,o)}function mn(e,o,a){return e.every((u,m)=>m<o||a(u,m))}function $n(e,o,a){let u=!0;return e.forEach((m,p)=>{if(p>=o&&!a(m,p))u=!1}),u}function Ca(e,o){return e.some((a,u)=>o(a,u))}function Wy(e,o){let a=!1;return e.forEach((u,m)=>{if(o(u,m))a=!0}),a}function Sd(e,o){return e.reduce((a,u,m)=>o(u,m)?++a:a,0)}function xt(e,o,a){return M(e.length,0)?a():o(e[0],e.slice(1))}function Cu(e){return M(e,"__proto__")||M(e,"constructor")||M(e,"prototype")}function pe(e,o){return Cu(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function wd(e){return Se(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function hn(e){return Object.entries(e)}function Se(e){return Object.getOwnPropertyNames(e)}function zy(e){return Object.getOwnPropertySymbols(e)}function Td(e){return Object.values(e)}function mO(e,o){if(!at(o))return!1;let a=Se(e);return M(a.length,Se(o).length)&&a.every((u)=>$a(e[u],o[u]))}function pO(e,o){return Fe(o)&&M(e.length,o.length)&&e.every((a,u)=>$a(e[u],o[u]))}function $a(e,o){return Fe(e)?pO(e,o):at(e)?mO(e,o):M(e,o)}var lO=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function dO(e){return lO.test(e)}function Rn(e,o){return`(${e} && ${o})`}function br(e,o){return`(${e} || ${o})`}function Un(e){return`!(${e})`}function mm(e){return`Array.isArray(${e})`}function Vy(e){return`typeof ${e} === "bigint"`}function fO(e){return`typeof ${e} === "boolean"`}function hO(e){return`Number.isInteger(${e})`}function gO(e){return`${e} === null`}function Jy(e){return`Number.isFinite(${e})`}function Qy(e){return Rn(Xy(e),Un(mm(e)))}function Xy(e){return`typeof ${e} === "object" && ${e} !== null`}function Yy(e){return`typeof ${e} === "string"`}function yO(e){return`typeof ${e} === "symbol"`}function Rd(e){return`${e} === undefined`}function xO(e){return`typeof ${e} === "function"`}function IO(e){return`Guard.IsConstructor(${e})`}function fo(e,o){return`${e} === ${o}`}function Zy(e,o){return`${e} > ${o}`}function kd(e,o){return`${e} < ${o}`}function Xi(e,o){return`${e} <= ${o}`}function $u(e,o){return`${e} >= ${o}`}function bO(e,o){return`Guard.IsMinLength(${e}, ${o})`}function EO(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function xs(e,o,a,u){return M(o,"0")?`${e}.every((${a[0]}, ${a[1]}) => (${u}))`:`${e}.every((${a[0]}, ${a[1]}) => (${a[1]} < ${o}) || (${u}))`}function SO(e,o,a){return`${e}.some((${o[0]}, ${o[1]}) => ${a})`}function wO(e,o,a){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${a}) result = true }); return result })(${e})`}function pm(e,o,a){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${a}) ? ++result : result, 0)`}function ex(e){return`Object.entries(${e})`}function Zi(e){return`Object.getOwnPropertyNames(${e})`}function ea(e,o){return M(o,'"__proto__"')||M(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function tx(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function TO(e){return`[${e.join(", ")}]`}function si(e,o){return`((${e.join(", ")}) => ${o})`}function Er(e,o){return`${e}(${o.join(", ")})`}function Ad(e,o){return`new ${e}(${o.join(", ")})`}function It(e,o){return`${e}${dO(o)?`.${o}`:`[${Pe(o)}]`}`}function Pe(e){if(!Ji(e))throw Error("Unsupported Constant");return lt(e)?JSON.stringify(e):`${e}`}function RO(e,o,a){return`(${e} ? ${o} : ${a})`}function lm(e){return`{ ${e.join("; ")}; }`}function Ds(e,o){return`const ${e} = ${o}`}function rx(e,o){return`if(${e}) { ${o} }`}function dm(e){return`return ${e}`}function vn(e){return M(e.length,0)?"true":e.reduce((o,a)=>Rn(o,a))}function Pd(e){return M(e.length,0)?"false":e.reduce((o,a)=>br(o,a))}function kO(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function AO(e){return e instanceof Boolean}function PO(e){return e instanceof Number}function CO(e){return e instanceof String}function nx(e){return globalThis.ArrayBuffer.isView(e)}function ox(e){return e instanceof globalThis.RegExp}function $O(e){return e instanceof globalThis.Date}function vO(e){return e instanceof globalThis.Set}function MO(e){return e instanceof globalThis.Map}var _O={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Bo(){return _O}function ii(e){return Bo().immutableTypes?Object.freeze(e):e}function gn(e,o){return hs.assign+=1,ii({...e,...o})}function LO(e){return e}function NO(e){return pe(e,"~kind")||pe(e,"~unsafe")}function DO(e){let o={};for(let a of Se(e)){if(Cu(a))continue;let u=Object.getOwnPropertyDescriptor(e,a);if(u.value=ta(u.value),M(u.enumerable,!0))o[a]=u.value;else Object.defineProperty(o,a,u)}return o}function qO(e){let o={};for(let a of Se(e)){if(Cu(a))continue;o[a]=ta(e[a])}for(let a of zy(e))o[a]=ta(e[a]);return o}function FO(e){return Gy(e)?LO(e):NO(e)?DO(e):qO(e)}function jO(e){return e.map((o)=>ta(o))}function UO(e){return e.slice()}function BO(e){return new RegExp(e.source,e.flags)}function GO(e){return new Map(ta([...e.entries()]))}function KO(e){return new Set(ta([...e.values()]))}function ta(e){return nx(e)?UO(e):ox(e)?BO(e):MO(e)?GO(e):vO(e)?KO(e):Fe(e)?jO(e):at(e)?FO(e):e}function va(e){return hs.clone+=1,ta(e)}function HO(e,o){for(let a of Object.keys(o))Object.defineProperty(e,a,{configurable:!0,writable:!0,enumerable:!1,value:o[a]});return e}function sx(e,o){return{...e,...o}}function $t(e,o,a={}){hs.create+=1;let u=sx(o,a),m=Bo().enumerableKind?sx(u,e):HO(u,e);return ii(m)}function Ho(e,o){hs.discard+=1;let a={};for(let u of Se(e)){if(o.includes(u))continue;let m=Object.getOwnPropertyDescriptor(e,u);m.value=va(m.value),Object.defineProperty(a,u,m)}return ii(a)}function Et(e,o,a){hs.update+=1;let u=Bo(),m=va(e);for(let p of Object.keys(o))Object.defineProperty(m,p,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[p]});for(let p of Object.keys(a))Object.defineProperty(m,p,{configurable:!0,enumerable:!0,writable:!0,value:a[p]});return ii(m)}function Re(e,o){return at(e)&&pe(e,"~kind")&&M(e["~kind"],o)}function Mr(e){return at(e)}function Ae(e,o,a){return $t({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:a},{})}function ai(e){return Re(e,"Deferred")}function WO(e){return Et(e,{"~readonly":!0},{})}function Mu(e,o){return Et(WO(e),{},o)}function ix(e,o,a,u){let m=he(e,o,a);return Mu(m,u)}function zO(e){return Et(e,{"~optional":!0},{})}function Ou(e,o){return Et(zO(e),{},o)}function ax(e,o,a,u){let m=he(e,o,a);return Ou(m,u)}function H(e,o){return $t({"~kind":"Array"},{type:"array",items:e},o)}function St(e){return Re(e,"Array")}function Ma(e){return Ho(e,["~kind","type","items"])}function Is(e,o,a={}){return $t({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},a)}function zr(e){return Re(e,"Constructor")}function ux(e){return Ho(e,["~kind","type","parameters","instanceType"])}function bs(e,o,a={}){return $t({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},a)}function en(e){return Re(e,"Function")}function cx(e){return Ho(e,["~kind","type","parameters","returnType"])}function pn(e,o){return $t({["~kind"]:"Ref"},{$ref:e},o)}function Ft(e){return Re(e,"Ref")}function ui(e,o){return $t({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Oa(e){return Re(e,"Generic")}function _a(e){return $t({["~kind"]:"Any"},{},e)}function Or(e){return Re(e,"Any")}var mx="(?!)";function Vt(e){return $t({"~kind":"Never"},{not:{}},e)}function ho(e){return Re(e,"Never")}function Es(e,o={}){return Ae("AddOptional",[e],o)}function ra(e,o={}){return Ou(e,o)}function n(e){return ra(e)}function ln(e){return Mr(e)&&pe(e,"~optional")}function px(e){return Se(e).filter((o)=>!ln(e[o]))}function fm(e){return Se(e)}function hm(e){return Td(e)}function l(e,o={}){let a=px(e),u=a.length>0?{required:a}:{};return $t({"~kind":"Object"},{type:"object",...u,properties:e},o)}function He(e){return Re(e,"Object")}function lx(e){return Ho(e,["~kind","type","properties","required"])}function Pr(e){return $t({["~kind"]:"Unknown"},{},e)}function tn(e){return Re(e,"Unknown")}function Ss(e,o,a){let u=Se(e).reduce((m,p)=>({...m,[p]:Et(e[p],{},{$id:p})}),{});return $t({["~kind"]:"Cyclic"},{$defs:u,$ref:o},a)}function Xt(e){return Re(e,"Cyclic")}function sr(e){return Et(e,{["~unsafe"]:null},{})}function gm(e){return Uo(e)&&pe(e,"~unsafe")&&bo(e["~unsafe"])}function kn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function _u(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m,m],1:(u)=>[u,Pr(),Pr()]});return $t({["~kind"]:"Infer"},{type:"infer",name:o,extends:a},{})}function an(e){return Re(e,"Infer")}function na(e,o,a,u={}){return $t({"~kind":"Dependent"},{if:e,then:o,else:a},u)}function Fr(e){return Re(e,"Dependent")}function dx(e){return Ho(e,["~kind","if","then","else"])}function fx(e){return Uo(e)}function hx(e){return Se(e).filter((a)=>isNaN(a)).reduce((a,u)=>[...a,e[u]],[])}function gx(e){return lt(e)||Ot(e)}function yx(e,o){let a=fx(e)?hx(e):e;return $t({"~kind":"Enum"},{enum:a},o)}function un(e){return Re(e,"Enum")}function Mn(e,o={}){return $t({"~kind":"Intersect"},{allOf:e},o)}function Ge(e){return Re(e,"Intersect")}function xx(e){return Ho(e,["~kind","allOf"])}var Cd=void 0;function VO(){try{return bx("null")(),!0}catch{return!1}}function Ix(){if(Bt(Cd))Cd=VO();return Cd&&Bo().useAcceleration}function bx(...e){return new globalThis.Function(...e)}function jr(){throw Error("Unreachable")}function JO(e){let o=new Set,a=e;while(a&&a!==Object.prototype){for(let u of Reflect.ownKeys(a))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);a=Object.getPrototypeOf(a)}return[...o]}function QO(e){return typeof e==="number"}var Bn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Bn||(Bn={}));var La=BigInt("14695981039346656037"),[XO,YO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],ZO=Array.from({length:256}).map((e,o)=>BigInt(o)),Tx=new Float64Array(1),Rx=new DataView(Tx.buffer),kx=new Uint8Array(Tx.buffer);function Sn(e){La=La^ZO[e],La=La*XO%YO}function e_(e){Sn(Bn.Array);for(let o of e)ci(o)}function t_(e){Sn(Bn.BigInt),Rx.setBigInt64(0,e);for(let o of kx)Sn(o)}function Sx(e){Sn(Bn.Boolean),Sn(e?1:0)}function r_(e){Sn(Bn.Constructor),ci(e.toString())}function n_(e){Sn(Bn.Date),ci(e.getTime())}function o_(e){Sn(Bn.Function),ci(e.toString())}function s_(e){Sn(Bn.Null)}function wx(e){Sn(Bn.Number),Rx.setFloat64(0,e,!0);for(let o of kx)Sn(o)}function i_(e){Sn(Bn.Object);for(let o of JO(e).sort())ci(o),ci(e[o])}function a_(e){Sn(Bn.RegExp),$d(e.toString())}var u_=new TextEncoder;function $d(e){Sn(Bn.String);for(let o of u_.encode(e))Sn(o)}function c_(e){Sn(Bn.Symbol),ci(e.toString())}function m_(e){Sn(Bn.TypeArray);let o=new Uint8Array(e.buffer);for(let a=0;a<o.length;a++)Sn(o[a])}function p_(e){return Sn(Bn.Undefined)}function ci(e){return nx(e)?m_(e):$O(e)?n_(e):ox(e)?a_(e):AO(e)?Sx(e.valueOf()):CO(e)?$d(e.valueOf()):PO(e)?wx(e.valueOf()):QO(e)?wx(e):Fe(e)?e_(e):fn(e)?Sx(e):qr(e)?t_(e):bd(e)?r_(e):bo(e)?s_(e):at(e)?i_(e):lt(e)?$d(e):Ed(e)?c_(e):Bt(e)?p_(e):gs(e)?o_(e):jr()}function Ax(e){return La=BigInt("14695981039346656037"),ci(e),La}function vd(e){return Ax(e).toString(16).padStart(16,"0")}function Px(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 l_=Px;function Cx(){return l_}class ym{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,a=Kn(o)?(p)=>this.decode(o["~codec"].decode(p)):this.decode,u=Kn(o)?(p)=>o["~codec"].encode(e(p)):e,m={decode:a,encode:u};return Et(this.type,{"~codec":m},{})}}class xm{constructor(e){this.type=e}Decode(e){return new ym(this.type,e)}}function Im(e){return new xm(e)}function vx(e,o){return Im(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function Mx(e,o){return Im(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Kn(e){return Mr(e)&&pe(e,"~codec")&&at(e["~codec"])&&pe(e["~codec"],"encode")&&pe(e["~codec"],"decode")}function Ox(e){return Na(e)}function sa(e){return Mr(e)&&pe(e,"~immutable")}function ws(e,o={}){return Ae("AddReadonly",[e],o)}function ia(e,o={}){return Mu(e,o)}function _x(e){return ia(e)}function aa(e){return Mr(e)&&pe(e,"~readonly")}function f_(e,o){let a=bm(e)?[...e["~refine"],o]:[o];return Et(e,{"~refine":a},{})}function Lx(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,()=>"Refine Error"]});return f_(o,{check:a,error:u})}function h_(e){return Uo(e)&&pe(e,"check")&&pe(e,"error")&&gs(e.check)&&gs(e.error)}function bm(e){return Mr(e)&&pe(e,"~refine")&&Fe(e["~refine"])&&mn(e["~refine"],0,(o)=>h_(o))}var Nx="-?(?:0|[1-9][0-9]*)n";function Lu(e){return $t({"~kind":"BigInt"},{type:"bigint"},e)}function go(e){return Re(e,"BigInt")}function N(e){return $t({"~kind":"Boolean"},{type:"boolean"},e)}function Vn(e){return Re(e,"Boolean")}function Nu(e){return $t({"~kind":"Identifier"},{name:e})}function Dx(e){return Re(e,"Identifier")}var Em="-?(?:0|[1-9][0-9]*)";function x(e){return $t({"~kind":"Integer"},{type:"integer"},e)}function yn(e){return Re(e,"Integer")}class qx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function g_(e){return qr(e)?"bigint":fn(e)?"boolean":Ot(e)?"number":lt(e)?"string":(()=>{throw new qx(e)})()}function i(e,o){return $t({"~kind":"Literal"},{type:g_(e),const:e},o)}function Sm(e){return qr(e)||fn(e)||Ot(e)||lt(e)}function Fx(e){return dt(e)&&qr(e.const)}function jx(e){return dt(e)&&fn(e.const)}function wm(e){return dt(e)&&Ot(e.const)}function Tm(e){return dt(e)&&lt(e.const)}function dt(e){return Re(e,"Literal")}function On(e){return $t({"~kind":"Null"},{type:"null"},e)}function Ts(e){return Re(e,"Null")}var Rm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function te(e){return $t({"~kind":"Number"},{type:"number"},e)}function Cr(e){return Re(e,"Number")}function Da(e){return $t({"~kind":"Symbol"},{type:"symbol"},e)}function Rs(e){return Re(e,"Symbol")}function ua(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,p],1:(m)=>[m,Pr(),Pr()]});return $t({"~kind":"Parameter"},{name:o,extends:a,equals:u},{})}function Ux(e){return Re(e,"Parameter")}var km=".*";function s(e){return $t({"~kind":"String"},{type:"string"},e)}function cn(e){return Re(e,"String")}function g(e,o={}){return $t({"~kind":"Union"},{anyOf:e},o)}function be(e){return Re(e,"Union")}function Bx(e){return Ho(e,["~kind","anyOf"])}function Du(e){let o=Gx(e);return M(o.length,2)?o[0]:[]}function y_(e){return!0}function Kx(e){return xt(e,(o,a)=>x_(o)?Kx(a):!1,()=>!0)}function Hx(e){return M(e.length,0)?!1:Kx(e)}function x_(e){return be(e)?Hx(e.anyOf):dt(e)?y_(e.const):!1}function Am(e){return Hx(e)}function Pm(e){return $t({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function Wx(e,o,a=[]){return xt(e,(u,m)=>Wx(m,o,[...a,`${u}${o}`]),()=>a)}function I_(e,o){return M(e.length,0)?[`${o}`]:Wx(e,o)}function zx(e,o,a=[]){return xt(o,(u,m)=>zx(e,m,[...a,...Vx(e,u)]),()=>a)}function Vx(e,o){return be(o)?zx(e,o.anyOf):dt(o)?I_(e,o.const):jr()}function Jx(e,o){return xt(o,(a,u)=>Jx(Vx(e,a),u),()=>e)}function b_(e){return e.map((o)=>i(o))}function E_(e){let o=Jx([],e),a=b_(o);return g(a)}function S_(e){return M(e.length,0)?jr():M(e.length,1)&&dt(e[0])?e[0]:E_(e)}function Md(e){let o=Du(e);return M(o.length,0)?s():Am(o)?S_(o):Pm(e)}function qu(e){let o=Md(e);return tr(o)?s():o}function Yn(e,o){let u={[e]:o};return $t({["~kind"]:"Record"},{type:"object",patternProperties:u})}function Qx(e){return Yn(Wo,e)}function Xx(e){return l({true:e,false:e})}function Ur(e,o={}){let[a,u,m]=[e,e.length,!1];return $t({["~kind"]:"Tuple"},{type:"array",additionalItems:m,items:a,minItems:u},o)}function ct(e){return Re(e,"Tuple")}function Yx(e){return Ho(e,["~kind","type","items","minItems","additionalItems"])}function w_(e){return Ho(e,["~readonly"])}function Od(e,o){return Et(w_(e),{},o)}function Zx(e,o,a,u){let m=he(e,o,a);return Od(m,u)}function eI(e,o={}){return Ae("RemoveReadonly",[e],o)}function tI(e,o={}){return Od(e,o)}function T_(e){return Ho(e,["~optional"])}function _d(e,o){return Et(T_(e),{},o)}function rI(e,o,a,u){let m=he(e,o,a);return _d(m,u)}function nI(e,o={}){return Ae("RemoveOptional",[e],o)}function Cm(e,o={}){return _d(e,o)}function Ld(e){return e.reduceRight((a,u,m)=>({[m]:u,...a}),{})}function oI(e){let o=Ld(e.items);return l(o)}function Nd(e){return He(e)||ct(e)}function R_(e,o){return aa(e)?aa(o)?!0:!1:!1}function k_(e,o){return ln(e)?ln(o)?!0:!1:!1}function A_(e,o){let a=R_(e,o),u=k_(e,o),m=$r([e,o]),p=tI(Cm(m));return a&&u?ia(ra(p)):a&&!u?ia(p):!a&&u?ra(p):p}function P_(e,o,a){return a in e?a in o?A_(e[a],o[a]):e[a]:(a in o)?o[a]:Vt()}function C_(e,o){return[...new Set([...Se(e),...Se(o)])].reduce((m,p)=>({...m,[p]:P_(e,o,p)}),{})}function sI(e){return He(e)?e.properties:ct(e)?Ld(e.items):{}}function iI(e,o){let a=sI(e),u=sI(o),m=C_(a,u);return l(m)}function $_(e,o){let a=qa(e,o);return M(a,ju)?e:M(a,Uu)?o:M(a,Fu)?o:Vt()}function v_(e,o){let a=Nd(e),u=Nd(o);return a&&u?iI(e,o):a&&!u?e:!a&&u?o:$_(e,o)}function aI(e,o){return ho(e)?e:Or(e)?e:tn(e)?o:ho(o)?o:Or(o)?o:tn(o)?e:v_(e,o)}function M_(e,o){return be(e)||be(o)}function O_(e,o){let a=vo(e),u=vo(o);return M_(a,u)?$r([a,u]):aI(a,u)}function uI(e,o,a=[]){return xt(o,(u,m)=>uI(e,m,[...a,O_(u,e)]),()=>M(a.length,0)?[e]:a)}function cI(e,o,a=[]){return xt(e,(u,m)=>cI(m,o,[...a,...Bu([u],o)]),()=>a)}function Bu(e,o=[]){return xt(e,(a,u)=>be(a)?Bu(u,cI(a.anyOf,o)):Bu(u,uI(a,o)),()=>o)}function __(e,o){let a=An({},e,o);return co(a)?[]:[e]}function mI(e,o,a=[]){return xt(e,(u,m)=>mI(m,o,[...a,...__(u,o)]),()=>a)}function $m(e,o){let a=vo(e),u=be(a)?a.anyOf:[a],m=mI(u,o);return Zn(m)}function es(e,o,a){let u=$r([e,o]),m=$m(a,e);return Zn([u,m])}function Jn(e,o=[]){return xt(e,(a,u)=>Jn(u,[...o,i(a)]),()=>Zn(o))}function $r(e){let o=Bu(e),a=Dd(o);return Zn(a)}function _n(e){let o=qu(e);return vo(o)}function Zn(e){let o=Dd(e);return mi(o)}function vo(e){return Fr(e)?es(e.if,e.then,e.else):un(e)?Jn(e.enum):Ge(e)?$r(e.allOf):tr(e)?_n(e.pattern):be(e)?Zn(e.anyOf):e}function mi(e){return M(e.length,1)?e[0]:M(e.length,0)?Vt():g(e)}function pI(e,o){let a=Jn(e);return pi(a,o)}function lI(e,o){return Yn(li,o)}function dI(e,o){let a=$r(e);return pi(a,o)}function fI(e,o){return lt(e)||Ot(e)?l({[e]:o}):M(e,!1)?l({false:o}):M(e,!0)?l({true:o}):l({})}function hI(e,o){return Yn(Fa,o)}function gI(e,o){return pe(e,"pattern")&&(lt(e.pattern)||e.pattern instanceof RegExp)?Yn(e.pattern.toString(),o):Yn(Wo,o)}function yI(e,o){let a=Du(e);return Am(a)?pi(_n(e),o):Yn(e,o)}function L_(e){return be(e)?ca(e.anyOf):[e]}function ca(e,o=[]){return xt(e,(a,u)=>ca(u,[...o,...L_(a)]),()=>o)}function N_(e){return e.some((o)=>cn(o)||Cr(o)||yn(o))}function D_(e,o){return M(N_(e),!0)?Yn(Wo,o):void 0}function q_(e,o){return e.reduce((a,u)=>dt(u)&&(lt(u.const)||Ot(u.const))?{...a,[u.const]:o}:a,{})}function F_(e,o){let a=q_(e,o);return l(a)}function xI(e,o){let a=ca(e),u=D_(a,o);return Mr(u)?u:F_(a,o)}function pi(e,o){return Or(e)?Qx(o):Vn(e)?Xx(o):un(e)?pI(e.enum,o):yn(e)?lI(e,o):Ge(e)?dI(e.allOf,o):dt(e)?fI(e.const,o):Cr(e)?hI(e,o):be(e)?xI(e.anyOf,o):cn(e)?gI(e,o):tr(e)?yI(e.pattern,o):l({})}function qd(e,o,a){return ut([e])?Et(pi(e,o),{},a):vm(e,o,a)}function II(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return qd(p,f,m)}var li=`^${Em}$`,Fa=`^${Rm}$`,Wo=`^${km}$`;function vm(e,o,a={}){return Ae("Record",[e,o],a)}function ks(e,o,a={}){return qd(e,o,a)}function bI(e,o){return Yn(e,o)}function Mm(e){return M(e,Wo)?s():M(e,li)?x():M(e,Fa)?te():Md(e)}function xn(e){return Se(e.patternProperties)[0]}function di(e){let o=xn(e);return Mm(o)}function or(e){return e.patternProperties[xn(e)]}function Kt(e){return Re(e,"Record")}function ma(e){return $t({"~kind":"Rest"},{type:"rest",items:e},{})}function fi(e){return Re(e,"Rest")}function Om(e){return $t({["~kind"]:"This"},{$ref:"#"},e)}function _m(e){return Re(e,"This")}function ja(e){return $t({"~kind":"Undefined"},{type:"undefined"},e)}function ss(e){return Re(e,"Undefined")}function Lm(e){return $t({"~kind":"Void"},{type:"void"},e)}function yo(e){return Re(e,"Void")}function U_(e,o){return M(e,"Array")?H(o[0]):M(e,"Capitalize")?Dm(o[0]):M(e,"ConstructorParameters")?Bm(o[0]):M(e,"Evaluate")?DE(o[0]):M(e,"Exclude")?Gm(o[0],o[1]):M(e,"Extract")?Km(o[0],o[1]):M(e,"Index")?Wu(o[0],o[1]):M(e,"InstanceType")?Hm(o[0]):M(e,"Lowercase")?qm(o[0]):M(e,"NonNullable")?Wm(o[0]):M(e,"Omit")?zm(o[0],o[1]):M(e,"Parameters")?Vm(o[0]):M(e,"Partial")?Jm(o[0]):M(e,"Pick")?Qm(o[0],o[1]):M(e,"Readonly")?Xm(o[0]):M(e,"KeyOf")?zu(o[0]):M(e,"Record")?vm(o[0],o[1]):M(e,"Required")?Ym(o[0]):M(e,"ReturnType")?Zm(o[0]):M(e,"Uncapitalize")?Fm(o[0]):M(e,"Uppercase")?jm(o[0]):Hu(pn(e),o)}function pa(){throw Error("Unreachable")}function RI(e,o=[]){return xt(e,(a,u)=>RI(u,[...o,a[1]]),()=>o)}function qs(e){return M(e.length,3)?[e[0],...RI(e[1])]:[]}function kI(e){return ua(e[0],e[2],e[4])}function AI(e){return ua(e[0],e[2],e[2])}function PI(e){return ua(e[0],Pr(),e[2])}function CI(e){return ua(e,Pr(),Pr())}function $I(e){return e}function vI(e){return qs(e)}function MI(e){return e[1]}function OI(e){return qs(e)}function _I(e){return e[1]}function LI(e){return U_(e[0],e[1])}function NI(e){return null}function DI(e){return s()}function qI(e){return te()}function FI(e){return N()}function jI(e){return ja()}function UI(e){return On()}function BI(e){return x()}function GI(e){return Lu()}function KI(e){return Pr()}function HI(e){return _a()}function WI(e){return l({})}function zI(e){return Vt()}function VI(e){return Da()}function JI(e){return Lm()}function QI(e){return Om()}function XI(e){return i(BigInt(e))}function YI(e){return i(M(e,"true"))}function ZI(e){return i(parseFloat(e))}function eb(e){return i(e)}function tb(e){return e[1]}function rb(e){return i(e)}function nb(e){return M(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function ob(e){return e[1]}function sb(e){return Nm(e)}function ib(e){return M(e.length,6)?na(e[1],e[3],e[5]):na(e[1],e[3],Pr())}function ab(e){return e.length>0}function ub(e){return e.reduce((o,a)=>M(a.length,3)?[...o,[a[1]]]:[...o,[]],[])}function cb(e){return M(e.length,6)?[e[1],e[3],e[5]]:[]}function mb(e){return Fe(e)&&M(e.length,3)?e[1]:e}function pb(e){return M(e.length,2)?e[1]:[]}function EI(e,o){return o.reduce((a,u)=>{let m=u;return M(m.length,1)?Wu(a,m[0]):M(m.length,0)?H(a):pa()},e)}function SI(e,o){return M(o.length,3)?Um(e,o[0],o[1],o[2]):e}function B_(e,o){return Fe(o)&&M(o.length,0)?e:ep(e,o)}function lb(e){let[o,a,u,m,p]=e;return B_(o?SI(zu(EI(a,u)),m):SI(EI(a,u),m),p)}function Fd(e,o){return M(o.length,3)?(()=>{let[a,u,m]=o,p=Fd(u,m);if(M(a,"&"))return Ge(p)?Mn([e,...p.allOf]):Mn([e,p]);if(M(a,"|"))return be(p)?g([e,...p.anyOf]):g([e,p]);pa()})():e}function db(e){return e}function fb(e){let[o,a]=e;return Fd(o,a)}function hb(e){return e}function gb(e){let[o,a]=e;return Fd(o,a)}function yb(e){return NE(e[1])}function xb(e){return e[1]}function Ib(e){return ui(e[0],e[2])}function bb(e){return M(e.length,4)?_u(e[1],e[3]):M(e.length,2)?_u(e[1],Pr()):pa()}function Eb(e){return e}function Sb(e){return`${e}`}function wb(e){return e}function Tb(e){return e}function Rb(e){return yn(e[3])?li:Cr(e[3])?Fa:Rs(e[3])?Wo:cn(e[3])?Wo:pa()}function kb(e){return e}function Ab(e){return e.length>0}function Pb(e){return e.length>0}function Cb(e){let[o,a,u,m,p]=e;return{[a]:o&&u?ws(Es(p)):o&&!u?ws(p):!o&&u?Es(p):p}}function $b(e){return e}function vb(e){return qs(e)}function Mb(e){return e.reduce((o,a)=>pe(a,li)||pe(a,Fa)||pe(a,Wo)?[o[0],gn(o[1],a)]:[gn(o[0],a),o[1]],[{},{}])}function Ob(e){return Mb(e[1])}function _b(e){let[o,a]=e,u=M(Se(a).length,0)?{}:{patternProperties:a};return l(o,u)}function Lb(e){return M(e.length,5)?ws(Es(e[4])):M(e.length,3)?e[2]:M(e.length,4)?M(e[2],"readonly")?ws(e[3]):Es(e[3]):pa()}function Nb(e){if(!Fe(e)||!M(e.length,3))return e;let[o,a,u]=e;return o&&u?ws(Es(a)):o&&!u?ws(a):!o&&u?Es(a):a}function Db(e){return M(e.length,2)?ma(e[1]):M(e.length,1)?e[0]:pa()}function qb(e){return qs(e)}function Fb(e){return Ur(e[1])}function jb(e){return ws(Es(e[4]))}function Ub(e){return ws(e[3])}function Bb(e){return Es(e[3])}function Gb(e){return e[2]}function Kb(e){return e}function Hb(e){return M(e.length,2)?ma(e[1]):M(e.length,1)?e[0]:pa()}function Wb(e){return qs(e)}function zb(e){return bs(e[1],e[4])}function Vb(e){return Is(e[2],e[5])}function wI(e,o){return M(e,"remove")?eI(o):M(e,"add")?ws(o):o}function Jb(e){return M(e.length,2)&&M(e[0],"-")?"remove":M(e.length,2)&&M(e[0],"+")?"add":M(e.length,1)?"add":"none"}function TI(e,o){return M(e,"remove")?nI(o):M(e,"add")?Es(o):o}function Qb(e){return M(e.length,2)&&M(e[0],"-")?"remove":M(e.length,2)&&M(e[0],"+")?"add":M(e.length,1)?"add":"none"}function Xb(e){return M(e.length,2)?[e[1]]:[]}function Yb(e){return Fe(e[6])&&M(e[6].length,1)?Gu(Nu(e[3]),e[5],e[6][0],wI(e[1],TI(e[8],e[10]))):Gu(Nu(e[3]),e[5],pn(e[3]),wI(e[1],TI(e[8],e[10])))}function Zb(e){return pn(e)}function eE(e){return BigInt(e)}function tE(e){return parseFloat(e)}function rE(e){return M(e,"true")}function nE(e){return e}function oE(e){return null}function sE(e){return}function iE(e){return{[e[0]]:e[2]}}function aE(e){return qs(e)}function G_(e){return e.reduce((o,a)=>gn(o,a),{})}function uE(e){return G_(e[1])}function cE(e){return qs(e)}function mE(e){return e[1]}function pE(e){return e}function lE(e){return Lu()}function dE(e){return s()}function fE(e){return te()}function hE(e){return x()}function gE(e){return Vt()}function yE(e){return i(e)}function xE(e){return e}function IE(e){return g(e[1])}function bE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function EE(e){return[e[0],...e[1]]}function SE(e){return e}function wE(e){return e[1]}function TE(e){return qs(e)}function RE(e){return M(e.length,2)?e[1]:[]}function kE(e){let o=e[2],a=e[3],[u,m]=e[4],p=M(Se(m).length,0)?{}:{patternProperties:m};return{[e[1]]:ui(o,Ku(a,u,p))}}function AE(e){let o=e[2],[a,u]=e[3],m=M(Se(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Ku(o,a,m)}}function PE(e){return{[e[1]]:ui(e[2],e[4])}}function CE(e){return{[e[1]]:e[3]}}function $E(e){return null}function vE(e){return e}function ME(e){return qs(e)}function OE(e){return e[1]}function _E(e){let[o,a]=[e[0],e[1]];return qE(gn(o,Mb(a)[0]))}function LE(e){return e}function Vu(e){return M(e.length,2)}function wt(e,o,a){return Vu(e)?o(e[0],e[1]):a()}function W_(e,o){return M(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Lr(e,o){for(let a=0;a<e.length;a++){let u=W_(e[a],o);if(Vu(u))return u}return[]}function jd(e,o){return Array.from({length:o-e+1},(a,u)=>String.fromCharCode(e+u))}var FE=[...jd(97,122),...jd(65,90)],Ud="0",Bd=jd(49,57),Ua=[Ud,...Bd],jE=" ",Ba=`
19
- `;var hi="_",tp=".",UE="$",rp="-";var BE="//",GE="/*",V_="*/";function KE(e){let o=e.indexOf(V_);return M(o,-1)?"":e.slice(o+2)}function HE(e){let o=e.indexOf(Ba);return M(o,-1)?"":e.slice(o)}function J_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function np(e){let o=J_(e);return o.startsWith(GE)?np(KE(o.slice(2))):o.startsWith(BE)?np(HE(o.slice(2))):o}function wn(e){let o=e.trimStart();return o.startsWith(GE)?wn(KE(o.slice(2))):o.startsWith(BE)?wn(HE(o.slice(2))):o}function op(e,o){return wt(Lr([e],o),(a,u)=>[a,u],()=>["",o])}function Q_(e,o){return e.includes(o)}function Ga(e,o,a,u=""){return wt(Lr(e,a),(m,p)=>Q_(o,m)?Ga(e,o,p,u):Ga(e,o,p,`${u}${m}`),()=>[u,a])}function X_(e){return Lr(Bd,e)}var Y_=[...Ua,hi];function Z_(e){return Ga(Y_,[hi],e)}function eL(e){return wt(Lr([Ud],e),(o,a)=>[o,a],()=>wt(X_(e),(o,a)=>wt(Z_(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[]))}function sp(e){return eL(wn(e))}function tL(e){return op(rp,e)}function rL(e){return wt(tL(e),(o,a)=>wt(sp(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function WE(e){return rL(wn(e))}function nL(e){return wt(WE(e),(o,a)=>wt(Lr(["n"],a),(u,m)=>[`${o}`,m],()=>[]),()=>[])}function Gd(e){return nL(e)}function Kd(e,o){return Lr([e],o)}function X(e,o){return M(e,"")?["",o]:e.startsWith(Ba)?Kd(e,np(o)):e.startsWith(jE)?Kd(e,o):Kd(e,wn(o))}var zE=[...FE,hi,UE];function oL(e){return Lr(zE,e)}var sL=[...zE,...Ua];function VE(e,o=""){return wt(Lr(sL,e),(a,u)=>VE(u,`${o}${a}`),()=>[o,e])}function iL(e){return wt(oL(e),(o,a)=>wt(VE(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function Br(e){return iL(wn(e))}var aL=[...Ua,hi];function uL(e){return Vu(Lr([tp],e))}function JE(e){return wt(Ga(aL,[hi],e),(o,a)=>M(o,"")?[]:[o,a],()=>[])}function cL(e){return wt(Lr([tp],e),(o,a)=>wt(JE(a),(u,m)=>[`0${o}${u}`,m],()=>[]),()=>[])}function mL(e){return wt(sp(e),(o,a)=>wt(Lr([tp],a),(u,m)=>wt(JE(m),(p,f)=>[`${o}${u}${p}`,f],()=>[`${o}`,m]),()=>[`${o}`,a]),()=>[])}function pL(e){return uL(e)?cL(e):mL(e)}function QE(e){return pL(wn(e))}function lL(e){return op(rp,e)}function dL(e){return wt(lL(e),(o,a)=>wt(QE(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function ip(e){return dL(wn(e))}function fL(e){return M(e,"")?[]:[e.slice(0,1),e.slice(1)]}function XE(e,o){return xt(e,(a,u)=>o.startsWith(a)?!0:XE(u,o),()=>!1)}function gi(e,o,a=""){return wt(fL(o),(u,m)=>XE(e,o)?[a,o]:gi(e,m,`${a}${u}`),()=>[])}function hL(e,o,a){return wt(Lr([e],a),(u,m)=>wt(gi([o],m),(p,f)=>wt(Lr([o],f),(h,I)=>[`${p}`,I],()=>[]),()=>[]),()=>[])}function gL(e,o,a){return wt(Lr([e],a),(u,m)=>wt(gi([Ba,o],m),(p,f)=>wt(Lr([o],f),(h,I)=>[`${p}`,I],()=>[]),()=>[]),()=>[])}function YE(e,o,a,u){return a?hL(e,o,wn(u)):gL(e,o,wn(u))}function yL(e,o){return Lr(e,o)}function xL(e,o){return YE(e,e,!1,o)}function IL(e,o){return wt(yL(e,o),(a,u)=>xL(a,`${a}${u}`),()=>[])}function ap(e,o){return IL(e,wn(o))}function ZE(e,o){return wt(gi(e,o),(a,u)=>M(a,"")?[]:[a,u],()=>[])}var w=(e,o,a=()=>[])=>e.length===2?o(e):a(),EL=(e)=>w(w(Br(e),([o,a])=>w(X("extends",a),([u,m])=>w(vt(m),([p,f])=>w(X("=",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[kI(o),a]),SL=(e)=>w(w(Br(e),([o,a])=>w(X("extends",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[AI(o),a]),wL=(e)=>w(w(Br(e),([o,a])=>w(X("=",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[PI(o),a]),TL=(e)=>w(Br(e),([o,a])=>[CI(o),a]),rS=(e)=>w(w(EL(e),([o,a])=>[o,a],()=>w(SL(e),([o,a])=>[o,a],()=>w(wL(e),([o,a])=>[o,a],()=>w(TL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[$I(o),a]),nS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(rS(u),([m,p])=>[[a,m],p])),([a,u])=>nS(u,[...o,a]),()=>[o,e]),RL=(e)=>w(w(w(rS(e),([o,a])=>w(nS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[vI(o),a]),zd=(e)=>w(w(X("<",e),([o,a])=>w(RL(a),([u,m])=>w(X(">",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[MI(o),a]),oS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(vt(u),([m,p])=>[[a,m],p])),([a,u])=>oS(u,[...o,a]),()=>[o,e]),kL=(e)=>w(w(w(vt(e),([o,a])=>w(oS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[OI(o),a]),AL=(e)=>w(w(X("<",e),([o,a])=>w(kL(a),([u,m])=>w(X(">",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[_I(o),a]),PL=(e)=>w(w(Br(e),([o,a])=>w(AL(a),([u,m])=>[[o,u],m])),([o,a])=>[LI(o),a]),sS=(e)=>w(w(w(X(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[NI(o),a]),iS=(e)=>w(X("string",e),([o,a])=>[DI(o),a]),aS=(e)=>w(X("number",e),([o,a])=>[qI(o),a]),CL=(e)=>w(X("boolean",e),([o,a])=>[FI(o),a]),$L=(e)=>w(X("undefined",e),([o,a])=>[jI(o),a]),vL=(e)=>w(X("null",e),([o,a])=>[UI(o),a]),uS=(e)=>w(X("integer",e),([o,a])=>[BI(o),a]),ML=(e)=>w(X("bigint",e),([o,a])=>[GI(o),a]),OL=(e)=>w(X("unknown",e),([o,a])=>[KI(o),a]),_L=(e)=>w(X("any",e),([o,a])=>[HI(o),a]),LL=(e)=>w(X("object",e),([o,a])=>[WI(o),a]),NL=(e)=>w(X("never",e),([o,a])=>[zI(o),a]),cS=(e)=>w(X("symbol",e),([o,a])=>[VI(o),a]),DL=(e)=>w(X("void",e),([o,a])=>[JI(o),a]),qL=(e)=>w(X("this",e),([o,a])=>[QI(o),a]),FL=(e)=>w(w(X("${",e),([o,a])=>w(vt(a),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[tb(o),a]),Hd=(e)=>w(gi(["${","`"],e),([o,a])=>[rb(o),a]),mS=(e)=>w(w(w(Hd(e),([o,a])=>w(FL(a),([u,m])=>w(mS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(w(Hd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(Hd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[nb(o),a]),Vd=(e)=>w(w(X("`",e),([o,a])=>w(mS(a),([u,m])=>w(X("`",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[ob(o),a]),jL=(e)=>w(Vd(e),([o,a])=>[sb(o),a]),UL=(e)=>w(w(w(X("if",e),([o,a])=>w(vt(a),([u,m])=>w(X("then",m),([p,f])=>w(vt(f),([h,I])=>w(X("else",I),([E,S])=>w(vt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[o,a],()=>w(w(X("if",e),([o,a])=>w(vt(a),([u,m])=>w(X("then",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>[])),([o,a])=>[ib(o),a]),BL=(e)=>w(Gd(e),([o,a])=>[XI(o),a]),GL=(e)=>w(w(X("true",e),([o,a])=>[o,a],()=>w(X("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[YI(o),a]),KL=(e)=>w(ip(e),([o,a])=>[ZI(o),a]),HL=(e)=>w(ap(["'",'"'],e),([o,a])=>[eb(o),a]),WL=(e)=>w(w(w(X("keyof",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[ab(o),a]),pS=(e,o=[])=>w(w(w(X("[",e),([a,u])=>w(vt(u),([m,p])=>w(X("]",p),([f,h])=>[[a,m,f],h]))),([a,u])=>[a,u],()=>w(w(X("[",e),([a,u])=>w(X("]",u),([m,p])=>[[a,m],p])),([a,u])=>[a,u],()=>[])),([a,u])=>pS(u,[...o,a]),()=>[o,e]),zL=(e)=>w(pS(e),([o,a])=>[ub(o),a]),VL=(e)=>w(w(w(X("extends",e),([o,a])=>w(vt(a),([u,m])=>w(X("?",m),([p,f])=>w(vt(f),([h,I])=>w(X(":",I),([E,S])=>w(vt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[cb(o),a]),JL=(e)=>w(w(w(X("(",e),([o,a])=>w(vt(a),([u,m])=>w(X(")",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(iS(e),([o,a])=>[o,a],()=>w(aS(e),([o,a])=>[o,a],()=>w(CL(e),([o,a])=>[o,a],()=>w($L(e),([o,a])=>[o,a],()=>w(vL(e),([o,a])=>[o,a],()=>w(uS(e),([o,a])=>[o,a],()=>w(ML(e),([o,a])=>[o,a],()=>w(OL(e),([o,a])=>[o,a],()=>w(_L(e),([o,a])=>[o,a],()=>w(LL(e),([o,a])=>[o,a],()=>w(NL(e),([o,a])=>[o,a],()=>w(cS(e),([o,a])=>[o,a],()=>w(DL(e),([o,a])=>[o,a],()=>w(qL(e),([o,a])=>[o,a],()=>w(BL(e),([o,a])=>[o,a],()=>w(GL(e),([o,a])=>[o,a],()=>w(KL(e),([o,a])=>[o,a],()=>w(HL(e),([o,a])=>[o,a],()=>w(jL(e),([o,a])=>[o,a],()=>w(UL(e),([o,a])=>[o,a],()=>w(iN(e),([o,a])=>[o,a],()=>w(cN(e),([o,a])=>[o,a],()=>w(hN(e),([o,a])=>[o,a],()=>w(fN(e),([o,a])=>[o,a],()=>w(IN(e),([o,a])=>[o,a],()=>w(PL(e),([o,a])=>[o,a],()=>w(bN(e),([o,a])=>[o,a],()=>[])))))))))))))))))))))))))))),([o,a])=>[mb(o),a]),QL=(e)=>w(w(w(X("with",e),([o,a])=>w(PS(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[pb(o),a]),lS=(e)=>w(w(WL(e),([o,a])=>w(JL(a),([u,m])=>w(zL(m),([p,f])=>w(VL(f),([h,I])=>w(QL(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[lb(o),a]),dS=(e)=>w(w(w(X("&",e),([o,a])=>w(lS(a),([u,m])=>w(dS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[db(o),a]),fS=(e)=>w(w(lS(e),([o,a])=>w(dS(a),([u,m])=>[[o,u],m])),([o,a])=>[fb(o),a]),hS=(e)=>w(w(w(X("|",e),([o,a])=>w(fS(a),([u,m])=>w(hS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[hb(o),a]),up=(e)=>w(w(fS(e),([o,a])=>w(hS(a),([u,m])=>[[o,u],m])),([o,a])=>[gb(o),a]),XL=(e)=>w(w(X("readonly",e),([o,a])=>w(up(a),([u,m])=>[[o,u],m])),([o,a])=>[yb(o),a]),YL=(e)=>w(w(X("|",e),([o,a])=>w(up(a),([u,m])=>[[o,u],m])),([o,a])=>[xb(o),a]),ZL=(e)=>w(w(zd(e),([o,a])=>w(X("=",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Ib(o),a]),eN=(e)=>w(w(w(X("infer",e),([o,a])=>w(Br(a),([u,m])=>w(X("extends",m),([p,f])=>w(up(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(X("infer",e),([o,a])=>w(Br(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>[])),([o,a])=>[bb(o),a]),vt=(e)=>w(w(eN(e),([o,a])=>[o,a],()=>w(YL(e),([o,a])=>[o,a],()=>w(XL(e),([o,a])=>[o,a],()=>w(up(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Eb(o),a]),tN=(e)=>w(ip(e),([o,a])=>[Sb(o),a]),rN=(e)=>w(Br(e),([o,a])=>[wb(o),a]),nN=(e)=>w(ap(["'",'"'],e),([o,a])=>[Tb(o),a]),oN=(e)=>w(w(X("[",e),([o,a])=>w(Br(a),([u,m])=>w(X(":",m),([p,f])=>w(w(uS(f),([h,I])=>[h,I],()=>w(aS(f),([h,I])=>[h,I],()=>w(iS(f),([h,I])=>[h,I],()=>w(cS(f),([h,I])=>[h,I],()=>[])))),([h,I])=>w(X("]",I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[Rb(o),a]),gS=(e)=>w(w(tN(e),([o,a])=>[o,a],()=>w(rN(e),([o,a])=>[o,a],()=>w(nN(e),([o,a])=>[o,a],()=>w(oN(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[kb(o),a]),yS=(e)=>w(w(w(X("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Ab(o),a]),xS=(e)=>w(w(w(X("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Pb(o),a]),IS=(e)=>w(w(yS(e),([o,a])=>w(gS(a),([u,m])=>w(xS(m),([p,f])=>w(X(":",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[Cb(o),a]),cp=(e)=>w(w(w(X(",",e),([o,a])=>w(X(`
18
+ `);return o}function am(e){try{let o=xd(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var hs={assign:0,create:0,clone:0,discard:0,update:0};function _i(e,o,a){return e>=o&&e<=a}function Ny(e){return e===8205}function uO(e){return _i(e,55296,56319)}function _y(e){return _i(e,127462,127487)}function Dy(e){return _i(e,65024,65039)}function qy(e){return _i(e,768,879)||_i(e,6832,6911)||_i(e,7616,7679)||_i(e,65056,65071)}function um(e){return e>65535?2:1}function Ly(e,o){while(o<e.length){let a=e.codePointAt(o);if(qy(a)||Dy(a))o+=um(a);else break}return o}function Id(e,o){let a=e.codePointAt(o),u=o+um(a);u=Ly(e,u);while(u<e.length-1&&Ny(e.codePointAt(u))){let m=e.codePointAt(u+1);u+=1+um(m),u=Ly(e,u)}if(_y(a)&&u<e.length&&_y(e.codePointAt(u)))u+=um(e.codePointAt(u));return u}function Fy(e){return e>=768&&(uO(e)||qy(e)||Dy(e)||Ny(e))}function jy(e){let o=0,a=0;while(a<e.length)a=Id(e,a),o++;return o}function cO(e,o){let a=0,u=0;while(u<e.length)if(u=Id(e,u),++a>=o)return!0;return!1}function mO(e,o){let a=0,u=0;while(u<e.length)if(u=Id(e,u),++a>o)return!1;return!0}function Uy(e,o){if(o===0)return!0;if(e.length<o)return!1;let a=0;while(!0){if(Fy(e.charCodeAt(a)))return cO(e,o);if(++a>=o)return!0}}function By(e,o){if(e.length<=o)return!0;let a=0;while(!0){if(Fy(e.charCodeAt(a)))return mO(e,o);if(++a>o)return!1}}function qe(e){return Array.isArray(e)}function qr(e){return M(typeof e,"bigint")}function fn(e){return M(typeof e,"boolean")}function bd(e){if(Bt(e)||!gs(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 gs(e){return M(typeof e,"function")}function cm(e){return Number.isInteger(e)}function bo(e){return M(e,null)}function Ot(e){return Number.isFinite(e)}function Uo(e){return ut(e)&&!qe(e)}function ut(e){return M(typeof e,"object")&&!bo(e)}function dt(e){return M(typeof e,"string")}function Ed(e){return M(typeof e,"symbol")}function Bt(e){return M(e,void 0)}function M(e,o){return e===o}function ji(e,o){return e>o}function Pu(e,o){return e<o}function ys(e,o){return e<=o}function Pa(e,o){return e>=o}function Gy(e,o){if(qr(e)||qr(o))return BigInt(e)%BigInt(o)===0n;let a=0.0000000001;if(!Ot(e))return!0;if(cm(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<a}function Ky(e){if(!ut(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(bo(o))return!1;return M(typeof o.constructor,"function")&&!(M(o.constructor,globalThis.Object)||M(o.constructor.name,"Object"))}function Ji(e){return qr(e)||fn(e)||bo(e)||Ot(e)||dt(e)||Bt(e)}function lO(e){return jy(e)}function Hy(e,o){return By(e,o)}function Wy(e,o){return Uy(e,o)}function mn(e,o,a){return e.every((u,m)=>m<o||a(u,m))}function $n(e,o,a){let u=!0;return e.forEach((m,p)=>{if(p>=o&&!a(m,p))u=!1}),u}function Ca(e,o){return e.some((a,u)=>o(a,u))}function zy(e,o){let a=!1;return e.forEach((u,m)=>{if(o(u,m))a=!0}),a}function Sd(e,o){return e.reduce((a,u,m)=>o(u,m)?++a:a,0)}function xt(e,o,a){return M(e.length,0)?a():o(e[0],e.slice(1))}function Cu(e){return M(e,"__proto__")||M(e,"constructor")||M(e,"prototype")}function pe(e,o){return Cu(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function wd(e){return Ee(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function hn(e){return Object.entries(e)}function Ee(e){return Object.getOwnPropertyNames(e)}function Vy(e){return Object.getOwnPropertySymbols(e)}function Td(e){return Object.values(e)}function dO(e,o){if(!ut(o))return!1;let a=Ee(e);return M(a.length,Ee(o).length)&&a.every((u)=>$a(e[u],o[u]))}function fO(e,o){return qe(o)&&M(e.length,o.length)&&e.every((a,u)=>$a(e[u],o[u]))}function $a(e,o){return qe(e)?fO(e,o):ut(e)?dO(e,o):M(e,o)}var hO=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function gO(e){return hO.test(e)}function Rn(e,o){return`(${e} && ${o})`}function br(e,o){return`(${e} || ${o})`}function Un(e){return`!(${e})`}function mm(e){return`Array.isArray(${e})`}function Jy(e){return`typeof ${e} === "bigint"`}function yO(e){return`typeof ${e} === "boolean"`}function xO(e){return`Number.isInteger(${e})`}function IO(e){return`${e} === null`}function Qy(e){return`Number.isFinite(${e})`}function Xy(e){return Rn(Yy(e),Un(mm(e)))}function Yy(e){return`typeof ${e} === "object" && ${e} !== null`}function Zy(e){return`typeof ${e} === "string"`}function bO(e){return`typeof ${e} === "symbol"`}function Rd(e){return`${e} === undefined`}function EO(e){return`typeof ${e} === "function"`}function SO(e){return`Guard.IsConstructor(${e})`}function fo(e,o){return`${e} === ${o}`}function ex(e,o){return`${e} > ${o}`}function kd(e,o){return`${e} < ${o}`}function Xi(e,o){return`${e} <= ${o}`}function $u(e,o){return`${e} >= ${o}`}function wO(e,o){return`Guard.IsMinLength(${e}, ${o})`}function TO(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function xs(e,o,a,u){return M(o,"0")?`${e}.every((${a[0]}, ${a[1]}) => (${u}))`:`${e}.every((${a[0]}, ${a[1]}) => (${a[1]} < ${o}) || (${u}))`}function RO(e,o,a){return`${e}.some((${o[0]}, ${o[1]}) => ${a})`}function kO(e,o,a){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${a}) result = true }); return result })(${e})`}function pm(e,o,a){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${a}) ? ++result : result, 0)`}function tx(e){return`Object.entries(${e})`}function Zi(e){return`Object.getOwnPropertyNames(${e})`}function ea(e,o){return M(o,'"__proto__"')||M(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function rx(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function AO(e){return`[${e.join(", ")}]`}function si(e,o){return`((${e.join(", ")}) => ${o})`}function Er(e,o){return`${e}(${o.join(", ")})`}function Ad(e,o){return`new ${e}(${o.join(", ")})`}function It(e,o){return`${e}${gO(o)?`.${o}`:`[${Pe(o)}]`}`}function Pe(e){if(!Ji(e))throw Error("Unsupported Constant");return dt(e)?JSON.stringify(e):`${e}`}function PO(e,o,a){return`(${e} ? ${o} : ${a})`}function lm(e){return`{ ${e.join("; ")}; }`}function Ds(e,o){return`const ${e} = ${o}`}function nx(e,o){return`if(${e}) { ${o} }`}function dm(e){return`return ${e}`}function vn(e){return M(e.length,0)?"true":e.reduce((o,a)=>Rn(o,a))}function Pd(e){return M(e.length,0)?"false":e.reduce((o,a)=>br(o,a))}function CO(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function $O(e){return e instanceof Boolean}function vO(e){return e instanceof Number}function MO(e){return e instanceof String}function ox(e){return globalThis.ArrayBuffer.isView(e)}function sx(e){return e instanceof globalThis.RegExp}function OO(e){return e instanceof globalThis.Date}function _O(e){return e instanceof globalThis.Set}function LO(e){return e instanceof globalThis.Map}var DO={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Bo(){return DO}function ii(e){return Bo().immutableTypes?Object.freeze(e):e}function gn(e,o){return hs.assign+=1,ii({...e,...o})}function qO(e){return e}function FO(e){return pe(e,"~kind")||pe(e,"~unsafe")}function jO(e){let o={};for(let a of Ee(e)){if(Cu(a))continue;let u=Object.getOwnPropertyDescriptor(e,a);if(u.value=ta(u.value),M(u.enumerable,!0))o[a]=u.value;else Object.defineProperty(o,a,u)}return o}function UO(e){let o={};for(let a of Ee(e)){if(Cu(a))continue;o[a]=ta(e[a])}for(let a of Vy(e))o[a]=ta(e[a]);return o}function BO(e){return Ky(e)?qO(e):FO(e)?jO(e):UO(e)}function GO(e){return e.map((o)=>ta(o))}function KO(e){return e.slice()}function HO(e){return new RegExp(e.source,e.flags)}function WO(e){return new Map(ta([...e.entries()]))}function zO(e){return new Set(ta([...e.values()]))}function ta(e){return ox(e)?KO(e):sx(e)?HO(e):LO(e)?WO(e):_O(e)?zO(e):qe(e)?GO(e):ut(e)?BO(e):e}function va(e){return hs.clone+=1,ta(e)}function VO(e,o){for(let a of Object.keys(o))Object.defineProperty(e,a,{configurable:!0,writable:!0,enumerable:!1,value:o[a]});return e}function ix(e,o){return{...e,...o}}function $t(e,o,a={}){hs.create+=1;let u=ix(o,a),m=Bo().enumerableKind?ix(u,e):VO(u,e);return ii(m)}function Ho(e,o){hs.discard+=1;let a={};for(let u of Ee(e)){if(o.includes(u))continue;let m=Object.getOwnPropertyDescriptor(e,u);m.value=va(m.value),Object.defineProperty(a,u,m)}return ii(a)}function Et(e,o,a){hs.update+=1;let u=Bo(),m=va(e);for(let p of Object.keys(o))Object.defineProperty(m,p,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[p]});for(let p of Object.keys(a))Object.defineProperty(m,p,{configurable:!0,enumerable:!0,writable:!0,value:a[p]});return ii(m)}function Re(e,o){return ut(e)&&pe(e,"~kind")&&M(e["~kind"],o)}function Mr(e){return ut(e)}function ke(e,o,a){return $t({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:a},{})}function ai(e){return Re(e,"Deferred")}function JO(e){return Et(e,{"~readonly":!0},{})}function Mu(e,o){return Et(JO(e),{},o)}function ax(e,o,a,u){let m=he(e,o,a);return Mu(m,u)}function QO(e){return Et(e,{"~optional":!0},{})}function Ou(e,o){return Et(QO(e),{},o)}function ux(e,o,a,u){let m=he(e,o,a);return Ou(m,u)}function F(e,o){return $t({"~kind":"Array"},{type:"array",items:e},o)}function St(e){return Re(e,"Array")}function Ma(e){return Ho(e,["~kind","type","items"])}function Is(e,o,a={}){return $t({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},a)}function zr(e){return Re(e,"Constructor")}function cx(e){return Ho(e,["~kind","type","parameters","instanceType"])}function bs(e,o,a={}){return $t({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},a)}function en(e){return Re(e,"Function")}function mx(e){return Ho(e,["~kind","type","parameters","returnType"])}function pn(e,o){return $t({["~kind"]:"Ref"},{$ref:e},o)}function Ft(e){return Re(e,"Ref")}function ui(e,o){return $t({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Oa(e){return Re(e,"Generic")}function _a(e){return $t({["~kind"]:"Any"},{},e)}function Or(e){return Re(e,"Any")}var px="(?!)";function Vt(e){return $t({"~kind":"Never"},{not:{}},e)}function ho(e){return Re(e,"Never")}function Es(e,o={}){return ke("AddOptional",[e],o)}function ra(e,o={}){return Ou(e,o)}function n(e){return ra(e)}function ln(e){return Mr(e)&&pe(e,"~optional")}function lx(e){return Ee(e).filter((o)=>!ln(e[o]))}function fm(e){return Ee(e)}function hm(e){return Td(e)}function l(e,o={}){let a=lx(e),u=a.length>0?{required:a}:{};return $t({"~kind":"Object"},{type:"object",...u,properties:e},o)}function He(e){return Re(e,"Object")}function dx(e){return Ho(e,["~kind","type","properties","required"])}function Pr(e){return $t({["~kind"]:"Unknown"},{},e)}function tn(e){return Re(e,"Unknown")}function Ss(e,o,a){let u=Ee(e).reduce((m,p)=>({...m,[p]:Et(e[p],{},{$id:p})}),{});return $t({["~kind"]:"Cyclic"},{$defs:u,$ref:o},a)}function Yt(e){return Re(e,"Cyclic")}function sr(e){return Et(e,{["~unsafe"]:null},{})}function gm(e){return Uo(e)&&pe(e,"~unsafe")&&bo(e["~unsafe"])}function kn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function _u(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m,m],1:(u)=>[u,Pr(),Pr()]});return $t({["~kind"]:"Infer"},{type:"infer",name:o,extends:a},{})}function an(e){return Re(e,"Infer")}function na(e,o,a,u={}){return $t({"~kind":"Dependent"},{if:e,then:o,else:a},u)}function Fr(e){return Re(e,"Dependent")}function fx(e){return Ho(e,["~kind","if","then","else"])}function hx(e){return Uo(e)}function gx(e){return Ee(e).filter((a)=>isNaN(a)).reduce((a,u)=>[...a,e[u]],[])}function yx(e){return dt(e)||Ot(e)}function xx(e,o){let a=hx(e)?gx(e):e;return $t({"~kind":"Enum"},{enum:a},o)}function un(e){return Re(e,"Enum")}function Mn(e,o={}){return $t({"~kind":"Intersect"},{allOf:e},o)}function Ke(e){return Re(e,"Intersect")}function Ix(e){return Ho(e,["~kind","allOf"])}var Cd=void 0;function XO(){try{return Ex("null")(),!0}catch{return!1}}function bx(){if(Bt(Cd))Cd=XO();return Cd&&Bo().useAcceleration}function Ex(...e){return new globalThis.Function(...e)}function jr(){throw Error("Unreachable")}function YO(e){let o=new Set,a=e;while(a&&a!==Object.prototype){for(let u of Reflect.ownKeys(a))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);a=Object.getPrototypeOf(a)}return[...o]}function ZO(e){return typeof e==="number"}var Bn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Bn||(Bn={}));var La=BigInt("14695981039346656037"),[e_,t_]=[BigInt("1099511628211"),BigInt("18446744073709551616")],r_=Array.from({length:256}).map((e,o)=>BigInt(o)),Rx=new Float64Array(1),kx=new DataView(Rx.buffer),Ax=new Uint8Array(Rx.buffer);function Sn(e){La=La^r_[e],La=La*e_%t_}function n_(e){Sn(Bn.Array);for(let o of e)ci(o)}function o_(e){Sn(Bn.BigInt),kx.setBigInt64(0,e);for(let o of Ax)Sn(o)}function wx(e){Sn(Bn.Boolean),Sn(e?1:0)}function s_(e){Sn(Bn.Constructor),ci(e.toString())}function i_(e){Sn(Bn.Date),ci(e.getTime())}function a_(e){Sn(Bn.Function),ci(e.toString())}function u_(e){Sn(Bn.Null)}function Tx(e){Sn(Bn.Number),kx.setFloat64(0,e,!0);for(let o of Ax)Sn(o)}function c_(e){Sn(Bn.Object);for(let o of YO(e).sort())ci(o),ci(e[o])}function m_(e){Sn(Bn.RegExp),$d(e.toString())}var p_=new TextEncoder;function $d(e){Sn(Bn.String);for(let o of p_.encode(e))Sn(o)}function l_(e){Sn(Bn.Symbol),ci(e.toString())}function d_(e){Sn(Bn.TypeArray);let o=new Uint8Array(e.buffer);for(let a=0;a<o.length;a++)Sn(o[a])}function f_(e){return Sn(Bn.Undefined)}function ci(e){return ox(e)?d_(e):OO(e)?i_(e):sx(e)?m_(e):$O(e)?wx(e.valueOf()):MO(e)?$d(e.valueOf()):vO(e)?Tx(e.valueOf()):ZO(e)?Tx(e):qe(e)?n_(e):fn(e)?wx(e):qr(e)?o_(e):bd(e)?s_(e):bo(e)?u_(e):ut(e)?c_(e):dt(e)?$d(e):Ed(e)?l_(e):Bt(e)?f_(e):gs(e)?a_(e):jr()}function Px(e){return La=BigInt("14695981039346656037"),ci(e),La}function vd(e){return Px(e).toString(16).padStart(16,"0")}function Cx(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 h_=Cx;function $x(){return h_}class ym{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,a=Kn(o)?(p)=>this.decode(o["~codec"].decode(p)):this.decode,u=Kn(o)?(p)=>o["~codec"].encode(e(p)):e,m={decode:a,encode:u};return Et(this.type,{"~codec":m},{})}}class xm{constructor(e){this.type=e}Decode(e){return new ym(this.type,e)}}function Im(e){return new xm(e)}function Mx(e,o){return Im(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function Ox(e,o){return Im(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Kn(e){return Mr(e)&&pe(e,"~codec")&&ut(e["~codec"])&&pe(e["~codec"],"encode")&&pe(e["~codec"],"decode")}function _x(e){return Na(e)}function sa(e){return Mr(e)&&pe(e,"~immutable")}function ws(e,o={}){return ke("AddReadonly",[e],o)}function ia(e,o={}){return Mu(e,o)}function Lx(e){return ia(e)}function aa(e){return Mr(e)&&pe(e,"~readonly")}function y_(e,o){let a=bm(e)?[...e["~refine"],o]:[o];return Et(e,{"~refine":a},{})}function Nx(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,()=>"Refine Error"]});return y_(o,{check:a,error:u})}function x_(e){return Uo(e)&&pe(e,"check")&&pe(e,"error")&&gs(e.check)&&gs(e.error)}function bm(e){return Mr(e)&&pe(e,"~refine")&&qe(e["~refine"])&&mn(e["~refine"],0,(o)=>x_(o))}var Dx="-?(?:0|[1-9][0-9]*)n";function Lu(e){return $t({"~kind":"BigInt"},{type:"bigint"},e)}function go(e){return Re(e,"BigInt")}function N(e){return $t({"~kind":"Boolean"},{type:"boolean"},e)}function Vn(e){return Re(e,"Boolean")}function Nu(e){return $t({"~kind":"Identifier"},{name:e})}function qx(e){return Re(e,"Identifier")}var Em="-?(?:0|[1-9][0-9]*)";function x(e){return $t({"~kind":"Integer"},{type:"integer"},e)}function yn(e){return Re(e,"Integer")}class Fx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function I_(e){return qr(e)?"bigint":fn(e)?"boolean":Ot(e)?"number":dt(e)?"string":(()=>{throw new Fx(e)})()}function i(e,o){return $t({"~kind":"Literal"},{type:I_(e),const:e},o)}function Sm(e){return qr(e)||fn(e)||Ot(e)||dt(e)}function jx(e){return gt(e)&&qr(e.const)}function Ux(e){return gt(e)&&fn(e.const)}function wm(e){return gt(e)&&Ot(e.const)}function Tm(e){return gt(e)&&dt(e.const)}function gt(e){return Re(e,"Literal")}function On(e){return $t({"~kind":"Null"},{type:"null"},e)}function Ts(e){return Re(e,"Null")}var Rm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function te(e){return $t({"~kind":"Number"},{type:"number"},e)}function Cr(e){return Re(e,"Number")}function Da(e){return $t({"~kind":"Symbol"},{type:"symbol"},e)}function Rs(e){return Re(e,"Symbol")}function ua(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,p],1:(m)=>[m,Pr(),Pr()]});return $t({"~kind":"Parameter"},{name:o,extends:a,equals:u},{})}function Bx(e){return Re(e,"Parameter")}var km=".*";function s(e){return $t({"~kind":"String"},{type:"string"},e)}function cn(e){return Re(e,"String")}function g(e,o={}){return $t({"~kind":"Union"},{anyOf:e},o)}function be(e){return Re(e,"Union")}function Gx(e){return Ho(e,["~kind","anyOf"])}function Du(e){let o=Kx(e);return M(o.length,2)?o[0]:[]}function b_(e){return!0}function Hx(e){return xt(e,(o,a)=>E_(o)?Hx(a):!1,()=>!0)}function Wx(e){return M(e.length,0)?!1:Hx(e)}function E_(e){return be(e)?Wx(e.anyOf):gt(e)?b_(e.const):!1}function Am(e){return Wx(e)}function Pm(e){return $t({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function zx(e,o,a=[]){return xt(e,(u,m)=>zx(m,o,[...a,`${u}${o}`]),()=>a)}function S_(e,o){return M(e.length,0)?[`${o}`]:zx(e,o)}function Vx(e,o,a=[]){return xt(o,(u,m)=>Vx(e,m,[...a,...Jx(e,u)]),()=>a)}function Jx(e,o){return be(o)?Vx(e,o.anyOf):gt(o)?S_(e,o.const):jr()}function Qx(e,o){return xt(o,(a,u)=>Qx(Jx(e,a),u),()=>e)}function w_(e){return e.map((o)=>i(o))}function T_(e){let o=Qx([],e),a=w_(o);return g(a)}function R_(e){return M(e.length,0)?jr():M(e.length,1)&&gt(e[0])?e[0]:T_(e)}function Md(e){let o=Du(e);return M(o.length,0)?s():Am(o)?R_(o):Pm(e)}function qu(e){let o=Md(e);return tr(o)?s():o}function Yn(e,o){let u={[e]:o};return $t({["~kind"]:"Record"},{type:"object",patternProperties:u})}function Xx(e){return Yn(Wo,e)}function Yx(e){return l({true:e,false:e})}function Ur(e,o={}){let[a,u,m]=[e,e.length,!1];return $t({["~kind"]:"Tuple"},{type:"array",additionalItems:m,items:a,minItems:u},o)}function pt(e){return Re(e,"Tuple")}function Zx(e){return Ho(e,["~kind","type","items","minItems","additionalItems"])}function k_(e){return Ho(e,["~readonly"])}function Od(e,o){return Et(k_(e),{},o)}function eI(e,o,a,u){let m=he(e,o,a);return Od(m,u)}function tI(e,o={}){return ke("RemoveReadonly",[e],o)}function rI(e,o={}){return Od(e,o)}function A_(e){return Ho(e,["~optional"])}function _d(e,o){return Et(A_(e),{},o)}function nI(e,o,a,u){let m=he(e,o,a);return _d(m,u)}function oI(e,o={}){return ke("RemoveOptional",[e],o)}function Cm(e,o={}){return _d(e,o)}function Ld(e){return e.reduceRight((a,u,m)=>({[m]:u,...a}),{})}function sI(e){let o=Ld(e.items);return l(o)}function Nd(e){return He(e)||pt(e)}function P_(e,o){return aa(e)?aa(o)?!0:!1:!1}function C_(e,o){return ln(e)?ln(o)?!0:!1:!1}function $_(e,o){let a=P_(e,o),u=C_(e,o),m=$r([e,o]),p=rI(Cm(m));return a&&u?ia(ra(p)):a&&!u?ia(p):!a&&u?ra(p):p}function v_(e,o,a){return a in e?a in o?$_(e[a],o[a]):e[a]:(a in o)?o[a]:Vt()}function M_(e,o){return[...new Set([...Ee(e),...Ee(o)])].reduce((m,p)=>({...m,[p]:v_(e,o,p)}),{})}function iI(e){return He(e)?e.properties:pt(e)?Ld(e.items):{}}function aI(e,o){let a=iI(e),u=iI(o),m=M_(a,u);return l(m)}function O_(e,o){let a=qa(e,o);return M(a,ju)?e:M(a,Uu)?o:M(a,Fu)?o:Vt()}function __(e,o){let a=Nd(e),u=Nd(o);return a&&u?aI(e,o):a&&!u?e:!a&&u?o:O_(e,o)}function uI(e,o){return ho(e)?e:Or(e)?e:tn(e)?o:ho(o)?o:Or(o)?o:tn(o)?e:__(e,o)}function L_(e,o){return be(e)||be(o)}function N_(e,o){let a=vo(e),u=vo(o);return L_(a,u)?$r([a,u]):uI(a,u)}function cI(e,o,a=[]){return xt(o,(u,m)=>cI(e,m,[...a,N_(u,e)]),()=>M(a.length,0)?[e]:a)}function mI(e,o,a=[]){return xt(e,(u,m)=>mI(m,o,[...a,...Bu([u],o)]),()=>a)}function Bu(e,o=[]){return xt(e,(a,u)=>be(a)?Bu(u,mI(a.anyOf,o)):Bu(u,cI(a,o)),()=>o)}function D_(e,o){let a=An({},e,o);return co(a)?[]:[e]}function pI(e,o,a=[]){return xt(e,(u,m)=>pI(m,o,[...a,...D_(u,o)]),()=>a)}function $m(e,o){let a=vo(e),u=be(a)?a.anyOf:[a],m=pI(u,o);return Zn(m)}function es(e,o,a){let u=$r([e,o]),m=$m(a,e);return Zn([u,m])}function Jn(e,o=[]){return xt(e,(a,u)=>Jn(u,[...o,i(a)]),()=>Zn(o))}function $r(e){let o=Bu(e),a=Dd(o);return Zn(a)}function _n(e){let o=qu(e);return vo(o)}function Zn(e){let o=Dd(e);return mi(o)}function vo(e){return Fr(e)?es(e.if,e.then,e.else):un(e)?Jn(e.enum):Ke(e)?$r(e.allOf):tr(e)?_n(e.pattern):be(e)?Zn(e.anyOf):e}function mi(e){return M(e.length,1)?e[0]:M(e.length,0)?Vt():g(e)}function lI(e,o){let a=Jn(e);return pi(a,o)}function dI(e,o){return Yn(li,o)}function fI(e,o){let a=$r(e);return pi(a,o)}function hI(e,o){return dt(e)||Ot(e)?l({[e]:o}):M(e,!1)?l({false:o}):M(e,!0)?l({true:o}):l({})}function gI(e,o){return Yn(Fa,o)}function yI(e,o){return pe(e,"pattern")&&(dt(e.pattern)||e.pattern instanceof RegExp)?Yn(e.pattern.toString(),o):Yn(Wo,o)}function xI(e,o){let a=Du(e);return Am(a)?pi(_n(e),o):Yn(e,o)}function q_(e){return be(e)?ca(e.anyOf):[e]}function ca(e,o=[]){return xt(e,(a,u)=>ca(u,[...o,...q_(a)]),()=>o)}function F_(e){return e.some((o)=>cn(o)||Cr(o)||yn(o))}function j_(e,o){return M(F_(e),!0)?Yn(Wo,o):void 0}function U_(e,o){return e.reduce((a,u)=>gt(u)&&(dt(u.const)||Ot(u.const))?{...a,[u.const]:o}:a,{})}function B_(e,o){let a=U_(e,o);return l(a)}function II(e,o){let a=ca(e),u=j_(a,o);return Mr(u)?u:B_(a,o)}function pi(e,o){return Or(e)?Xx(o):Vn(e)?Yx(o):un(e)?lI(e.enum,o):yn(e)?dI(e,o):Ke(e)?fI(e.allOf,o):gt(e)?hI(e.const,o):Cr(e)?gI(e,o):be(e)?II(e.anyOf,o):cn(e)?yI(e,o):tr(e)?xI(e.pattern,o):l({})}function qd(e,o,a){return ct([e])?Et(pi(e,o),{},a):vm(e,o,a)}function bI(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return qd(p,f,m)}var li=`^${Em}$`,Fa=`^${Rm}$`,Wo=`^${km}$`;function vm(e,o,a={}){return ke("Record",[e,o],a)}function ks(e,o,a={}){return qd(e,o,a)}function EI(e,o){return Yn(e,o)}function Mm(e){return M(e,Wo)?s():M(e,li)?x():M(e,Fa)?te():Md(e)}function xn(e){return Ee(e.patternProperties)[0]}function di(e){let o=xn(e);return Mm(o)}function or(e){return e.patternProperties[xn(e)]}function Kt(e){return Re(e,"Record")}function ma(e){return $t({"~kind":"Rest"},{type:"rest",items:e},{})}function fi(e){return Re(e,"Rest")}function Om(e){return $t({["~kind"]:"This"},{$ref:"#"},e)}function _m(e){return Re(e,"This")}function ja(e){return $t({"~kind":"Undefined"},{type:"undefined"},e)}function ss(e){return Re(e,"Undefined")}function Lm(e){return $t({"~kind":"Void"},{type:"void"},e)}function yo(e){return Re(e,"Void")}function K_(e,o){return M(e,"Array")?F(o[0]):M(e,"Capitalize")?Dm(o[0]):M(e,"ConstructorParameters")?Bm(o[0]):M(e,"Evaluate")?qE(o[0]):M(e,"Exclude")?Gm(o[0],o[1]):M(e,"Extract")?Km(o[0],o[1]):M(e,"Index")?Wu(o[0],o[1]):M(e,"InstanceType")?Hm(o[0]):M(e,"Lowercase")?qm(o[0]):M(e,"NonNullable")?Wm(o[0]):M(e,"Omit")?zm(o[0],o[1]):M(e,"Parameters")?Vm(o[0]):M(e,"Partial")?Jm(o[0]):M(e,"Pick")?Qm(o[0],o[1]):M(e,"Readonly")?Xm(o[0]):M(e,"KeyOf")?zu(o[0]):M(e,"Record")?vm(o[0],o[1]):M(e,"Required")?Ym(o[0]):M(e,"ReturnType")?Zm(o[0]):M(e,"Uncapitalize")?Fm(o[0]):M(e,"Uppercase")?jm(o[0]):Hu(pn(e),o)}function pa(){throw Error("Unreachable")}function kI(e,o=[]){return xt(e,(a,u)=>kI(u,[...o,a[1]]),()=>o)}function qs(e){return M(e.length,3)?[e[0],...kI(e[1])]:[]}function AI(e){return ua(e[0],e[2],e[4])}function PI(e){return ua(e[0],e[2],e[2])}function CI(e){return ua(e[0],Pr(),e[2])}function $I(e){return ua(e,Pr(),Pr())}function vI(e){return e}function MI(e){return qs(e)}function OI(e){return e[1]}function _I(e){return qs(e)}function LI(e){return e[1]}function NI(e){return K_(e[0],e[1])}function DI(e){return null}function qI(e){return s()}function FI(e){return te()}function jI(e){return N()}function UI(e){return ja()}function BI(e){return On()}function GI(e){return x()}function KI(e){return Lu()}function HI(e){return Pr()}function WI(e){return _a()}function zI(e){return l({})}function VI(e){return Vt()}function JI(e){return Da()}function QI(e){return Lm()}function XI(e){return Om()}function YI(e){return i(BigInt(e))}function ZI(e){return i(M(e,"true"))}function eb(e){return i(parseFloat(e))}function tb(e){return i(e)}function rb(e){return e[1]}function nb(e){return i(e)}function ob(e){return M(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function sb(e){return e[1]}function ib(e){return Nm(e)}function ab(e){return M(e.length,6)?na(e[1],e[3],e[5]):na(e[1],e[3],Pr())}function ub(e){return e.length>0}function cb(e){return e.reduce((o,a)=>M(a.length,3)?[...o,[a[1]]]:[...o,[]],[])}function mb(e){return M(e.length,6)?[e[1],e[3],e[5]]:[]}function pb(e){return qe(e)&&M(e.length,3)?e[1]:e}function lb(e){return M(e.length,2)?e[1]:[]}function SI(e,o){return o.reduce((a,u)=>{let m=u;return M(m.length,1)?Wu(a,m[0]):M(m.length,0)?F(a):pa()},e)}function wI(e,o){return M(o.length,3)?Um(e,o[0],o[1],o[2]):e}function H_(e,o){return qe(o)&&M(o.length,0)?e:ep(e,o)}function db(e){let[o,a,u,m,p]=e;return H_(o?wI(zu(SI(a,u)),m):wI(SI(a,u),m),p)}function Fd(e,o){return M(o.length,3)?(()=>{let[a,u,m]=o,p=Fd(u,m);if(M(a,"&"))return Ke(p)?Mn([e,...p.allOf]):Mn([e,p]);if(M(a,"|"))return be(p)?g([e,...p.anyOf]):g([e,p]);pa()})():e}function fb(e){return e}function hb(e){let[o,a]=e;return Fd(o,a)}function gb(e){return e}function yb(e){let[o,a]=e;return Fd(o,a)}function xb(e){return DE(e[1])}function Ib(e){return e[1]}function bb(e){return ui(e[0],e[2])}function Eb(e){return M(e.length,4)?_u(e[1],e[3]):M(e.length,2)?_u(e[1],Pr()):pa()}function Sb(e){return e}function wb(e){return`${e}`}function Tb(e){return e}function Rb(e){return e}function kb(e){return yn(e[3])?li:Cr(e[3])?Fa:Rs(e[3])?Wo:cn(e[3])?Wo:pa()}function Ab(e){return e}function Pb(e){return e.length>0}function Cb(e){return e.length>0}function $b(e){let[o,a,u,m,p]=e;return{[a]:o&&u?ws(Es(p)):o&&!u?ws(p):!o&&u?Es(p):p}}function vb(e){return e}function Mb(e){return qs(e)}function Ob(e){return e.reduce((o,a)=>pe(a,li)||pe(a,Fa)||pe(a,Wo)?[o[0],gn(o[1],a)]:[gn(o[0],a),o[1]],[{},{}])}function _b(e){return Ob(e[1])}function Lb(e){let[o,a]=e,u=M(Ee(a).length,0)?{}:{patternProperties:a};return l(o,u)}function Nb(e){return M(e.length,5)?ws(Es(e[4])):M(e.length,3)?e[2]:M(e.length,4)?M(e[2],"readonly")?ws(e[3]):Es(e[3]):pa()}function Db(e){if(!qe(e)||!M(e.length,3))return e;let[o,a,u]=e;return o&&u?ws(Es(a)):o&&!u?ws(a):!o&&u?Es(a):a}function qb(e){return M(e.length,2)?ma(e[1]):M(e.length,1)?e[0]:pa()}function Fb(e){return qs(e)}function jb(e){return Ur(e[1])}function Ub(e){return ws(Es(e[4]))}function Bb(e){return ws(e[3])}function Gb(e){return Es(e[3])}function Kb(e){return e[2]}function Hb(e){return e}function Wb(e){return M(e.length,2)?ma(e[1]):M(e.length,1)?e[0]:pa()}function zb(e){return qs(e)}function Vb(e){return bs(e[1],e[4])}function Jb(e){return Is(e[2],e[5])}function TI(e,o){return M(e,"remove")?tI(o):M(e,"add")?ws(o):o}function Qb(e){return M(e.length,2)&&M(e[0],"-")?"remove":M(e.length,2)&&M(e[0],"+")?"add":M(e.length,1)?"add":"none"}function RI(e,o){return M(e,"remove")?oI(o):M(e,"add")?Es(o):o}function Xb(e){return M(e.length,2)&&M(e[0],"-")?"remove":M(e.length,2)&&M(e[0],"+")?"add":M(e.length,1)?"add":"none"}function Yb(e){return M(e.length,2)?[e[1]]:[]}function Zb(e){return qe(e[6])&&M(e[6].length,1)?Gu(Nu(e[3]),e[5],e[6][0],TI(e[1],RI(e[8],e[10]))):Gu(Nu(e[3]),e[5],pn(e[3]),TI(e[1],RI(e[8],e[10])))}function eE(e){return pn(e)}function tE(e){return BigInt(e)}function rE(e){return parseFloat(e)}function nE(e){return M(e,"true")}function oE(e){return e}function sE(e){return null}function iE(e){return}function aE(e){return{[e[0]]:e[2]}}function uE(e){return qs(e)}function W_(e){return e.reduce((o,a)=>gn(o,a),{})}function cE(e){return W_(e[1])}function mE(e){return qs(e)}function pE(e){return e[1]}function lE(e){return e}function dE(e){return Lu()}function fE(e){return s()}function hE(e){return te()}function gE(e){return x()}function yE(e){return Vt()}function xE(e){return i(e)}function IE(e){return e}function bE(e){return g(e[1])}function EE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function SE(e){return[e[0],...e[1]]}function wE(e){return e}function TE(e){return e[1]}function RE(e){return qs(e)}function kE(e){return M(e.length,2)?e[1]:[]}function AE(e){let o=e[2],a=e[3],[u,m]=e[4],p=M(Ee(m).length,0)?{}:{patternProperties:m};return{[e[1]]:ui(o,Ku(a,u,p))}}function PE(e){let o=e[2],[a,u]=e[3],m=M(Ee(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Ku(o,a,m)}}function CE(e){return{[e[1]]:ui(e[2],e[4])}}function $E(e){return{[e[1]]:e[3]}}function vE(e){return null}function ME(e){return e}function OE(e){return qs(e)}function _E(e){return e[1]}function LE(e){let[o,a]=[e[0],e[1]];return FE(gn(o,Ob(a)[0]))}function NE(e){return e}function Vu(e){return M(e.length,2)}function wt(e,o,a){return Vu(e)?o(e[0],e[1]):a()}function J_(e,o){return M(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Lr(e,o){for(let a=0;a<e.length;a++){let u=J_(e[a],o);if(Vu(u))return u}return[]}function jd(e,o){return Array.from({length:o-e+1},(a,u)=>String.fromCharCode(e+u))}var jE=[...jd(97,122),...jd(65,90)],Ud="0",Bd=jd(49,57),Ua=[Ud,...Bd],UE=" ",Ba=`
19
+ `;var hi="_",tp=".",BE="$",rp="-";var GE="//",KE="/*",X_="*/";function HE(e){let o=e.indexOf(X_);return M(o,-1)?"":e.slice(o+2)}function WE(e){let o=e.indexOf(Ba);return M(o,-1)?"":e.slice(o)}function Y_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function np(e){let o=Y_(e);return o.startsWith(KE)?np(HE(o.slice(2))):o.startsWith(GE)?np(WE(o.slice(2))):o}function wn(e){let o=e.trimStart();return o.startsWith(KE)?wn(HE(o.slice(2))):o.startsWith(GE)?wn(WE(o.slice(2))):o}function op(e,o){return wt(Lr([e],o),(a,u)=>[a,u],()=>["",o])}function Z_(e,o){return e.includes(o)}function Ga(e,o,a,u=""){return wt(Lr(e,a),(m,p)=>Z_(o,m)?Ga(e,o,p,u):Ga(e,o,p,`${u}${m}`),()=>[u,a])}function eL(e){return Lr(Bd,e)}var tL=[...Ua,hi];function rL(e){return Ga(tL,[hi],e)}function nL(e){return wt(Lr([Ud],e),(o,a)=>[o,a],()=>wt(eL(e),(o,a)=>wt(rL(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[]))}function sp(e){return nL(wn(e))}function oL(e){return op(rp,e)}function sL(e){return wt(oL(e),(o,a)=>wt(sp(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function zE(e){return sL(wn(e))}function iL(e){return wt(zE(e),(o,a)=>wt(Lr(["n"],a),(u,m)=>[`${o}`,m],()=>[]),()=>[])}function Gd(e){return iL(e)}function Kd(e,o){return Lr([e],o)}function X(e,o){return M(e,"")?["",o]:e.startsWith(Ba)?Kd(e,np(o)):e.startsWith(UE)?Kd(e,o):Kd(e,wn(o))}var VE=[...jE,hi,BE];function aL(e){return Lr(VE,e)}var uL=[...VE,...Ua];function JE(e,o=""){return wt(Lr(uL,e),(a,u)=>JE(u,`${o}${a}`),()=>[o,e])}function cL(e){return wt(aL(e),(o,a)=>wt(JE(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function Br(e){return cL(wn(e))}var mL=[...Ua,hi];function pL(e){return Vu(Lr([tp],e))}function QE(e){return wt(Ga(mL,[hi],e),(o,a)=>M(o,"")?[]:[o,a],()=>[])}function lL(e){return wt(Lr([tp],e),(o,a)=>wt(QE(a),(u,m)=>[`0${o}${u}`,m],()=>[]),()=>[])}function dL(e){return wt(sp(e),(o,a)=>wt(Lr([tp],a),(u,m)=>wt(QE(m),(p,f)=>[`${o}${u}${p}`,f],()=>[`${o}`,m]),()=>[`${o}`,a]),()=>[])}function fL(e){return pL(e)?lL(e):dL(e)}function XE(e){return fL(wn(e))}function hL(e){return op(rp,e)}function gL(e){return wt(hL(e),(o,a)=>wt(XE(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function ip(e){return gL(wn(e))}function yL(e){return M(e,"")?[]:[e.slice(0,1),e.slice(1)]}function YE(e,o){return xt(e,(a,u)=>o.startsWith(a)?!0:YE(u,o),()=>!1)}function gi(e,o,a=""){return wt(yL(o),(u,m)=>YE(e,o)?[a,o]:gi(e,m,`${a}${u}`),()=>[])}function xL(e,o,a){return wt(Lr([e],a),(u,m)=>wt(gi([o],m),(p,f)=>wt(Lr([o],f),(h,I)=>[`${p}`,I],()=>[]),()=>[]),()=>[])}function IL(e,o,a){return wt(Lr([e],a),(u,m)=>wt(gi([Ba,o],m),(p,f)=>wt(Lr([o],f),(h,I)=>[`${p}`,I],()=>[]),()=>[]),()=>[])}function ZE(e,o,a,u){return a?xL(e,o,wn(u)):IL(e,o,wn(u))}function bL(e,o){return Lr(e,o)}function EL(e,o){return ZE(e,e,!1,o)}function SL(e,o){return wt(bL(e,o),(a,u)=>EL(a,`${a}${u}`),()=>[])}function ap(e,o){return SL(e,wn(o))}function eS(e,o){return wt(gi(e,o),(a,u)=>M(a,"")?[]:[a,u],()=>[])}var w=(e,o,a=()=>[])=>e.length===2?o(e):a(),TL=(e)=>w(w(Br(e),([o,a])=>w(X("extends",a),([u,m])=>w(vt(m),([p,f])=>w(X("=",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[AI(o),a]),RL=(e)=>w(w(Br(e),([o,a])=>w(X("extends",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[PI(o),a]),kL=(e)=>w(w(Br(e),([o,a])=>w(X("=",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[CI(o),a]),AL=(e)=>w(Br(e),([o,a])=>[$I(o),a]),nS=(e)=>w(w(TL(e),([o,a])=>[o,a],()=>w(RL(e),([o,a])=>[o,a],()=>w(kL(e),([o,a])=>[o,a],()=>w(AL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[vI(o),a]),oS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(nS(u),([m,p])=>[[a,m],p])),([a,u])=>oS(u,[...o,a]),()=>[o,e]),PL=(e)=>w(w(w(nS(e),([o,a])=>w(oS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[MI(o),a]),zd=(e)=>w(w(X("<",e),([o,a])=>w(PL(a),([u,m])=>w(X(">",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[OI(o),a]),sS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(vt(u),([m,p])=>[[a,m],p])),([a,u])=>sS(u,[...o,a]),()=>[o,e]),CL=(e)=>w(w(w(vt(e),([o,a])=>w(sS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[_I(o),a]),$L=(e)=>w(w(X("<",e),([o,a])=>w(CL(a),([u,m])=>w(X(">",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[LI(o),a]),vL=(e)=>w(w(Br(e),([o,a])=>w($L(a),([u,m])=>[[o,u],m])),([o,a])=>[NI(o),a]),iS=(e)=>w(w(w(X(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[DI(o),a]),aS=(e)=>w(X("string",e),([o,a])=>[qI(o),a]),uS=(e)=>w(X("number",e),([o,a])=>[FI(o),a]),ML=(e)=>w(X("boolean",e),([o,a])=>[jI(o),a]),OL=(e)=>w(X("undefined",e),([o,a])=>[UI(o),a]),_L=(e)=>w(X("null",e),([o,a])=>[BI(o),a]),cS=(e)=>w(X("integer",e),([o,a])=>[GI(o),a]),LL=(e)=>w(X("bigint",e),([o,a])=>[KI(o),a]),NL=(e)=>w(X("unknown",e),([o,a])=>[HI(o),a]),DL=(e)=>w(X("any",e),([o,a])=>[WI(o),a]),qL=(e)=>w(X("object",e),([o,a])=>[zI(o),a]),FL=(e)=>w(X("never",e),([o,a])=>[VI(o),a]),mS=(e)=>w(X("symbol",e),([o,a])=>[JI(o),a]),jL=(e)=>w(X("void",e),([o,a])=>[QI(o),a]),UL=(e)=>w(X("this",e),([o,a])=>[XI(o),a]),BL=(e)=>w(w(X("${",e),([o,a])=>w(vt(a),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[rb(o),a]),Hd=(e)=>w(gi(["${","`"],e),([o,a])=>[nb(o),a]),pS=(e)=>w(w(w(Hd(e),([o,a])=>w(BL(a),([u,m])=>w(pS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(w(Hd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(Hd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[ob(o),a]),Vd=(e)=>w(w(X("`",e),([o,a])=>w(pS(a),([u,m])=>w(X("`",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[sb(o),a]),GL=(e)=>w(Vd(e),([o,a])=>[ib(o),a]),KL=(e)=>w(w(w(X("if",e),([o,a])=>w(vt(a),([u,m])=>w(X("then",m),([p,f])=>w(vt(f),([h,I])=>w(X("else",I),([E,S])=>w(vt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[o,a],()=>w(w(X("if",e),([o,a])=>w(vt(a),([u,m])=>w(X("then",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>[])),([o,a])=>[ab(o),a]),HL=(e)=>w(Gd(e),([o,a])=>[YI(o),a]),WL=(e)=>w(w(X("true",e),([o,a])=>[o,a],()=>w(X("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[ZI(o),a]),zL=(e)=>w(ip(e),([o,a])=>[eb(o),a]),VL=(e)=>w(ap(["'",'"'],e),([o,a])=>[tb(o),a]),JL=(e)=>w(w(w(X("keyof",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[ub(o),a]),lS=(e,o=[])=>w(w(w(X("[",e),([a,u])=>w(vt(u),([m,p])=>w(X("]",p),([f,h])=>[[a,m,f],h]))),([a,u])=>[a,u],()=>w(w(X("[",e),([a,u])=>w(X("]",u),([m,p])=>[[a,m],p])),([a,u])=>[a,u],()=>[])),([a,u])=>lS(u,[...o,a]),()=>[o,e]),QL=(e)=>w(lS(e),([o,a])=>[cb(o),a]),XL=(e)=>w(w(w(X("extends",e),([o,a])=>w(vt(a),([u,m])=>w(X("?",m),([p,f])=>w(vt(f),([h,I])=>w(X(":",I),([E,S])=>w(vt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[mb(o),a]),YL=(e)=>w(w(w(X("(",e),([o,a])=>w(vt(a),([u,m])=>w(X(")",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(aS(e),([o,a])=>[o,a],()=>w(uS(e),([o,a])=>[o,a],()=>w(ML(e),([o,a])=>[o,a],()=>w(OL(e),([o,a])=>[o,a],()=>w(_L(e),([o,a])=>[o,a],()=>w(cS(e),([o,a])=>[o,a],()=>w(LL(e),([o,a])=>[o,a],()=>w(NL(e),([o,a])=>[o,a],()=>w(DL(e),([o,a])=>[o,a],()=>w(qL(e),([o,a])=>[o,a],()=>w(FL(e),([o,a])=>[o,a],()=>w(mS(e),([o,a])=>[o,a],()=>w(jL(e),([o,a])=>[o,a],()=>w(UL(e),([o,a])=>[o,a],()=>w(HL(e),([o,a])=>[o,a],()=>w(WL(e),([o,a])=>[o,a],()=>w(zL(e),([o,a])=>[o,a],()=>w(VL(e),([o,a])=>[o,a],()=>w(GL(e),([o,a])=>[o,a],()=>w(KL(e),([o,a])=>[o,a],()=>w(cN(e),([o,a])=>[o,a],()=>w(lN(e),([o,a])=>[o,a],()=>w(xN(e),([o,a])=>[o,a],()=>w(yN(e),([o,a])=>[o,a],()=>w(SN(e),([o,a])=>[o,a],()=>w(vL(e),([o,a])=>[o,a],()=>w(wN(e),([o,a])=>[o,a],()=>[])))))))))))))))))))))))))))),([o,a])=>[pb(o),a]),ZL=(e)=>w(w(w(X("with",e),([o,a])=>w(CS(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[lb(o),a]),dS=(e)=>w(w(JL(e),([o,a])=>w(YL(a),([u,m])=>w(QL(m),([p,f])=>w(XL(f),([h,I])=>w(ZL(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[db(o),a]),fS=(e)=>w(w(w(X("&",e),([o,a])=>w(dS(a),([u,m])=>w(fS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[fb(o),a]),hS=(e)=>w(w(dS(e),([o,a])=>w(fS(a),([u,m])=>[[o,u],m])),([o,a])=>[hb(o),a]),gS=(e)=>w(w(w(X("|",e),([o,a])=>w(hS(a),([u,m])=>w(gS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[gb(o),a]),up=(e)=>w(w(hS(e),([o,a])=>w(gS(a),([u,m])=>[[o,u],m])),([o,a])=>[yb(o),a]),eN=(e)=>w(w(X("readonly",e),([o,a])=>w(up(a),([u,m])=>[[o,u],m])),([o,a])=>[xb(o),a]),tN=(e)=>w(w(X("|",e),([o,a])=>w(up(a),([u,m])=>[[o,u],m])),([o,a])=>[Ib(o),a]),rN=(e)=>w(w(zd(e),([o,a])=>w(X("=",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[bb(o),a]),nN=(e)=>w(w(w(X("infer",e),([o,a])=>w(Br(a),([u,m])=>w(X("extends",m),([p,f])=>w(up(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(X("infer",e),([o,a])=>w(Br(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>[])),([o,a])=>[Eb(o),a]),vt=(e)=>w(w(nN(e),([o,a])=>[o,a],()=>w(tN(e),([o,a])=>[o,a],()=>w(eN(e),([o,a])=>[o,a],()=>w(up(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Sb(o),a]),oN=(e)=>w(ip(e),([o,a])=>[wb(o),a]),sN=(e)=>w(Br(e),([o,a])=>[Tb(o),a]),iN=(e)=>w(ap(["'",'"'],e),([o,a])=>[Rb(o),a]),aN=(e)=>w(w(X("[",e),([o,a])=>w(Br(a),([u,m])=>w(X(":",m),([p,f])=>w(w(cS(f),([h,I])=>[h,I],()=>w(uS(f),([h,I])=>[h,I],()=>w(aS(f),([h,I])=>[h,I],()=>w(mS(f),([h,I])=>[h,I],()=>[])))),([h,I])=>w(X("]",I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[kb(o),a]),yS=(e)=>w(w(oN(e),([o,a])=>[o,a],()=>w(sN(e),([o,a])=>[o,a],()=>w(iN(e),([o,a])=>[o,a],()=>w(aN(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Ab(o),a]),xS=(e)=>w(w(w(X("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Pb(o),a]),IS=(e)=>w(w(w(X("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Cb(o),a]),bS=(e)=>w(w(xS(e),([o,a])=>w(yS(a),([u,m])=>w(IS(m),([p,f])=>w(X(":",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[$b(o),a]),cp=(e)=>w(w(w(X(",",e),([o,a])=>w(X(`
20
20
  `,a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X(";",e),([o,a])=>w(X(`
21
21
  `,a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X(",",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(X(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(X(`
22
- `,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))))),([o,a])=>[$b(o),a]),bS=(e,o=[])=>w(w(cp(e),([a,u])=>w(IS(u),([m,p])=>[[a,m],p])),([a,u])=>bS(u,[...o,a]),()=>[o,e]),sN=(e)=>w(w(w(IS(e),([o,a])=>w(bS(a),([u,m])=>w(w(cp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[vb(o),a]),Jd=(e)=>w(w(X("{",e),([o,a])=>w(sN(a),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Ob(o),a]),iN=(e)=>w(Jd(e),([o,a])=>[_b(o),a]),aN=(e)=>w(w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(X("readonly",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[o,a],()=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(X("readonly",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>[])))),([o,a])=>[Lb(o),a]),eS=(e)=>w(w(aN(e),([o,a])=>[o,a],()=>w(w(yS(e),([o,a])=>w(vt(a),([u,m])=>w(xS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>[])),([o,a])=>[Nb(o),a]),ES=(e)=>w(w(w(X("...",e),([o,a])=>w(eS(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(eS(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[Db(o),a]),SS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(ES(u),([m,p])=>[[a,m],p])),([a,u])=>SS(u,[...o,a]),()=>[o,e]),uN=(e)=>w(w(w(ES(e),([o,a])=>w(SS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[qb(o),a]),cN=(e)=>w(w(X("[",e),([o,a])=>w(uN(a),([u,m])=>w(X("]",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Fb(o),a]),mN=(e)=>w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(X("readonly",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[jb(o),a]),pN=(e)=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(X("readonly",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[Ub(o),a]),lN=(e)=>w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[Bb(o),a]),dN=(e)=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Gb(o),a]),tS=(e)=>w(w(mN(e),([o,a])=>[o,a],()=>w(pN(e),([o,a])=>[o,a],()=>w(lN(e),([o,a])=>[o,a],()=>w(dN(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Kb(o),a]),wS=(e)=>w(w(w(X("...",e),([o,a])=>w(tS(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(tS(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[Hb(o),a]),TS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(wS(u),([m,p])=>[[a,m],p])),([a,u])=>TS(u,[...o,a]),()=>[o,e]),RS=(e)=>w(w(w(wS(e),([o,a])=>w(TS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Wb(o),a]),fN=(e)=>w(w(X("(",e),([o,a])=>w(RS(a),([u,m])=>w(X(")",m),([p,f])=>w(X("=>",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[zb(o),a]),hN=(e)=>w(w(X("new",e),([o,a])=>w(X("(",a),([u,m])=>w(RS(m),([p,f])=>w(X(")",f),([h,I])=>w(X("=>",I),([E,S])=>w(vt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[Vb(o),a]),gN=(e)=>w(w(w(X("+",e),([o,a])=>w(X("readonly",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("-",e),([o,a])=>w(X("readonly",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[Jb(o),a]),yN=(e)=>w(w(w(X("+",e),([o,a])=>w(X("?",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("-",e),([o,a])=>w(X("?",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[Qb(o),a]),xN=(e)=>w(w(w(X("as",e),([o,a])=>w(vt(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Xb(o),a]),IN=(e)=>w(w(X("{",e),([o,a])=>w(gN(a),([u,m])=>w(X("[",m),([p,f])=>w(Br(f),([h,I])=>w(X("in",I),([E,S])=>w(vt(S),([R,k])=>w(xN(k),([P,v])=>w(X("]",v),([_,Q])=>w(yN(Q),([L,V])=>w(X(":",V),([J,Z])=>w(vt(Z),([ne,z])=>w(sS(z),([oe,fe])=>w(X("}",fe),([ke,Ee])=>[[o,u,p,h,E,R,P,_,L,J,ne,oe,ke],Ee]))))))))))))),([o,a])=>[Yb(o),a]),bN=(e)=>w(Br(e),([o,a])=>[Zb(o),a]),EN=(e)=>w(Gd(e),([o,a])=>[eE(o),a]),SN=(e)=>w(ip(e),([o,a])=>[tE(o),a]),wN=(e)=>w(w(X("true",e),([o,a])=>[o,a],()=>w(X("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[rE(o),a]),TN=(e)=>w(ap(['"',"'"],e),([o,a])=>[nE(o),a]),RN=(e)=>w(X("null",e),([o,a])=>[oE(o),a]),kN=(e)=>w(X("undefined",e),([o,a])=>[sE(o),a]),kS=(e)=>w(w(gS(e),([o,a])=>w(X(":",a),([u,m])=>w(Qd(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[iE(o),a]),AS=(e,o=[])=>w(w(cp(e),([a,u])=>w(kS(u),([m,p])=>[[a,m],p])),([a,u])=>AS(u,[...o,a]),()=>[o,e]),AN=(e)=>w(w(w(kS(e),([o,a])=>w(AS(a),([u,m])=>w(w(cp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[aE(o),a]),PS=(e)=>w(w(X("{",e),([o,a])=>w(AN(a),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[uE(o),a]),CS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(Qd(u),([m,p])=>[[a,m],p])),([a,u])=>CS(u,[...o,a]),()=>[o,e]),PN=(e)=>w(w(w(Qd(e),([o,a])=>w(CS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[cE(o),a]),CN=(e)=>w(w(X("[",e),([o,a])=>w(PN(a),([u,m])=>w(X("]",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[mE(o),a]),Qd=(e)=>w(w(EN(e),([o,a])=>[o,a],()=>w(SN(e),([o,a])=>[o,a],()=>w(wN(e),([o,a])=>[o,a],()=>w(TN(e),([o,a])=>[o,a],()=>w(RN(e),([o,a])=>[o,a],()=>w(kN(e),([o,a])=>[o,a],()=>w(PS(e),([o,a])=>[o,a],()=>w(CN(e),([o,a])=>[o,a],()=>[])))))))),([o,a])=>[pE(o),a]),$N=(e)=>w(X("-?(?:0|[1-9][0-9]*)n",e),([o,a])=>[lE(o),a]),vN=(e)=>w(X(".*",e),([o,a])=>[dE(o),a]),MN=(e)=>w(X("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,a])=>[fE(o),a]),ON=(e)=>w(X("-?(?:0|[1-9][0-9]*)",e),([o,a])=>[hE(o),a]),_N=(e)=>w(X("(?!)",e),([o,a])=>[gE(o),a]),LN=(e)=>w(ZE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,a])=>[yE(o),a]),NN=(e)=>w(w($N(e),([o,a])=>[o,a],()=>w(vN(e),([o,a])=>[o,a],()=>w(MN(e),([o,a])=>[o,a],()=>w(ON(e),([o,a])=>[o,a],()=>w(_N(e),([o,a])=>[o,a],()=>w(DN(e),([o,a])=>[o,a],()=>w(LN(e),([o,a])=>[o,a],()=>[]))))))),([o,a])=>[xE(o),a]),DN=(e)=>w(w(X("(",e),([o,a])=>w(Xd(a),([u,m])=>w(X(")",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[IE(o),a]),$S=(e)=>w(w(w(Wd(e),([o,a])=>w(X("|",a),([u,m])=>w($S(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(w(Wd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[]))),([o,a])=>[bE(o),a]),Wd=(e)=>w(w(NN(e),([o,a])=>w(Xd(a),([u,m])=>[[o,u],m])),([o,a])=>[EE(o),a]),Xd=(e)=>w(w($S(e),([o,a])=>[o,a],()=>w(Wd(e),([o,a])=>[o,a],()=>[])),([o,a])=>[SE(o),a]),Gx=(e)=>w(w(X("^",e),([o,a])=>w(Xd(a),([u,m])=>w(X("$",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[wE(o),a]),vS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(vt(u),([m,p])=>[[a,m],p])),([a,u])=>vS(u,[...o,a]),()=>[o,e]),qN=(e)=>w(w(w(vt(e),([o,a])=>w(vS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[TE(o),a]),MS=(e)=>w(w(w(X("extends",e),([o,a])=>w(qN(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[RE(o),a]),FN=(e)=>w(w(X("interface",e),([o,a])=>w(Br(a),([u,m])=>w(zd(m),([p,f])=>w(MS(f),([h,I])=>w(Jd(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[kE(o),a]),jN=(e)=>w(w(X("interface",e),([o,a])=>w(Br(a),([u,m])=>w(MS(m),([p,f])=>w(Jd(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[AE(o),a]),UN=(e)=>w(w(X("type",e),([o,a])=>w(Br(a),([u,m])=>w(zd(m),([p,f])=>w(X("=",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[PE(o),a]),BN=(e)=>w(w(X("type",e),([o,a])=>w(Br(a),([u,m])=>w(X("=",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[CE(o),a]),GN=(e)=>w(w(w(X("export",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[$E(o),a]),OS=(e)=>w(w(w(X(";",e),([o,a])=>w(X(`
22
+ `,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))))),([o,a])=>[vb(o),a]),ES=(e,o=[])=>w(w(cp(e),([a,u])=>w(bS(u),([m,p])=>[[a,m],p])),([a,u])=>ES(u,[...o,a]),()=>[o,e]),uN=(e)=>w(w(w(bS(e),([o,a])=>w(ES(a),([u,m])=>w(w(cp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Mb(o),a]),Jd=(e)=>w(w(X("{",e),([o,a])=>w(uN(a),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[_b(o),a]),cN=(e)=>w(Jd(e),([o,a])=>[Lb(o),a]),mN=(e)=>w(w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(X("readonly",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[o,a],()=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(X("readonly",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>[])))),([o,a])=>[Nb(o),a]),tS=(e)=>w(w(mN(e),([o,a])=>[o,a],()=>w(w(xS(e),([o,a])=>w(vt(a),([u,m])=>w(IS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>[])),([o,a])=>[Db(o),a]),SS=(e)=>w(w(w(X("...",e),([o,a])=>w(tS(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(tS(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[qb(o),a]),wS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(SS(u),([m,p])=>[[a,m],p])),([a,u])=>wS(u,[...o,a]),()=>[o,e]),pN=(e)=>w(w(w(SS(e),([o,a])=>w(wS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Fb(o),a]),lN=(e)=>w(w(X("[",e),([o,a])=>w(pN(a),([u,m])=>w(X("]",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[jb(o),a]),dN=(e)=>w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(X("readonly",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[Ub(o),a]),fN=(e)=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(X("readonly",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[Bb(o),a]),hN=(e)=>w(w(Br(e),([o,a])=>w(X("?",a),([u,m])=>w(X(":",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[Gb(o),a]),gN=(e)=>w(w(Br(e),([o,a])=>w(X(":",a),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Kb(o),a]),rS=(e)=>w(w(dN(e),([o,a])=>[o,a],()=>w(fN(e),([o,a])=>[o,a],()=>w(hN(e),([o,a])=>[o,a],()=>w(gN(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Hb(o),a]),TS=(e)=>w(w(w(X("...",e),([o,a])=>w(rS(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(rS(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[Wb(o),a]),RS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(TS(u),([m,p])=>[[a,m],p])),([a,u])=>RS(u,[...o,a]),()=>[o,e]),kS=(e)=>w(w(w(TS(e),([o,a])=>w(RS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[zb(o),a]),yN=(e)=>w(w(X("(",e),([o,a])=>w(kS(a),([u,m])=>w(X(")",m),([p,f])=>w(X("=>",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[Vb(o),a]),xN=(e)=>w(w(X("new",e),([o,a])=>w(X("(",a),([u,m])=>w(kS(m),([p,f])=>w(X(")",f),([h,I])=>w(X("=>",I),([E,S])=>w(vt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[Jb(o),a]),IN=(e)=>w(w(w(X("+",e),([o,a])=>w(X("readonly",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("-",e),([o,a])=>w(X("readonly",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[Qb(o),a]),bN=(e)=>w(w(w(X("+",e),([o,a])=>w(X("?",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("-",e),([o,a])=>w(X("?",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[Xb(o),a]),EN=(e)=>w(w(w(X("as",e),([o,a])=>w(vt(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Yb(o),a]),SN=(e)=>w(w(X("{",e),([o,a])=>w(IN(a),([u,m])=>w(X("[",m),([p,f])=>w(Br(f),([h,I])=>w(X("in",I),([E,S])=>w(vt(S),([R,k])=>w(EN(k),([P,v])=>w(X("]",v),([_,Q])=>w(bN(Q),([L,V])=>w(X(":",V),([J,Z])=>w(vt(Z),([ne,z])=>w(iS(z),([oe,fe])=>w(X("}",fe),([Ae,Ge])=>[[o,u,p,h,E,R,P,_,L,J,ne,oe,Ae],Ge]))))))))))))),([o,a])=>[Zb(o),a]),wN=(e)=>w(Br(e),([o,a])=>[eE(o),a]),TN=(e)=>w(Gd(e),([o,a])=>[tE(o),a]),RN=(e)=>w(ip(e),([o,a])=>[rE(o),a]),kN=(e)=>w(w(X("true",e),([o,a])=>[o,a],()=>w(X("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[nE(o),a]),AN=(e)=>w(ap(['"',"'"],e),([o,a])=>[oE(o),a]),PN=(e)=>w(X("null",e),([o,a])=>[sE(o),a]),CN=(e)=>w(X("undefined",e),([o,a])=>[iE(o),a]),AS=(e)=>w(w(yS(e),([o,a])=>w(X(":",a),([u,m])=>w(Qd(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[aE(o),a]),PS=(e,o=[])=>w(w(cp(e),([a,u])=>w(AS(u),([m,p])=>[[a,m],p])),([a,u])=>PS(u,[...o,a]),()=>[o,e]),$N=(e)=>w(w(w(AS(e),([o,a])=>w(PS(a),([u,m])=>w(w(cp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[uE(o),a]),CS=(e)=>w(w(X("{",e),([o,a])=>w($N(a),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[cE(o),a]),$S=(e,o=[])=>w(w(X(",",e),([a,u])=>w(Qd(u),([m,p])=>[[a,m],p])),([a,u])=>$S(u,[...o,a]),()=>[o,e]),vN=(e)=>w(w(w(Qd(e),([o,a])=>w($S(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[mE(o),a]),MN=(e)=>w(w(X("[",e),([o,a])=>w(vN(a),([u,m])=>w(X("]",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[pE(o),a]),Qd=(e)=>w(w(TN(e),([o,a])=>[o,a],()=>w(RN(e),([o,a])=>[o,a],()=>w(kN(e),([o,a])=>[o,a],()=>w(AN(e),([o,a])=>[o,a],()=>w(PN(e),([o,a])=>[o,a],()=>w(CN(e),([o,a])=>[o,a],()=>w(CS(e),([o,a])=>[o,a],()=>w(MN(e),([o,a])=>[o,a],()=>[])))))))),([o,a])=>[lE(o),a]),ON=(e)=>w(X("-?(?:0|[1-9][0-9]*)n",e),([o,a])=>[dE(o),a]),_N=(e)=>w(X(".*",e),([o,a])=>[fE(o),a]),LN=(e)=>w(X("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,a])=>[hE(o),a]),NN=(e)=>w(X("-?(?:0|[1-9][0-9]*)",e),([o,a])=>[gE(o),a]),DN=(e)=>w(X("(?!)",e),([o,a])=>[yE(o),a]),qN=(e)=>w(eS(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,a])=>[xE(o),a]),FN=(e)=>w(w(ON(e),([o,a])=>[o,a],()=>w(_N(e),([o,a])=>[o,a],()=>w(LN(e),([o,a])=>[o,a],()=>w(NN(e),([o,a])=>[o,a],()=>w(DN(e),([o,a])=>[o,a],()=>w(jN(e),([o,a])=>[o,a],()=>w(qN(e),([o,a])=>[o,a],()=>[]))))))),([o,a])=>[IE(o),a]),jN=(e)=>w(w(X("(",e),([o,a])=>w(Xd(a),([u,m])=>w(X(")",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[bE(o),a]),vS=(e)=>w(w(w(Wd(e),([o,a])=>w(X("|",a),([u,m])=>w(vS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(w(Wd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[]))),([o,a])=>[EE(o),a]),Wd=(e)=>w(w(FN(e),([o,a])=>w(Xd(a),([u,m])=>[[o,u],m])),([o,a])=>[SE(o),a]),Xd=(e)=>w(w(vS(e),([o,a])=>[o,a],()=>w(Wd(e),([o,a])=>[o,a],()=>[])),([o,a])=>[wE(o),a]),Kx=(e)=>w(w(X("^",e),([o,a])=>w(Xd(a),([u,m])=>w(X("$",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[TE(o),a]),MS=(e,o=[])=>w(w(X(",",e),([a,u])=>w(vt(u),([m,p])=>[[a,m],p])),([a,u])=>MS(u,[...o,a]),()=>[o,e]),UN=(e)=>w(w(w(vt(e),([o,a])=>w(MS(a),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[RE(o),a]),OS=(e)=>w(w(w(X("extends",e),([o,a])=>w(UN(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kE(o),a]),BN=(e)=>w(w(X("interface",e),([o,a])=>w(Br(a),([u,m])=>w(zd(m),([p,f])=>w(OS(f),([h,I])=>w(Jd(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[AE(o),a]),GN=(e)=>w(w(X("interface",e),([o,a])=>w(Br(a),([u,m])=>w(OS(m),([p,f])=>w(Jd(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[PE(o),a]),KN=(e)=>w(w(X("type",e),([o,a])=>w(Br(a),([u,m])=>w(zd(m),([p,f])=>w(X("=",f),([h,I])=>w(vt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[CE(o),a]),HN=(e)=>w(w(X("type",e),([o,a])=>w(Br(a),([u,m])=>w(X("=",m),([p,f])=>w(vt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[$E(o),a]),WN=(e)=>w(w(w(X("export",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[vE(o),a]),_S=(e)=>w(w(w(X(";",e),([o,a])=>w(X(`
23
23
  `,a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(X(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(X(`
24
- `,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[vE(o),a]),_S=(e,o=[])=>w(w(OS(e),([a,u])=>w(Yd(u),([m,p])=>[[a,m],p])),([a,u])=>_S(u,[...o,a]),()=>[o,e]),KN=(e)=>w(w(w(Yd(e),([o,a])=>w(_S(a),([u,m])=>w(w(OS(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[ME(o),a]),Yd=(e)=>w(w(GN(e),([o,a])=>w(w(FN(a),([u,m])=>[u,m],()=>w(jN(a),([u,m])=>[u,m],()=>w(UN(a),([u,m])=>[u,m],()=>w(BN(a),([u,m])=>[u,m],()=>[])))),([u,m])=>w(sS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[OE(o),a]),HN=(e)=>w(w(Yd(e),([o,a])=>w(KN(a),([u,m])=>[[o,u],m])),([o,a])=>[_E(o),a]),LS=(e)=>w(w(HN(e),([o,a])=>[o,a],()=>w(ZL(e),([o,a])=>[o,a],()=>w(vt(e),([o,a])=>[o,a],()=>[]))),([o,a])=>[LE(o),a]);function NS(e){let o=Vd(`\`${e}\``);return M(o.length,2)?o[0]:jr()}function zN(e){return e.join("|")}function VN(e){return e.slice(1,e.length-1)}function JN(e,o,a){return yi(o,`${a}${e}`)}function QN(e,o){return yi(e,`${o}${Nx}`)}function XN(e,o){return yi(e,`${o}${Em}`)}function YN(e,o){return yi(e,`${o}${Rm}`)}function ZN(e,o){return Ju(g([i("false"),i("true")]),e,o)}function eD(e,o){return yi(e,`${o}${km}`)}function tD(e,o,a){return yi(o,`${a}${VN(e)}`)}function rD(e,o,a){let u=Qu(e,{});return Ju(u,o,a)}function nD(e,o,a){let u=Jn(e);return Ju(u,o,a)}function DS(e,o,a,u=[]){return xt(e,(m,p)=>DS(p,o,a,[...u,Ju(m,[],"")]),()=>yi(o,`${a}(${zN(u)})`))}function Ju(e,o,a){return un(e)?nD(e.enum,o,a):yn(e)?XN(o,a):dt(e)?JN(e.const,o,a):go(e)?QN(o,a):Vn(e)?ZN(o,a):Cr(e)?YN(o,a):cn(e)?eD(o,a):tr(e)?tD(e.pattern,o,a):FS(e)?rD(e.parameters[0],o,a):be(e)?DS(e.anyOf,o,a):mx}function yi(e,o){return xt(e,(a,u)=>Ju(a,u,o),()=>o)}function oD(e){return`^${yi(e,"")}$`}function qS(e){let o=oD(e);return Pm(o)}function Qu(e,o){return ut(e)?Et(qS(e),{},o):Nm(e,o)}function jS(e,o,a,u){let m=So(e,o,a);return Qu(m,u)}function Nm(e,o={}){return Ae("TemplateLiteral",[e],o)}function FS(e){return Mr(e)&&pe(e,"action")&&M(e.action,"TemplateLiteral")}function US(e){return Qu(e,{})}function sD(e){let o=NS(e);return US(o)}function BS(e,o={}){let a=lt(e)?sD(e):US(e);return Et(a,{},o)}function tr(e){return Re(e,"TemplateLiteral")}function Zd(e){return $t({["~kind"]:"ExtendsUnion"},{inferred:e})}function ef(e){return at(e)&&pe(e,"~kind")&&pe(e,"inferred")&&M(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function we(e){return $t({["~kind"]:"ExtendsTrue"},{inferred:e})}function tf(e){return at(e)&&pe(e,"~kind")&&pe(e,"inferred")&&M(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ye(){return $t({["~kind"]:"ExtendsFalse"},{})}function rf(e){return at(e)&&pe(e,"~kind")&&M(e["~kind"],"ExtendsFalse")}function co(e){return ef(e)||tf(e)}function wr(e,o,a){return co(e)?o(e.inferred):a()}function iD(e,o,a,u){return wr(Tt(e,a,u),(m)=>we(gn(gn(e,m),{[o]:a})),()=>Ye())}function aD(e,o){return we(e)}function uD(e,o,a,u,m){return wr(Tt(e,o,a),(p)=>wr(Tt(p,o,u),(f)=>we(f),()=>Ye()),()=>wr(Tt(e,o,m),(p)=>we(p),()=>Ye()))}function cD(e,o,a){let u=Jn(a);return Tt(e,o,u)}function GS(e,o,a){return xt(a,(u,m)=>wr(Tt(e,o,u),(p)=>GS(p,o,m),()=>Ye()),()=>we(e))}function mD(e,o,a){let u=_n(a);return Tt(e,o,u)}function KS(e,o,a){return xt(a,(u,m)=>wr(Tt(e,o,u),(p)=>we(p),()=>KS(e,o,m)),()=>Ye())}function Nt(e,o,a){return Or(a)?aD(e,o):Fr(a)?uD(e,o,a.if,a.then,a.else):un(a)?cD(e,o,a.enum):an(a)?iD(e,a.name,o,a.extends):Ge(a)?GS(e,o,a.allOf):tr(a)?mD(e,o,a.pattern):be(a)?KS(e,o,a.anyOf):tn(a)?we(e):Ye()}function HS(e,o,a){return an(a)?Nt(e,o,a):Or(a)?we(e):tn(a)?we(e):Zd(e)}function pD(e,o){let a=sa(e),u=sa(o);return a&&u?!0:!a&&u?!0:a&&!u?!1:!0}function WS(e,o,a,u){return St(u)?pD(o,u)?Tt(e,a,u.items):Ye():Nt(e,o,u)}function zS(e,o,a){return go(a)?we(e):Nt(e,o,a)}function VS(e,o,a){return Vn(a)?we(e):Nt(e,o,a)}function lD(e,o,a,u,m){let p=an(u)?o:u,f=an(u)?u:o,h=ln(o),I=ln(u);return!h&&I?Ye():wr(Tt(e,p,f),(E)=>Xu(E,a,m),()=>Ye())}function dD(e,o,a,u){return xt(u,(m,p)=>lD(e,o,a,m,p),()=>ln(o)?we(e):Ye())}function fD(e,o,a){return xt(o,(u,m)=>dD(e,u,m,a),()=>we(e))}function Xu(e,o,a){return fD(e,o,a)}function mp(e,o,a){return yo(a)?we(e):Tt(e,o,a)}function JS(e,o,a,u){return Or(u)?we(e):tn(u)?we(e):zr(u)?wr(Xu(e,o,u.parameters),(m)=>mp(m,a,u.instanceType),()=>Ye()):Ye()}function QS(e,o,a,u,m){return wr(Tt(e,o,m),()=>Tt(e,a,m),()=>Tt(e,u,m))}function XS(e,o,a){let u=Jn(o);return Tt(e,u,a)}function YS(e,o,a,u){return Or(u)?we(e):tn(u)?we(e):en(u)?wr(Xu(e,o,u.parameters),(m)=>mp(m,a,u.returnType),()=>Ye()):Ye()}function ZS(e,o,a){return yn(a)?we(e):Cr(a)?we(e):Nt(e,o,a)}function ew(e,o,a){let u=$r(o);return Tt(e,u,a)}function pp(e,o,a){return o===a?we(e):Ye()}function hD(e,o,a){return dt(a)?pp(e,o,a.const):go(a)?we(e):Nt(e,i(o),a)}function gD(e,o,a){return dt(a)?pp(e,o,a.const):Vn(a)?we(e):Nt(e,i(o),a)}function yD(e,o,a){return dt(a)?pp(e,o,a.const):Cr(a)?we(e):Nt(e,i(o),a)}function xD(e,o,a){return dt(a)?pp(e,o,a.const):cn(a)?we(e):Nt(e,i(o),a)}function tw(e,o,a){return qr(o.const)?hD(e,o.const,a):fn(o.const)?gD(e,o.const,a):Ot(o.const)?yD(e,o.const,a):lt(o.const)?xD(e,o.const,a):jr()}function rw(e,o,a){return an(a)?Nt(e,o,a):we(e)}function nw(e,o,a){return Ts(a)?we(e):Nt(e,o,a)}function ow(e,o,a){return Cr(a)?we(e):Nt(e,o,a)}function ID(e,o,a){return ln(o)?ln(a)?we(e):Ye():we(e)}function bD(e,o,a){return an(a)&&ho(a.extends)?Ye():wr(Tt(e,o,a),(u)=>ID(u,o,a),()=>Ye())}function ED(e,o){return e.reduce((a,u)=>(u in o)?co(o[u])?{...a,...o[u].inferred}:jr():jr(),{})}function SD(e,o,a){let u={};for(let f of Se(a))u[f]=f in o?bD({},o[f],a[f]):ln(a[f])?an(a[f])?we(gn(e,{[a[f].name]:a[f].extends})):we(e):Ye();let m=Td(u).every((f)=>co(f)),p=m?ED(Se(u),u):{};return m?we(p):Ye()}function wD(e,o,a){let u=SD(e,o,a);return co(u)?we(gn(e,u.inferred)):Ye()}function TD(e,o,a){return wD(e,o,a)}function RD(e,o){return Se(o).reduce((a,u)=>({...a,[u]:pe(e,u)?be(a[u])?g([...a[u].anyOf,o[u]]):g([e[u],o[u]]):o[u]}),e)}function sw(e,o,a,u){return xt(o,(m,p)=>wr(Tt({},e[m],a),(f)=>sw(e,p,a,RD(u,f)),()=>Ye()),()=>we(u))}function kD(e,o,a,u){let m=Se(o);return sw(o,m,u,e)}function iw(e,o,a){return Kt(a)?kD(e,o,xn(a),or(a)):He(a)?TD(e,o,a.properties):Nt(e,l(o),a)}function AD(e,o){return M(Se(o).length,0)?we(e):Ye()}function PD(e,o,a,u,m){return Tt(e,a,m)}function aw(e,o,a,u){return Kt(u)?PD(e,Mm(o),a,Mm(xn(u)),or(u)):He(u)?AD(e,u.properties):Or(u)?we(e):tn(u)?we(e):Ye()}function uw(e,o,a){return cn(a)?we(e):Nt(e,o,a)}function cw(e,o,a){return Rs(a)?we(e):Nt(e,o,a)}function mw(e,o,a){let u=_n(o);return Tt(e,u,a)}function nf(e,o){return $t({"~kind":"Inferrable"},{name:e,type:o},{})}function Yu(e){return at(e)&&pe(e,"~kind")&&pe(e,"name")&&pe(e,"type")&&M(e["~kind"],"Inferrable")&&lt(e.name)&&at(e.type)}function of(e){return fi(e)?an(e.items)?St(e.items.extends)?nf(e.items.name,e.items.extends.items):tn(e.items.extends)?nf(e.items.name,e.items.extends):void 0:jr():void 0}function lp(e){return an(e)?nf(e.name,e.extends):void 0}function sf(e,o,a=[]){return xt(e,(u,m)=>wr(Tt({},u,o),()=>sf(m,o,[...a,u]),()=>{return}),()=>a)}function pw(e,o,a,u){let m=sf(a,u);return Fe(m)?we(gn(e,{[o]:Ur(m)})):Ye()}function dp(e,o,a,u){let m=sf(a,u);return Fe(m)?we(gn(e,{[o]:g(m)})):Ye()}function CD(e){return[...e].reverse()}function af(e,o){return o?CD(e):e}function $D(e){let o=e.length>0?e[0]:void 0,a=Mr(o)?of(o):void 0;return Mr(a)}function vD(e,o,a,u,m,p){return wr(Tt(e,a,m),(f)=>lw(f,o,u,p),()=>Ye())}function MD(e,o,a,u,m){let p=of(u);return Yu(p)?pw(e,p.name,af(a,o),p.type):xt(a,(f,h)=>vD(e,o,f,h,u,m),()=>Ye())}function OD(e,o,a,u){return xt(u,(m,p)=>MD(e,o,a,m,p),()=>M(a.length,0)?we(e):Ye())}function lw(e,o,a,u){return OD(e,o,a,u)}function _D(e,o,a){let u=xi(e,yr([],[]),a),m=$D(u);return lw(e,m,af(o,m),af(u,m))}function dw(e,o,a){let u=lp(a);return Yu(u)?dp(e,u.name,o,u.type):xt(o,(m,p)=>wr(Tt(e,m,a),(f)=>dw(f,p,a),()=>Ye()),()=>we(e))}function fw(e,o,a){let u=xi(e,yr([],[]),o);return ct(a)?_D(e,u,a.items):St(a)?dw(e,u,a.items):Nt(e,Ur(u),a)}function hw(e,o,a){return yo(a)?we(e):ss(a)?we(e):Nt(e,o,a)}function gw(e,o,a){return xt(a,(u,m)=>wr(Tt(e,o,u),(p)=>we(p),()=>gw(e,o,m)),()=>Ye())}function uf(e,o,a){return xt(o,(u,m)=>wr(gw(e,u,a),(p)=>uf(p,m,a),()=>Ye()),()=>we(e))}function yw(e,o,a){let u=lp(a);return Yu(u)?dp(e,u.name,o,u.type):be(a)?uf(e,o,a.anyOf):uf(e,o,[a])}function xw(e,o,a){return an(a)?Nt(e,o,a):Or(a)?we(e):tn(a)?we(e):Ye()}function Iw(e,o,a){return yo(a)?we(e):Nt(e,o,a)}function Tt(e,o,a){return Or(o)?HS(e,o,a):St(o)?WS(e,o,o.items,a):go(o)?zS(e,o,a):Vn(o)?VS(e,o,a):zr(o)?JS(e,o.parameters,o.instanceType,a):Fr(o)?QS(e,o.if,o.then,o.else,a):un(o)?XS(e,o.enum,a):en(o)?YS(e,o.parameters,o.returnType,a):yn(o)?ZS(e,o,a):Ge(o)?ew(e,o.allOf,a):dt(o)?tw(e,o,a):ho(o)?rw(e,o,a):Ts(o)?nw(e,o,a):Cr(o)?ow(e,o,a):He(o)?iw(e,o.properties,a):Kt(o)?aw(e,xn(o),or(o),a):cn(o)?uw(e,o,a):Rs(o)?cw(e,o,a):tr(o)?mw(e,o.pattern,a):ct(o)?fw(e,o.items,a):ss(o)?hw(e,o,a):be(o)?yw(e,o.anyOf,a):tn(o)?xw(e,o,a):yo(o)?Iw(e,o,a):Ye()}function LD(e,o){return $r([...e,l(o)])}function cf(e,o,a){return ut(e)?Et(LD(e,o),{},a):Ku(e,o,a)}function bw(e,o,a,u,m){let p=So(e,o,a),f=Zu(e,o,u);return cf(p,f,m)}function Ku(e,o,a={}){return Ae("Interface",[e,o],a)}function Ka(e){return Mr(e)&&pe(e,"action")&&M(e.action,"Interface")}function Ew(e,o,a={}){return cf(e,o,a)}function ND(e,o,a){return e.includes(a)?!0:ec([...e,a],o,o[a])}function Sw(e,o,a){let u=hm(a);return la(e,o,u)}function la(e,o,a){return xt(a,(u,m)=>ec(e,o,u)?!0:la(e,o,m),()=>!1)}function ec(e,o,a){return Ft(a)?ND(e,o,a.$ref):St(a)?ec(e,o,a.items):zr(a)?la(e,o,[...a.parameters,a.instanceType]):en(a)?la(e,o,[...a.parameters,a.returnType]):Ka(a)?Sw(e,o,a.parameters[1]):Ge(a)?la(e,o,a.allOf):He(a)?Sw(e,o,a.properties):be(a)?la(e,o,a.anyOf):ct(a)?la(e,o,a.items):Kt(a)?ec(e,o,or(a)):!1}function ww(e,o,a){return ec(e,o,a)}function DD(e,o){return o.reduce((a,u)=>ww([u],e,e[u])?[...a,u]:a,[])}function Tw(e){let o=fm(e);return DD(e,o)}function qD(e,o,a){return a.includes(o)?a:(o in e)?tc(e,e[o],[...a,o]):jr()}function Rw(e,o,a){let u=hm(o);return Ha(e,u,a)}function Ha(e,o,a){return o.reduce((u,m)=>tc(e,m,u),a)}function tc(e,o,a){return Ft(o)?qD(e,o.$ref,a):St(o)?tc(e,o.items,a):zr(o)?Ha(e,[...o.parameters,o.instanceType],a):en(o)?Ha(e,[...o.parameters,o.returnType],a):Ka(o)?Rw(e,o.parameters[1],a):Ge(o)?Ha(e,o.allOf,a):He(o)?Rw(e,o.properties,a):be(o)?Ha(e,o.anyOf,a):ct(o)?Ha(e,o.items,a):Kt(o)?tc(e,or(o),a):a}function kw(e,o,a){return tc(e,a,[o])}function FD(e){return _a()}function jD(e){return Se(e).reduce((o,a)=>({...o,[a]:da(e[a])}),{})}function rc(e){return e.reduce((o,a)=>[...o,da(a)],[])}function da(e){return Ft(e)?FD(e.$ref):St(e)?H(da(e.items),Ma(e)):zr(e)?Is(rc(e.parameters),da(e.instanceType)):en(e)?bs(rc(e.parameters),da(e.returnType)):Ge(e)?Mn(rc(e.allOf)):He(e)?l(jD(e.properties)):Kt(e)?ks(di(e),da(or(e))):be(e)?g(rc(e.anyOf)):ct(e)?Ur(rc(e.items)):e}function UD(e,o){return o in e?da(e[o]):Pr()}function Aw(e){return UD(e.$defs,e.$ref)}function BD(e,o,a){let u=So(e,yr([],[]),o),m=Zu({},yr([],[]),a);return $r([...u,l(m)])}function GD(e,o){return Se(e).filter((u)=>o.includes(u)).reduce((u,m)=>{let p=e[m],f=Ka(p)?BD(e,p.parameters[0],p.parameters[1]):p;return{...u,[m]:f}},{})}function Pw(e,o,a){let u=kw(e,o,a),m=GD(e,u);return Ss(m,o)}function Cw(e,o){return o in e?Ft(e[o])?Cw(e,e[o].$ref):e[o]:Vt()}function As(e,o){return Cw(e,o)}function $w(e){return Xt(e)?Aw(e):gm(e)?Pr():e}function An(e,o,a){let u=$w(o),m=$w(a);return Tt(e,u,m)}var Fu=0,nc=1,ju=2,Uu=3;function qa(e,o){let a=[An({},e,o),An({},o,e)];return co(a[0])&&co(a[1])?Fu:co(a[0])&&rf(a[1])?ju:rf(a[0])&&co(a[1])?Uu:nc}function mf(e,o,a=[],u=o){return xt(o,(m,p)=>{let f=qa(e,m);return M(f,ju)||M(f,Fu)?u:M(f,nc)?mf(e,p,[...a,m],u):mf(e,p,a,u)},()=>[...a,e])}function KD(e,o,a){let u=vo(e);return Or(u)?[u]:tn(u)?[u]:ho(u)?fp(o,a):He(u)?fp(o,[...a,u]):fp(o,mf(u,a))}function fp(e,o=[]){return xt(e,(a,u)=>KD(a,u,o),()=>o)}function Dd(e){let o=fp(e);return ca(o)}function pf(e,o){return Et(vo(e),{},o)}function vw(e,o,a,u){let m=he(e,o,a);return pf(m,u)}function oc(e,o=[]){return ai(e)&&M(e.action,"Conditional")?Ft(e.parameters[0])?oc(e.parameters[2],oc(e.parameters[3],[...o,e.parameters[0].$ref])):oc(e.parameters[2],oc(e.parameters[3],o)):ai(e)&&M(e.action,"Mapped")?ai(e.parameters[1])&&M(e.parameters[1].action,"KeyOf")&&Ft(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function HD(e,o){return e.reduce((a,u)=>[...a,o.includes(u.name)],[])}function _w(e,o,a=[]){return xt(e,(u,m)=>xt(o,(p,f)=>_w(m,f,[...a,[p,u]]),()=>a),()=>a)}function WD(e){return tr(e)?_n(e.pattern):un(e)?Jn(e.enum):e}function zD(e){let o=WD(e);return be(o)?[...o.anyOf]:[o]}function VD(e,o){return e.reduce((a,u)=>[...a,[...u,o]],[])}function Mw(e,o){return o.reduce((a,u)=>[...a,...VD(e,u)],[])}function Ow(e){return e.reduce((o,a)=>M(a[0],!0)?Mw(o,zD(a[1])):Mw(o,[a[1]]),[[]])}function Lw(e,o,a){let u=oc(a),m=HD(e,u),p=_w(o,m);return ai(a)&&M(a.action,"Conditional")?Ow(p):ai(a)&&M(a.action,"Mapped")?Ow(p):[o]}function JD(){return["(not-resolvable)",Vt()]}function QD(){return["(not-generic)",Vt()]}function XD(e,o,a){return[e,ui(o,a)]}function YD(e,o,a){return o in e?Nw(e,o,e[o],a):JD()}function Nw(e,o,a,u){return Oa(a)?XD(o,a.parameters,a.expression):Ft(a)?YD(e,a.$ref,u):QD()}function Dw(e,o,a){return Nw(e,"(anonymous)",o,a)}function ZD(e,o,a){if(an(o)||Wa(o)||co(An({},o,a)))return;let u={parameter:e,expect:a,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function qw(e,o,a,u,m){let p=he(e,o,m);return ZD(a,p,u),gn(e,{[a]:p})}function eq(e,o,a,u,m){let p=he(e,o,a.extends),f=he(e,o,a.equals);return xt(m,(h,I)=>lf(qw(e,o,a.name,p,h),o,u,I),()=>lf(qw(e,o,a.name,p,f),o,u,[]))}function lf(e,o,a,u){return xt(a,(m,p)=>eq(e,o,m,p,u),()=>e)}function Fw(e,o,a,u){return lf(e,o,a,u)}var df=0,ff=0;function tq(){if(Pu(ff,Bo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function rq(){tq(),ff++,df++}function nq(){if(df--,M(df,0))ff=0}function oq(e){return ji(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function sq(e,o){return M(oq(e),o)}function iq(e,o,a,u,m,p){rq();try{let f=Fw(e,o,u,p),h=he(f,yr([...o.callstack,a.$ref],o.visited),m);return he(f,yr([],[]),h)}finally{nq()}}function aq(e,o,a,u,m,p){return p.reduce((f,h)=>{let I=iq(e,o,a,u,m,h);return[...f,I]},[])}function uq(e,o,a,u,m,p){let f=Lw(u,p,m),h=aq(e,o,a,u,m,f);return M(h.length,1)?h[0]:Zn(h)}function hp(e,o,a,u){let m=So(e,o,u),p=Dw(e,a,u),f=p[0],h=p[1];return Oa(h)?sq(o,f)?Hu(pn(f),m):uq(e,o,pn(f),h.parameters,h.expression,m):Hu(a,m)}function Hu(e,o){return $t({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function jw(e,o){return hp({},yr([],[]),e,o)}function Wa(e){return Re(e,"Call")}function cq(e){return Ho(e,["~immutable"])}function Uw(e,o){return Et(cq(e),{},o)}function Bw(e,o,a,u){let m=he(e,o,a);return Uw(m,u)}function Gw(e,o){return e(o)}function Kw(e,o){return lt(o)?i(Gw(e,o)):i(o)}function Hw(e,o){let a=_n(o);return Fs(e,a)}function Ww(e,o){let a=o.map((u)=>Fs(e,u));return g(a)}function Fs(e,o){return dt(o)?Kw(e,o.const):tr(o)?Hw(e,o.pattern):be(o)?Ww(e,o.anyOf):o}function Dm(e,o={}){return Ae("Capitalize",[e],o)}function zw(e,o={}){return hf(e,o)}function qm(e,o={}){return Ae("Lowercase",[e],o)}function Vw(e,o={}){return gf(e,o)}function Fm(e,o={}){return Ae("Uncapitalize",[e],o)}function Jw(e,o={}){return yf(e,o)}function jm(e,o={}){return Ae("Uppercase",[e],o)}function Qw(e,o={}){return xf(e,o)}var mq=(e)=>e[0].toUpperCase()+e.slice(1),pq=(e)=>e.toLowerCase(),lq=(e)=>e[0].toLowerCase()+e.slice(1),dq=(e)=>e.toUpperCase();function hf(e,o){return ut([e])?Et(Fs(mq,e),{},o):Dm(e,o)}function gf(e,o){return ut([e])?Et(Fs(pq,e),{},o):qm(e,o)}function yf(e,o){return ut([e])?Et(Fs(lq,e),{},o):Fm(e,o)}function xf(e,o){return ut([e])?Et(Fs(dq,e),{},o):jm(e,o)}function Xw(e,o,a,u){let m=he(e,o,a);return hf(m,u)}function Yw(e,o,a,u){let m=he(e,o,a);return gf(m,u)}function Zw(e,o,a,u){let m=he(e,o,a);return yf(m,u)}function eT(e,o,a,u){let m=he(e,o,a);return xf(m,u)}function Um(e,o,a,u,m={}){return Ae("Conditional",[e,o,a,u],m)}function tT(e,o,a,u,m={}){return If({},yr([],[]),e,o,a,u,m)}function fq(e,o,a,u,m,p){let f=An(e,a,u);return ef(f)?g([he(f.inferred,o,m),he(e,o,p)]):tf(f)?he(f.inferred,o,m):he(e,o,p)}function If(e,o,a,u,m,p,f){return ut([a,u])?Et(fq(e,o,a,u,m,p),{},f):Um(a,u,m,p,f)}function rT(e,o,a,u,m,p,f){let h=he(e,o,a),I=he(e,o,u);return If(e,o,h,I,m,p,f)}function Bm(e,o={}){return Ae("ConstructorParameters",[e],o)}function nT(e,o={}){return bf(e,o)}function hq(e){let o=zr(e)?e.parameters:[],a=xi({},yr([],[]),o);return Ur(a)}function bf(e,o){return ut([e])?Et(hq(e),{},o):Bm(e,o)}function oT(e,o,a,u){let m=he(e,o,a);return bf(m,u)}function Gm(e,o,a={}){return Ae("Exclude",[e,o],a)}function sT(e,o,a={}){return sc(e,o,a)}function sc(e,o,a){return ut([e,o])?Et($m(e,o),{},a):Gm(e,o,a)}function iT(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return sc(p,f,m)}function Km(e,o,a={}){return Ae("Extract",[e,o],a)}function aT(e,o,a={}){return Ef(e,o,a)}function gq(e,o){let a=An({},e,o);return co(a)?[e]:[]}function uT(e,o,a=[]){return xt(e,(u,m)=>uT(m,o,[...a,...gq(u,o)]),()=>a)}function cT(e,o){let a=vo(e),u=be(a)?a.anyOf:[a],m=uT(u,o);return Zn(m)}function Ef(e,o,a){return ut([e,o])?Et(cT(e,o),{},a):Km(e,o,a)}function mT(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return Ef(p,f,m)}function yq(e){return e.reduce((o,a)=>Sm(a)?[...o,i(a)]:o,[])}function za(e){let o=yq(e);return g(o)}function Wu(e,o,a={}){return Ae("Index",[e,o],a)}function pT(e,o,a={}){let u=Fe(o)?za(o):o;return Sf(e,u,a)}function lT(e,o){let a=As(e,o);return wo(a)}function dT(e,o,a){let u=es(e,o,a);return wo(u)}function xq(e,o){let a=Se(e).filter((S)=>!pe(o,S)),u=Se(o).filter((S)=>!pe(e,S)),m=Se(e).filter((S)=>pe(o,S)),p=a.reduce((S,R)=>({...S,[R]:e[R]}),{}),f=u.reduce((S,R)=>({...S,[R]:o[R]}),{}),h=m.reduce((S,R)=>({...S,[R]:$r([e[R],o[R]])}),{}),I=gn(p,f);return gn(I,h)}function fT(e){return e.reduce((o,a)=>xq(o,wo(a)),{})}function hT(e){return e}function gT(e){let o=oI(Ur(e));return wo(o)}function Iq(e,o){return Se(e).filter((m)=>(m in o)).reduce((m,p)=>({...m,[p]:Zn([e[p],o[p]])}),{})}function yT(e,o){return xt(e,(a,u)=>yT(u,Iq(o,wo(a))),()=>o)}function xT(e){return xt(e,(o,a)=>yT(a,wo(o)),()=>jr())}function wo(e){return Xt(e)?lT(e.$defs,e.$ref):Fr(e)?dT(e.if,e.then,e.else):Ge(e)?fT(e.allOf):be(e)?xT(e.anyOf):ct(e)?gT(e.items):He(e)?hT(e.properties):{}}function Va(e){let o=wo(e);return l(o)}var bq=new RegExp("^(?:0|[1-9][0-9]*)$");function Ja(e){let o=`${e}`;return bq.test(o)?parseInt(o):e}function Eq(e){return i(Ja(e))}function IT(e){return e.map((o)=>bT(o))}function bT(e){return Ge(e)?Mn(IT(e.allOf)):be(e)?g(IT(e.anyOf)):dt(e)?Eq(e.const):e}function ET(e,o){let a=bT(o),u=An({},a,te());return co(u)?e:dt(o)&&M(o.const,"length")?te():Vt()}function ST(e,o){let a=As(e,o);return xo(a)}function wT(e,o,a){let u=es(e,o,a);return xo(u)}function TT(e){let o=Jn(e);return xo(o)}function RT(e){let o=$r(e);return xo(o)}function kT(e){return[`${e}`]}function AT(e){let o=_n(e);return xo(o)}function PT(e){return e.reduce((o,a)=>[...o,...xo(a)],[])}function xo(e){return Xt(e)?ST(e.$defs,e.$ref):Fr(e)?wT(e.if,e.then,e.else):un(e)?TT(e.enum):Ge(e)?RT(e.allOf):dt(e)?kT(e.const):tr(e)?AT(e.pattern):be(e)?PT(e.anyOf):[]}function Qa(e){return xo(e)}function ic(e,o){return o.map((a)=>ac(e,a))}function ac(e,o){return St(o)?H(ac(e,o.items)):zr(o)?Is(ic(e,o.parameters),ac(e,o.instanceType)):en(o)?bs(ic(e,o.parameters),ac(e,o.returnType)):ct(o)?Ur(ic(e,o.items)):be(o)?g(ic(e,o.anyOf)):Ge(o)?Mn(ic(e,o.allOf)):_m(o)?l(e):o}function CT(e,o){return ac(e,o)}function Sq(e,o){let a=o in e?e[o]:Vt();return CT(e,a)}function $T(e,o){return o.reduce((a,u)=>[...a,Sq(e,u)],[])}function wq(e,o){let a=Qa(o),u=$T(e,a);return Zn(u)}var Tq=new RegExp(li);function Rq(e){return e.filter((a)=>Tq.test(a))}function kq(e){let o=fm(e),a=Rq(o),u=$T(e,a);return Zn(u)}function vT(e,o){return Cr(o)?kq(e):wq(e,o)}function Aq(e){return i(Ja(e))}function MT(e){return e.map((o)=>wf(o))}function wf(e){return Ge(e)?Mn(MT(e.allOf)):be(e)?g(MT(e.anyOf)):dt(e)?Aq(e.const):e}function Pq(e,o){return e.reduceRight((a,u,m)=>{let p=An({},i(m),o);return co(p)?[u,...a]:a},[])}function Cq(e,o){let a=wf(o),u=Pq(e,a);return mi(u)}function $q(e){return mi(e)}function OT(e,o){return dt(o)&&M(o.const,"length")?i(e.length):Cr(o)||yn(o)?$q(e):Cq(e,o)}function _T(e,o){return St(e)?ET(e.items,o):He(e)?vT(e.properties,o):ct(e)?OT(e.items,o):Vt()}function vq(e){return Xt(e)||Fr(e)||Ge(e)||be(e)?Va(e):e}function Sf(e,o,a){return ut([e,o])?Et(_T(vq(e),o),{},a):Wu(e,o,a)}function LT(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return Sf(p,f,m)}function Hm(e,o={}){return Ae("InstanceType",[e],o)}function NT(e,o={}){return Tf(e,o)}function Mq(e){return zr(e)?e.instanceType:Vt()}function Tf(e,o){return ut([e])?Et(Mq(e),{},o):Hm(e,o)}function DT(e,o,a,u={}){let m=he(e,o,a);return Tf(m,u)}function zu(e,o={}){return Ae("KeyOf",[e],o)}function qT(e,o={}){return Rf(e,o)}function FT(){return g([te(),s(),Da()])}function jT(e){return te()}function Oq(e){return e.reduce((a,u)=>Sm(u)?[...a,i(Ja(u))]:jr(),[])}function UT(e){let o=Se(e),a=Oq(o);return mi(a)}function BT(e){return di(e)}function GT(e){let o=e.map((a,u)=>i(u));return mi(o)}function KT(e){return Or(e)?FT():St(e)?jT(e.items):He(e)?UT(e.properties):Kt(e)?BT(e):ct(e)?GT(e.items):Vt()}function _q(e){return Xt(e)||Fr(e)||Ge(e)||be(e)?Va(e):e}function Rf(e,o){return ut([e])?Et(KT(_q(e)),{},o):zu(e,o)}function HT(e,o,a,u){let m=he(e,o,a);return Rf(m,u)}function Gu(e,o,a,u,m={}){return Ae("Mapped",[e,o,a,u],m)}function WT(e,o,a,u,m={}){return kf({},yr([],[]),e,o,a,u,m)}function Lq(e){let o=_n(e);return gp(o)}function Nq(e){return e.reduce((o,a)=>[...o,...gp(a)],[])}function Dq(e){let o=Jn(e);return gp(o)}function qq(e){return Ot(e)?[i(`${e}`)]:[i(e)]}function gp(e){return un(e)?Dq(e.enum):dt(e)?qq(e.const):tr(e)?Lq(e.pattern):be(e)?Nq(e.anyOf):[e]}function zT(e){return gp(e)}function Fq(e){return tr(e)?_n(e.pattern):e}function jq(e,o,a,u,m,p){let f=gn(e,{[a.name]:u}),h=he(f,o,m),I=Fq(h),E=he(f,o,p);return wm(I)||Tm(I)?{[I.const]:E}:{}}function Uq(e,o,a,u,m,p){return u.reduce((f,h)=>[...f,jq(e,o,a,h,m,p)],[])}function Bq(e){return e.reduce((o,a)=>[...o,l(a)],[])}function VT(e,o,a,u,m,p){let f=zT(u),h=Uq(e,o,a,f,m,p),I=Bq(h);return $r(I)}function kf(e,o,a,u,m,p,f){return ut([u])?Et(VT(e,o,a,u,m,p),{},f):Gu(a,u,m,p,f)}function JT(e,o,a,u,m,p,f){let h=he(e,o,u);return kf(e,o,a,h,m,p,f)}function Gq(e,o,a){let u=gn(e,o);return Se(o).filter((p)=>a.includes(p)).reduce((p,f)=>({...p,[f]:Pw(u,f,o[f])}),{})}function Kq(e,o,a){let u=gn(e,o);return Se(o).filter((p)=>!a.includes(p)).reduce((p,f)=>({...p,[f]:he(u,yr([],[]),o[f])}),{})}function Hq(e,o,a){let u=Tw(o),m=Gq(e,o,u),p=Kq(e,o,u),f={...m,...p};return Et(f,{},a)}function yp(e,o,a,u){return Hq(e,a,u)}function Wm(e,o={}){return Ae("NonNullable",[e],o)}function QT(e,o={}){return Af(e,o)}function Wq(e){let o=g([On(),ja()]);return sc(e,o,{})}function Af(e,o){return ut([e])?Et(Wq(e),{},o):Wm(e,o)}function XT(e,o,a,u){let m=he(e,o,a);return Af(m,u)}function zm(e,o,a={}){return Ae("Omit",[e,o],a)}function YT(e,o,a={}){let u=Fe(o)?za(o):o;return Pf(e,u,a)}function xp(e){let o=Va(e);return He(o)?o.properties:jr()}function zq(e,o){return Se(e).reduce((u,m)=>o.includes(m)?u:{...u,[m]:e[m]},{})}function ZT(e,o){let a=xp(e),u=Qa(o),m=zq(a,u);return l(m)}function Pf(e,o,a){return ut([e,o])?Et(ZT(e,o),{},a):zm(e,o,a)}function eR(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return Pf(p,f,m)}function Vm(e,o={}){return Ae("Parameters",[e],o)}function tR(e,o={}){return Cf(e,o)}function Vq(e){let o=en(e)?e.parameters:[],a=xi({},yr([],[]),o);return Ur(a)}function Cf(e,o){return ut([e])?Et(Vq(e),{},o):Vm(e,o)}function rR(e,o,a,u){let m=he(e,o,a);return Cf(m,u)}function Jm(e,o={}){return Ae("Partial",[e],o)}function nR(e,o={}){return $f(e,o)}function oR(e,o){let a=As(e,o),u=Ps(a);return Ss(gn(e,{[o]:u}),o)}function sR(e,o,a){let u=es(e,o,a);return Ps(u)}function iR(e){let o=$r(e);return Ps(o)}function aR(e){let o=e.map((a)=>Ps(a));return g(o)}function uR(e){let o=Se(e).reduce((u,m)=>({...u,[m]:ra(e[m])}),{});return l(o)}function Ps(e){return Xt(e)?oR(e.$defs,e.$ref):Fr(e)?sR(e.if,e.then,e.else):Ge(e)?iR(e.allOf):be(e)?aR(e.anyOf):He(e)?uR(e.properties):l({})}function $f(e,o){return ut([e])?Et(Ps(e),{},o):Jm(e,o)}function cR(e,o,a,u){let m=he(e,o,a);return $f(m,u)}function Qm(e,o,a={}){return Ae("Pick",[e,o],a)}function mR(e,o,a={}){let u=Fe(o)?za(o):o;return vf(e,u,a)}function Jq(e,o){return Se(e).reduce((u,m)=>o.includes(m)?gn(u,{[m]:e[m]}):u,{})}function pR(e,o){let a=xp(e),u=Qa(o),m=Jq(a,u);return l(m)}function vf(e,o,a){return ut([e,o])?Et(pR(e,o),{},a):Qm(e,o,a)}function lR(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return vf(p,f,m)}function Xm(e,o={}){return Ae("ReadonlyObject",[e],o)}function Mf(e,o={}){return Of(e,o)}var dR=Mf;function fR(e){return Na(H(e))}function hR(e,o){let a=As(e,o),u=Cs(a);return Ss(gn(e,{[o]:u}),o)}function gR(e,o,a){let u=es(e,o,a);return Cs(u)}function yR(e){let o=$r(e);return Cs(o)}function xR(e){let o=Se(e).reduce((u,m)=>({...u,[m]:ia(e[m])}),{});return l(o)}function IR(e){return Na(Ur(e))}function bR(e){let o=e.map((a)=>Cs(a));return g(o)}function Cs(e){return St(e)?fR(e.items):Xt(e)?hR(e.$defs,e.$ref):Fr(e)?gR(e.if,e.then,e.else):Ge(e)?yR(e.allOf):He(e)?xR(e.properties):ct(e)?IR(e.items):be(e)?bR(e.anyOf):e}function Of(e,o){return ut([e])?Et(Cs(e),{},o):Xm(e)}function ER(e,o,a,u){let m=he(e,o,a);return Of(m,u)}function SR(e,o,a,u){return o.visited.includes(u)?a:(u in e)?he(e,yr(o.callstack,[...o.visited,u]),e[u]):a}function wR(e,o){let a=As(e,o),u=$s(a);return Ss(gn(e,{[o]:u}),o)}function TR(e,o,a){let u=es(e,o,a);return $s(u)}function RR(e){let o=$r(e);return $s(o)}function kR(e){let o=e.map((a)=>$s(a));return g(o)}function AR(e){let o=Se(e).reduce((u,m)=>({...u,[m]:Cm(e[m])}),{});return l(o)}function $s(e){return Xt(e)?wR(e.$defs,e.$ref):Fr(e)?TR(e.if,e.then,e.else):Ge(e)?RR(e.allOf):be(e)?kR(e.anyOf):He(e)?AR(e.properties):l({})}function Ym(e,o={}){return Ae("Required",[e],o)}function PR(e,o={}){return _f(e,o)}function _f(e,o){return ut([e])?Et($s(e),{},o):Ym(e,o)}function CR(e,o,a,u){let m=he(e,o,a);return _f(m,u)}function Zm(e,o={}){return Ae("ReturnType",[e],o)}function $R(e,o={}){return Lf(e,o)}function Qq(e){return en(e)?e.returnType:Vt()}function Lf(e,o){return ut([e])?Et(Qq(e),{},o):Zm(e,o)}function vR(e,o,a,u={}){let m=he(e,o,a);return Lf(m,u)}function ep(e,o){return Ae("With",[e,o],{})}function Ip(e,o){return Nf(e,o)}function Nf(e,o){return ut([e])?Et(e,{},o):ep(e,o)}function MR(e,o,a,u){let m=he(e,o,a);return Nf(m,u)}function Xq(e){return fi(e)?ct(e.items)?Df(e.items.items):an(e.items)?[e]:Ft(e.items)?[e]:[Vt()]:[e]}function Df(e){return e.reduce((a,u)=>[...a,...Xq(u)],[])}function yr(e,o){return{callstack:e,visited:o}}function ut(e){return xt(e,(o,a)=>Ft(o)?!1:ut(a),()=>!0)}function Zu(e,o,a){return Se(a).reduce((u,m)=>({...u,[m]:he(e,o,a[m])}),{})}function xi(e,o,a){let u=So(e,o,a);return Df(u)}function So(e,o,a){return a.map((u)=>he(e,o,u))}function Yq(e,o){let a=ln(e)?Ou(o,{}):o,u=aa(e)?Mu(a,{}):a;return sa(e)?uc(u,{}):u}function Zq(e,o,a,u,m){return M(a,"AddImmutable")?OR(e,o,u[0],m):M(a,"RemoveImmutable")?Bw(e,o,u[0],m):M(a,"AddReadonly")?ix(e,o,u[0],m):M(a,"RemoveReadonly")?Zx(e,o,u[0],m):M(a,"AddOptional")?ax(e,o,u[0],m):M(a,"RemoveOptional")?rI(e,o,u[0],m):M(a,"Capitalize")?Xw(e,o,u[0],m):M(a,"Conditional")?rT(e,o,u[0],u[1],u[2],u[3],m):M(a,"ConstructorParameters")?oT(e,o,u[0],m):M(a,"Evaluate")?vw(e,o,u[0],m):M(a,"Exclude")?iT(e,o,u[0],u[1],m):M(a,"Extract")?mT(e,o,u[0],u[1],m):M(a,"Index")?LT(e,o,u[0],u[1],m):M(a,"InstanceType")?DT(e,o,u[0],m):M(a,"Interface")?bw(e,o,u[0],u[1],m):M(a,"KeyOf")?HT(e,o,u[0],m):M(a,"Lowercase")?Yw(e,o,u[0],m):M(a,"Mapped")?JT(e,o,u[0],u[1],u[2],u[3],m):M(a,"Module")?yp(e,o,u[0],m):M(a,"NonNullable")?XT(e,o,u[0],m):M(a,"Pick")?lR(e,o,u[0],u[1],m):M(a,"Parameters")?rR(e,o,u[0],m):M(a,"Partial")?cR(e,o,u[0],m):M(a,"Omit")?eR(e,o,u[0],u[1],m):M(a,"ReadonlyObject")?ER(e,o,u[0],m):M(a,"Record")?II(e,o,u[0],u[1],m):M(a,"Required")?CR(e,o,u[0],m):M(a,"ReturnType")?vR(e,o,u[0],m):M(a,"TemplateLiteral")?jS(e,o,u[0],m):M(a,"Uncapitalize")?Zw(e,o,u[0],m):M(a,"Uppercase")?eT(e,o,u[0],m):M(a,"With")?MR(e,o,u[0],u[1]):Ae(a,u,m)}function eF(e,o,a){let u=Ft(a)?SR(e,o,a,a.$ref):St(a)?H(he(e,o,a.items),Ma(a)):Wa(a)?hp(e,o,a.target,a.arguments):zr(a)?Is(So(e,o,a.parameters),he(e,o,a.instanceType),ux(a)):en(a)?bs(So(e,o,a.parameters),he(e,o,a.returnType),cx(a)):Fr(a)?na(he(e,o,a.if),he(e,o,a.then),he(e,o,a.else),dx(a)):Ge(a)?Mn(So(e,o,a.allOf),xx(a)):He(a)?l(Zu(e,o,a.properties),lx(a)):Kt(a)?bI(xn(a),he(e,o,or(a))):fi(a)?ma(he(e,o,a.items)):ct(a)?Ur(xi(e,o,a.items),Yx(a)):be(a)?g(So(e,o,a.anyOf),Bx(a)):a;return Yq(a,u)}function he(e,o,a){return ai(a)?Zq(e,o,a.action,a.parameters,a.options):eF(e,o,a)}function Mo(e,o){return he(e,yr([],[]),o)}function tF(e){return Et(e,{"~immutable":!0},{})}function uc(e,o){return Et(tF(e),{},o)}function OR(e,o,a,u){let m=he(e,o,a);return uc(m,u)}function NE(e,o={}){return Ae("AddImmutable",[e],o)}function Na(e,o={}){return uc(e,o)}function DE(e,o={}){return Ae("Evaluate",[e],o)}function Pn(e,o={}){return pf(e,o)}function qE(e,o={}){return Ae("Module",[e],o)}function _R(e,o={}){return yp({},yr([],[]),e,o)}function rF(e,o){let a=qa(e,o);return M(a,Uu)?1:M(a,nc)?1:0}function LR(e,o,a=[]){return xt(o,(u,m)=>M(rF(e,u),1)?LR(e,m,[...a,u]):[...a,e,...o],()=>[...a,e])}function NR(e,o=[]){return xt(e,(a,u)=>NR(u,LR(a,o)),()=>o)}function DR(e){return NR(e)}function qR(...e){let[o,a,u]=kn(e,{2:(f,h)=>lt(f)?[{},f,h]:[f,h,{}],3:(f,h,I)=>[f,h,I],1:(f)=>[{},f,{}]}),m=LS(a),p=Fe(m)&&M(m.length,2)?he(o,yr([],[]),m[0]):Vt();return Et(p,{},u)}function b(e,o){return{name:e,login:async(a)=>{a.signal.throwIfAborted();let u=await a.prompt({type:"secret",message:`Enter ${e}`});return a.signal.throwIfAborted(),{type:"api_key",key:u}},resolve:async({ctx:a,credential:u,signal:m})=>{if(m.throwIfAborted(),u?.key)return{auth:{apiKey:u.key},env:u.env,source:"stored credential"};for(let p of o){let f=await a.env(p);if(m.throwIfAborted(),f)return{auth:{apiKey:f},source:p}}return}}}function de(e){let o,a=()=>(o??=e.load(),o);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(u,m)=>(await a()).login(u,m),refresh:async(u,m)=>(await a()).refresh(u,m),toAuth:async(u)=>(await a()).toAuth(u)}}var BR="faux",GR="faux",KR="faux-1",nF="Faux Model",oF="http://localhost:0",sF=3,FR=5,Sp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function qn(e){return{type:"text",text:e}}function jo(e){return{type:"thinking",thinking:e}}function iF(e,o,a={}){return{type:"toolCall",id:a.id??jf("tool"),name:e,arguments:o}}function aF(e){if(typeof e==="string")return[qn(e)];return Array.isArray(e)?e:[e]}function Vo(e,o={}){return{role:"assistant",content:aF(e),api:BR,provider:GR,model:KR,usage:Sp,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 HR(e){return Math.ceil(e.length/4)}function jf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function WR(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(`
25
- `)}function zR(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(`
26
- `)}function uF(e){return[e.toolName,...e.content.map((o)=>WR([o]))].join(`
27
- `)}function cF(e){if(e.role==="system")return[W(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
28
- `);if(e.role==="user")return WR(e.content);if(e.role==="assistant")return zR(e.content);return uF(e)}function VR(e,o=e.length){let a=o>0?(o-1)*2:0;for(let u=0;u<o;u++)a+=e[u].length;return a}function mF(e,o){let a=0;while(a<e.length&&a<o.length&&e[a]===o[a])a++;let u=(m)=>a===m.length?"":(a>0?`
24
+ `,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[ME(o),a]),LS=(e,o=[])=>w(w(_S(e),([a,u])=>w(Yd(u),([m,p])=>[[a,m],p])),([a,u])=>LS(u,[...o,a]),()=>[o,e]),zN=(e)=>w(w(w(Yd(e),([o,a])=>w(LS(a),([u,m])=>w(w(_S(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[OE(o),a]),Yd=(e)=>w(w(WN(e),([o,a])=>w(w(BN(a),([u,m])=>[u,m],()=>w(GN(a),([u,m])=>[u,m],()=>w(KN(a),([u,m])=>[u,m],()=>w(HN(a),([u,m])=>[u,m],()=>[])))),([u,m])=>w(iS(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[_E(o),a]),VN=(e)=>w(w(Yd(e),([o,a])=>w(zN(a),([u,m])=>[[o,u],m])),([o,a])=>[LE(o),a]),NS=(e)=>w(w(VN(e),([o,a])=>[o,a],()=>w(rN(e),([o,a])=>[o,a],()=>w(vt(e),([o,a])=>[o,a],()=>[]))),([o,a])=>[NE(o),a]);function DS(e){let o=Vd(`\`${e}\``);return M(o.length,2)?o[0]:jr()}function QN(e){return e.join("|")}function XN(e){return e.slice(1,e.length-1)}function YN(e,o,a){return yi(o,`${a}${e}`)}function ZN(e,o){return yi(e,`${o}${Dx}`)}function eD(e,o){return yi(e,`${o}${Em}`)}function tD(e,o){return yi(e,`${o}${Rm}`)}function rD(e,o){return Ju(g([i("false"),i("true")]),e,o)}function nD(e,o){return yi(e,`${o}${km}`)}function oD(e,o,a){return yi(o,`${a}${XN(e)}`)}function sD(e,o,a){let u=Qu(e,{});return Ju(u,o,a)}function iD(e,o,a){let u=Jn(e);return Ju(u,o,a)}function qS(e,o,a,u=[]){return xt(e,(m,p)=>qS(p,o,a,[...u,Ju(m,[],"")]),()=>yi(o,`${a}(${QN(u)})`))}function Ju(e,o,a){return un(e)?iD(e.enum,o,a):yn(e)?eD(o,a):gt(e)?YN(e.const,o,a):go(e)?ZN(o,a):Vn(e)?rD(o,a):Cr(e)?tD(o,a):cn(e)?nD(o,a):tr(e)?oD(e.pattern,o,a):jS(e)?sD(e.parameters[0],o,a):be(e)?qS(e.anyOf,o,a):px}function yi(e,o){return xt(e,(a,u)=>Ju(a,u,o),()=>o)}function aD(e){return`^${yi(e,"")}$`}function FS(e){let o=aD(e);return Pm(o)}function Qu(e,o){return ct(e)?Et(FS(e),{},o):Nm(e,o)}function US(e,o,a,u){let m=So(e,o,a);return Qu(m,u)}function Nm(e,o={}){return ke("TemplateLiteral",[e],o)}function jS(e){return Mr(e)&&pe(e,"action")&&M(e.action,"TemplateLiteral")}function BS(e){return Qu(e,{})}function uD(e){let o=DS(e);return BS(o)}function GS(e,o={}){let a=dt(e)?uD(e):BS(e);return Et(a,{},o)}function tr(e){return Re(e,"TemplateLiteral")}function Zd(e){return $t({["~kind"]:"ExtendsUnion"},{inferred:e})}function ef(e){return ut(e)&&pe(e,"~kind")&&pe(e,"inferred")&&M(e["~kind"],"ExtendsUnion")&&ut(e.inferred)}function Se(e){return $t({["~kind"]:"ExtendsTrue"},{inferred:e})}function tf(e){return ut(e)&&pe(e,"~kind")&&pe(e,"inferred")&&M(e["~kind"],"ExtendsTrue")&&ut(e.inferred)}function et(){return $t({["~kind"]:"ExtendsFalse"},{})}function rf(e){return ut(e)&&pe(e,"~kind")&&M(e["~kind"],"ExtendsFalse")}function co(e){return ef(e)||tf(e)}function wr(e,o,a){return co(e)?o(e.inferred):a()}function cD(e,o,a,u){return wr(Tt(e,a,u),(m)=>Se(gn(gn(e,m),{[o]:a})),()=>et())}function mD(e,o){return Se(e)}function pD(e,o,a,u,m){return wr(Tt(e,o,a),(p)=>wr(Tt(p,o,u),(f)=>Se(f),()=>et()),()=>wr(Tt(e,o,m),(p)=>Se(p),()=>et()))}function lD(e,o,a){let u=Jn(a);return Tt(e,o,u)}function KS(e,o,a){return xt(a,(u,m)=>wr(Tt(e,o,u),(p)=>KS(p,o,m),()=>et()),()=>Se(e))}function dD(e,o,a){let u=_n(a);return Tt(e,o,u)}function HS(e,o,a){return xt(a,(u,m)=>wr(Tt(e,o,u),(p)=>Se(p),()=>HS(e,o,m)),()=>et())}function Nt(e,o,a){return Or(a)?mD(e,o):Fr(a)?pD(e,o,a.if,a.then,a.else):un(a)?lD(e,o,a.enum):an(a)?cD(e,a.name,o,a.extends):Ke(a)?KS(e,o,a.allOf):tr(a)?dD(e,o,a.pattern):be(a)?HS(e,o,a.anyOf):tn(a)?Se(e):et()}function WS(e,o,a){return an(a)?Nt(e,o,a):Or(a)?Se(e):tn(a)?Se(e):Zd(e)}function fD(e,o){let a=sa(e),u=sa(o);return a&&u?!0:!a&&u?!0:a&&!u?!1:!0}function zS(e,o,a,u){return St(u)?fD(o,u)?Tt(e,a,u.items):et():Nt(e,o,u)}function VS(e,o,a){return go(a)?Se(e):Nt(e,o,a)}function JS(e,o,a){return Vn(a)?Se(e):Nt(e,o,a)}function hD(e,o,a,u,m){let p=an(u)?o:u,f=an(u)?u:o,h=ln(o),I=ln(u);return!h&&I?et():wr(Tt(e,p,f),(E)=>Xu(E,a,m),()=>et())}function gD(e,o,a,u){return xt(u,(m,p)=>hD(e,o,a,m,p),()=>ln(o)?Se(e):et())}function yD(e,o,a){return xt(o,(u,m)=>gD(e,u,m,a),()=>Se(e))}function Xu(e,o,a){return yD(e,o,a)}function mp(e,o,a){return yo(a)?Se(e):Tt(e,o,a)}function QS(e,o,a,u){return Or(u)?Se(e):tn(u)?Se(e):zr(u)?wr(Xu(e,o,u.parameters),(m)=>mp(m,a,u.instanceType),()=>et()):et()}function XS(e,o,a,u,m){return wr(Tt(e,o,m),()=>Tt(e,a,m),()=>Tt(e,u,m))}function YS(e,o,a){let u=Jn(o);return Tt(e,u,a)}function ZS(e,o,a,u){return Or(u)?Se(e):tn(u)?Se(e):en(u)?wr(Xu(e,o,u.parameters),(m)=>mp(m,a,u.returnType),()=>et()):et()}function ew(e,o,a){return yn(a)?Se(e):Cr(a)?Se(e):Nt(e,o,a)}function tw(e,o,a){let u=$r(o);return Tt(e,u,a)}function pp(e,o,a){return o===a?Se(e):et()}function xD(e,o,a){return gt(a)?pp(e,o,a.const):go(a)?Se(e):Nt(e,i(o),a)}function ID(e,o,a){return gt(a)?pp(e,o,a.const):Vn(a)?Se(e):Nt(e,i(o),a)}function bD(e,o,a){return gt(a)?pp(e,o,a.const):Cr(a)?Se(e):Nt(e,i(o),a)}function ED(e,o,a){return gt(a)?pp(e,o,a.const):cn(a)?Se(e):Nt(e,i(o),a)}function rw(e,o,a){return qr(o.const)?xD(e,o.const,a):fn(o.const)?ID(e,o.const,a):Ot(o.const)?bD(e,o.const,a):dt(o.const)?ED(e,o.const,a):jr()}function nw(e,o,a){return an(a)?Nt(e,o,a):Se(e)}function ow(e,o,a){return Ts(a)?Se(e):Nt(e,o,a)}function sw(e,o,a){return Cr(a)?Se(e):Nt(e,o,a)}function SD(e,o,a){return ln(o)?ln(a)?Se(e):et():Se(e)}function wD(e,o,a){return an(a)&&ho(a.extends)?et():wr(Tt(e,o,a),(u)=>SD(u,o,a),()=>et())}function TD(e,o){return e.reduce((a,u)=>(u in o)?co(o[u])?{...a,...o[u].inferred}:jr():jr(),{})}function RD(e,o,a){let u={};for(let f of Ee(a))u[f]=f in o?wD({},o[f],a[f]):ln(a[f])?an(a[f])?Se(gn(e,{[a[f].name]:a[f].extends})):Se(e):et();let m=Td(u).every((f)=>co(f)),p=m?TD(Ee(u),u):{};return m?Se(p):et()}function kD(e,o,a){let u=RD(e,o,a);return co(u)?Se(gn(e,u.inferred)):et()}function AD(e,o,a){return kD(e,o,a)}function PD(e,o){return Ee(o).reduce((a,u)=>({...a,[u]:pe(e,u)?be(a[u])?g([...a[u].anyOf,o[u]]):g([e[u],o[u]]):o[u]}),e)}function iw(e,o,a,u){return xt(o,(m,p)=>wr(Tt({},e[m],a),(f)=>iw(e,p,a,PD(u,f)),()=>et()),()=>Se(u))}function CD(e,o,a,u){let m=Ee(o);return iw(o,m,u,e)}function aw(e,o,a){return Kt(a)?CD(e,o,xn(a),or(a)):He(a)?AD(e,o,a.properties):Nt(e,l(o),a)}function $D(e,o){return M(Ee(o).length,0)?Se(e):et()}function vD(e,o,a,u,m){return Tt(e,a,m)}function uw(e,o,a,u){return Kt(u)?vD(e,Mm(o),a,Mm(xn(u)),or(u)):He(u)?$D(e,u.properties):Or(u)?Se(e):tn(u)?Se(e):et()}function cw(e,o,a){return cn(a)?Se(e):Nt(e,o,a)}function mw(e,o,a){return Rs(a)?Se(e):Nt(e,o,a)}function pw(e,o,a){let u=_n(o);return Tt(e,u,a)}function nf(e,o){return $t({"~kind":"Inferrable"},{name:e,type:o},{})}function Yu(e){return ut(e)&&pe(e,"~kind")&&pe(e,"name")&&pe(e,"type")&&M(e["~kind"],"Inferrable")&&dt(e.name)&&ut(e.type)}function of(e){return fi(e)?an(e.items)?St(e.items.extends)?nf(e.items.name,e.items.extends.items):tn(e.items.extends)?nf(e.items.name,e.items.extends):void 0:jr():void 0}function lp(e){return an(e)?nf(e.name,e.extends):void 0}function sf(e,o,a=[]){return xt(e,(u,m)=>wr(Tt({},u,o),()=>sf(m,o,[...a,u]),()=>{return}),()=>a)}function lw(e,o,a,u){let m=sf(a,u);return qe(m)?Se(gn(e,{[o]:Ur(m)})):et()}function dp(e,o,a,u){let m=sf(a,u);return qe(m)?Se(gn(e,{[o]:g(m)})):et()}function MD(e){return[...e].reverse()}function af(e,o){return o?MD(e):e}function OD(e){let o=e.length>0?e[0]:void 0,a=Mr(o)?of(o):void 0;return Mr(a)}function _D(e,o,a,u,m,p){return wr(Tt(e,a,m),(f)=>dw(f,o,u,p),()=>et())}function LD(e,o,a,u,m){let p=of(u);return Yu(p)?lw(e,p.name,af(a,o),p.type):xt(a,(f,h)=>_D(e,o,f,h,u,m),()=>et())}function ND(e,o,a,u){return xt(u,(m,p)=>LD(e,o,a,m,p),()=>M(a.length,0)?Se(e):et())}function dw(e,o,a,u){return ND(e,o,a,u)}function DD(e,o,a){let u=xi(e,yr([],[]),a),m=OD(u);return dw(e,m,af(o,m),af(u,m))}function fw(e,o,a){let u=lp(a);return Yu(u)?dp(e,u.name,o,u.type):xt(o,(m,p)=>wr(Tt(e,m,a),(f)=>fw(f,p,a),()=>et()),()=>Se(e))}function hw(e,o,a){let u=xi(e,yr([],[]),o);return pt(a)?DD(e,u,a.items):St(a)?fw(e,u,a.items):Nt(e,Ur(u),a)}function gw(e,o,a){return yo(a)?Se(e):ss(a)?Se(e):Nt(e,o,a)}function yw(e,o,a){return xt(a,(u,m)=>wr(Tt(e,o,u),(p)=>Se(p),()=>yw(e,o,m)),()=>et())}function uf(e,o,a){return xt(o,(u,m)=>wr(yw(e,u,a),(p)=>uf(p,m,a),()=>et()),()=>Se(e))}function xw(e,o,a){let u=lp(a);return Yu(u)?dp(e,u.name,o,u.type):be(a)?uf(e,o,a.anyOf):uf(e,o,[a])}function Iw(e,o,a){return an(a)?Nt(e,o,a):Or(a)?Se(e):tn(a)?Se(e):et()}function bw(e,o,a){return yo(a)?Se(e):Nt(e,o,a)}function Tt(e,o,a){return Or(o)?WS(e,o,a):St(o)?zS(e,o,o.items,a):go(o)?VS(e,o,a):Vn(o)?JS(e,o,a):zr(o)?QS(e,o.parameters,o.instanceType,a):Fr(o)?XS(e,o.if,o.then,o.else,a):un(o)?YS(e,o.enum,a):en(o)?ZS(e,o.parameters,o.returnType,a):yn(o)?ew(e,o,a):Ke(o)?tw(e,o.allOf,a):gt(o)?rw(e,o,a):ho(o)?nw(e,o,a):Ts(o)?ow(e,o,a):Cr(o)?sw(e,o,a):He(o)?aw(e,o.properties,a):Kt(o)?uw(e,xn(o),or(o),a):cn(o)?cw(e,o,a):Rs(o)?mw(e,o,a):tr(o)?pw(e,o.pattern,a):pt(o)?hw(e,o.items,a):ss(o)?gw(e,o,a):be(o)?xw(e,o.anyOf,a):tn(o)?Iw(e,o,a):yo(o)?bw(e,o,a):et()}function qD(e,o){return $r([...e,l(o)])}function cf(e,o,a){return ct(e)?Et(qD(e,o),{},a):Ku(e,o,a)}function Ew(e,o,a,u,m){let p=So(e,o,a),f=Zu(e,o,u);return cf(p,f,m)}function Ku(e,o,a={}){return ke("Interface",[e,o],a)}function Ka(e){return Mr(e)&&pe(e,"action")&&M(e.action,"Interface")}function Sw(e,o,a={}){return cf(e,o,a)}function FD(e,o,a){return e.includes(a)?!0:ec([...e,a],o,o[a])}function ww(e,o,a){let u=hm(a);return la(e,o,u)}function la(e,o,a){return xt(a,(u,m)=>ec(e,o,u)?!0:la(e,o,m),()=>!1)}function ec(e,o,a){return Ft(a)?FD(e,o,a.$ref):St(a)?ec(e,o,a.items):zr(a)?la(e,o,[...a.parameters,a.instanceType]):en(a)?la(e,o,[...a.parameters,a.returnType]):Ka(a)?ww(e,o,a.parameters[1]):Ke(a)?la(e,o,a.allOf):He(a)?ww(e,o,a.properties):be(a)?la(e,o,a.anyOf):pt(a)?la(e,o,a.items):Kt(a)?ec(e,o,or(a)):!1}function Tw(e,o,a){return ec(e,o,a)}function jD(e,o){return o.reduce((a,u)=>Tw([u],e,e[u])?[...a,u]:a,[])}function Rw(e){let o=fm(e);return jD(e,o)}function UD(e,o,a){return a.includes(o)?a:(o in e)?tc(e,e[o],[...a,o]):jr()}function kw(e,o,a){let u=hm(o);return Ha(e,u,a)}function Ha(e,o,a){return o.reduce((u,m)=>tc(e,m,u),a)}function tc(e,o,a){return Ft(o)?UD(e,o.$ref,a):St(o)?tc(e,o.items,a):zr(o)?Ha(e,[...o.parameters,o.instanceType],a):en(o)?Ha(e,[...o.parameters,o.returnType],a):Ka(o)?kw(e,o.parameters[1],a):Ke(o)?Ha(e,o.allOf,a):He(o)?kw(e,o.properties,a):be(o)?Ha(e,o.anyOf,a):pt(o)?Ha(e,o.items,a):Kt(o)?tc(e,or(o),a):a}function Aw(e,o,a){return tc(e,a,[o])}function BD(e){return _a()}function GD(e){return Ee(e).reduce((o,a)=>({...o,[a]:da(e[a])}),{})}function rc(e){return e.reduce((o,a)=>[...o,da(a)],[])}function da(e){return Ft(e)?BD(e.$ref):St(e)?F(da(e.items),Ma(e)):zr(e)?Is(rc(e.parameters),da(e.instanceType)):en(e)?bs(rc(e.parameters),da(e.returnType)):Ke(e)?Mn(rc(e.allOf)):He(e)?l(GD(e.properties)):Kt(e)?ks(di(e),da(or(e))):be(e)?g(rc(e.anyOf)):pt(e)?Ur(rc(e.items)):e}function KD(e,o){return o in e?da(e[o]):Pr()}function Pw(e){return KD(e.$defs,e.$ref)}function HD(e,o,a){let u=So(e,yr([],[]),o),m=Zu({},yr([],[]),a);return $r([...u,l(m)])}function WD(e,o){return Ee(e).filter((u)=>o.includes(u)).reduce((u,m)=>{let p=e[m],f=Ka(p)?HD(e,p.parameters[0],p.parameters[1]):p;return{...u,[m]:f}},{})}function Cw(e,o,a){let u=Aw(e,o,a),m=WD(e,u);return Ss(m,o)}function $w(e,o){return o in e?Ft(e[o])?$w(e,e[o].$ref):e[o]:Vt()}function As(e,o){return $w(e,o)}function vw(e){return Yt(e)?Pw(e):gm(e)?Pr():e}function An(e,o,a){let u=vw(o),m=vw(a);return Tt(e,u,m)}var Fu=0,nc=1,ju=2,Uu=3;function qa(e,o){let a=[An({},e,o),An({},o,e)];return co(a[0])&&co(a[1])?Fu:co(a[0])&&rf(a[1])?ju:rf(a[0])&&co(a[1])?Uu:nc}function mf(e,o,a=[],u=o){return xt(o,(m,p)=>{let f=qa(e,m);return M(f,ju)||M(f,Fu)?u:M(f,nc)?mf(e,p,[...a,m],u):mf(e,p,a,u)},()=>[...a,e])}function zD(e,o,a){let u=vo(e);return Or(u)?[u]:tn(u)?[u]:ho(u)?fp(o,a):He(u)?fp(o,[...a,u]):fp(o,mf(u,a))}function fp(e,o=[]){return xt(e,(a,u)=>zD(a,u,o),()=>o)}function Dd(e){let o=fp(e);return ca(o)}function pf(e,o){return Et(vo(e),{},o)}function Mw(e,o,a,u){let m=he(e,o,a);return pf(m,u)}function oc(e,o=[]){return ai(e)&&M(e.action,"Conditional")?Ft(e.parameters[0])?oc(e.parameters[2],oc(e.parameters[3],[...o,e.parameters[0].$ref])):oc(e.parameters[2],oc(e.parameters[3],o)):ai(e)&&M(e.action,"Mapped")?ai(e.parameters[1])&&M(e.parameters[1].action,"KeyOf")&&Ft(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function VD(e,o){return e.reduce((a,u)=>[...a,o.includes(u.name)],[])}function Lw(e,o,a=[]){return xt(e,(u,m)=>xt(o,(p,f)=>Lw(m,f,[...a,[p,u]]),()=>a),()=>a)}function JD(e){return tr(e)?_n(e.pattern):un(e)?Jn(e.enum):e}function QD(e){let o=JD(e);return be(o)?[...o.anyOf]:[o]}function XD(e,o){return e.reduce((a,u)=>[...a,[...u,o]],[])}function Ow(e,o){return o.reduce((a,u)=>[...a,...XD(e,u)],[])}function _w(e){return e.reduce((o,a)=>M(a[0],!0)?Ow(o,QD(a[1])):Ow(o,[a[1]]),[[]])}function Nw(e,o,a){let u=oc(a),m=VD(e,u),p=Lw(o,m);return ai(a)&&M(a.action,"Conditional")?_w(p):ai(a)&&M(a.action,"Mapped")?_w(p):[o]}function YD(){return["(not-resolvable)",Vt()]}function ZD(){return["(not-generic)",Vt()]}function eq(e,o,a){return[e,ui(o,a)]}function tq(e,o,a){return o in e?Dw(e,o,e[o],a):YD()}function Dw(e,o,a,u){return Oa(a)?eq(o,a.parameters,a.expression):Ft(a)?tq(e,a.$ref,u):ZD()}function qw(e,o,a){return Dw(e,"(anonymous)",o,a)}function rq(e,o,a){if(an(o)||Wa(o)||co(An({},o,a)))return;let u={parameter:e,expect:a,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function Fw(e,o,a,u,m){let p=he(e,o,m);return rq(a,p,u),gn(e,{[a]:p})}function nq(e,o,a,u,m){let p=he(e,o,a.extends),f=he(e,o,a.equals);return xt(m,(h,I)=>lf(Fw(e,o,a.name,p,h),o,u,I),()=>lf(Fw(e,o,a.name,p,f),o,u,[]))}function lf(e,o,a,u){return xt(a,(m,p)=>nq(e,o,m,p,u),()=>e)}function jw(e,o,a,u){return lf(e,o,a,u)}var df=0,ff=0;function oq(){if(Pu(ff,Bo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function sq(){oq(),ff++,df++}function iq(){if(df--,M(df,0))ff=0}function aq(e){return ji(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function uq(e,o){return M(aq(e),o)}function cq(e,o,a,u,m,p){sq();try{let f=jw(e,o,u,p),h=he(f,yr([...o.callstack,a.$ref],o.visited),m);return he(f,yr([],[]),h)}finally{iq()}}function mq(e,o,a,u,m,p){return p.reduce((f,h)=>{let I=cq(e,o,a,u,m,h);return[...f,I]},[])}function pq(e,o,a,u,m,p){let f=Nw(u,p,m),h=mq(e,o,a,u,m,f);return M(h.length,1)?h[0]:Zn(h)}function hp(e,o,a,u){let m=So(e,o,u),p=qw(e,a,u),f=p[0],h=p[1];return Oa(h)?uq(o,f)?Hu(pn(f),m):pq(e,o,pn(f),h.parameters,h.expression,m):Hu(a,m)}function Hu(e,o){return $t({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function Uw(e,o){return hp({},yr([],[]),e,o)}function Wa(e){return Re(e,"Call")}function lq(e){return Ho(e,["~immutable"])}function Bw(e,o){return Et(lq(e),{},o)}function Gw(e,o,a,u){let m=he(e,o,a);return Bw(m,u)}function Kw(e,o){return e(o)}function Hw(e,o){return dt(o)?i(Kw(e,o)):i(o)}function Ww(e,o){let a=_n(o);return Fs(e,a)}function zw(e,o){let a=o.map((u)=>Fs(e,u));return g(a)}function Fs(e,o){return gt(o)?Hw(e,o.const):tr(o)?Ww(e,o.pattern):be(o)?zw(e,o.anyOf):o}function Dm(e,o={}){return ke("Capitalize",[e],o)}function Vw(e,o={}){return hf(e,o)}function qm(e,o={}){return ke("Lowercase",[e],o)}function Jw(e,o={}){return gf(e,o)}function Fm(e,o={}){return ke("Uncapitalize",[e],o)}function Qw(e,o={}){return yf(e,o)}function jm(e,o={}){return ke("Uppercase",[e],o)}function Xw(e,o={}){return xf(e,o)}var dq=(e)=>e[0].toUpperCase()+e.slice(1),fq=(e)=>e.toLowerCase(),hq=(e)=>e[0].toLowerCase()+e.slice(1),gq=(e)=>e.toUpperCase();function hf(e,o){return ct([e])?Et(Fs(dq,e),{},o):Dm(e,o)}function gf(e,o){return ct([e])?Et(Fs(fq,e),{},o):qm(e,o)}function yf(e,o){return ct([e])?Et(Fs(hq,e),{},o):Fm(e,o)}function xf(e,o){return ct([e])?Et(Fs(gq,e),{},o):jm(e,o)}function Yw(e,o,a,u){let m=he(e,o,a);return hf(m,u)}function Zw(e,o,a,u){let m=he(e,o,a);return gf(m,u)}function eT(e,o,a,u){let m=he(e,o,a);return yf(m,u)}function tT(e,o,a,u){let m=he(e,o,a);return xf(m,u)}function Um(e,o,a,u,m={}){return ke("Conditional",[e,o,a,u],m)}function rT(e,o,a,u,m={}){return If({},yr([],[]),e,o,a,u,m)}function yq(e,o,a,u,m,p){let f=An(e,a,u);return ef(f)?g([he(f.inferred,o,m),he(e,o,p)]):tf(f)?he(f.inferred,o,m):he(e,o,p)}function If(e,o,a,u,m,p,f){return ct([a,u])?Et(yq(e,o,a,u,m,p),{},f):Um(a,u,m,p,f)}function nT(e,o,a,u,m,p,f){let h=he(e,o,a),I=he(e,o,u);return If(e,o,h,I,m,p,f)}function Bm(e,o={}){return ke("ConstructorParameters",[e],o)}function oT(e,o={}){return bf(e,o)}function xq(e){let o=zr(e)?e.parameters:[],a=xi({},yr([],[]),o);return Ur(a)}function bf(e,o){return ct([e])?Et(xq(e),{},o):Bm(e,o)}function sT(e,o,a,u){let m=he(e,o,a);return bf(m,u)}function Gm(e,o,a={}){return ke("Exclude",[e,o],a)}function iT(e,o,a={}){return sc(e,o,a)}function sc(e,o,a){return ct([e,o])?Et($m(e,o),{},a):Gm(e,o,a)}function aT(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return sc(p,f,m)}function Km(e,o,a={}){return ke("Extract",[e,o],a)}function uT(e,o,a={}){return Ef(e,o,a)}function Iq(e,o){let a=An({},e,o);return co(a)?[e]:[]}function cT(e,o,a=[]){return xt(e,(u,m)=>cT(m,o,[...a,...Iq(u,o)]),()=>a)}function mT(e,o){let a=vo(e),u=be(a)?a.anyOf:[a],m=cT(u,o);return Zn(m)}function Ef(e,o,a){return ct([e,o])?Et(mT(e,o),{},a):Km(e,o,a)}function pT(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return Ef(p,f,m)}function bq(e){return e.reduce((o,a)=>Sm(a)?[...o,i(a)]:o,[])}function za(e){let o=bq(e);return g(o)}function Wu(e,o,a={}){return ke("Index",[e,o],a)}function lT(e,o,a={}){let u=qe(o)?za(o):o;return Sf(e,u,a)}function dT(e,o){let a=As(e,o);return wo(a)}function fT(e,o,a){let u=es(e,o,a);return wo(u)}function Eq(e,o){let a=Ee(e).filter((S)=>!pe(o,S)),u=Ee(o).filter((S)=>!pe(e,S)),m=Ee(e).filter((S)=>pe(o,S)),p=a.reduce((S,R)=>({...S,[R]:e[R]}),{}),f=u.reduce((S,R)=>({...S,[R]:o[R]}),{}),h=m.reduce((S,R)=>({...S,[R]:$r([e[R],o[R]])}),{}),I=gn(p,f);return gn(I,h)}function hT(e){return e.reduce((o,a)=>Eq(o,wo(a)),{})}function gT(e){return e}function yT(e){let o=sI(Ur(e));return wo(o)}function Sq(e,o){return Ee(e).filter((m)=>(m in o)).reduce((m,p)=>({...m,[p]:Zn([e[p],o[p]])}),{})}function xT(e,o){return xt(e,(a,u)=>xT(u,Sq(o,wo(a))),()=>o)}function IT(e){return xt(e,(o,a)=>xT(a,wo(o)),()=>jr())}function wo(e){return Yt(e)?dT(e.$defs,e.$ref):Fr(e)?fT(e.if,e.then,e.else):Ke(e)?hT(e.allOf):be(e)?IT(e.anyOf):pt(e)?yT(e.items):He(e)?gT(e.properties):{}}function Va(e){let o=wo(e);return l(o)}var wq=new RegExp("^(?:0|[1-9][0-9]*)$");function Ja(e){let o=`${e}`;return wq.test(o)?parseInt(o):e}function Tq(e){return i(Ja(e))}function bT(e){return e.map((o)=>ET(o))}function ET(e){return Ke(e)?Mn(bT(e.allOf)):be(e)?g(bT(e.anyOf)):gt(e)?Tq(e.const):e}function ST(e,o){let a=ET(o),u=An({},a,te());return co(u)?e:gt(o)&&M(o.const,"length")?te():Vt()}function wT(e,o){let a=As(e,o);return xo(a)}function TT(e,o,a){let u=es(e,o,a);return xo(u)}function RT(e){let o=Jn(e);return xo(o)}function kT(e){let o=$r(e);return xo(o)}function AT(e){return[`${e}`]}function PT(e){let o=_n(e);return xo(o)}function CT(e){return e.reduce((o,a)=>[...o,...xo(a)],[])}function xo(e){return Yt(e)?wT(e.$defs,e.$ref):Fr(e)?TT(e.if,e.then,e.else):un(e)?RT(e.enum):Ke(e)?kT(e.allOf):gt(e)?AT(e.const):tr(e)?PT(e.pattern):be(e)?CT(e.anyOf):[]}function Qa(e){return xo(e)}function ic(e,o){return o.map((a)=>ac(e,a))}function ac(e,o){return St(o)?F(ac(e,o.items)):zr(o)?Is(ic(e,o.parameters),ac(e,o.instanceType)):en(o)?bs(ic(e,o.parameters),ac(e,o.returnType)):pt(o)?Ur(ic(e,o.items)):be(o)?g(ic(e,o.anyOf)):Ke(o)?Mn(ic(e,o.allOf)):_m(o)?l(e):o}function $T(e,o){return ac(e,o)}function Rq(e,o){let a=o in e?e[o]:Vt();return $T(e,a)}function vT(e,o){return o.reduce((a,u)=>[...a,Rq(e,u)],[])}function kq(e,o){let a=Qa(o),u=vT(e,a);return Zn(u)}var Aq=new RegExp(li);function Pq(e){return e.filter((a)=>Aq.test(a))}function Cq(e){let o=fm(e),a=Pq(o),u=vT(e,a);return Zn(u)}function MT(e,o){return Cr(o)?Cq(e):kq(e,o)}function $q(e){return i(Ja(e))}function OT(e){return e.map((o)=>wf(o))}function wf(e){return Ke(e)?Mn(OT(e.allOf)):be(e)?g(OT(e.anyOf)):gt(e)?$q(e.const):e}function vq(e,o){return e.reduceRight((a,u,m)=>{let p=An({},i(m),o);return co(p)?[u,...a]:a},[])}function Mq(e,o){let a=wf(o),u=vq(e,a);return mi(u)}function Oq(e){return mi(e)}function _T(e,o){return gt(o)&&M(o.const,"length")?i(e.length):Cr(o)||yn(o)?Oq(e):Mq(e,o)}function LT(e,o){return St(e)?ST(e.items,o):He(e)?MT(e.properties,o):pt(e)?_T(e.items,o):Vt()}function _q(e){return Yt(e)||Fr(e)||Ke(e)||be(e)?Va(e):e}function Sf(e,o,a){return ct([e,o])?Et(LT(_q(e),o),{},a):Wu(e,o,a)}function NT(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return Sf(p,f,m)}function Hm(e,o={}){return ke("InstanceType",[e],o)}function DT(e,o={}){return Tf(e,o)}function Lq(e){return zr(e)?e.instanceType:Vt()}function Tf(e,o){return ct([e])?Et(Lq(e),{},o):Hm(e,o)}function qT(e,o,a,u={}){let m=he(e,o,a);return Tf(m,u)}function zu(e,o={}){return ke("KeyOf",[e],o)}function FT(e,o={}){return Rf(e,o)}function jT(){return g([te(),s(),Da()])}function UT(e){return te()}function Nq(e){return e.reduce((a,u)=>Sm(u)?[...a,i(Ja(u))]:jr(),[])}function BT(e){let o=Ee(e),a=Nq(o);return mi(a)}function GT(e){return di(e)}function KT(e){let o=e.map((a,u)=>i(u));return mi(o)}function HT(e){return Or(e)?jT():St(e)?UT(e.items):He(e)?BT(e.properties):Kt(e)?GT(e):pt(e)?KT(e.items):Vt()}function Dq(e){return Yt(e)||Fr(e)||Ke(e)||be(e)?Va(e):e}function Rf(e,o){return ct([e])?Et(HT(Dq(e)),{},o):zu(e,o)}function WT(e,o,a,u){let m=he(e,o,a);return Rf(m,u)}function Gu(e,o,a,u,m={}){return ke("Mapped",[e,o,a,u],m)}function zT(e,o,a,u,m={}){return kf({},yr([],[]),e,o,a,u,m)}function qq(e){let o=_n(e);return gp(o)}function Fq(e){return e.reduce((o,a)=>[...o,...gp(a)],[])}function jq(e){let o=Jn(e);return gp(o)}function Uq(e){return Ot(e)?[i(`${e}`)]:[i(e)]}function gp(e){return un(e)?jq(e.enum):gt(e)?Uq(e.const):tr(e)?qq(e.pattern):be(e)?Fq(e.anyOf):[e]}function VT(e){return gp(e)}function Bq(e){return tr(e)?_n(e.pattern):e}function Gq(e,o,a,u,m,p){let f=gn(e,{[a.name]:u}),h=he(f,o,m),I=Bq(h),E=he(f,o,p);return wm(I)||Tm(I)?{[I.const]:E}:{}}function Kq(e,o,a,u,m,p){return u.reduce((f,h)=>[...f,Gq(e,o,a,h,m,p)],[])}function Hq(e){return e.reduce((o,a)=>[...o,l(a)],[])}function JT(e,o,a,u,m,p){let f=VT(u),h=Kq(e,o,a,f,m,p),I=Hq(h);return $r(I)}function kf(e,o,a,u,m,p,f){return ct([u])?Et(JT(e,o,a,u,m,p),{},f):Gu(a,u,m,p,f)}function QT(e,o,a,u,m,p,f){let h=he(e,o,u);return kf(e,o,a,h,m,p,f)}function Wq(e,o,a){let u=gn(e,o);return Ee(o).filter((p)=>a.includes(p)).reduce((p,f)=>({...p,[f]:Cw(u,f,o[f])}),{})}function zq(e,o,a){let u=gn(e,o);return Ee(o).filter((p)=>!a.includes(p)).reduce((p,f)=>({...p,[f]:he(u,yr([],[]),o[f])}),{})}function Vq(e,o,a){let u=Rw(o),m=Wq(e,o,u),p=zq(e,o,u),f={...m,...p};return Et(f,{},a)}function yp(e,o,a,u){return Vq(e,a,u)}function Wm(e,o={}){return ke("NonNullable",[e],o)}function XT(e,o={}){return Af(e,o)}function Jq(e){let o=g([On(),ja()]);return sc(e,o,{})}function Af(e,o){return ct([e])?Et(Jq(e),{},o):Wm(e,o)}function YT(e,o,a,u){let m=he(e,o,a);return Af(m,u)}function zm(e,o,a={}){return ke("Omit",[e,o],a)}function ZT(e,o,a={}){let u=qe(o)?za(o):o;return Pf(e,u,a)}function xp(e){let o=Va(e);return He(o)?o.properties:jr()}function Qq(e,o){return Ee(e).reduce((u,m)=>o.includes(m)?u:{...u,[m]:e[m]},{})}function eR(e,o){let a=xp(e),u=Qa(o),m=Qq(a,u);return l(m)}function Pf(e,o,a){return ct([e,o])?Et(eR(e,o),{},a):zm(e,o,a)}function tR(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return Pf(p,f,m)}function Vm(e,o={}){return ke("Parameters",[e],o)}function rR(e,o={}){return Cf(e,o)}function Xq(e){let o=en(e)?e.parameters:[],a=xi({},yr([],[]),o);return Ur(a)}function Cf(e,o){return ct([e])?Et(Xq(e),{},o):Vm(e,o)}function nR(e,o,a,u){let m=he(e,o,a);return Cf(m,u)}function Jm(e,o={}){return ke("Partial",[e],o)}function oR(e,o={}){return $f(e,o)}function sR(e,o){let a=As(e,o),u=Ps(a);return Ss(gn(e,{[o]:u}),o)}function iR(e,o,a){let u=es(e,o,a);return Ps(u)}function aR(e){let o=$r(e);return Ps(o)}function uR(e){let o=e.map((a)=>Ps(a));return g(o)}function cR(e){let o=Ee(e).reduce((u,m)=>({...u,[m]:ra(e[m])}),{});return l(o)}function Ps(e){return Yt(e)?sR(e.$defs,e.$ref):Fr(e)?iR(e.if,e.then,e.else):Ke(e)?aR(e.allOf):be(e)?uR(e.anyOf):He(e)?cR(e.properties):l({})}function $f(e,o){return ct([e])?Et(Ps(e),{},o):Jm(e,o)}function mR(e,o,a,u){let m=he(e,o,a);return $f(m,u)}function Qm(e,o,a={}){return ke("Pick",[e,o],a)}function pR(e,o,a={}){let u=qe(o)?za(o):o;return vf(e,u,a)}function Yq(e,o){return Ee(e).reduce((u,m)=>o.includes(m)?gn(u,{[m]:e[m]}):u,{})}function lR(e,o){let a=xp(e),u=Qa(o),m=Yq(a,u);return l(m)}function vf(e,o,a){return ct([e,o])?Et(lR(e,o),{},a):Qm(e,o,a)}function dR(e,o,a,u,m){let p=he(e,o,a),f=he(e,o,u);return vf(p,f,m)}function Xm(e,o={}){return ke("ReadonlyObject",[e],o)}function Mf(e,o={}){return Of(e,o)}var fR=Mf;function hR(e){return Na(F(e))}function gR(e,o){let a=As(e,o),u=Cs(a);return Ss(gn(e,{[o]:u}),o)}function yR(e,o,a){let u=es(e,o,a);return Cs(u)}function xR(e){let o=$r(e);return Cs(o)}function IR(e){let o=Ee(e).reduce((u,m)=>({...u,[m]:ia(e[m])}),{});return l(o)}function bR(e){return Na(Ur(e))}function ER(e){let o=e.map((a)=>Cs(a));return g(o)}function Cs(e){return St(e)?hR(e.items):Yt(e)?gR(e.$defs,e.$ref):Fr(e)?yR(e.if,e.then,e.else):Ke(e)?xR(e.allOf):He(e)?IR(e.properties):pt(e)?bR(e.items):be(e)?ER(e.anyOf):e}function Of(e,o){return ct([e])?Et(Cs(e),{},o):Xm(e)}function SR(e,o,a,u){let m=he(e,o,a);return Of(m,u)}function wR(e,o,a,u){return o.visited.includes(u)?a:(u in e)?he(e,yr(o.callstack,[...o.visited,u]),e[u]):a}function TR(e,o){let a=As(e,o),u=$s(a);return Ss(gn(e,{[o]:u}),o)}function RR(e,o,a){let u=es(e,o,a);return $s(u)}function kR(e){let o=$r(e);return $s(o)}function AR(e){let o=e.map((a)=>$s(a));return g(o)}function PR(e){let o=Ee(e).reduce((u,m)=>({...u,[m]:Cm(e[m])}),{});return l(o)}function $s(e){return Yt(e)?TR(e.$defs,e.$ref):Fr(e)?RR(e.if,e.then,e.else):Ke(e)?kR(e.allOf):be(e)?AR(e.anyOf):He(e)?PR(e.properties):l({})}function Ym(e,o={}){return ke("Required",[e],o)}function CR(e,o={}){return _f(e,o)}function _f(e,o){return ct([e])?Et($s(e),{},o):Ym(e,o)}function $R(e,o,a,u){let m=he(e,o,a);return _f(m,u)}function Zm(e,o={}){return ke("ReturnType",[e],o)}function vR(e,o={}){return Lf(e,o)}function Zq(e){return en(e)?e.returnType:Vt()}function Lf(e,o){return ct([e])?Et(Zq(e),{},o):Zm(e,o)}function MR(e,o,a,u={}){let m=he(e,o,a);return Lf(m,u)}function ep(e,o){return ke("With",[e,o],{})}function Ip(e,o){return Nf(e,o)}function Nf(e,o){return ct([e])?Et(e,{},o):ep(e,o)}function OR(e,o,a,u){let m=he(e,o,a);return Nf(m,u)}function eF(e){return fi(e)?pt(e.items)?Df(e.items.items):an(e.items)?[e]:Ft(e.items)?[e]:[Vt()]:[e]}function Df(e){return e.reduce((a,u)=>[...a,...eF(u)],[])}function yr(e,o){return{callstack:e,visited:o}}function ct(e){return xt(e,(o,a)=>Ft(o)?!1:ct(a),()=>!0)}function Zu(e,o,a){return Ee(a).reduce((u,m)=>({...u,[m]:he(e,o,a[m])}),{})}function xi(e,o,a){let u=So(e,o,a);return Df(u)}function So(e,o,a){return a.map((u)=>he(e,o,u))}function tF(e,o){let a=ln(e)?Ou(o,{}):o,u=aa(e)?Mu(a,{}):a;return sa(e)?uc(u,{}):u}function rF(e,o,a,u,m){return M(a,"AddImmutable")?_R(e,o,u[0],m):M(a,"RemoveImmutable")?Gw(e,o,u[0],m):M(a,"AddReadonly")?ax(e,o,u[0],m):M(a,"RemoveReadonly")?eI(e,o,u[0],m):M(a,"AddOptional")?ux(e,o,u[0],m):M(a,"RemoveOptional")?nI(e,o,u[0],m):M(a,"Capitalize")?Yw(e,o,u[0],m):M(a,"Conditional")?nT(e,o,u[0],u[1],u[2],u[3],m):M(a,"ConstructorParameters")?sT(e,o,u[0],m):M(a,"Evaluate")?Mw(e,o,u[0],m):M(a,"Exclude")?aT(e,o,u[0],u[1],m):M(a,"Extract")?pT(e,o,u[0],u[1],m):M(a,"Index")?NT(e,o,u[0],u[1],m):M(a,"InstanceType")?qT(e,o,u[0],m):M(a,"Interface")?Ew(e,o,u[0],u[1],m):M(a,"KeyOf")?WT(e,o,u[0],m):M(a,"Lowercase")?Zw(e,o,u[0],m):M(a,"Mapped")?QT(e,o,u[0],u[1],u[2],u[3],m):M(a,"Module")?yp(e,o,u[0],m):M(a,"NonNullable")?YT(e,o,u[0],m):M(a,"Pick")?dR(e,o,u[0],u[1],m):M(a,"Parameters")?nR(e,o,u[0],m):M(a,"Partial")?mR(e,o,u[0],m):M(a,"Omit")?tR(e,o,u[0],u[1],m):M(a,"ReadonlyObject")?SR(e,o,u[0],m):M(a,"Record")?bI(e,o,u[0],u[1],m):M(a,"Required")?$R(e,o,u[0],m):M(a,"ReturnType")?MR(e,o,u[0],m):M(a,"TemplateLiteral")?US(e,o,u[0],m):M(a,"Uncapitalize")?eT(e,o,u[0],m):M(a,"Uppercase")?tT(e,o,u[0],m):M(a,"With")?OR(e,o,u[0],u[1]):ke(a,u,m)}function nF(e,o,a){let u=Ft(a)?wR(e,o,a,a.$ref):St(a)?F(he(e,o,a.items),Ma(a)):Wa(a)?hp(e,o,a.target,a.arguments):zr(a)?Is(So(e,o,a.parameters),he(e,o,a.instanceType),cx(a)):en(a)?bs(So(e,o,a.parameters),he(e,o,a.returnType),mx(a)):Fr(a)?na(he(e,o,a.if),he(e,o,a.then),he(e,o,a.else),fx(a)):Ke(a)?Mn(So(e,o,a.allOf),Ix(a)):He(a)?l(Zu(e,o,a.properties),dx(a)):Kt(a)?EI(xn(a),he(e,o,or(a))):fi(a)?ma(he(e,o,a.items)):pt(a)?Ur(xi(e,o,a.items),Zx(a)):be(a)?g(So(e,o,a.anyOf),Gx(a)):a;return tF(a,u)}function he(e,o,a){return ai(a)?rF(e,o,a.action,a.parameters,a.options):nF(e,o,a)}function Mo(e,o){return he(e,yr([],[]),o)}function oF(e){return Et(e,{"~immutable":!0},{})}function uc(e,o){return Et(oF(e),{},o)}function _R(e,o,a,u){let m=he(e,o,a);return uc(m,u)}function DE(e,o={}){return ke("AddImmutable",[e],o)}function Na(e,o={}){return uc(e,o)}function qE(e,o={}){return ke("Evaluate",[e],o)}function Pn(e,o={}){return pf(e,o)}function FE(e,o={}){return ke("Module",[e],o)}function LR(e,o={}){return yp({},yr([],[]),e,o)}function sF(e,o){let a=qa(e,o);return M(a,Uu)?1:M(a,nc)?1:0}function NR(e,o,a=[]){return xt(o,(u,m)=>M(sF(e,u),1)?NR(e,m,[...a,u]):[...a,e,...o],()=>[...a,e])}function DR(e,o=[]){return xt(e,(a,u)=>DR(u,NR(a,o)),()=>o)}function qR(e){return DR(e)}function FR(...e){let[o,a,u]=kn(e,{2:(f,h)=>dt(f)?[{},f,h]:[f,h,{}],3:(f,h,I)=>[f,h,I],1:(f)=>[{},f,{}]}),m=NS(a),p=qe(m)&&M(m.length,2)?he(o,yr([],[]),m[0]):Vt();return Et(p,{},u)}function b(e,o){return{name:e,login:async(a)=>{a.signal.throwIfAborted();let u=await a.prompt({type:"secret",message:`Enter ${e}`});return a.signal.throwIfAborted(),{type:"api_key",key:u}},resolve:async({ctx:a,credential:u,signal:m})=>{if(m.throwIfAborted(),u?.key)return{auth:{apiKey:u.key},env:u.env,source:"stored credential"};for(let p of o){let f=await a.env(p);if(m.throwIfAborted(),f)return{auth:{apiKey:f},source:p}}return}}}function de(e){let o,a=()=>(o??=e.load(),o);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(u,m)=>(await a()).login(u,m),refresh:async(u,m)=>(await a()).refresh(u,m),toAuth:async(u)=>(await a()).toAuth(u)}}var GR="faux",KR="faux",HR="faux-1",iF="Faux Model",aF="http://localhost:0",uF=3,jR=5,Sp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function qn(e){return{type:"text",text:e}}function jo(e){return{type:"thinking",thinking:e}}function cF(e,o,a={}){return{type:"toolCall",id:a.id??jf("tool"),name:e,arguments:o}}function mF(e){if(typeof e==="string")return[qn(e)];return Array.isArray(e)?e:[e]}function Vo(e,o={}){return{role:"assistant",content:mF(e),api:GR,provider:KR,model:HR,usage:Sp,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 WR(e){return Math.ceil(e.length/4)}function jf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function zR(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(`
25
+ `)}function VR(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(`
26
+ `)}function pF(e){return[e.toolName,...e.content.map((o)=>zR([o]))].join(`
27
+ `)}function lF(e){if(e.role==="system")return[H(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
28
+ `);if(e.role==="user")return zR(e.content);if(e.role==="assistant")return VR(e.content);return pF(e)}function JR(e,o=e.length){let a=o>0?(o-1)*2:0;for(let u=0;u<o;u++)a+=e[u].length;return a}function dF(e,o){let a=0;while(a<e.length&&a<o.length&&e[a]===o[a])a++;let u=(m)=>a===m.length?"":(a>0?`
29
29
 
30
30
  `:"")+m.slice(a).join(`
31
31
 
32
- `);return VR(e,a)+pF(u(e),u(o))}function pF(e,o){let a=Math.min(e.length,o.length),u=0;while(u<a&&e[u]===o[u])u++;return u}function jR(e,o,a,u){let m=o.messages.map((k)=>`${k.role}:${cF(k)}`),p=VR(m),f=Math.ceil(p/4),h=HR(zR(e.content)),I=f,E=0,S=0,R=a?.sessionId;if(R&&a?.cacheRetention!=="none"){let k=u.get(R);if(k){let P=mF(k,m);E=Math.ceil(P/4),S=Math.ceil((p-P)/4),I=Math.max(0,f-E)}else S=f;u.set(R,m)}return{...e,usage:{input:I,output:h,cacheRead:E,cacheWrite:S,totalTokens:I+h+E+S,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function qf(e,o,a){let u=[],m=0;while(m<e.length){let p=o+Math.floor(Math.random()*(a-o+1)),f=Math.max(1,p*4);u.push(e.slice(m,m+f)),m+=f}return u.length>0?u:[""]}function lF(e,o,a,u){let m=structuredClone(e);return{...m,api:o,provider:a,model:u,timestamp:m.timestamp??Date.now(),usage:m.usage??Sp}}function UR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:Sp,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function bp(e,o,a,u){return{role:"assistant",content:[],api:o,provider:a,model:u,usage:Sp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function cc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Ff(e,o){if(!o||o<=0)return new Promise((u)=>queueMicrotask(u));let a=HR(e)/o*1000;return new Promise((u)=>setTimeout(u,a))}async function Ep(e,o,a,u,m,p){let f={...o,content:[],stopReason:"pending"};if(p?.aborted){let h=cc(f);e.push({type:"error",reason:"aborted",error:h}),e.end(h);return}e.push({type:"start",partial:{...f}});for(let h=0;h<o.content.length;h++){if(p?.aborted){let E=cc(f);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}let I=o.content[h];if(I.type==="thinking"){f.content=[...f.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:h,partial:{...f}});for(let E of qf(I.thinking,a,u)){if(await Ff(E,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}f.content[h].thinking+=E,e.push({type:"thinking_delta",contentIndex:h,delta:E,partial:{...f}})}e.push({type:"thinking_end",contentIndex:h,content:I.thinking,partial:{...f}});continue}if(I.type==="text"){f.content=[...f.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:h,partial:{...f}});for(let E of qf(I.text,a,u)){if(await Ff(E,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}f.content[h].text+=E,e.push({type:"text_delta",contentIndex:h,delta:E,partial:{...f}})}e.push({type:"text_end",contentIndex:h,content:I.text,partial:{...f}});continue}f.content=[...f.content,{type:"toolCall",id:I.id,name:I.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:h,partial:{...f}});for(let E of qf(JSON.stringify(I.arguments),a,u)){if(await Ff(E,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}e.push({type:"toolcall_delta",contentIndex:h,delta:E,partial:{...f}})}f.content[h].arguments=I.arguments,e.push({type:"toolcall_end",contentIndex:h,toolCall:I,partial:{...f}})}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 JR(e){let o=e.api??jf(BR),a=e.provider??GR,u=Math.max(1,Math.min(e.tokenSize?.min??sF,e.tokenSize?.max??FR)),m=Math.max(u,e.tokenSize?.max??FR),p=[],f=e.tokensPerSecond,h={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},I=new Map,E=new Map,R=((e.models?.length)?e.models:[{id:KR,name:nF,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:a,baseUrl:oF,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),k=async(V,J,Z,ne)=>{let z=typeof V==="function"?await V(J,Z,h,ne):V;return jR(lF(z,o,a,ne.id),J,Z,I)},P=(V,J,Z)=>{let ne=ao(),z=p.shift();return h.callCount++,queueMicrotask(async()=>{try{if(await Z?.onResponse?.({status:200,headers:{}},V),!z){let fe=bp(Error("No more faux responses queued"),o,a,V.id);fe=jR(fe,J,Z,I),ne.push({type:"error",reason:"error",error:fe}),ne.end(fe);return}if(Z?.deferred){let fe={provider:V.provider,modelId:V.id,api:V.api,id:jf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};E.set(fe.id,{handle:fe,step:z,context:J,options:Z,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await Ep(ne,UR(V,fe),u,m,f,Z.signal);return}let oe=await k(z,J,Z,V);await Ep(ne,oe,u,m,f,Z?.signal)}catch(oe){let fe=bp(oe,o,a,V.id);ne.push({type:"error",reason:"error",error:fe}),ne.end(fe)}}),ne},v=(V,J,Z)=>P(V,J,Z),_=(V,J,Z)=>{let ne=ao();return h.deferredFetchCount++,queueMicrotask(async()=>{try{await Z?.onResponse?.({status:200,headers:{}},V);let z=E.get(J.id);if(!z||z.handle.provider!==J.provider||z.handle.modelId!==J.modelId||z.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(z.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(z.pendingFetches>0){z.pendingFetches--,await Ep(ne,UR(V,z.handle),u,m,f,Z?.signal);return}if(!z.final){let{deferred:oe,signal:fe,onResponse:ke,...Ee}=z.options??{};try{z.final=await k(z.step,z.context,Ee,z.model)}catch(ee){z.final=bp(ee,o,a,z.model.id)}}await Ep(ne,z.final,u,m,f,Z?.signal)}catch(z){let oe=bp(z,o,a,V.id);ne.push({type:"error",reason:"error",error:oe}),ne.end(oe)}}),ne},Q=async(V,J,Z)=>{h.cancelledDeferred.push(structuredClone(J));let ne=E.get(J.id);if(ne)ne.cancelled=!0;await Z?.onResponse?.({status:200,headers:{}},V)};function L(V){if(!V)return R[0];return R.find((J)=>J.id===V)}return{api:o,provider:a,models:R,stream:P,streamSimple:v,fetchDeferred:_,cancelDeferred:Q,getModel:L,state:h,setResponses(V){p=[...V]},appendResponses(V){p.push(...V)},getPendingResponseCount(){return p.length}}}function Ko(e={}){let o=JR(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 dF(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function fF(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function hF(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 gF(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 mc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Xa(e){mc(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 Bf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var yF=Bf(G(""));function Gf(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,m)=>Gf(u,o[m]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let a=o;return Object.entries(e).every(([u,m])=>Object.hasOwn(a,u)&&Gf(m,a[u]))}class QR{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:gF(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=Xa(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:dF(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Xa(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=Xa(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:fF(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Xa(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=Xa(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let a=Bf(o.arguments),u=a===yF;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":a}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:hF(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let a=G(o.catchupJson);if(Bf(a)!==o.snapshotArguments){let m=G(o.snapshotArguments);if(!Gf(m,a))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=Xa(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(mc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){mc(e);let a=this.blocks.get(e);if(a===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(a.kind!==o)throw Error(`Assistant message block ${e} is ${a.kind}, not ${o}`);return a}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,a){let u=this.block(e,a);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let m=u.deltaChars;u.deltaChars+=o.length;let p=Math.max(0,u.coveredChars-m);if(p>=o.length)return;let f=p===0?o:o.slice(p);return a==="text"?{type:"text_delta",contentIndex:e,delta:f}:{type:"thinking_delta",contentIndex:e,delta:f}}}function Uf(e,o,a,u,m){if(mc(a),a!==e.content.length){let p=a<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${a}: ${p}`)}e.content.push(structuredClone(u)),o.set(a,m)}function fa(e,o,a,u,m){mc(a);let p=o.get(a),f=e.content[a];if(!p||!f)throw Error(`${m} frame has no started block at index ${a}`);if(p.kind!==u||f.type!==u)throw Error(`${m} frame expected ${u} block at index ${a}, found ${f.type}`);if(p.ended)throw Error(`${m} frame follows the end of block at index ${a}`);return{block:f,state:p}}function xF(e){let o,a,u=new Map;for(let m of e){if(m.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(a!==void 0)throw Error(`${a} frame appears before the start frame`);o=structuredClone(m.partial);continue}if(!o){a??=m.type;continue}switch(m.type){case"text_start":if(m.content.type!=="text")throw Error(`text_start frame contains ${m.content.type} content`);Uf(o,u,m.contentIndex,m.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:p}=fa(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");p.text+=m.delta;break}case"text_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");if(p.text=m.content,delete p.textSignature,m.textSignature!==void 0)p.textSignature=m.textSignature;f.ended=!0;break}case"thinking_start":if(m.content.type!=="thinking")throw Error(`thinking_start frame contains ${m.content.type} content`);Uf(o,u,m.contentIndex,m.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:p}=fa(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");p.thinking+=m.delta;break}case"thinking_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");if(p.thinking=m.content,delete p.thinkingSignature,delete p.redacted,m.thinkingSignature!==void 0)p.thinkingSignature=m.thinkingSignature;if(m.redacted!==void 0)p.redacted=m.redacted;f.ended=!0;break}case"toolcall_start":if(m.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${m.toolCall.type} content`);Uf(o,u,m.contentIndex,m.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");f.json=m.json,p.arguments=G(m.json);break}case"toolcall_delta":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call frame state");f.json+=m.delta;break}case"toolcall_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(p.id=m.id,p.name=m.name,p.arguments=structuredClone(m.arguments),delete p.thoughtSignature,delete p.namespace,m.thoughtSignature!==void 0)p.thoughtSignature=m.thoughtSignature;if(m.namespace!==void 0)p.namespace=m.namespace;f.ended=!0;break}}}if(!o)return;for(let[m,p]of u){if(p.kind!=="toolCall"||p.ended||p.json.length===0)continue;let f=o.content[m];if(f?.type!=="toolCall")throw Error("Unreachable tool-call frame state");f.arguments=G(p.json)}return o}var XR=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],IF=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,bF=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ha(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!bF.some((u)=>u.test(e.errorMessage))){if(XR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&IF.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 EF(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function SF(){return[...XR]}function YR(e){return new RegExp(e.join("|"),"i")}var wF=YR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),TF=YR(["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"]),ZR=60000;function ek(e,o){let a=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??ZR)}class wp extends Error{constructor(){super("Aborted")}}function RF(e,o){return new Promise((a,u)=>{if(o?.aborted){u(new wp);return}let m=setTimeout(a,e);o?.addEventListener("abort",()=>{clearTimeout(m),u(new wp)},{once:!0})})}async function kF(e,o,a,u){let m=o?.enabled?o.maxRetries:0,p=0,f;for(;;){let h=await e();if(h.stopReason==="aborted"){if(f)await u?.onRetryFinished?.(!1,f.attempt);return h}if(h.stopReason!=="error"){if(f)await u?.onRetryFinished?.(!0,f.attempt);return h}if(p>=m||!tk(h)){if(f)await u?.onRetryFinished?.(!1,f.attempt,h.errorMessage);return h}p++,f={attempt:p,errorMessage:h.errorMessage||"Unknown error"};let I=ek(o,p);await u?.onRetryScheduled?.(p,m,I,f.errorMessage);try{await RF(I,a)}catch(E){if(await u?.onRetryFinished?.(!1,p,f.errorMessage),E instanceof wp){let{errorMessage:S,...R}=h;return{...R,stopReason:"aborted"}}throw E}await u?.onRetryAttemptStart?.()}}function tk(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(wF.test(o))return!1;return TF.test(o)}function AF(e,o){return sr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function pc(e){return pe(e,"~refine")&&Fe(e["~refine"])&&mn(e["~refine"],0,(o)=>at(o)&&pe(o,"check")&&pe(o,"error")&&gs(o.check)&&gs(o.error))}function In(e){return at(e)&&!Fe(e)}function js(e){return fn(e)}function Ve(e){return In(e)||js(e)}function Ya(e){return pe(e,"additionalItems")&&Ve(e.additionalItems)}function Oo(e){return pe(e,"additionalProperties")&&Ve(e.additionalProperties)}function lc(e){return pe(e,"allOf")&&Fe(e.allOf)&&e.allOf.every((o)=>Ve(o))}function dc(e){return pe(e,"$anchor")&&lt(e.$anchor)}function fc(e){return pe(e,"anyOf")&&Fe(e.anyOf)&&e.anyOf.every((o)=>Ve(o))}function Tp(e){return pe(e,"const")}function vs(e){return pe(e,"contains")&&Ve(e.contains)}function To(e){return pe(e,"default")}function hc(e){return pe(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ve(o)||Fe(o)&&o.every((a)=>lt(a)))}function gc(e){return pe(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Fe(o)&&o.every((a)=>lt(a)))}function Za(e){return pe(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ve(o))}function Us(e){return pe(e,"$dynamicAnchor")&&lt(e.$dynamicAnchor)}function yc(e){return pe(e,"$dynamicRef")&&lt(e.$dynamicRef)}function xc(e){return pe(e,"else")&&Ve(e.else)}function Rp(e){return pe(e,"enum")&&Fe(e.enum)}function Ic(e){return pe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||qr(e.exclusiveMaximum))}function is(e){return pe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||qr(e.exclusiveMinimum))}function ga(e){return pe(e,"format")&&lt(e.format)}function Ro(e){return pe(e,"$id")&&lt(e.$id)}function bc(e){return pe(e,"if")&&Ve(e.if)}function Bs(e){return pe(e,"items")&&(Ve(e.items)||Fe(e.items)&&e.items.every((o)=>Ve(o)))}function Ec(e){return Bs(e)&&Fe(e.items)}function Sc(e){return pe(e,"maximum")&&(Ot(e.maximum)||qr(e.maximum))}function wc(e){return pe(e,"maxContains")&&Ot(e.maxContains)}function eu(e){return pe(e,"maxItems")&&Ot(e.maxItems)}function Tc(e){return pe(e,"maxLength")&&Ot(e.maxLength)}function Rc(e){return pe(e,"maxProperties")&&Ot(e.maxProperties)}function as(e){return pe(e,"minimum")&&(Ot(e.minimum)||qr(e.minimum))}function Gs(e){return pe(e,"minContains")&&Ot(e.minContains)}function Ii(e){return pe(e,"minItems")&&Ot(e.minItems)}function ya(e){return pe(e,"minLength")&&Ot(e.minLength)}function xa(e){return pe(e,"minProperties")&&Ot(e.minProperties)}function kc(e){return pe(e,"multipleOf")&&(Ot(e.multipleOf)||qr(e.multipleOf))}function Ac(e){return pe(e,"not")&&Ve(e.not)}function Pc(e){return pe(e,"oneOf")&&Fe(e.oneOf)&&e.oneOf.every((o)=>Ve(o))}function Ia(e){return pe(e,"pattern")&&(lt(e.pattern)||e.pattern instanceof RegExp)}function Ks(e){return pe(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ve(o))}function us(e){return pe(e,"prefixItems")&&Fe(e.prefixItems)&&e.prefixItems.every((o)=>Ve(o))}function Hs(e){return pe(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((o)=>Ve(o))}function tu(e){return pe(e,"propertyNames")&&(at(e.propertyNames)||Ve(e.propertyNames))}function PF(e){return pe(e,"$recursiveAnchor")&&fn(e.$recursiveAnchor)}function Cc(e){return PF(e)&&M(e.$recursiveAnchor,!0)}function $c(e){return pe(e,"$recursiveRef")&&lt(e.$recursiveRef)}function vc(e){return pe(e,"$ref")&&lt(e.$ref)}function cs(e){return pe(e,"required")&&Fe(e.required)&&e.required.every((o)=>lt(o))}function Mc(e){return pe(e,"then")&&Ve(e.then)}function Oc(e){return pe(e,"type")&&(lt(e.type)||Fe(e.type)&&e.type.every((o)=>lt(o)))}function bi(e){return pe(e,"uniqueItems")&&fn(e.uniqueItems)}function Ei(e){return pe(e,"unevaluatedItems")&&Ve(e.unevaluatedItems)}function Si(e){return pe(e,"unevaluatedProperties")&&Ve(e.unevaluatedProperties)}function CF(e){return Ei(e)||Si(e)||Ca(Se(e),(o)=>kp(e[o]))}function $F(e){return Ca(e,(o)=>kp(o))}function kp(e){return Fe(e)?$F(e):at(e)?CF(e):!1}function rk(e,o){return kp(o)||Ca(Se(e),(a)=>kp(e[a]))}class Kf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Er(It("context","Push"),[])}Pop(){return Er(It("context","Pop"),[])}AddIndex(e){return Er(It("context","AddIndex"),[e])}AddKey(e){return Er(It("context","AddKey"),[e])}Merge(e){return Er(It("context","Merge"),[e])}}class Nn{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((a)=>this.GetIndices().add(a)),o.GetKeys().forEach((a)=>this.GetKeys().add(a));return!0}}class Dn extends Nn{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Bo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var Ap={identifier:"External",variables:[]};function _o(e){let o=`External[${Ap.variables.length}]`;return Ap.variables.push(e),o}function nk(){Ap.variables=[]}function ok(){return{...Ap}}function sk(e,o,a,u){let m=_o(a["~refine"].map((p)=>p));return xs(m,Pe(0),["refinement","_"],Er(It("refinement","check"),[u]))}function ik(e,o,a,u){return mn(a["~refine"],0,(m,p)=>m.check(u))}function ak(e,o,a,u,m,p){return $n(m["~refine"],0,(f,h)=>f.check(p)||o.AddError({keyword:"~refine",schemaPath:a,instancePath:u,params:{index:h,message:f.error(p)}}))}var vF=0;function Jt(){return`var_${vF++}`}function Hf(e){return Bs(e)&&Fe(e.items)}function MF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Qn(e,o,a.additionalItems,m),h=kd(p,Pe(a.items.length)),I=o.AddIndex(p);return xs(u,Pe(0),[m,p],br(h,Rn(f,I)))}function OF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Qn(e,o,a.additionalItems,m),h=kd(p,Pe(a.items.length));return xs(u,Pe(0),[m,p],br(h,f))}function uk(e,o,a,u){if(!Hf(a))return Pe(!0);return o.UseUnevaluated()?MF(e,o,a,u):OF(e,o,a,u)}function ck(e,o,a,u){if(!Hf(a))return!0;return mn(u,0,(p,f)=>Pu(f,a.items.length)||ko(e,o,a.additionalItems,p)&&o.AddIndex(f))}function mk(e,o,a,u,m,p){if(!Hf(m))return!0;return mn(p,0,(h,I)=>{let E=`${a}/additionalItems`,S=`${u}/${I}`;return Pu(I,m.items.length)||Ao(e,o,E,S,m.additionalItems,h)&&o.AddIndex(I)})}function ms(e){return new RegExp(e,"u")}function _F(e,o){return!e.UseUnevaluated()&&(M(o,!0)||at(o)&&M(Se(o).length,0))}function LF(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Wf(e){let o=[];if(Ks(e))o.push(...Se(e.patternProperties));if(Hs(e))o.push(...Se(e.properties).map(LF));return M(o.length,0)?"(?!)":`(${o.join("|")})`}function NF(e,o,a){return cs(o)&&Hs(o)&&!Ks(o)&&M(o.additionalProperties,!1)&&M(Se(o.properties).length,o.required.length)}function DF(e,o,a){return fo(It(Er(It("Object","getOwnPropertyNames"),[a]),"length"),Pe(o.required.length))}function qF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=_o(ms(Wf(a))),h=Qn(e,o,a.additionalProperties,`${u}[${m}]`),I=Er(It(f,"test"),[m]),E=o.AddKey(m),S=o.UseUnevaluated()?br(I,Rn(h,E)):br(I,h);return xs(Zi(u),Pe(0),[m,p],S)}function pk(e,o,a,u){if(_F(o,a.additionalProperties))return Pe(!0);return NF(o,a,u)?DF(o,a,u):qF(e,o,a,u)}function lk(e,o,a,u){let m=ms(Wf(a));return mn(Se(u),0,(f,h)=>m.test(f)||ko(e,o,a.additionalProperties,u[f])&&o.AddKey(f))}function dk(e,o,a,u,m,p){let f=ms(Wf(m)),h=[];return $n(Se(p),0,(E,S)=>{let R=`${a}/additionalProperties`,k=`${u}/${E}`,P=f.test(E)||Ao(e,o,R,k,m.additionalProperties,p[E])&&o.AddKey(E);if(!P)h.push(E);return P})||o.AddError({keyword:"additionalProperties",schemaPath:a,instancePath:u,params:{additionalProperties:h}})}function wi(e,o,a,u,m){let p=Ds("results","[]"),f=a.map((S,R)=>Ds(`context_${R}`,Ad("CheckContext",[]))),h=a.map((S,R)=>Ds(`condition_${R}`,Er(si(["context"],Lt(e,o,S,u)),[`context_${R}`]))),I=a.map((S,R)=>rx(`condition_${R}`,Er(It("results","push"),[`context_${R}`]))),E=dm(Rn(m,o.Merge("results")));return Er(si([],lm([p,...f,...h,...I,E])),[])}function FF(e,o,a,u){return wi(e,o,a.allOf,u,fo(It("results","length"),Pe(a.allOf.length)))}function jF(e,o,a,u){return vn(a.allOf.map((m)=>Lt(e,o,m,u)))}function fk(e,o,a,u){return o.UseUnevaluated()?FF(e,o,a,u):jF(e,o,a,u)}function hk(e,o,a,u){let m=a.allOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return M(m.length,a.allOf.length)&&o.Merge(m)}function gk(e,o,a,u,m,p){let f=[],h=m.allOf.reduce((E,S,R)=>{let k=`${a}/allOf/${R}`,P=new Dn,v=rr(e,P,k,u,S,p);if(!v)f.push(P);return v?[...E,P]:E},[]),I=M(h.length,m.allOf.length)&&o.Merge(h);if(!I)f.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I}function UF(e,o,a,u){return wi(e,o,a.anyOf,u,Zy(It("results","length"),Pe(0)))}function BF(e,o,a,u){return Pd(a.anyOf.map((m)=>Lt(e,o,m,u)))}function yk(e,o,a,u){return o.UseUnevaluated()?UF(e,o,a,u):BF(e,o,a,u)}function xk(e,o,a,u){let m=a.anyOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return ji(m.length,0)&&o.Merge(m)}function Ik(e,o,a,u,m,p){let f=[],h=m.anyOf.reduce((E,S,R)=>{let k=new Dn,P=`${a}/anyOf/${R}`,v=rr(e,k,P,u,S,p);if(!v)f.push(k);return v?[...E,k]:E},[]),I=ji(h.length,0)&&o.Merge(h);if(!I)f.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I||o.AddError({keyword:"anyOf",schemaPath:a,instancePath:u,params:{}})}function bk(e,o,a,u){return a?Pe(!0):Pe(!1)}function zf(e,o,a,u){return a}function Ek(e,o,a,u,m,p){return zf(e,o,m,p)||o.AddError({keyword:"boolean",schemaPath:a,instancePath:u,params:{}})}function Sk(e,o,a,u){return Ji(a.const)?fo(u,Pe(a.const)):tx(u,_o(a.const))}function Vf(e,o,a,u){return Ji(a.const)?M(u,a.const):$a(u,a.const)}function wk(e,o,a,u,m,p){return Vf(e,o,m,p)||o.AddError({keyword:"const",schemaPath:a,instancePath:u,params:{allowedValue:m.const}})}function Tk(e){return!(Gs(e)&&M(e.minContains,0))}function GF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Un(fo(It(u,"length"),Pe(0))),h=wO(u,[m,p],Rn(Lt(e,o,a.contains,m),o.AddIndex(p)));return Rn(f,h)}function KF(e,o,a,u){let[m]=[Jt()],p=Un(fo(It(u,"length"),Pe(0))),f=SO(u,[m,"_"],Lt(e,o,a.contains,m));return Rn(p,f)}function Rk(e,o,a,u){if(!Tk(a))return Pe(!0);return o.UseUnevaluated()?GF(e,o,a,u):KF(e,o,a,u)}function Jf(e,o,a,u){if(!Tk(a))return!0;return!M(u.length,0)&&Wy(u,(m,p)=>At(e,o,a.contains,m)&&o.AddIndex(p))}function kk(e,o,a,u,m,p){return Jf(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:1}})}function Ak(e,o,a,u){let m=fo(It(Zi(u),"length"),Pe(0)),p=vn(hn(a.dependencies).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=Lt(e,o,h,u),S=(R)=>vn(R.map((k)=>ea(u,Pe(k))));return br(I,Fe(h)?S(h):E)}));return br(m,p)}function Pk(e,o,a,u){let m=M(Se(u).length,0),p=mn(hn(a.dependencies),0,([f,h])=>!pe(u,f)||(Fe(h)?h.every((I)=>pe(u,I)):At(e,o,h,u)));return m||p}function Ck(e,o,a,u,m,p){let f=M(Se(p).length,0),h=$n(hn(m.dependencies),0,([I,E])=>{let S=`${a}/dependencies/${I}`;return!pe(p,I)||(Fe(E)?E.every((R)=>pe(p,R)||o.AddError({keyword:"dependencies",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})):rr(e,o,S,u,E,p))});return f||h}function $k(e,o,a,u){let m=fo(It(Zi(u),"length"),Pe(0)),p=vn(hn(a.dependentRequired).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=vn(h.map((S)=>ea(u,Pe(S))));return br(I,E)}));return br(m,p)}function vk(e,o,a,u){let m=M(Se(u).length,0),p=mn(hn(a.dependentRequired),0,([f,h])=>!pe(u,f)||h.every((I)=>pe(u,I)));return m||p}function Mk(e,o,a,u,m,p){let f=M(Se(p).length,0),h=$n(hn(m.dependentRequired),0,([I,E])=>!pe(p,I)||$n(E,0,(S)=>pe(p,S)||o.AddError({keyword:"dependentRequired",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})));return f||h}function Ok(e,o,a,u){let m=fo(It(Zi(u),"length"),Pe(0)),p=vn(hn(a.dependentSchemas).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=Lt(e,o,h,u);return br(I,E)}));return br(m,p)}function _k(e,o,a,u){let m=M(Se(u).length,0),p=mn(hn(a.dependentSchemas),0,([f,h])=>!pe(u,f)||At(e,o,h,u));return m||p}function Lk(e,o,a,u,m,p){let f=M(Se(p).length,0),h=$n(hn(m.dependentSchemas),0,([I,E])=>{let S=`${a}/dependentSchemas/${I}`;return!pe(p,I)||rr(e,o,S,u,E,p)});return f||h}function Nk(e,o,a,u){let m=e.DynamicRef(a)??!1;return Ws(e,o,m,u)}function Dk(e,o,a,u){let m=e.DynamicRef(a)??!1;return Ve(m)&&At(e,o,m,u)}function qk(e,o,a,u,m,p){let f=e.DynamicRef(m)??!1;return Ve(f)&&rr(e,o,"#",u,f,p)}function Fk(e,o,a,u){return Pd(a.enum.map((m)=>{if(Ji(m))return fo(u,Pe(m));let p=_o(m);return tx(u,p)}))}function Xf(e,o,a,u){return Ca(a.enum,(m)=>Ji(m)?M(u,m):$a(u,m))}function jk(e,o,a,u,m,p){return Xf(e,o,m,p)||o.AddError({keyword:"enum",schemaPath:a,instancePath:u,params:{allowedValues:m.enum}})}function Uk(e,o,a,u){return kd(u,Pe(a.exclusiveMaximum))}function Yf(e,o,a,u){return Pu(u,a.exclusiveMaximum)}function Bk(e,o,a,u,m,p){return Yf(e,o,m,p)||o.AddError({keyword:"exclusiveMaximum",schemaPath:a,instancePath:u,params:{comparison:"<",limit:m.exclusiveMaximum}})}function Gk(e,o,a,u){return Zy(u,Pe(a.exclusiveMinimum))}function Zf(e,o,a,u){return ji(u,a.exclusiveMinimum)}function Kk(e,o,a,u,m,p){return Zf(e,o,m,p)||o.AddError({keyword:"exclusiveMinimum",schemaPath:a,instancePath:u,params:{comparison:">",limit:m.exclusiveMinimum}})}var HF=[0,31,28,31,30,31,30,31,31,30,31,30,31],WF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function zF(e){return e%4===0&&(e%100!==0||e%400===0)}function nu(e){let o=WF.exec(e);if(!o)return!1;let a=+o[1],u=+o[2],m=+o[3];return u>=1&&u<=12&&m>=1&&m<=(u===2&&zF(a)?29:HF[u])}var VF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function ou(e,o=!0){let a=VF.exec(e);if(!a)return!1;if(o&&!a[4]&&!a[5])return!1;let u=+a[1],m=+a[2],p=+a[3];if(u>23||m>59||p>60)return!1;if(a[5]){let S=+a[6],R=+a[7];if(S>23||R>59)return!1}if(p<60)return!0;let f=a[5]==="-"?-1:1,h=+(a[6]||0),I=+(a[7]||0);return((u*60+m-f*(h*60+I))%1440+1440)%1440===1439}function Pp(e){let o=e.split(/T/i);return o.length===2&&nu(o[0])&&ou(o[1])}var JF=/^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 Cp(e){return JF.test(e)}var QF=/^(?:[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 $p(e){return QF.test(e)}var Hk=/^(?!-).*(?<!-)$/,Wk=/^(?!..--)/,zk=/^[a-zA-Z0-9-]*$/;var su=/[^\p{ASCII}]/u;var XF=/[0-9]/,Vk=/[\u{0660}-\u{0669}]/u,YF=/[\u{06f0}-\u{06f9}]/u,ZF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,e1=/[\u{002d}\u{002b}]/u,eh=/\p{Mn}/u,t1=/\p{Mc}/u;var Jk=/[\p{Mn}\p{Mc}\p{Me}]/u,th=/\p{L}/u,r1=/\p{Nd}/u,Qk=/\p{Script=Greek}/u,vp=/\p{Script=Hebrew}/u,Xk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Yk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,rh=/[\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,Zk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,n1=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,o1=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,eA=new RegExp([XF,YF].map((e)=>e.source).join("|"),"u"),tA=new RegExp([th,e1,ZF,r1,eh,t1,n1,o1].map((e)=>e.source).join("|"),"u");function rA(e){return Hk.test(e)&&Wk.test(e)&&zk.test(e)}var ps=36,Lc=1,Nc=26,i1=38,a1=700,oA=72,sA=128;function nh(){throw null}function Mp(e){return e.toLowerCase().startsWith("xn--")}function iA(e,o,a){e=a?Math.floor(e/a1):e>>1,e+=Math.floor(e/o);let u=0;while(e>(ps-Lc)*Nc>>1)e=Math.floor(e/(ps-Lc)),u+=ps;return u+Math.floor((ps-Lc+1)*e/(e+i1))}function Op(e){let o=[],a=sA,u=0,m=oA,p=e.lastIndexOf("-");if(p>0)for(let h=0;h<p;h++){let I=e.charCodeAt(h);if(I>=128)nh();o.push(I)}let f=p<0?0:p+1;while(f<e.length){let h=u,I=1,E=ps;while(!0){if(f>=e.length)nh();let R=e.charCodeAt(f++),k;if(R>=97&&R<=122)k=R-97;else if(R>=48&&R<=57)k=R-48+26;else nh();u+=k*I;let P=E<=m?Lc:E>=m+Nc?Nc:E-m;if(k<P)break;I*=ps-P,E+=ps}let S=o.length+1;m=iA(u-h,S,h===0),a+=Math.floor(u/S),u%=S,o.splice(u,0,a),u++}return String.fromCodePoint(...o)}function nA(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var u1=new RegExp(su.source,"gu");function aA(e){let o=e.replace(u1,""),a=o.length,u=a>0?[o,"-"]:[],m=Array.from(e,(E)=>E.codePointAt(0)),p=sA,f=0,h=oA,I=a;while(I<m.length){let E=1/0;for(let S of m)if(S>=p&&S<E)E=S;f+=(E-p)*(I+1),p=E;for(let S of m){if(S<p)f++;if(S===p){let R=f;for(let k=ps;;k+=ps){let P=k<=h?Lc:k>=h+Nc?Nc:k-h;if(R<P)break;let v=P+(R-P)%(ps-P);u.push(nA(v)),R=Math.floor((R-P)/(ps-P))}u.push(nA(R)),h=iA(f,I+1,I===a),f=0,I++}}f++,p++}return u.join("")}var c1=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,uA=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,m1=/^(?:R|AL|AN)$/;function cA(e){if(Mp(e))try{return _p(Op(e.slice(4).toLowerCase()))}catch{return!1}return _p(e)}function mA(e){let o=String.fromCodePoint(e);return eA.test(o)?"EN":Vk.test(o)?"AN":eh.test(o)?"NSM":vp.test(o)?"R":Yk.test(o)?"AL":th.test(o)?"L":"ON"}function _p(e){for(let o of e)if(m1.test(mA(o.codePointAt(0))))return!0;return!1}function Lp(e){let o=!1,a=uA,u=!1,m=!1,p=!0;for(let f of e){let h=mA(f.codePointAt(0));if(p){if(h!=="L"&&h!=="R"&&h!=="AL")return!1;o=h==="R"||h==="AL",a=o?c1:uA,p=!1}if(!a.test(h))return!1;if(h==="EN")u=!0;else if(h==="AN")m=!0}if(o&&u&&m)return!1;return!0}function p1(e){return su.test(e)&&aA(e).length+4>63}function l1(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Np(e){if(p1(e))return!1;if(_p(e)&&!Lp(e))return!1;let o=[...e],a=o.map((p)=>p.codePointAt(0)),u=a.length;if(l1(o))return!1;if(Jk.test(o[0]))return!1;let m=!1;for(let p=0;p<u;p++){let f=a[p],h=o[p];if(Zk.test(h))return!1;if(!tA.test(h))return!1;if(Xk.test(h))m=!0;let I=a[p-1],E=a[p+1];switch(f){case 183:if(I!==108||E!==108)return!1;break;case 885:if(!E||!Qk.test(o[p+1]))return!1;break;case 1523:case 1524:if(!I||!vp.test(o[p-1]))return!1;break;case 8204:if(!I||I<128&&!rh.test(o[p-1]))return!1;break;case 8205:if(!I||!rh.test(o[p-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!m)return!1;return!0}function Dp(e){if(!Mp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let a=Op(o);if(!su.test(a))return!1;return Np(a)}catch{return!1}}function d1(e){return e.length>0&&e.length<=63}function f1(e){return d1(e)&&(Dp(e)||rA(e))}function fA(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>f1(o))}function h1(e){return e.length>0&&e.length<=63}function g1(e){return h1(e)&&(Dp(e)||Np(e))}function y1(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 hA(e){if(e.length===0||e.includes(" "))return!1;let o=y1(e);if(o.length>253)return!1;let a=o.split("."),u=a.some((m)=>cA(m));return a.every((m)=>g1(m)&&(!u||Lp(m)))}function qp(e){return fA(e)}var x1=/^(?:[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 Fp(e){return x1.test(e.normalize("NFC"))}function jp(e){return hA(e)}var I1=/^(?:(?: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 Up(e){return I1.test(e)}var b1=/^(?:(?:(?:[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 Bp(e){return b1.test(e)}var E1=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,S1=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Gp(e){return!E1.test(e)&&!S1.test(e)&&URL.canParse(e,"http://example.com")}var w1=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,T1=/[\x00-\x20<>\^`{|}\\]/,R1=/%(?![0-9a-fA-F]{2})/;function k1(e){return e.length<2048?e.replace(w1,"[::1]"):e}function Kp(e){if(T1.test(e))return!1;if(R1.test(e))return!1;return URL.canParse(k1(e))}var A1=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Hp(e){return A1.test(e)}var P1=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Wp(e){return P1.test(e)}function zp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var C1=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Vp(e){return C1.test(e)}var $1=/^(?:[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 Jp(e){return $1.test(e)}var v1=/^(?:(?:[^\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 Qp(e){return v1.test(e)}var M1=/^[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 Xp(e){return M1.test(e)}function Yp(e){return URL.canParse(e)}var O1=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Zp(e){return O1.test(e)}var Tr=new Map;function yA(){Tr.clear()}function _1(){return[...Tr.entries()]}function L1(e,o){Tr.set(e,o)}function N1(e){return Tr.has(e)}function D1(e){return Tr.get(e)}function xA(e,o){return Tr.get(e)?.(o)??!0}function IA(){yA(),Tr.set("date-time",Pp),Tr.set("date",nu),Tr.set("duration",Cp),Tr.set("email",$p),Tr.set("hostname",qp),Tr.set("idn-email",Fp),Tr.set("idn-hostname",jp),Tr.set("ipv4",Up),Tr.set("ipv6",Bp),Tr.set("iri-reference",Gp),Tr.set("iri",Kp),Tr.set("json-pointer-uri-fragment",Hp),Tr.set("json-pointer",Wp),Tr.set("regex",zp),Tr.set("relative-json-pointer",Vp),Tr.set("time",ou),Tr.set("uri-reference",Jp),Tr.set("uri-template",Qp),Tr.set("uri",Xp),Tr.set("url",Yp),Tr.set("uuid",Zp)}IA();function bA(e,o,a,u){return Er(It("Format","Test"),[Pe(a.format),u])}function sh(e,o,a,u){return xA(a.format,u)}function EA(e,o,a,u,m,p){return sh(e,o,m,p)||o.AddError({keyword:"format",schemaPath:a,instancePath:u,params:{format:m.format}})}function SA(e,o,a,u){let m=Mc(a)?a.then:!0,p=xc(a)?a.else:!0;return RO(Lt(e,o,a.if,u),Lt(e,o,m,u),Lt(e,o,p,u))}function wA(e,o,a,u){let m=Mc(a)?a.then:!0,p=xc(a)?a.else:!0;return At(e,o,a.if,u)?At(e,o,m,u):At(e,o,p,u)}function TA(e,o,a,u,m,p){let f=Mc(m)?m.then:!0,h=xc(m)?m.else:!0,I=new Dn,E=rr(e,I,`${a}/if`,u,m.if,p)?rr(e,I,`${a}/then`,u,f,p)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"then"}}):rr(e,o,`${a}/else`,u,h,p)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"else"}});if(E)o.Merge([I]);return E}function q1(e,o,a,u){return vn(a.items.map((m,p)=>{let f=Xi(It(u,"length"),Pe(p)),h=Qn(e,o,m,`${u}[${p}]`),I=o.AddIndex(Pe(p));return br(f,Rn(h,I))}))}function F1(e,o,a,u){return vn(a.items.map((m,p)=>{let f=Xi(It(u,"length"),Pe(p)),h=Qn(e,o,m,`${u}[${p}]`);return br(f,h)}))}function j1(e,o,a,u){return o.UseUnevaluated()?q1(e,o,a,u):F1(e,o,a,u)}function U1(e,o,a,u){return mn(a.items,0,(m,p)=>ys(u.length,p)||ko(e,o,m,u[p])&&o.AddIndex(p))}function B1(e,o,a,u,m,p){return $n(m.items,0,(f,h)=>{let I=`${a}/items/${h}`,E=`${u}/${h}`;return ys(p.length,h)||Ao(e,o,I,E,f,p[h])&&o.AddIndex(h)})}function G1(e,o,a,u){let m=us(a)?a.prefixItems.length:0,p=Qn(e,o,a.items,"element"),f=o.AddIndex("index");return xs(u,Pe(m),["element","index"],Rn(p,f))}function K1(e,o,a,u){let m=us(a)?a.prefixItems.length:0,p=Qn(e,o,a.items,"element");return xs(u,Pe(m),["element","index"],p)}function H1(e,o,a,u){return o.UseUnevaluated()?G1(e,o,a,u):K1(e,o,a,u)}function W1(e,o,a,u){let m=us(a)?a.prefixItems.length:0;return mn(u,m,(p,f)=>ko(e,o,a.items,p)&&o.AddIndex(f))}function z1(e,o,a,u,m,p){let f=us(m)?m.prefixItems.length:0;return $n(p,f,(h,I)=>{let E=`${a}/items`,S=`${u}/${I}`;return Ao(e,o,E,S,m.items,h)&&o.AddIndex(I)})}function RA(e,o,a,u){return Ec(a)?j1(e,o,a,u):H1(e,o,a,u)}function kA(e,o,a,u){return Ec(a)?U1(e,o,a,u):W1(e,o,a,u)}function AA(e,o,a,u,m,p){return Ec(m)?B1(e,o,a,u,m,p):z1(e,o,a,u,m,p)}function PA(e){return vs(e)}function CA(e,o,a,u){if(!PA(a))return Pe(!0);let[m]=[Jt()],p=pm(u,[m,"_"],Lt(e,o,a.contains,m));return Xi(p,Pe(a.maxContains))}function ih(e,o,a,u){if(!PA(a))return!0;let m=Sd(u,(p)=>At(e,o,a.contains,p));return ys(m,a.maxContains)}function $A(e,o,a,u,m,p){let f=Gs(m)?m.minContains:1;return ih(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:f,maxContains:m.maxContains}})}function vA(e,o,a,u){return Xi(u,Pe(a.maximum))}function ah(e,o,a,u){return ys(u,a.maximum)}function MA(e,o,a,u,m,p){return ah(e,o,m,p)||o.AddError({keyword:"maximum",schemaPath:a,instancePath:u,params:{comparison:"<=",limit:m.maximum}})}function OA(e,o,a,u){return Xi(It(u,"length"),Pe(a.maxItems))}function uh(e,o,a,u){return ys(u.length,a.maxItems)}function _A(e,o,a,u,m,p){return uh(e,o,m,p)||o.AddError({keyword:"maxItems",schemaPath:a,instancePath:u,params:{limit:m.maxItems}})}function LA(e,o,a,u){return EO(u,Pe(a.maxLength))}function ch(e,o,a,u){return Ky(u,a.maxLength)}function NA(e,o,a,u,m,p){return ch(e,o,m,p)||o.AddError({keyword:"maxLength",schemaPath:a,instancePath:u,params:{limit:m.maxLength}})}function DA(e,o,a,u){return Xi(It(Zi(u),"length"),Pe(a.maxProperties))}function mh(e,o,a,u){return ys(Se(u).length,a.maxProperties)}function qA(e,o,a,u,m,p){return mh(e,o,m,p)||o.AddError({keyword:"maxProperties",schemaPath:a,instancePath:u,params:{limit:m.maxProperties}})}function FA(e){return vs(e)}function V1(e,o,a,u){let[m,p]=[Jt(),Jt()],f=pm(u,[m,p],Rn(Lt(e,o,a.contains,m),o.AddIndex(p)));return $u(f,Pe(a.minContains))}function J1(e,o,a,u){let[m]=[Jt()],p=pm(u,[m,"_"],Lt(e,o,a.contains,m));return $u(p,Pe(a.minContains))}function jA(e,o,a,u){if(!FA(a))return Pe(!0);return o.UseUnevaluated()?V1(e,o,a,u):J1(e,o,a,u)}function ph(e,o,a,u){if(!FA(a))return!0;let m=Sd(u,(p,f)=>At(e,o,a.contains,p)&&o.AddIndex(f));return Pa(m,a.minContains)}function UA(e,o,a,u,m,p){return ph(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:m.minContains}})}function BA(e,o,a,u){return $u(u,Pe(a.minimum))}function lh(e,o,a,u){return Pa(u,a.minimum)}function GA(e,o,a,u,m,p){return lh(e,o,m,p)||o.AddError({keyword:"minimum",schemaPath:a,instancePath:u,params:{comparison:">=",limit:m.minimum}})}function KA(e,o,a,u){return $u(It(u,"length"),Pe(a.minItems))}function dh(e,o,a,u){return Pa(u.length,a.minItems)}function HA(e,o,a,u,m,p){return dh(e,o,m,p)||o.AddError({keyword:"minItems",schemaPath:a,instancePath:u,params:{limit:m.minItems}})}function WA(e,o,a,u){return bO(u,Pe(a.minLength))}function fh(e,o,a,u){return Hy(u,a.minLength)}function zA(e,o,a,u,m,p){return fh(e,o,m,p)||o.AddError({keyword:"minLength",schemaPath:a,instancePath:u,params:{limit:m.minLength}})}function VA(e,o,a,u){return $u(It(Zi(u),"length"),Pe(a.minProperties))}function hh(e,o,a,u){return Pa(Se(u).length,a.minProperties)}function JA(e,o,a,u,m,p){return hh(e,o,m,p)||o.AddError({keyword:"minProperties",schemaPath:a,instancePath:u,params:{limit:m.minProperties}})}function QA(e,o,a,u){return kO(u,Pe(a.multipleOf))}function gh(e,o,a,u){return By(u,a.multipleOf)}function XA(e,o,a,u,m,p){return gh(e,o,m,p)||o.AddError({keyword:"multipleOf",schemaPath:a,instancePath:u,params:{multipleOf:m.multipleOf}})}function Q1(e,o,a,u){return wi(e,o,[a.not],u,Un(fo(It("results","length"),Pe(1))))}function X1(e,o,a,u){return Un(Lt(e,o,a.not,u))}function YA(e,o,a,u){return o.UseUnevaluated()?Q1(e,o,a,u):X1(e,o,a,u)}function yh(e,o,a,u){let m=new Nn;return!At(e,m,a.not,u)&&o.Merge([m])}function ZA(e,o,a,u,m,p){return yh(e,o,m,p)||o.AddError({keyword:"not",schemaPath:a,instancePath:u,params:{}})}function Y1(e,o,a,u){return wi(e,o,a.oneOf,u,fo(It("results","length"),Pe(1)))}function Z1(e,o,a,u){let[m]=[Jt()],p=TO(a.oneOf.map((h)=>Lt(e,o,h,u))),f=pm(p,[m,"_"],fo(m,Pe(!0)));return fo(f,Pe(1))}function eP(e,o,a,u){return o.UseUnevaluated()?Y1(e,o,a,u):Z1(e,o,a,u)}function tP(e,o,a,u){let m=a.oneOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return M(m.length,1)&&o.Merge(m)}function rP(e,o,a,u,m,p){let f=[],h=[],I=m.oneOf.reduce((S,R,k)=>{let P=new Dn,v=`${a}/oneOf/${k}`,_=rr(e,P,v,u,R,p);if(_)h.push(k);if(!_)f.push(P);return _?[...S,P]:S},[]),E=M(I.length,1)&&o.Merge(I);if(!E&&M(h.length,0))f.forEach((S)=>S.GetErrors().forEach((R)=>o.AddError(R)));return E||o.AddError({keyword:"oneOf",schemaPath:a,instancePath:u,params:{passingSchemas:h}})}function nP(e,o,a,u){let m=_o(lt(a.pattern)?ms(a.pattern):a.pattern);return Er(It(m,"test"),[u])}function xh(e,o,a,u){return(lt(a.pattern)?ms(a.pattern):a.pattern).test(u)}function oP(e,o,a,u,m,p){return xh(e,o,m,p)||o.AddError({keyword:"pattern",schemaPath:a,instancePath:u,params:{pattern:m.pattern}})}function sP(e,o,a,u){return vn(hn(a.patternProperties).map(([m,p])=>{let[f,h]=[Jt(),Jt()],I=_o(ms(m)),E=Un(Er(It(I,"test"),[f])),S=Qn(e,o,p,h),R=o.AddKey(f),k=o.UseUnevaluated()?br(E,Rn(S,R)):br(E,S);return xs(ex(u),Pe(0),[`[${f}, ${h}]`,"_"],k)}))}function iP(e,o,a,u){return mn(hn(a.patternProperties),0,([m,p])=>{let f=ms(m);return mn(hn(u),0,([h,I])=>!f.test(h)||ko(e,o,p,I)&&o.AddKey(h))})}function aP(e,o,a,u,m,p){return $n(hn(m.patternProperties),0,([f,h])=>{let I=`${a}/patternProperties/${f}`,E=ms(f);return $n(hn(p),0,([S,R])=>{let k=`${u}/${S}`;return!E.test(S)||Ao(e,o,I,k,h,R)&&o.AddKey(S)})})}function uP(e,o,a,u){return vn(a.prefixItems.map((m,p)=>{let f=Xi(It(u,"length"),Pe(p)),h=Qn(e,o,m,`${u}[${p}]`),I=o.AddIndex(Pe(p)),E=o.UseUnevaluated()?Rn(h,I):h;return br(f,E)}))}function cP(e,o,a,u){return M(u.length,0)||mn(a.prefixItems,0,(m,p)=>ys(u.length,p)||ko(e,o,m,u[p])&&o.AddIndex(p))}function mP(e,o,a,u,m,p){return M(p.length,0)||$n(m.prefixItems,0,(f,h)=>{let I=`${a}/prefixItems/${h}`,E=`${u}/${h}`;return ys(p.length,h)||Ao(e,o,I,E,f,p[h])&&o.AddIndex(h)})}function el(e,o){return e.includes(o)||Bo().exactOptionalPropertyTypes}function pP(e,o){return Rd(It(e,o))}function Ih(e,o){return Bt(e[o])}function lP(e,o,a,u){let m=cs(a)?a.required:[],p=hn(a.properties).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=Qn(e,o,h,It(u,f)),S=o.AddKey(Pe(f)),R=o.UseUnevaluated()?Rn(E,S):E,k=m.includes(f)?R:br(I,R);return el(m,f)?k:br(pP(u,f),k)});return vn(p)}function dP(e,o,a,u){let m=cs(a)?a.required:[];return mn(hn(a.properties),0,([f,h])=>{let I=!pe(u,f)||ko(e,o,h,u[f])&&o.AddKey(f);return el(m,f)?I:Ih(u,f)||I})}function fP(e,o,a,u,m,p){let f=cs(m)?m.required:[];return $n(hn(m.properties),0,([I,E])=>{let S=`${a}/properties/${I}`,R=`${u}/${I}`,k=()=>!pe(p,I)||Ao(e,o,S,R,E,p[I])&&o.AddKey(I);return el(f,I)?k():Ih(p,I)||k()})}function hP(e,o,a,u){let[m,p]=[Jt(),Jt()];return xs(Zi(u),Pe(0),[m,p],Lt(e,o,a.propertyNames,m))}function gP(e,o,a,u){return mn(Se(u),0,(m,p)=>At(e,o,a.propertyNames,m))}function yP(e,o,a,u,m,p){let f=[];return $n(Se(p),0,(I,E)=>{let S=`${u}/${I}`,R=`${a}/propertyNames`,k=rr(e,o,R,S,m.propertyNames,I);if(!k)f.push(I);return k})||o.AddError({keyword:"propertyNames",schemaPath:a,instancePath:u,params:{propertyNames:f}})}function xP(e,o,a,u){let m=e.RecursiveRef(a)??!1;return Ws(e,o,m,u)}function IP(e,o,a,u){let m=e.RecursiveRef(a)??!1;return Ve(m)&&At(e,o,m,u)}function bP(e,o,a,u,m,p){let f=e.RecursiveRef(m)??!1;return Ve(f)&&rr(e,o,"#",u,f,p)}function ej(e,o,a,u){let m=si(["context","value"],Ws(e,o,a,"value")),p=si(["context","value"],lm([Ds("nextContext",Ad("CheckContext",[])),Ds("result",Er(m,["nextContext","value"])),rx("result",o.Merge("[nextContext]")),dm("result")]));return Er(p,["context",u])}function tj(e,o,a,u){return Ws(e,o,a,u)}function EP(e,o,a,u){let m=e.Ref(a)??!1;return o.UseUnevaluated()?ej(e,o,m,u):tj(e,o,m,u)}function SP(e,o,a,u){let m=e.Ref(a)??!1,p=new Nn,f=Ve(m)&&At(e,p,m,u);if(f)o.Merge([p]);return f}function wP(e,o,a,u,m,p){let f=e.Ref(m)??!1,h=new Dn,I=Ve(f)&&rr(e,h,"#",u,f,p);if(I)o.Merge([h]);if(!I)h.GetErrors().forEach((E)=>o.AddError(E));return I}function TP(e,o,a,u){return vn(a.required.map((m)=>ea(u,Pe(m))))}function RP(e,o,a,u){return mn(a.required,0,(m)=>pe(u,m))}function kP(e,o,a,u,m,p){let f=[];return $n(m.required,0,(I)=>{let E=pe(p,I);if(!E)f.push(I);return E})||o.AddError({keyword:"required",schemaPath:a,instancePath:u,params:{requiredProperties:f}})}function AP(e,o,a,u){return M(a,"object")?Qy(u):M(a,"array")?mm(u):M(a,"boolean")?fO(u):M(a,"integer")?hO(u):M(a,"number")?Jy(u):M(a,"null")?gO(u):M(a,"string")?Yy(u):M(a,"bigint")?Vy(u):M(a,"constructor")?IO(u):M(a,"function")?xO(u):M(a,"symbol")?yO(u):M(a,"undefined")?Rd(u):M(a,"void")?Rd(u):Pe(!0)}function bh(e,o,a,u,m){return M(a,"object")?Uo(m):M(a,"array")?Fe(m):M(a,"boolean")?fn(m):M(a,"integer")?cm(m):M(a,"number")?Ot(m):M(a,"null")?bo(m):M(a,"string")?lt(m):M(a,"bigint")?qr(m):M(a,"constructor")?bd(m):M(a,"function")?gs(m):M(a,"symbol")?Ed(m):M(a,"undefined")?Bt(m):M(a,"void")?Bt(m):!0}function rj(e,o,a,u){return Pd(a.map((m)=>AP(e,o,m,u)))}function PP(e,o,a,u,m){return Ca(a,(p)=>bh(e,o,p,u,m))}function CP(e,o,a,u){return Fe(a.type)?rj(e,o,a.type,u):AP(e,o,a.type,u)}function $P(e,o,a,u){return Fe(a.type)?PP(e,o,a.type,a,u):bh(e,o,a.type,a,u)}function vP(e,o,a,u,m,p){return(Fe(m.type)?PP(e,o,m.type,m,p):bh(e,o,m.type,m,p))||o.AddError({keyword:"type",schemaPath:a,instancePath:u,params:{type:m.type}})}function MP(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Er(It("context","GetIndices"),[]),h=Er(It("indices","has"),[m]),I=Lt(e,o,a.unevaluatedItems,p),E=Er(It("context","AddIndex"),[m]),S=xs(u,Pe(0),[p,m],Rn(br(h,I),E));return Er(si(["context"],lm([Ds("indices",f),dm(S)])),["context"])}function OP(e,o,a,u){let m=o.GetIndices();return mn(u,0,(p,f)=>(m.has(f)||At(e,o,a.unevaluatedItems,p))&&o.AddIndex(f))}function _P(e,o,a,u,m,p){let f=o.GetIndices(),h=[];return $n(p,0,(E,S)=>{let R=new Dn,k=(f.has(S)||rr(e,R,a,u,m.unevaluatedItems,E))&&o.AddIndex(S);if(!k)h.push(S);return k})||o.AddError({keyword:"unevaluatedItems",schemaPath:a,instancePath:u,params:{unevaluatedItems:h}})}function LP(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Er(It("context","GetKeys"),[]),h=Er(It("keys","has"),[m]),I=Er(It("context","AddKey"),[m]),E=Lt(e,o,a.unevaluatedProperties,p),S=xs(ex(u),Pe(0),[`[${m}, ${p}]`,"_"],br(h,Rn(E,I)));return Er(si(["context"],lm([Ds("keys",f),dm(S)])),["context"])}function NP(e,o,a,u){let m=o.GetKeys();return mn(hn(u),0,([p,f])=>m.has(p)||At(e,o,a.unevaluatedProperties,f)&&o.AddKey(p))}function DP(e,o,a,u,m,p){let f=o.GetKeys(),h=[];return $n(hn(p),0,([E,S])=>{let R=new Dn,k=f.has(E)||rr(e,R,a,u,m.unevaluatedProperties,S)&&o.AddKey(E);if(!k)h.push(E);return k})||o.AddError({keyword:"unevaluatedProperties",schemaPath:a,instancePath:u,params:{unevaluatedProperties:h}})}function Eh(e){return!M(e.uniqueItems,!1)}function qP(e,o,a,u){if(!Eh(a))return Pe(!0);let m=It(Ad("Set",[Er(It(u,"map"),[It("Hashing","Hash")])]),"size"),p=It(u,"length");return fo(m,p)}function FP(e,o,a,u){if(!Eh(a))return!0;let m=new Set(u.map(vd)).size,p=u.length;return M(m,p)}function jP(e,o,a,u,m,p){if(!Eh(m))return!0;let f=new Set,h=p.reduce((E,S,R)=>{let k=vd(S);if(f.has(k))return[...E,R];return f.add(k),E},[]);return M(h.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:a,instancePath:u,params:{duplicateItems:h}})}function Dc(e,o){return Oc(e)&&(Fe(e.type)&&ji(e.type.length,0)&&mn(e.type,0,(a)=>M(a,o))||M(e.type,o))}function nj(e){return Dc(e,"object")}function oj(e){return In(e)&&(Oo(e)||hc(e)||gc(e)||Za(e)||Hs(e)||Ks(e)||tu(e)||xa(e)||Rc(e)||cs(e)||Si(e))}function sj(e){return Dc(e,"array")}function ij(e){return In(e)&&(Ya(e)||Bs(e)||vs(e)||wc(e)||eu(e)||Gs(e)||Ii(e)||us(e)||Ei(e)||bi(e))}function aj(e){return Dc(e,"string")}function uj(e){return In(e)&&(ya(e)||Tc(e)||ga(e)||Ia(e))}function cj(e){return Dc(e,"number")||Dc(e,"bigint")}function mj(e){return In(e)&&(as(e)||Sc(e)||Ic(e)||is(e)||kc(e))}function Qn(e,o,a,u){return o.UseUnevaluated()?Rn(Rn(o.Push(),Lt(e,o,a,u)),o.Pop()):Lt(e,o,a,u)}function Lt(e,o,a,u){e.Push(a);let m=[];if(js(a))return bk(e,o,a,u);if(Oc(a))m.push(CP(e,o,a,u));if(oj(a)){let f=[];if(cs(a))f.push(TP(e,o,a,u));if(Oo(a))f.push(pk(e,o,a,u));if(hc(a))f.push(Ak(e,o,a,u));if(gc(a))f.push($k(e,o,a,u));if(Za(a))f.push(Ok(e,o,a,u));if(Ks(a))f.push(sP(e,o,a,u));if(Hs(a))f.push(lP(e,o,a,u));if(tu(a))f.push(hP(e,o,a,u));if(xa(a))f.push(VA(e,o,a,u));if(Rc(a))f.push(DA(e,o,a,u));let h=vn(f),I=br(Un(Qy(u)),h);m.push(nj(a)?h:I)}if(ij(a)){let f=[];if(Ya(a))f.push(uk(e,o,a,u));if(vs(a))f.push(Rk(e,o,a,u));if(Bs(a))f.push(RA(e,o,a,u));if(wc(a))f.push(CA(e,o,a,u));if(eu(a))f.push(OA(e,o,a,u));if(Gs(a))f.push(jA(e,o,a,u));if(Ii(a))f.push(KA(e,o,a,u));if(us(a))f.push(uP(e,o,a,u));if(bi(a))f.push(qP(e,o,a,u));let h=vn(f),I=br(Un(mm(u)),h);m.push(sj(a)?h:I)}if(uj(a)){let f=[];if(Tc(a))f.push(LA(e,o,a,u));if(ya(a))f.push(WA(e,o,a,u));if(ga(a))f.push(bA(e,o,a,u));if(Ia(a))f.push(nP(e,o,a,u));let h=vn(f),I=br(Un(Yy(u)),h);m.push(aj(a)?h:I)}if(mj(a)){let f=[];if(Ic(a))f.push(Uk(e,o,a,u));if(is(a))f.push(Gk(e,o,a,u));if(Sc(a))f.push(vA(e,o,a,u));if(as(a))f.push(BA(e,o,a,u));if(kc(a))f.push(QA(e,o,a,u));let h=vn(f),I=br(Un(br(Jy(u),Vy(u))),h);m.push(cj(a)?h:I)}if(vc(a))m.push(EP(e,o,a,u));if($c(a))m.push(xP(e,o,a,u));if(yc(a))m.push(Nk(e,o,a,u));if(Tp(a))m.push(Sk(e,o,a,u));if(Rp(a))m.push(Fk(e,o,a,u));if(bc(a))m.push(SA(e,o,a,u));if(Ac(a))m.push(YA(e,o,a,u));if(lc(a))m.push(fk(e,o,a,u));if(fc(a))m.push(yk(e,o,a,u));if(Pc(a))m.push(eP(e,o,a,u));if(Ei(a))m.push(br(Un(mm(u)),MP(e,o,a,u)));if(Si(a))m.push(br(Un(Xy(u)),LP(e,o,a,u)));if(pc(a))m.push(sk(e,o,a,u));let p=vn(m);return e.Pop(a),p}function ko(e,o,a,u){return o.Push()&&At(e,o,a,u)&&o.Pop()}function At(e,o,a,u){e.Push(a);let m=js(a)?zf(e,o,a,u):(!Oc(a)||$P(e,o,a,u))&&(!(at(u)&&!Fe(u))||(!cs(a)||RP(e,o,a,u))&&(!Oo(a)||lk(e,o,a,u))&&(!hc(a)||Pk(e,o,a,u))&&(!gc(a)||vk(e,o,a,u))&&(!Za(a)||_k(e,o,a,u))&&(!Ks(a)||iP(e,o,a,u))&&(!Hs(a)||dP(e,o,a,u))&&(!tu(a)||gP(e,o,a,u))&&(!xa(a)||hh(e,o,a,u))&&(!Rc(a)||mh(e,o,a,u)))&&(!Fe(u)||(!Ya(a)||ck(e,o,a,u))&&(!vs(a)||Jf(e,o,a,u))&&(!Bs(a)||kA(e,o,a,u))&&(!wc(a)||ih(e,o,a,u))&&(!eu(a)||uh(e,o,a,u))&&(!Gs(a)||ph(e,o,a,u))&&(!Ii(a)||dh(e,o,a,u))&&(!us(a)||cP(e,o,a,u))&&(!bi(a)||FP(e,o,a,u)))&&(!lt(u)||(!Tc(a)||ch(e,o,a,u))&&(!ya(a)||fh(e,o,a,u))&&(!ga(a)||sh(e,o,a,u))&&(!Ia(a)||xh(e,o,a,u)))&&(!(Ot(u)||qr(u))||(!Ic(a)||Yf(e,o,a,u))&&(!is(a)||Zf(e,o,a,u))&&(!Sc(a)||ah(e,o,a,u))&&(!as(a)||lh(e,o,a,u))&&(!kc(a)||gh(e,o,a,u)))&&(!vc(a)||SP(e,o,a,u))&&(!$c(a)||IP(e,o,a,u))&&(!yc(a)||Dk(e,o,a,u))&&(!Tp(a)||Vf(e,o,a,u))&&(!Rp(a)||Xf(e,o,a,u))&&(!bc(a)||wA(e,o,a,u))&&(!Ac(a)||yh(e,o,a,u))&&(!lc(a)||hk(e,o,a,u))&&(!fc(a)||xk(e,o,a,u))&&(!Pc(a)||tP(e,o,a,u))&&(!Ei(a)||(!Fe(u)||OP(e,o,a,u)))&&(!Si(a)||(!at(u)||NP(e,o,a,u)))&&(!pc(a)||ik(e,o,a,u));return e.Pop(a),m}function Ao(e,o,a,u,m,p){return o.Push()&&rr(e,o,a,u,m,p)&&o.Pop()}function rr(e,o,a,u,m,p){if(o.AtCapacity())return!1;e.Push(m);let f=js(m)?Ek(e,o,a,u,m,p):!!(+(!Oc(m)||vP(e,o,a,u,m,p))&+(!(at(p)&&!Fe(p))||!!(+(!cs(m)||kP(e,o,a,u,m,p))&+(!Oo(m)||dk(e,o,a,u,m,p))&+(!hc(m)||Ck(e,o,a,u,m,p))&+(!gc(m)||Mk(e,o,a,u,m,p))&+(!Za(m)||Lk(e,o,a,u,m,p))&+(!Ks(m)||aP(e,o,a,u,m,p))&+(!Hs(m)||fP(e,o,a,u,m,p))&+(!tu(m)||yP(e,o,a,u,m,p))&+(!xa(m)||JA(e,o,a,u,m,p))&+(!Rc(m)||qA(e,o,a,u,m,p))))&+(!Fe(p)||!!(+(!Ya(m)||mk(e,o,a,u,m,p))&+(!vs(m)||kk(e,o,a,u,m,p))&+(!Bs(m)||AA(e,o,a,u,m,p))&+(!wc(m)||$A(e,o,a,u,m,p))&+(!eu(m)||_A(e,o,a,u,m,p))&+(!Gs(m)||UA(e,o,a,u,m,p))&+(!Ii(m)||HA(e,o,a,u,m,p))&+(!us(m)||mP(e,o,a,u,m,p))&+(!bi(m)||jP(e,o,a,u,m,p))))&+(!lt(p)||!!(+(!Tc(m)||NA(e,o,a,u,m,p))&+(!ya(m)||zA(e,o,a,u,m,p))&+(!ga(m)||EA(e,o,a,u,m,p))&+(!Ia(m)||oP(e,o,a,u,m,p))))&+(!(Ot(p)||qr(p))||!!(+(!Ic(m)||Bk(e,o,a,u,m,p))&+(!is(m)||Kk(e,o,a,u,m,p))&+(!Sc(m)||MA(e,o,a,u,m,p))&+(!as(m)||GA(e,o,a,u,m,p))&+(!kc(m)||XA(e,o,a,u,m,p))))&+(!vc(m)||wP(e,o,a,u,m,p))&+(!$c(m)||bP(e,o,a,u,m,p))&+(!yc(m)||qk(e,o,a,u,m,p))&+(!Tp(m)||wk(e,o,a,u,m,p))&+(!Rp(m)||jk(e,o,a,u,m,p))&+(!bc(m)||TA(e,o,a,u,m,p))&+(!Ac(m)||ZA(e,o,a,u,m,p))&+(!lc(m)||gk(e,o,a,u,m,p))&+(!fc(m)||Ik(e,o,a,u,m,p))&+(!Pc(m)||rP(e,o,a,u,m,p))&+(!Ei(m)||(!Fe(p)||_P(e,o,a,u,m,p)))&+(!Si(m)||(!at(p)||DP(e,o,a,u,m,p))))&&(!pc(m)||ak(e,o,a,u,m,p));return e.Pop(m),f}var UP=[0],tl=new Map,qc=new Map;function pj(){return`${UP[0]++}`}function lj(e,o){if(!tl.has(e))tl.set(e,new Map);let a=tl.get(e);if(a.has(o))return a.get(o);let u=pj();return a.set(o,u),u}function dj(e,o,a,u){return e.UseUnevaluated()?Er(`check_${a}`,["context",u]):Er(`check_${a}`,[u])}function fj(e,o,a,u){let m=Lt(e,o,a,"value");return o.UseUnevaluated()?Ds(`check_${u}`,si(["context","value"],m)):Ds(`check_${u}`,si(["value"],m))}function BP(){UP[0]=0,tl.clear(),qc.clear()}function GP(){return[...qc.values()]}function Ws(e,o,a,u){let m=lj(a,e.LexicalBaseURL()),p=dj(o,a,m,u);if(qc.has(m))return p;return qc.set(m,""),qc.set(m,fj(e,o,a,m)),p}function hj(e,o){return at(o)&&!Cu(e)?o[e]:void 0}function gj(e,o){return e.reduce((a,u)=>hj(u,a),o)}function yj(e){if(M(e.length,0))return[];let o=e.split("/").map((a)=>a.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function xj(e,o){let a=yj(o);return gj(a,e)}var nl="https://json-schema.org";function HP(e,o){if(at(e)&&Us(e)&&M(e.$dynamicAnchor,o))return e;if(at(e))for(let a of Se(e)){let u=HP(e[a],o);if(u)return u}return}function Sh(e,o,a){if(M(e,a))return o.href;let u=In(e)&&Ro(e)?new URL(e.$id,o.href):o;if(Fe(e))for(let m of e){let p=Sh(m,u,a);if(!Bt(p))return p}else if(at(e))for(let m of Se(e)){let p=Sh(e[m],u,a);if(!Bt(p))return p}return}function Ij(e,o,a){if(M(e.$id,a.hash))return e;let u=new URL(a.href,o.href);if(M(o.pathname,u.pathname))return a.hash.startsWith("#")?WP(e,a):e;return}function bj(e,o,a){let u=new URL(`#${e.$anchor}`,o.href),m=new URL(a.href,o.href);return M(u.href,m.href)?e:void 0}function Ej(e,o,a){let u=new URL(`#${e.$dynamicAnchor}`,o.href),m=new URL(a.href,o.href);return M(u.href,m.href)?e:void 0}function WP(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let a=decodeURIComponent(o.hash.slice(1));if(!a.startsWith("/"))return;return xj(e,a)}function Sj(e,o,a){if(Ro(e)){let u=Ij(e,o,a);if(!Bt(u))return u}if(dc(e)){let u=bj(e,o,a);if(!Bt(u))return u}if(Us(e)){let u=Ej(e,o,a);if(!Bt(u))return u}return WP(e,a)}function wj(e,o,a){return e.reduce((u,m)=>{let p=ol(m,o,a);return!Bt(p)?p:u},void 0)}function Tj(e){return M(e,"const")||M(e,"enum")}function Rj(e,o,a){return Se(e).reduce((u,m)=>{if(Tj(m))return u;let p=ol(e[m],o,a);return!Bt(p)?p:u},void 0)}function ol(e,o,a){let u=In(e)&&Ro(e)?new URL(e.$id,o.href):o;if(In(e)){let m=Sj(e,u,a);if(!Bt(m))return m}if(Fe(e))return wj(e,u,a);if(at(e))return Rj(e,u,a);return}function kj(e,o,a){return Sh(e,new URL(o||".",nl),a)}function Aj(e,o,a,u){let m=sl(e,o,a,u,!1);return In(m)&&Ro(m)?m:void 0}function KP(e){return e.href.split("#")[0]}function Pj(e,o){return pe(e,o)?e[o]:void 0}function Cj(e,o,a){return ol(e,o,a)}function $j(e,o,a){let u=KP(a);if(M(u,KP(o)))return;if(!pe(e,u))return;let m=e[u],p=In(m)&&Ro(m)?new URL(m.$id,u):new URL(u);return M(a.hash,"")?m:ol(m,p,a)}function vj(e,o,a,u,m){if(!u.$ref.startsWith("#"))return;if(pe(e,"$schema"))return;let p=kj(o,a,m);if(Bt(p)||M(p,a))return;return{target:m,base:p,root:o}}function Mj(e,o,a){let u=e[o];if(!In(u))return;return{target:a,base:o,root:u}}function Oj(e,o,a,u,m){let p=m?Mj(e.context,u,a):void 0;if(!Bt(p))return p;return vj(e.root,e.lexicalSchema,e.referenceBase,o,a)}function _j(e,o,a,u,m,p){if(Ro(m))return;let f=Aj(e,o,a,u);if(!f||p.includes(f))return;return{target:m,resource:f}}function sl(e,o,a,u,m=!0){let p=new URL(a||".",nl),f=m&&Ro(o)?new URL(o.$id,p):p,h=new URL(u,f.href);return Pj(e,u)??Cj(o,f,h)??$j(e,f,h)}function Lj(e,o,a,u,m,p){let f=new URL(a||".",nl),h=m.$dynamicRef.startsWith("#")?u:o,I=sl(e,h,a,m.$dynamicRef,!1);if(Bt(I)){let R=new URL(m.$dynamicRef,f).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let k=decodeURIComponent(R.slice(1));return p.find((v)=>M(v.$dynamicAnchor,k))??HP(o,k)}return}if(!In(I)||!Us(I))return I;if(new URL(m.$dynamicRef,f).hash.startsWith("#/"))return I;return p.find((R)=>M(R.$dynamicAnchor,I.$dynamicAnchor))??I}function Nj(e,o){let a=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:a,m=sl(e.context,u,e.referenceBase,o.$ref,!1);if(!m||!In(m))return{schema:m};let p=new URL(o.$ref,e.referenceBase).href.split("#")[0],f=!M(p,e.resourceBase),h=Oj(e,o,m,p,f),I=f?_j(e.context,e.root,e.referenceBase,p,m,e.ids):void 0;return{schema:m,retrievedResource:h,resolvedResource:I}}function Dj(e,o){let a=Cc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return sl(e.context,a,e.lexicalBase,o.$recursiveRef,!1)}function qj(e,o){return Lj(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var Nr=function(e,o,a,u){if(a==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?u:a==="a"?u.call(e):u?u.value:o.get(e)},Rr,al,YP,kh,il,zP,VP,JP,QP,Th,Rh,Ah,Ph,XP,ZP;class Ti{constructor(e,o){Rr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return Nr(this,Rr,"m",kh).call(this,this.ids)}Push(e){if(!In(e))return;if(Ro(e))Nr(this,Rr,"m",Ah).call(this,e);if(dc(e))this.anchors.push(e);if(Cc(e))this.recursiveAnchors.push(e);if(Us(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(!In(e))return;if(Ro(e))Nr(this,Rr,"m",Ph).call(this,e);if(dc(e))this.anchors.pop();if(Cc(e))this.recursiveAnchors.pop();if(Us(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Nr(this,Rr,"m",ZP).call(this,e)}Ref(e){let o=Nj(Nr(this,Rr,"m",al).call(this),e);return Nr(this,Rr,"m",YP).call(this,o),o.schema}RecursiveRef(e){let o=Dj(Nr(this,Rr,"m",al).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=qj(Nr(this,Rr,"m",al).call(this),e);if(o)this.pendingResource=!0;return o}}Rr=new WeakSet,al=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Nr(this,Rr,"m",VP).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Nr(this,Rr,"m",zP).call(this),resourceBase:Nr(this,Rr,"m",il).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},YP=function(o){if(!Bt(o.schema))this.pendingResource=!0;if(!Bt(o.resolvedResource))Nr(this,Rr,"m",XP).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})},kh=function(o){let a=this.retrievedFrames[this.retrievedFrames.length-1],u=a?new URL(a.base):new URL(nl);return(a?o.slice(a.idDepth):o).reduce((p,f)=>new URL(f.$id,p),u).href},il=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return Nr(this,Rr,"m",kh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((a,u)=>new URL(u.$id,a),new URL(o.base)).href},zP=function(){if(this.retrievedFrames.length>0)return Nr(this,Rr,"m",il).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 Nr(this,Rr,"m",il).call(this)},VP=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},JP=function(o){o.forEach((a)=>Nr(this,Rr,"m",Th).call(this,a,!1))},QP=function(o){o.forEach((a)=>Nr(this,Rr,"m",Rh).call(this,a,!1))},Th=function e(o,a=!0){if(js(o))return;if(Fe(o))return Nr(this,Rr,"m",JP).call(this,o);if(!In(o))return;let u=o;if(!a&&Ro(u))return;if(!a&&Us(u))this.dynamicAnchors.push(u);for(let m of Se(u))Nr(this,Rr,"m",e).call(this,u[m],!1)},Rh=function e(o,a=!0){if(js(o))return;if(Fe(o))return Nr(this,Rr,"m",QP).call(this,o);if(!In(o))return;let u=o;if(!a&&Ro(u))return;if(!a&&Us(u))this.dynamicAnchors.pop();for(let m of Se(u))Nr(this,Rr,"m",e).call(this,u[m],!1)},Ah=function(o){this.ids.push(o);let a=this.pendingResource;if(this.pendingResource=!1,a)this.resourceIds.push(o);Nr(this,Rr,"m",Th).call(this,o,!0)},Ph=function(o){if(this.ids.pop(),this.resourceIds.length>0&&M(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();Nr(this,Rr,"m",Rh).call(this,o,!0)},XP=function(o,a){Nr(this,Rr,"m",Ah).call(this,a),this.resolvedResources.set(o,a)},ZP=function(o){if(!this.resolvedResources.has(o))return;let a=this.resolvedResources.get(o);Nr(this,Rr,"m",Ph).call(this,a),this.resolvedResources.delete(o)};function Fj(e){let o=e.Functions().join(`;
33
- `),a=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${a.join("; ")} }`}function jj(e,o){return bx("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Nn,B,iu,oa,e.External().variables)}function Uj(e){let o=new Ti(e.Context(),e.Schema()),a=new Nn;return(u)=>At(o,a,e.Schema(),u)}function Bj(e,o){return Ix()?jj(e,o):Uj(e)}class eC{constructor(e,o,a){this.isAccelerated=e,this.code=o,this.check=a}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class tC{constructor(e,o,a,u,m,p){this.context=e,this.schema=o,this.external=a,this.functions=u,this.entry=m,this.useUnevaluated=p}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=Fj(this),o=Bj(this,e);return new eC(Ix(),e,o)}}function ul(...e){let[o,a]=kn(e,{2:(I,E)=>[I,E],1:(I)=>[{},I]});nk(),BP();let u=new Ti(o,a),m=new Kf(rk(o,a)),p=Ws(u,m,a,"value"),f=GP(),h=ok();return new tC(o,a,h,f,p,m.UseUnevaluated())}function cl(...e){let[o,a,u]=kn(e,{3:(S,R,k)=>[S,R,k],2:(S,R)=>[{},S,R]}),m=new Ti(o,a),p=new Dn,f=rr(m,p,"#","",a,u),h=p.GetErrors(),I=Cx(),E=h.map((S)=>({...S,message:I(S)}));return[f,E]}function $h(...e){let[o,a,u]=kn(e,{3:(f,h,I)=>[f,h,I],2:(f,h)=>[{},f,h]}),m=new Ti(o,a),p=new Nn;return At(m,p,a,u)}function Yt(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return $h(o,a,u)}function Ms(...e){let[o,a,u]=kn(e,{3:(f,h,I)=>[f,h,I],2:(f,h)=>[{},f,h]}),[m,p]=cl(o,a,u);return p}class ba extends Error{constructor(e,o,a){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:a,value:o},writable:!1,configurable:!1,enumerable:!1})}}function rC(e,o,a){if(!Fe(a))return a;return a.map((u)=>bn(e,o.items,u))}function nC(e,o,a){return bn({...e,...o.$defs},pn(o.$ref),a)}function Hj(e,o){let a=pe(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Mo(e,o),m=Pn(u);return He(m)?Ip(m,a):m}function oC(e,o,a){let u=Hj(e,o);return bn(e,u,a)}function ml(e){return pe(e,"additionalProperties")?e.additionalProperties:void 0}function sC(e,o,a){if(!at(a)||Fe(a))return a;let u=ml(o);for(let m of Se(a)){if(pe(o.properties,m)){a[m]=bn(e,o.properties[m],a[m]);continue}if(fn(u)&&M(u,!0)||Mr(u)&&Yt(e,u,a[m])){a[m]=bn(e,u,a[m]);continue}delete a[m]}return a}function iC(e,o,a){if(!at(a))return a;let u=ml(o),[m,p]=[new RegExp(xn(o)),or(o)];for(let f of Se(a)){if(m.test(f)){a[f]=bn(e,p,a[f]);continue}if(fn(u)&&M(u,!0)||Mr(u)&&Yt(e,u,a[f])){a[f]=bn(e,u,a[f]);continue}delete a[f]}return a}function aC(e,o,a){return pe(e,o.$ref)?bn(e,e[o.$ref],a):a}function uC(e,o,a){if(!Fe(a))return a;let u=Math.min(a.length,o.items.length);for(let m=0;m<u;m++)a[m]=bn(e,o.items[m],a[m]);return ji(a.length,u)?a.slice(0,u):a}function Gr(e){return va(e)}function cC(e,o,a){for(let u of o.anyOf){let m=bn(e,u,Gr(a));if(Yt(e,u,m))return m}return a}function bn(e,o,a){return St(o)?rC(e,o,a):Xt(o)?nC(e,o,a):Ge(o)?oC(e,o,a):He(o)?sC(e,o,a):Kt(o)?iC(e,o,a):Ft(o)?aC(e,o,a):ct(o)?uC(e,o,a):be(o)?cC(e,o,a):a}function Wj(e,o){for(let a of Se(e)){if(pe(o,a))continue;o[a]=e[a]}return o}function zj(e){let o={};for(let a of Se(e))o[a]=Fc(e[a]);return o}function Vj(e){return vh(DR(e))}function vh(e){return e.map((o)=>Fc(o))}function Fc(e){let o=St(e)?H(Fc(e.items),Ma(e)):Ge(e)?Mn(vh(e.allOf)):be(e)?g(Vj(e.anyOf)):He(e)?l(zj(e.properties)):Kt(e)?ks(di(e),Fc(or(e))):ct(e)?Ur(vh(e.items)):e;return Wj(e,o)}function au(e){return Fc(e)}function Lo(...e){let[o,a,u]=kn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]}),m=Bo().unionPrioritySort?au(a):a;return bn(o,m,u)}function Io(e){return at(e)&&pe(e,"value")}function je(e){return{value:e}}function kr(){return}function Jj(e){return Fe(e)?je(e):je([e])}function Qj(e){return M(e,!0)?je(BigInt(1)):je(BigInt(0))}var Xj=/^-?(0|[1-9]\d*)n$/,Yj=/^-?(0|[1-9]\d*)\.\d+$/,Zj=/^-?(0|[1-9]\d*)$/;function eU(e){return Xj.test(e)}function tU(e){return Yj.test(e)}function rU(e){return Zj.test(e)}function nU(e){let o=e.toLowerCase();return eU(e)?je(BigInt(e.slice(0,e.length-1))):tU(e)?je(BigInt(e.split(".")[0])):rU(e)?je(BigInt(e)):M(o,"false")?je(BigInt(0)):M(o,"true")?je(BigInt(1)):kr()}function pl(e){return qr(e)?je(e):fn(e)?Qj(e):Ot(e)?je(BigInt(Math.trunc(e))):bo(e)?je(BigInt(0)):lt(e)?nU(e):Bt(e)?je(BigInt(0)):kr()}function oU(e){return M(e,BigInt(0))?je(!1):M(e,BigInt(1))?je(!0):kr()}function sU(e){return M(e,0)?je(!1):M(e,1)?je(!0):kr()}function iU(e){return M(e.toLowerCase(),"false")?je(!1):M(e.toLowerCase(),"true")?je(!0):M(e,"0")?je(!1):M(e,"1")?je(!0):kr()}function mC(e){return qr(e)?oU(e):fn(e)?je(e):Ot(e)?sU(e):bo(e)?je(!1):lt(e)?iU(e):Bt(e)?je(!1):kr()}function aU(e){return M(e,BigInt(0))?je(null):kr()}function uU(e){return M(e,!1)?je(null):kr()}function cU(e){return M(e,0)?je(null):kr()}function mU(e){let o=e.toLowerCase();return M(o,"undefined")||M(o,"null")||M(e,"")||M(e,"0")?je(null):kr()}function pU(e){return qr(e)?aU(e):fn(e)?uU(e):Ot(e)?cU(e):bo(e)?je(null):lt(e)?mU(e):Bt(e)?je(null):kr()}var pC=BigInt(Number.MAX_SAFE_INTEGER),lC=BigInt(Number.MIN_SAFE_INTEGER);function lU(e){return e<=pC&&e>=lC?je(Number(e)):kr()}function dU(e){return je(e?1:0)}function fU(e){let o=+e;if(Ot(o))return je(o);let a=e.toLowerCase();if(M(a,"false"))return je(0);if(M(a,"true"))return je(1);let u=pl(e);if(Io(u))return u.value<=pC&&u.value>=lC?je(Number(u.value)):kr();return kr()}function Mh(e){return qr(e)?lU(e):fn(e)?dU(e):Ot(e)?je(e):bo(e)?je(0):lt(e)?fU(e):Bt(e)?je(0):kr()}function dC(e){return qr(e)?je(e.toString()):fn(e)?je(e.toString()):Ot(e)?je(e.toString()):bo(e)?je("null"):lt(e)?je(e):Bt(e)?je(""):kr()}function hU(e){return M(e,BigInt(0))?je(void 0):kr()}function gU(e){return M(e,!1)?je(void 0):kr()}function yU(e){return M(e,0)?je(void 0):kr()}function xU(e){let o=e.toLowerCase();return M(o,"undefined")||M(o,"null")||M(e,"")||M(e,"0")?je(void 0):kr()}function fC(e){return qr(e)?hU(e):fn(e)?gU(e):Ot(e)?yU(e):bo(e)?je(void 0):lt(e)?xU(e):Bt(e)?je(e):kr()}function hC(e,o,a){return Jj(a).value.map((m)=>Hr(e,o.items,m))}function gC(e,o,a){let u=pl(a);return Io(u)?u.value:a}function yC(e,o,a){let u=mC(a);return Io(u)?u.value:a}function xC(e,o,a){return Hr({...e,...o.$defs},pn(o.$ref),a)}function IC(e,o,a){return Hr(e,Pn(o),a)}function bC(e,o,a){let u=Mh(a);return Io(u)?Math.trunc(u.value):a}function EC(e,o,a){let u=Mo(e,o),m=Pn(u);return Hr(e,m,a)}function IU(e,o,a){let u=pl(a);return Io(u)&&M(o.const,u.value)?u.value:a}function bU(e,o,a){let u=mC(a);return Io(u)&&M(o.const,u.value)?u.value:a}function EU(e,o,a){let u=Mh(a);return Io(u)&&M(o.const,u.value)?u.value:a}function SU(e,o,a){let u=dC(a);return Io(u)&&M(o.const,u.value)?u.value:a}function SC(e,o,a){if(M(o.const,a))return a;return Fx(o)?IU(e,o,a):jx(o)?bU(e,o,a):wm(o)?EU(e,o,a):Tm(o)?SU(e,o,a):jr()}function wC(e,o,a){let u=pU(a);return Io(u)?u.value:a}function TC(e,o,a){let u=Mh(a);return Io(u)?u.value:a}function ll(e,o,a,u){let m=Se(u);for(let[p,f]of o)for(let h of m)if(!p.test(h))u[h]=Hr(e,a,u[h]);return u}function jc(e,o,a){return ln(e)&&Bt(a[o])}function wU(e,o,a){let u=wd(o.properties),m=Se(a);for(let[p,f]of u)for(let h of m){if(!p.test(h)||jc(f,h,a))continue;a[h]=Hr(e,f,a[h])}return pe(o,"additionalProperties")&&at(o.additionalProperties)?ll(e,u,o.additionalProperties,a):a}function RC(e,o,a){return Uo(a)?wU(e,o,a):a}function TU(e,o,a){let u=wd(o.patternProperties),m=Se(a);for(let[p,f]of u)for(let h of m)if(p.test(h))a[h]=Hr(e,f,a[h]);return pe(o,"additionalProperties")&&at(o.additionalProperties)?ll(e,u,o.additionalProperties,a):a}function kC(e,o,a){return Uo(a)?TU(e,o,a):a}function AC(e,o,a){return pe(e,o.$ref)?Hr(e,e[o.$ref],a):a}function PC(e,o,a){let u=dC(a);return Io(u)?u.value:a}function CC(e,o,a){return Hr(e,Pn(o),a)}function $C(e,o,a){if(!Fe(a))return a;for(let u=0;u<Math.min(o.items.length,a.length);u++)a[u]=Hr(e,o.items[u],a[u]);return a}function vC(e,o,a){let u=fC(a);return Io(u)?u.value:a}function MC(e,o,a){if(o.anyOf.some((f)=>Yt(e,f,a)))return a;let p=o.anyOf.map((f)=>Hr(e,f,Gr(a))).find((f)=>Yt(e,o,f));return Bt(p)?a:p}function OC(e,o,a){let u=fC(a);return Io(u)?void 0:a}function Hr(e,o,a){return St(o)?hC(e,o,a):go(o)?gC(e,o,a):Vn(o)?yC(e,o,a):Xt(o)?xC(e,o,a):un(o)?IC(e,o,a):yn(o)?bC(e,o,a):Ge(o)?EC(e,o,a):dt(o)?SC(e,o,a):Ts(o)?wC(e,o,a):Cr(o)?TC(e,o,a):He(o)?RC(e,o,a):Kt(o)?kC(e,o,a):Ft(o)?AC(e,o,a):cn(o)?PC(e,o,a):tr(o)?CC(e,o,a):ct(o)?$C(e,o,a):ss(o)?vC(e,o,a):be(o)?MC(e,o,a):yo(o)?OC(e,o,a):a}function ds(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return Hr(o,a,u)}function _C(e,o,a){if(!Fe(a))return a;for(let u=0;u<a.length;u++)a[u]=En(e,o.items,a[u]);return a}function LC(e,o,a){return En({...e,...o.$defs},pn(o.$ref),a)}function NC(e,o){if(!Bt(o))return o;return gs(e.default)?e.default():Gr(e.default)}function DC(e,o,a){let u=Mo(e,o),m=Pn(u);return En(e,m,a)}function qC(e,o,a){if(!at(a))return a;let u=Se(o.properties);for(let m of u){let p=En(e,o.properties[m],a[m]);if(Bt(p)&&(ln(o.properties[m])||!pe(o.properties[m],"default")))continue;a[m]=p}if(!Oo(o)||fn(o.additionalProperties))return a;for(let m of Se(a)){if(u.includes(m))continue;a[m]=En(e,o.additionalProperties,a[m])}return a}function FC(e,o,a){if(!at(a))return a;let[u,m]=[new RegExp(xn(o)),or(o)];for(let p of Se(a)){if(!(u.test(p)&&To(m)))continue;a[p]=En(e,m,a[p])}if(!Oo(o))return a;for(let p of Se(a)){if(u.test(p))continue;a[p]=En(e,o.additionalProperties,a[p])}return a}function jC(e,o,a){return pe(e,o.$ref)?En(e,e[o.$ref],a):a}function UC(e,o,a){if(!Fe(a))return a;let[u,m]=[o.items,Math.max(o.items.length,a.length)];for(let p=0;p<m;p++)if(p<u.length)a[p]=En(e,u[p],a[p]);return a}function BC(e,o,a){for(let u of o.anyOf){let m=En(e,u,Gr(a));if(Yt(e,u,m))return m}return a}function En(e,o,a){let u=To(o)?NC(o,a):a;return St(o)?_C(e,o,u):Xt(o)?LC(e,o,u):Ge(o)?DC(e,o,u):He(o)?qC(e,o,u):Kt(o)?FC(e,o,u):Ft(o)?jC(e,o,u):ct(o)?UC(e,o,u):be(o)?BC(e,o,u):u}function zs(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return En(o,a,u)}function uu(e){return(...o)=>{let[a,u,m]=kn(o,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return e.reduce((p,f)=>f(a,u,p),m)}}function RU(e,o,a){return o["~codec"].decode(a)}function kU(e,o,a){return o["~codec"].encode(a)}function Ar(e,o,a,u){if(!Kn(a))return u;return M(e,"Decode")?RU(o,a,u):kU(o,a,u)}function AU(e,o,a,u){if(!Fe(u))return u;for(let m=0;m<u.length;m++)u[m]=vr(e,o,a.items,u[m]);return Ar(e,o,a,u)}function PU(e,o,a,u){let m=Ar(e,o,a,u);if(!Fe(m))return m;for(let p=0;p<m.length;p++)m[p]=vr(e,o,a.items,m[p]);return m}function GC(e,o,a,u){return M(e,"Decode")?AU(e,o,a,u):PU(e,o,a,u)}function KC(e,o,a,u){return u=vr(e,{...o,...a.$defs},pn(a.$ref),u),Ar(e,o,a,u)}function HC(e){return e.reduce((o,a)=>({...o,...a}),{})}function WC(e,o){for(let a of o)if(!$a(e,a))return a;return e}function CU(e,o,a,u){if(M(a.allOf.length,0))return Ar(e,o,a,u);let m=a.allOf.map((h)=>vr(e,o,h,Lo(h,Gr(u)))),f=m.every((h)=>at(h))?HC(m):WC(u,m);return Ar(e,o,a,f)}function $U(e,o,a,u){if(M(a.allOf.length,0))return Ar(e,o,a,u);let m=Ar(e,o,a,u),p=a.allOf.map((h)=>vr(e,o,h,Lo(h,Gr(m))));if(p.every((h)=>at(h)))return HC(p);return WC(m,p)}function zC(e,o,a,u){return M(e,"Decode")?CU(e,o,a,u):$U(e,o,a,u)}function vU(e,o,a,u){if(!Uo(u))return u;for(let m of Se(a.properties)){if(!pe(u,m)||jc(a.properties[m],m,u))continue;u[m]=vr(e,o,a.properties[m],u[m])}return Ar(e,o,a,u)}function MU(e,o,a,u){let m=Ar(e,o,a,u);if(!Uo(m))return m;for(let p of Se(a.properties)){if(!pe(m,p)||jc(a.properties[p],p,m))continue;m[p]=vr(e,o,a.properties[p],m[p])}return m}function VC(e,o,a,u){return M(e,"Decode")?vU(e,o,a,u):MU(e,o,a,u)}function OU(e,o,a,u){if(!Uo(u))return u;let m=new RegExp(xn(a));for(let p of Se(u)){if(!m.test(p))continue;u[p]=vr(e,o,or(a),u[p])}return Ar(e,o,a,u)}function _U(e,o,a,u){let m=Ar(e,o,a,u);if(!Uo(m))return m;let p=new RegExp(xn(a));for(let f of Se(m)){if(!p.test(f))continue;m[f]=vr(e,o,or(a),m[f])}return m}function JC(e,o,a,u){return M(e,"Decode")?OU(e,o,a,u):_U(e,o,a,u)}function QC(e,o,a,u){return pe(o,a.$ref)?vr(e,o,o[a.$ref],u):u}function XC(e,o,a,u){return M(e,"Decode")?Ar(e,o,a,QC(e,o,a,u)):QC(e,o,a,Ar(e,o,a,u))}function LU(e,o,a,u){if(!Fe(u))return u;for(let m=0;m<Math.min(a.items.length,u.length);m++)u[m]=vr(e,o,a.items[m],u[m]);return Ar(e,o,a,u)}function NU(e,o,a,u){let m=Ar(e,o,a,u);if(!Fe(m))return u;for(let p=0;p<Math.min(a.items.length,m.length);p++)m[p]=vr(e,o,a.items[p],m[p]);return m}function YC(e,o,a,u){return M(e,"Decode")?LU(e,o,a,u):NU(e,o,a,u)}function DU(e,o,a,u){for(let m of a.anyOf){if(!Yt(o,m,u))continue;let p=vr(e,o,m,u);return Ar(e,o,a,p)}return u}function qU(e,o,a,u){let m=Ar(e,o,a,u);for(let p of a.anyOf){let f=vr(e,o,p,Gr(m));if(!Yt(o,p,f))continue;return f}return m}function ZC(e,o,a,u){return M(e,"Decode")?DU(e,o,a,u):qU(e,o,a,u)}function vr(e,o,a,u){return St(a)?GC(e,o,a,u):Xt(a)?KC(e,o,a,u):Ge(a)?zC(e,o,a,u):He(a)?VC(e,o,a,u):Kt(a)?JC(e,o,a,u):Ft(a)?XC(e,o,a,u):ct(a)?YC(e,o,a,u):be(a)?ZC(e,o,a,u):Ar(e,o,a,u)}class e0 extends ba{constructor(e,o){super("Decode",e,o)}}function FU(e,o,a){if(!Yt(e,o,a))throw new e0(a,Ms(e,o,a));return a}function jU(e,o,a){let u=Bo().unionPrioritySort?au(o):o;return vr("Decode",e,u,a)}var UU=uu([(e,o,a)=>Gr(a),(e,o,a)=>zs(e,o,a),(e,o,a)=>ds(e,o,a),(e,o,a)=>Lo(e,o,a),(e,o,a)=>FU(e,o,a),(e,o,a)=>jU(e,o,a)]);function Oh(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return UU(o,a,u)}class t0 extends ba{constructor(e,o){super("Encode",e,o)}}function BU(e,o,a){if(!Yt(e,o,a))throw new t0(a,Ms(e,o,a));return a}function GU(e,o,a){let u=Bo().unionPrioritySort?au(o):o;return vr("Encode",e,u,a)}var KU=uu([(e,o,a)=>Gr(a),(e,o,a)=>GU(e,o,a),(e,o,a)=>zs(e,o,a),(e,o,a)=>ds(e,o,a),(e,o,a)=>Lo(e,o,a),(e,o,a)=>BU(e,o,a)]);function _h(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return KU(o,a,u)}function HU(e,o){return Kn(o)||Ri(e,o.items)}function WU(e,o){return Kn(o)||r0({...e,...o.$defs},pn(o.$ref))}function zU(e,o){return Kn(o)||o.allOf.some((a)=>Ri(e,a))}function VU(e,o){return Kn(o)||Se(o.properties).some((a)=>Ri(e,o.properties[a]))}function JU(e,o){return Kn(o)||Ri(e,or(o))}function r0(e,o){if(Lh.has(o.$ref))return!1;return Lh.add(o.$ref),Kn(o)||pe(e,o.$ref)&&Ri(e,e[o.$ref])}function QU(e,o){return Kn(o)||o.items.some((a)=>Ri(e,a))}function XU(e,o){return Kn(o)||o.anyOf.some((a)=>Ri(e,a))}function Ri(e,o){return St(o)?HU(e,o):Xt(o)?WU(e,o):Ge(o)?zU(e,o):He(o)?VU(e,o):Kt(o)?JU(e,o):Ft(o)?r0(e,o):ct(o)?QU(e,o):be(o)?XU(e,o):Kn(o)}var Lh=new Set;function Nh(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Lh.clear(),Ri(o,a)}class fs extends Error{constructor(e,o){super(o);this.type=e}}function n0(e,o){return gs(o.default)?o.default(o):at(o.default)?Gr(o.default):o.default}function o0(e,o){if(bi(o)&&!To(o))throw new fs(o,"Arrays with uniqueItems constraints must specify a default annotation");let a=Ii(o)?o.minItems:0;return Array.from({length:a},()=>Wr(e,o.items))}function s0(e,o){return is(o)?BigInt(o.exclusiveMinimum)+BigInt(1):as(o)?BigInt(o.minimum):BigInt(0)}function i0(e,o){return!1}function a0(e,o){let a=Wr(e,o.instanceType);return class{constructor(){Object.assign(this,a)}}}function u0(e,o){return Wr({...e,...o.$defs},pn(o.$ref))}function c0(e,o){return Wr(e,Pn(o))}function m0(e,o){let a=Wr(e,o.returnType);return()=>a}function p0(e,o){return is(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:as(o)?o.minimum:0}function l0(e,o){let a=Mo(e,o),u=Pn(a);return Wr(e,u)}function d0(e,o){return o.const}function f0(e,o){throw new fs(o,"Cannot create TNever types")}function h0(e,o){return null}function g0(e,o){return is(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:as(o)?o.minimum:0}function y0(e,o){return(Bt(o.required)?[]:o.required).reduce((u,m)=>({...u,[m]:Wr(e,o.properties[m])}),{})}function x0(e,o){if(xa(o)&&!To(o))throw new fs(o,"Record with the minProperties constraint must have a default annotation");return{}}function I0(e,o){return pe(e,o.$ref)?Wr(e,e[o.$ref]):(()=>{throw new fs(o,"Unable to deref Ref")})()}function b0(e,o){if((Ia(o)||ga(o))&&!To(o))throw Error("Strings with format or pattern constraints must specify default");let u=ya(o)?o.minLength:0;return"".padEnd(u)}function E0(e,o){return Symbol()}function S0(e,o){let a=qu(o.pattern);if(cn(a))throw new fs(o,"Unable to create TemplateLiteral due to infinite type expansion");return Wr(e,a)}function w0(e,o){return Array.from({length:o.minItems},(a,u)=>Wr(e,o.items[u]))}function T0(e,o){return}function R0(e,o){if(M(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Wr(e,o.anyOf[0])}function k0(e,o){return}function Wr(e,o){return To(o)?n0(e,o):St(o)?o0(e,o):go(o)?s0(e,o):Vn(o)?i0(e,o):zr(o)?a0(e,o):Xt(o)?u0(e,o):un(o)?c0(e,o):en(o)?m0(e,o):yn(o)?p0(e,o):Ge(o)?l0(e,o):dt(o)?d0(e,o):ho(o)?f0(e,o):Ts(o)?h0(e,o):Cr(o)?g0(e,o):He(o)?y0(e,o):Kt(o)?x0(e,o):Ft(o)?I0(e,o):cn(o)?b0(e,o):Rs(o)?E0(e,o):tr(o)?S0(e,o):ct(o)?w0(e,o):ss(o)?T0(e,o):be(o)?R0(e,o):yo(o)?k0(e,o):void 0}function Os(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Wr(o,a)}class dl extends ba{constructor(e,o){super("Parse",e,o)}}function YU(e,o,a){if(!Yt(e,o,a))throw new dl(a,Ms(e,o,a));return a}var A0=uu([(e,o,a)=>Gr(a),(e,o,a)=>zs(e,o,a),(e,o,a)=>ds(e,o,a),(e,o,a)=>Lo(e,o,a),(e,o,a)=>YU(e,o,a)]);var eB=l({type:i("insert"),path:s(),value:Pr()}),tB=Object({type:i("update"),path:s(),value:Pr()}),rB=l({type:i("delete"),path:s()}),q_e=g([eB,tB,rB]);class fl{constructor(e,o){this.hasCodec=Nh(e,o),this.buildResult=ul(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(Bo().correctiveParse)return A0(this.Context(),this.Type(),e);throw new dl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Ms(this.Context(),this.Type(),e)}Clean(e){return Lo(this.Context(),this.Type(),e)}Convert(e){return ds(this.Context(),this.Type(),e)}Create(){return Os(this.Context(),this.Type())}Default(e){return zs(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Oh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?_h(this.Context(),this.Type(),e):this.Parse(e)}}function qh(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return new fl(o,a)}var C0=new WeakMap,sB=Symbol.for("TypeBox.Kind");function iB(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function aB(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 Fh(e){try{return v0(e)}catch{return}}function uB(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isFinite(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isInteger(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function cB(e,o){let a=o.properties,u=new Set(a?Object.keys(a):[]);if(a)for(let[m,p]of Object.entries(a)){if(!(m in e))continue;e[m]=Sa(e[m],p)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[m,p]of Object.entries(e)){if(u.has(m))continue;e[m]=Sa(p,o.additionalProperties)}}function mB(e,o){if(Array.isArray(o.items)){for(let a=0;a<e.length;a++){let u=o.items[a];if(!u)continue;e[a]=Sa(e[a],u)}return}if(o.items&&typeof o.items==="object")for(let a=0;a<e.length;a++)e[a]=Sa(e[a],o.items)}function $0(e,o){for(let a of o)if(Fh(a)?.Check(e))return e;for(let a of o){let u=structuredClone(e),m=Sa(u,a);if(Fh(a)?.Check(m))return m}return e}function Sa(e,o){let a=e;if(Array.isArray(o.allOf))for(let p of o.allOf)a=Sa(a,p);if(Array.isArray(o.anyOf))a=$0(a,o.anyOf);if(Array.isArray(o.oneOf))a=$0(a,o.oneOf);let u=iB(o),m=u.length>1&&u.some((p)=>aB(a,p));if(u.length>0&&!m)for(let p of u){let f=uB(a,p);if(f!==a){a=f;break}}if(u.includes("object")&&typeof a==="object"&&a!==null&&!Array.isArray(a))cB(a,o);if(u.includes("array")&&Array.isArray(a))mB(a,o);return a}function hl(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let m=0;m<e.length;m++){let p=o.items[m];if(p)hl(e[m],p)}else if(o.items)for(let m of e)hl(m,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let a=e,u=new Set(o.required??[]);for(let[m,p]of Object.entries(o.properties)){if(!(m in a))continue;if(a[m]===null&&!u.has(m)&&typeof p.$ref!=="string"&&Fh(p)?.Check(null)===!1)delete a[m];else hl(a[m],p)}}function v0(e){let o=e,a=C0.get(o);if(a)return a;let u=qh(e);return C0.set(o,u),u}function pB(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let m=e.instancePath.replace(/^\//,"").replace(/\//g,".");return m?`${m}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function lB(e,o){let a=e.find((u)=>u.name===o.name);if(!a)throw Error(`Tool "${o.name}" not found`);return cu(a,o)}function cu(e,o){let a=structuredClone(o.arguments);hl(a,e.parameters),ds(e.parameters,a);let u=v0(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(sB)){let f=Sa(a,e.parameters);if(f!==a)if(typeof a==="object"&&a!==null&&typeof f==="object"&&f!==null){for(let h of Object.keys(a))delete a[h];Object.assign(a,f)}else return u.Check(f)?f:a}if(u.Check(a))return a;let m=u.Errors(a).map((f)=>` - ${pB(f)}: ${f.message}`).join(`
32
+ `);return JR(e,a)+fF(u(e),u(o))}function fF(e,o){let a=Math.min(e.length,o.length),u=0;while(u<a&&e[u]===o[u])u++;return u}function UR(e,o,a,u){let m=o.messages.map((k)=>`${k.role}:${lF(k)}`),p=JR(m),f=Math.ceil(p/4),h=WR(VR(e.content)),I=f,E=0,S=0,R=a?.sessionId;if(R&&a?.cacheRetention!=="none"){let k=u.get(R);if(k){let P=dF(k,m);E=Math.ceil(P/4),S=Math.ceil((p-P)/4),I=Math.max(0,f-E)}else S=f;u.set(R,m)}return{...e,usage:{input:I,output:h,cacheRead:E,cacheWrite:S,totalTokens:I+h+E+S,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function qf(e,o,a){let u=[],m=0;while(m<e.length){let p=o+Math.floor(Math.random()*(a-o+1)),f=Math.max(1,p*4);u.push(e.slice(m,m+f)),m+=f}return u.length>0?u:[""]}function hF(e,o,a,u){let m=structuredClone(e);return{...m,api:o,provider:a,model:u,timestamp:m.timestamp??Date.now(),usage:m.usage??Sp}}function BR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:Sp,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function bp(e,o,a,u){return{role:"assistant",content:[],api:o,provider:a,model:u,usage:Sp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function cc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Ff(e,o){if(!o||o<=0)return new Promise((u)=>queueMicrotask(u));let a=WR(e)/o*1000;return new Promise((u)=>setTimeout(u,a))}async function Ep(e,o,a,u,m,p){let f={...o,content:[],stopReason:"pending"};if(p?.aborted){let h=cc(f);e.push({type:"error",reason:"aborted",error:h}),e.end(h);return}e.push({type:"start",partial:{...f}});for(let h=0;h<o.content.length;h++){if(p?.aborted){let E=cc(f);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}let I=o.content[h];if(I.type==="thinking"){f.content=[...f.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:h,partial:{...f}});for(let E of qf(I.thinking,a,u)){if(await Ff(E,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}f.content[h].thinking+=E,e.push({type:"thinking_delta",contentIndex:h,delta:E,partial:{...f}})}e.push({type:"thinking_end",contentIndex:h,content:I.thinking,partial:{...f}});continue}if(I.type==="text"){f.content=[...f.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:h,partial:{...f}});for(let E of qf(I.text,a,u)){if(await Ff(E,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}f.content[h].text+=E,e.push({type:"text_delta",contentIndex:h,delta:E,partial:{...f}})}e.push({type:"text_end",contentIndex:h,content:I.text,partial:{...f}});continue}f.content=[...f.content,{type:"toolCall",id:I.id,name:I.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:h,partial:{...f}});for(let E of qf(JSON.stringify(I.arguments),a,u)){if(await Ff(E,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}e.push({type:"toolcall_delta",contentIndex:h,delta:E,partial:{...f}})}f.content[h].arguments=I.arguments,e.push({type:"toolcall_end",contentIndex:h,toolCall:I,partial:{...f}})}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 QR(e){let o=e.api??jf(GR),a=e.provider??KR,u=Math.max(1,Math.min(e.tokenSize?.min??uF,e.tokenSize?.max??jR)),m=Math.max(u,e.tokenSize?.max??jR),p=[],f=e.tokensPerSecond,h={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},I=new Map,E=new Map,R=((e.models?.length)?e.models:[{id:HR,name:iF,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:a,baseUrl:aF,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),k=async(V,J,Z,ne)=>{let z=typeof V==="function"?await V(J,Z,h,ne):V;return UR(hF(z,o,a,ne.id),J,Z,I)},P=(V,J,Z)=>{let ne=ao(),z=p.shift();return h.callCount++,queueMicrotask(async()=>{try{if(await Z?.onResponse?.({status:200,headers:{}},V),!z){let fe=bp(Error("No more faux responses queued"),o,a,V.id);fe=UR(fe,J,Z,I),ne.push({type:"error",reason:"error",error:fe}),ne.end(fe);return}if(Z?.deferred){let fe={provider:V.provider,modelId:V.id,api:V.api,id:jf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};E.set(fe.id,{handle:fe,step:z,context:J,options:Z,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await Ep(ne,BR(V,fe),u,m,f,Z.signal);return}let oe=await k(z,J,Z,V);await Ep(ne,oe,u,m,f,Z?.signal)}catch(oe){let fe=bp(oe,o,a,V.id);ne.push({type:"error",reason:"error",error:fe}),ne.end(fe)}}),ne},v=(V,J,Z)=>P(V,J,Z),_=(V,J,Z)=>{let ne=ao();return h.deferredFetchCount++,queueMicrotask(async()=>{try{await Z?.onResponse?.({status:200,headers:{}},V);let z=E.get(J.id);if(!z||z.handle.provider!==J.provider||z.handle.modelId!==J.modelId||z.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(z.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(z.pendingFetches>0){z.pendingFetches--,await Ep(ne,BR(V,z.handle),u,m,f,Z?.signal);return}if(!z.final){let{deferred:oe,signal:fe,onResponse:Ae,...Ge}=z.options??{};try{z.final=await k(z.step,z.context,Ge,z.model)}catch(ee){z.final=bp(ee,o,a,z.model.id)}}await Ep(ne,z.final,u,m,f,Z?.signal)}catch(z){let oe=bp(z,o,a,V.id);ne.push({type:"error",reason:"error",error:oe}),ne.end(oe)}}),ne},Q=async(V,J,Z)=>{h.cancelledDeferred.push(structuredClone(J));let ne=E.get(J.id);if(ne)ne.cancelled=!0;await Z?.onResponse?.({status:200,headers:{}},V)};function L(V){if(!V)return R[0];return R.find((J)=>J.id===V)}return{api:o,provider:a,models:R,stream:P,streamSimple:v,fetchDeferred:_,cancelDeferred:Q,getModel:L,state:h,setResponses(V){p=[...V]},appendResponses(V){p.push(...V)},getPendingResponseCount(){return p.length}}}function Ko(e={}){let o=QR(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 gF(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function yF(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function xF(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 IF(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 mc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Xa(e){mc(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 Bf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var bF=Bf(G(""));function Gf(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,m)=>Gf(u,o[m]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let a=o;return Object.entries(e).every(([u,m])=>Object.hasOwn(a,u)&&Gf(m,a[u]))}class XR{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:IF(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=Xa(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:gF(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Xa(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=Xa(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:yF(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Xa(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=Xa(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let a=Bf(o.arguments),u=a===bF;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":a}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:xF(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let a=G(o.catchupJson);if(Bf(a)!==o.snapshotArguments){let m=G(o.snapshotArguments);if(!Gf(m,a))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=Xa(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(mc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){mc(e);let a=this.blocks.get(e);if(a===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(a.kind!==o)throw Error(`Assistant message block ${e} is ${a.kind}, not ${o}`);return a}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,a){let u=this.block(e,a);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let m=u.deltaChars;u.deltaChars+=o.length;let p=Math.max(0,u.coveredChars-m);if(p>=o.length)return;let f=p===0?o:o.slice(p);return a==="text"?{type:"text_delta",contentIndex:e,delta:f}:{type:"thinking_delta",contentIndex:e,delta:f}}}function Uf(e,o,a,u,m){if(mc(a),a!==e.content.length){let p=a<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${a}: ${p}`)}e.content.push(structuredClone(u)),o.set(a,m)}function fa(e,o,a,u,m){mc(a);let p=o.get(a),f=e.content[a];if(!p||!f)throw Error(`${m} frame has no started block at index ${a}`);if(p.kind!==u||f.type!==u)throw Error(`${m} frame expected ${u} block at index ${a}, found ${f.type}`);if(p.ended)throw Error(`${m} frame follows the end of block at index ${a}`);return{block:f,state:p}}function EF(e){let o,a,u=new Map;for(let m of e){if(m.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(a!==void 0)throw Error(`${a} frame appears before the start frame`);o=structuredClone(m.partial);continue}if(!o){a??=m.type;continue}switch(m.type){case"text_start":if(m.content.type!=="text")throw Error(`text_start frame contains ${m.content.type} content`);Uf(o,u,m.contentIndex,m.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:p}=fa(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");p.text+=m.delta;break}case"text_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");if(p.text=m.content,delete p.textSignature,m.textSignature!==void 0)p.textSignature=m.textSignature;f.ended=!0;break}case"thinking_start":if(m.content.type!=="thinking")throw Error(`thinking_start frame contains ${m.content.type} content`);Uf(o,u,m.contentIndex,m.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:p}=fa(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");p.thinking+=m.delta;break}case"thinking_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");if(p.thinking=m.content,delete p.thinkingSignature,delete p.redacted,m.thinkingSignature!==void 0)p.thinkingSignature=m.thinkingSignature;if(m.redacted!==void 0)p.redacted=m.redacted;f.ended=!0;break}case"toolcall_start":if(m.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${m.toolCall.type} content`);Uf(o,u,m.contentIndex,m.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");f.json=m.json,p.arguments=G(m.json);break}case"toolcall_delta":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call frame state");f.json+=m.delta;break}case"toolcall_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(p.id=m.id,p.name=m.name,p.arguments=structuredClone(m.arguments),delete p.thoughtSignature,delete p.namespace,m.thoughtSignature!==void 0)p.thoughtSignature=m.thoughtSignature;if(m.namespace!==void 0)p.namespace=m.namespace;f.ended=!0;break}}}if(!o)return;for(let[m,p]of u){if(p.kind!=="toolCall"||p.ended||p.json.length===0)continue;let f=o.content[m];if(f?.type!=="toolCall")throw Error("Unreachable tool-call frame state");f.arguments=G(p.json)}return o}var YR=[/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],SF=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,wF=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ha(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!wF.some((u)=>u.test(e.errorMessage))){if(YR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&SF.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 TF(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function RF(){return[...YR]}function ZR(e){return new RegExp(e.join("|"),"i")}var kF=ZR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),AF=ZR(["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"]),ek=60000;function tk(e,o){let a=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??ek)}class wp extends Error{constructor(){super("Aborted")}}function PF(e,o){return new Promise((a,u)=>{if(o?.aborted){u(new wp);return}let m=setTimeout(a,e);o?.addEventListener("abort",()=>{clearTimeout(m),u(new wp)},{once:!0})})}async function CF(e,o,a,u){let m=o?.enabled?o.maxRetries:0,p=0,f;for(;;){let h=await e();if(h.stopReason==="aborted"){if(f)await u?.onRetryFinished?.(!1,f.attempt);return h}if(h.stopReason!=="error"){if(f)await u?.onRetryFinished?.(!0,f.attempt);return h}if(p>=m||!rk(h)){if(f)await u?.onRetryFinished?.(!1,f.attempt,h.errorMessage);return h}p++,f={attempt:p,errorMessage:h.errorMessage||"Unknown error"};let I=tk(o,p);await u?.onRetryScheduled?.(p,m,I,f.errorMessage);try{await PF(I,a)}catch(E){if(await u?.onRetryFinished?.(!1,p,f.errorMessage),E instanceof wp){let{errorMessage:S,...R}=h;return{...R,stopReason:"aborted"}}throw E}await u?.onRetryAttemptStart?.()}}function rk(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(kF.test(o))return!1;return AF.test(o)}function $F(e,o){return sr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function pc(e){return pe(e,"~refine")&&qe(e["~refine"])&&mn(e["~refine"],0,(o)=>ut(o)&&pe(o,"check")&&pe(o,"error")&&gs(o.check)&&gs(o.error))}function In(e){return ut(e)&&!qe(e)}function js(e){return fn(e)}function Ye(e){return In(e)||js(e)}function Ya(e){return pe(e,"additionalItems")&&Ye(e.additionalItems)}function Oo(e){return pe(e,"additionalProperties")&&Ye(e.additionalProperties)}function lc(e){return pe(e,"allOf")&&qe(e.allOf)&&e.allOf.every((o)=>Ye(o))}function dc(e){return pe(e,"$anchor")&&dt(e.$anchor)}function fc(e){return pe(e,"anyOf")&&qe(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function Tp(e){return pe(e,"const")}function vs(e){return pe(e,"contains")&&Ye(e.contains)}function To(e){return pe(e,"default")}function hc(e){return pe(e,"dependencies")&&ut(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||qe(o)&&o.every((a)=>dt(a)))}function gc(e){return pe(e,"dependentRequired")&&ut(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>qe(o)&&o.every((a)=>dt(a)))}function Za(e){return pe(e,"dependentSchemas")&&ut(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function Us(e){return pe(e,"$dynamicAnchor")&&dt(e.$dynamicAnchor)}function yc(e){return pe(e,"$dynamicRef")&&dt(e.$dynamicRef)}function xc(e){return pe(e,"else")&&Ye(e.else)}function Rp(e){return pe(e,"enum")&&qe(e.enum)}function Ic(e){return pe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||qr(e.exclusiveMaximum))}function is(e){return pe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||qr(e.exclusiveMinimum))}function ga(e){return pe(e,"format")&&dt(e.format)}function Ro(e){return pe(e,"$id")&&dt(e.$id)}function bc(e){return pe(e,"if")&&Ye(e.if)}function Bs(e){return pe(e,"items")&&(Ye(e.items)||qe(e.items)&&e.items.every((o)=>Ye(o)))}function Ec(e){return Bs(e)&&qe(e.items)}function Sc(e){return pe(e,"maximum")&&(Ot(e.maximum)||qr(e.maximum))}function wc(e){return pe(e,"maxContains")&&Ot(e.maxContains)}function eu(e){return pe(e,"maxItems")&&Ot(e.maxItems)}function Tc(e){return pe(e,"maxLength")&&Ot(e.maxLength)}function Rc(e){return pe(e,"maxProperties")&&Ot(e.maxProperties)}function as(e){return pe(e,"minimum")&&(Ot(e.minimum)||qr(e.minimum))}function Gs(e){return pe(e,"minContains")&&Ot(e.minContains)}function Ii(e){return pe(e,"minItems")&&Ot(e.minItems)}function ya(e){return pe(e,"minLength")&&Ot(e.minLength)}function xa(e){return pe(e,"minProperties")&&Ot(e.minProperties)}function kc(e){return pe(e,"multipleOf")&&(Ot(e.multipleOf)||qr(e.multipleOf))}function Ac(e){return pe(e,"not")&&Ye(e.not)}function Pc(e){return pe(e,"oneOf")&&qe(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function Ia(e){return pe(e,"pattern")&&(dt(e.pattern)||e.pattern instanceof RegExp)}function Ks(e){return pe(e,"patternProperties")&&ut(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function us(e){return pe(e,"prefixItems")&&qe(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function Hs(e){return pe(e,"properties")&&ut(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function tu(e){return pe(e,"propertyNames")&&(ut(e.propertyNames)||Ye(e.propertyNames))}function vF(e){return pe(e,"$recursiveAnchor")&&fn(e.$recursiveAnchor)}function Cc(e){return vF(e)&&M(e.$recursiveAnchor,!0)}function $c(e){return pe(e,"$recursiveRef")&&dt(e.$recursiveRef)}function vc(e){return pe(e,"$ref")&&dt(e.$ref)}function cs(e){return pe(e,"required")&&qe(e.required)&&e.required.every((o)=>dt(o))}function Mc(e){return pe(e,"then")&&Ye(e.then)}function Oc(e){return pe(e,"type")&&(dt(e.type)||qe(e.type)&&e.type.every((o)=>dt(o)))}function bi(e){return pe(e,"uniqueItems")&&fn(e.uniqueItems)}function Ei(e){return pe(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function Si(e){return pe(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function MF(e){return Ei(e)||Si(e)||Ca(Ee(e),(o)=>kp(e[o]))}function OF(e){return Ca(e,(o)=>kp(o))}function kp(e){return qe(e)?OF(e):ut(e)?MF(e):!1}function nk(e,o){return kp(o)||Ca(Ee(e),(a)=>kp(e[a]))}class Kf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Er(It("context","Push"),[])}Pop(){return Er(It("context","Pop"),[])}AddIndex(e){return Er(It("context","AddIndex"),[e])}AddKey(e){return Er(It("context","AddKey"),[e])}Merge(e){return Er(It("context","Merge"),[e])}}class Nn{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((a)=>this.GetIndices().add(a)),o.GetKeys().forEach((a)=>this.GetKeys().add(a));return!0}}class Dn extends Nn{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Bo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var Ap={identifier:"External",variables:[]};function _o(e){let o=`External[${Ap.variables.length}]`;return Ap.variables.push(e),o}function ok(){Ap.variables=[]}function sk(){return{...Ap}}function ik(e,o,a,u){let m=_o(a["~refine"].map((p)=>p));return xs(m,Pe(0),["refinement","_"],Er(It("refinement","check"),[u]))}function ak(e,o,a,u){return mn(a["~refine"],0,(m,p)=>m.check(u))}function uk(e,o,a,u,m,p){return $n(m["~refine"],0,(f,h)=>f.check(p)||o.AddError({keyword:"~refine",schemaPath:a,instancePath:u,params:{index:h,message:f.error(p)}}))}var _F=0;function Jt(){return`var_${_F++}`}function Hf(e){return Bs(e)&&qe(e.items)}function LF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Qn(e,o,a.additionalItems,m),h=kd(p,Pe(a.items.length)),I=o.AddIndex(p);return xs(u,Pe(0),[m,p],br(h,Rn(f,I)))}function NF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Qn(e,o,a.additionalItems,m),h=kd(p,Pe(a.items.length));return xs(u,Pe(0),[m,p],br(h,f))}function ck(e,o,a,u){if(!Hf(a))return Pe(!0);return o.UseUnevaluated()?LF(e,o,a,u):NF(e,o,a,u)}function mk(e,o,a,u){if(!Hf(a))return!0;return mn(u,0,(p,f)=>Pu(f,a.items.length)||ko(e,o,a.additionalItems,p)&&o.AddIndex(f))}function pk(e,o,a,u,m,p){if(!Hf(m))return!0;return mn(p,0,(h,I)=>{let E=`${a}/additionalItems`,S=`${u}/${I}`;return Pu(I,m.items.length)||Ao(e,o,E,S,m.additionalItems,h)&&o.AddIndex(I)})}function ms(e){return new RegExp(e,"u")}function DF(e,o){return!e.UseUnevaluated()&&(M(o,!0)||ut(o)&&M(Ee(o).length,0))}function qF(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Wf(e){let o=[];if(Ks(e))o.push(...Ee(e.patternProperties));if(Hs(e))o.push(...Ee(e.properties).map(qF));return M(o.length,0)?"(?!)":`(${o.join("|")})`}function FF(e,o,a){return cs(o)&&Hs(o)&&!Ks(o)&&M(o.additionalProperties,!1)&&M(Ee(o.properties).length,o.required.length)}function jF(e,o,a){return fo(It(Er(It("Object","getOwnPropertyNames"),[a]),"length"),Pe(o.required.length))}function UF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=_o(ms(Wf(a))),h=Qn(e,o,a.additionalProperties,`${u}[${m}]`),I=Er(It(f,"test"),[m]),E=o.AddKey(m),S=o.UseUnevaluated()?br(I,Rn(h,E)):br(I,h);return xs(Zi(u),Pe(0),[m,p],S)}function lk(e,o,a,u){if(DF(o,a.additionalProperties))return Pe(!0);return FF(o,a,u)?jF(o,a,u):UF(e,o,a,u)}function dk(e,o,a,u){let m=ms(Wf(a));return mn(Ee(u),0,(f,h)=>m.test(f)||ko(e,o,a.additionalProperties,u[f])&&o.AddKey(f))}function fk(e,o,a,u,m,p){let f=ms(Wf(m)),h=[];return $n(Ee(p),0,(E,S)=>{let R=`${a}/additionalProperties`,k=`${u}/${E}`,P=f.test(E)||Ao(e,o,R,k,m.additionalProperties,p[E])&&o.AddKey(E);if(!P)h.push(E);return P})||o.AddError({keyword:"additionalProperties",schemaPath:a,instancePath:u,params:{additionalProperties:h}})}function wi(e,o,a,u,m){let p=Ds("results","[]"),f=a.map((S,R)=>Ds(`context_${R}`,Ad("CheckContext",[]))),h=a.map((S,R)=>Ds(`condition_${R}`,Er(si(["context"],Lt(e,o,S,u)),[`context_${R}`]))),I=a.map((S,R)=>nx(`condition_${R}`,Er(It("results","push"),[`context_${R}`]))),E=dm(Rn(m,o.Merge("results")));return Er(si([],lm([p,...f,...h,...I,E])),[])}function BF(e,o,a,u){return wi(e,o,a.allOf,u,fo(It("results","length"),Pe(a.allOf.length)))}function GF(e,o,a,u){return vn(a.allOf.map((m)=>Lt(e,o,m,u)))}function hk(e,o,a,u){return o.UseUnevaluated()?BF(e,o,a,u):GF(e,o,a,u)}function gk(e,o,a,u){let m=a.allOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return M(m.length,a.allOf.length)&&o.Merge(m)}function yk(e,o,a,u,m,p){let f=[],h=m.allOf.reduce((E,S,R)=>{let k=`${a}/allOf/${R}`,P=new Dn,v=rr(e,P,k,u,S,p);if(!v)f.push(P);return v?[...E,P]:E},[]),I=M(h.length,m.allOf.length)&&o.Merge(h);if(!I)f.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I}function KF(e,o,a,u){return wi(e,o,a.anyOf,u,ex(It("results","length"),Pe(0)))}function HF(e,o,a,u){return Pd(a.anyOf.map((m)=>Lt(e,o,m,u)))}function xk(e,o,a,u){return o.UseUnevaluated()?KF(e,o,a,u):HF(e,o,a,u)}function Ik(e,o,a,u){let m=a.anyOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return ji(m.length,0)&&o.Merge(m)}function bk(e,o,a,u,m,p){let f=[],h=m.anyOf.reduce((E,S,R)=>{let k=new Dn,P=`${a}/anyOf/${R}`,v=rr(e,k,P,u,S,p);if(!v)f.push(k);return v?[...E,k]:E},[]),I=ji(h.length,0)&&o.Merge(h);if(!I)f.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I||o.AddError({keyword:"anyOf",schemaPath:a,instancePath:u,params:{}})}function Ek(e,o,a,u){return a?Pe(!0):Pe(!1)}function zf(e,o,a,u){return a}function Sk(e,o,a,u,m,p){return zf(e,o,m,p)||o.AddError({keyword:"boolean",schemaPath:a,instancePath:u,params:{}})}function wk(e,o,a,u){return Ji(a.const)?fo(u,Pe(a.const)):rx(u,_o(a.const))}function Vf(e,o,a,u){return Ji(a.const)?M(u,a.const):$a(u,a.const)}function Tk(e,o,a,u,m,p){return Vf(e,o,m,p)||o.AddError({keyword:"const",schemaPath:a,instancePath:u,params:{allowedValue:m.const}})}function Rk(e){return!(Gs(e)&&M(e.minContains,0))}function WF(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Un(fo(It(u,"length"),Pe(0))),h=kO(u,[m,p],Rn(Lt(e,o,a.contains,m),o.AddIndex(p)));return Rn(f,h)}function zF(e,o,a,u){let[m]=[Jt()],p=Un(fo(It(u,"length"),Pe(0))),f=RO(u,[m,"_"],Lt(e,o,a.contains,m));return Rn(p,f)}function kk(e,o,a,u){if(!Rk(a))return Pe(!0);return o.UseUnevaluated()?WF(e,o,a,u):zF(e,o,a,u)}function Jf(e,o,a,u){if(!Rk(a))return!0;return!M(u.length,0)&&zy(u,(m,p)=>At(e,o,a.contains,m)&&o.AddIndex(p))}function Ak(e,o,a,u,m,p){return Jf(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:1}})}function Pk(e,o,a,u){let m=fo(It(Zi(u),"length"),Pe(0)),p=vn(hn(a.dependencies).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=Lt(e,o,h,u),S=(R)=>vn(R.map((k)=>ea(u,Pe(k))));return br(I,qe(h)?S(h):E)}));return br(m,p)}function Ck(e,o,a,u){let m=M(Ee(u).length,0),p=mn(hn(a.dependencies),0,([f,h])=>!pe(u,f)||(qe(h)?h.every((I)=>pe(u,I)):At(e,o,h,u)));return m||p}function $k(e,o,a,u,m,p){let f=M(Ee(p).length,0),h=$n(hn(m.dependencies),0,([I,E])=>{let S=`${a}/dependencies/${I}`;return!pe(p,I)||(qe(E)?E.every((R)=>pe(p,R)||o.AddError({keyword:"dependencies",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})):rr(e,o,S,u,E,p))});return f||h}function vk(e,o,a,u){let m=fo(It(Zi(u),"length"),Pe(0)),p=vn(hn(a.dependentRequired).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=vn(h.map((S)=>ea(u,Pe(S))));return br(I,E)}));return br(m,p)}function Mk(e,o,a,u){let m=M(Ee(u).length,0),p=mn(hn(a.dependentRequired),0,([f,h])=>!pe(u,f)||h.every((I)=>pe(u,I)));return m||p}function Ok(e,o,a,u,m,p){let f=M(Ee(p).length,0),h=$n(hn(m.dependentRequired),0,([I,E])=>!pe(p,I)||$n(E,0,(S)=>pe(p,S)||o.AddError({keyword:"dependentRequired",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})));return f||h}function _k(e,o,a,u){let m=fo(It(Zi(u),"length"),Pe(0)),p=vn(hn(a.dependentSchemas).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=Lt(e,o,h,u);return br(I,E)}));return br(m,p)}function Lk(e,o,a,u){let m=M(Ee(u).length,0),p=mn(hn(a.dependentSchemas),0,([f,h])=>!pe(u,f)||At(e,o,h,u));return m||p}function Nk(e,o,a,u,m,p){let f=M(Ee(p).length,0),h=$n(hn(m.dependentSchemas),0,([I,E])=>{let S=`${a}/dependentSchemas/${I}`;return!pe(p,I)||rr(e,o,S,u,E,p)});return f||h}function Dk(e,o,a,u){let m=e.DynamicRef(a)??!1;return Ws(e,o,m,u)}function qk(e,o,a,u){let m=e.DynamicRef(a)??!1;return Ye(m)&&At(e,o,m,u)}function Fk(e,o,a,u,m,p){let f=e.DynamicRef(m)??!1;return Ye(f)&&rr(e,o,"#",u,f,p)}function jk(e,o,a,u){return Pd(a.enum.map((m)=>{if(Ji(m))return fo(u,Pe(m));let p=_o(m);return rx(u,p)}))}function Xf(e,o,a,u){return Ca(a.enum,(m)=>Ji(m)?M(u,m):$a(u,m))}function Uk(e,o,a,u,m,p){return Xf(e,o,m,p)||o.AddError({keyword:"enum",schemaPath:a,instancePath:u,params:{allowedValues:m.enum}})}function Bk(e,o,a,u){return kd(u,Pe(a.exclusiveMaximum))}function Yf(e,o,a,u){return Pu(u,a.exclusiveMaximum)}function Gk(e,o,a,u,m,p){return Yf(e,o,m,p)||o.AddError({keyword:"exclusiveMaximum",schemaPath:a,instancePath:u,params:{comparison:"<",limit:m.exclusiveMaximum}})}function Kk(e,o,a,u){return ex(u,Pe(a.exclusiveMinimum))}function Zf(e,o,a,u){return ji(u,a.exclusiveMinimum)}function Hk(e,o,a,u,m,p){return Zf(e,o,m,p)||o.AddError({keyword:"exclusiveMinimum",schemaPath:a,instancePath:u,params:{comparison:">",limit:m.exclusiveMinimum}})}var VF=[0,31,28,31,30,31,30,31,31,30,31,30,31],JF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function QF(e){return e%4===0&&(e%100!==0||e%400===0)}function nu(e){let o=JF.exec(e);if(!o)return!1;let a=+o[1],u=+o[2],m=+o[3];return u>=1&&u<=12&&m>=1&&m<=(u===2&&QF(a)?29:VF[u])}var XF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function ou(e,o=!0){let a=XF.exec(e);if(!a)return!1;if(o&&!a[4]&&!a[5])return!1;let u=+a[1],m=+a[2],p=+a[3];if(u>23||m>59||p>60)return!1;if(a[5]){let S=+a[6],R=+a[7];if(S>23||R>59)return!1}if(p<60)return!0;let f=a[5]==="-"?-1:1,h=+(a[6]||0),I=+(a[7]||0);return((u*60+m-f*(h*60+I))%1440+1440)%1440===1439}function Pp(e){let o=e.split(/T/i);return o.length===2&&nu(o[0])&&ou(o[1])}var YF=/^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 Cp(e){return YF.test(e)}var ZF=/^(?:[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 $p(e){return ZF.test(e)}var Wk=/^(?!-).*(?<!-)$/,zk=/^(?!..--)/,Vk=/^[a-zA-Z0-9-]*$/;var su=/[^\p{ASCII}]/u;var e1=/[0-9]/,Jk=/[\u{0660}-\u{0669}]/u,t1=/[\u{06f0}-\u{06f9}]/u,r1=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,n1=/[\u{002d}\u{002b}]/u,eh=/\p{Mn}/u,o1=/\p{Mc}/u;var Qk=/[\p{Mn}\p{Mc}\p{Me}]/u,th=/\p{L}/u,s1=/\p{Nd}/u,Xk=/\p{Script=Greek}/u,vp=/\p{Script=Hebrew}/u,Yk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Zk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,rh=/[\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,eA=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,i1=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,a1=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,tA=new RegExp([e1,t1].map((e)=>e.source).join("|"),"u"),rA=new RegExp([th,n1,r1,s1,eh,o1,i1,a1].map((e)=>e.source).join("|"),"u");function nA(e){return Wk.test(e)&&zk.test(e)&&Vk.test(e)}var ps=36,Lc=1,Nc=26,c1=38,m1=700,sA=72,iA=128;function nh(){throw null}function Mp(e){return e.toLowerCase().startsWith("xn--")}function aA(e,o,a){e=a?Math.floor(e/m1):e>>1,e+=Math.floor(e/o);let u=0;while(e>(ps-Lc)*Nc>>1)e=Math.floor(e/(ps-Lc)),u+=ps;return u+Math.floor((ps-Lc+1)*e/(e+c1))}function Op(e){let o=[],a=iA,u=0,m=sA,p=e.lastIndexOf("-");if(p>0)for(let h=0;h<p;h++){let I=e.charCodeAt(h);if(I>=128)nh();o.push(I)}let f=p<0?0:p+1;while(f<e.length){let h=u,I=1,E=ps;while(!0){if(f>=e.length)nh();let R=e.charCodeAt(f++),k;if(R>=97&&R<=122)k=R-97;else if(R>=48&&R<=57)k=R-48+26;else nh();u+=k*I;let P=E<=m?Lc:E>=m+Nc?Nc:E-m;if(k<P)break;I*=ps-P,E+=ps}let S=o.length+1;m=aA(u-h,S,h===0),a+=Math.floor(u/S),u%=S,o.splice(u,0,a),u++}return String.fromCodePoint(...o)}function oA(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var p1=new RegExp(su.source,"gu");function uA(e){let o=e.replace(p1,""),a=o.length,u=a>0?[o,"-"]:[],m=Array.from(e,(E)=>E.codePointAt(0)),p=iA,f=0,h=sA,I=a;while(I<m.length){let E=1/0;for(let S of m)if(S>=p&&S<E)E=S;f+=(E-p)*(I+1),p=E;for(let S of m){if(S<p)f++;if(S===p){let R=f;for(let k=ps;;k+=ps){let P=k<=h?Lc:k>=h+Nc?Nc:k-h;if(R<P)break;let v=P+(R-P)%(ps-P);u.push(oA(v)),R=Math.floor((R-P)/(ps-P))}u.push(oA(R)),h=aA(f,I+1,I===a),f=0,I++}}f++,p++}return u.join("")}var l1=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,cA=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,d1=/^(?:R|AL|AN)$/;function mA(e){if(Mp(e))try{return _p(Op(e.slice(4).toLowerCase()))}catch{return!1}return _p(e)}function pA(e){let o=String.fromCodePoint(e);return tA.test(o)?"EN":Jk.test(o)?"AN":eh.test(o)?"NSM":vp.test(o)?"R":Zk.test(o)?"AL":th.test(o)?"L":"ON"}function _p(e){for(let o of e)if(d1.test(pA(o.codePointAt(0))))return!0;return!1}function Lp(e){let o=!1,a=cA,u=!1,m=!1,p=!0;for(let f of e){let h=pA(f.codePointAt(0));if(p){if(h!=="L"&&h!=="R"&&h!=="AL")return!1;o=h==="R"||h==="AL",a=o?l1:cA,p=!1}if(!a.test(h))return!1;if(h==="EN")u=!0;else if(h==="AN")m=!0}if(o&&u&&m)return!1;return!0}function f1(e){return su.test(e)&&uA(e).length+4>63}function h1(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Np(e){if(f1(e))return!1;if(_p(e)&&!Lp(e))return!1;let o=[...e],a=o.map((p)=>p.codePointAt(0)),u=a.length;if(h1(o))return!1;if(Qk.test(o[0]))return!1;let m=!1;for(let p=0;p<u;p++){let f=a[p],h=o[p];if(eA.test(h))return!1;if(!rA.test(h))return!1;if(Yk.test(h))m=!0;let I=a[p-1],E=a[p+1];switch(f){case 183:if(I!==108||E!==108)return!1;break;case 885:if(!E||!Xk.test(o[p+1]))return!1;break;case 1523:case 1524:if(!I||!vp.test(o[p-1]))return!1;break;case 8204:if(!I||I<128&&!rh.test(o[p-1]))return!1;break;case 8205:if(!I||!rh.test(o[p-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!m)return!1;return!0}function Dp(e){if(!Mp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let a=Op(o);if(!su.test(a))return!1;return Np(a)}catch{return!1}}function g1(e){return e.length>0&&e.length<=63}function y1(e){return g1(e)&&(Dp(e)||nA(e))}function hA(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>y1(o))}function x1(e){return e.length>0&&e.length<=63}function I1(e){return x1(e)&&(Dp(e)||Np(e))}function b1(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 gA(e){if(e.length===0||e.includes(" "))return!1;let o=b1(e);if(o.length>253)return!1;let a=o.split("."),u=a.some((m)=>mA(m));return a.every((m)=>I1(m)&&(!u||Lp(m)))}function qp(e){return hA(e)}var E1=/^(?:[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 Fp(e){return E1.test(e.normalize("NFC"))}function jp(e){return gA(e)}var S1=/^(?:(?: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 Up(e){return S1.test(e)}var w1=/^(?:(?:(?:[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 Bp(e){return w1.test(e)}var T1=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,R1=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Gp(e){return!T1.test(e)&&!R1.test(e)&&URL.canParse(e,"http://example.com")}var k1=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,A1=/[\x00-\x20<>\^`{|}\\]/,P1=/%(?![0-9a-fA-F]{2})/;function C1(e){return e.length<2048?e.replace(k1,"[::1]"):e}function Kp(e){if(A1.test(e))return!1;if(P1.test(e))return!1;return URL.canParse(C1(e))}var $1=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Hp(e){return $1.test(e)}var v1=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Wp(e){return v1.test(e)}function zp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var M1=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Vp(e){return M1.test(e)}var O1=/^(?:[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 Jp(e){return O1.test(e)}var _1=/^(?:(?:[^\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 Qp(e){return _1.test(e)}var L1=/^[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 Xp(e){return L1.test(e)}function Yp(e){return URL.canParse(e)}var N1=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Zp(e){return N1.test(e)}var Tr=new Map;function xA(){Tr.clear()}function D1(){return[...Tr.entries()]}function q1(e,o){Tr.set(e,o)}function F1(e){return Tr.has(e)}function j1(e){return Tr.get(e)}function IA(e,o){return Tr.get(e)?.(o)??!0}function bA(){xA(),Tr.set("date-time",Pp),Tr.set("date",nu),Tr.set("duration",Cp),Tr.set("email",$p),Tr.set("hostname",qp),Tr.set("idn-email",Fp),Tr.set("idn-hostname",jp),Tr.set("ipv4",Up),Tr.set("ipv6",Bp),Tr.set("iri-reference",Gp),Tr.set("iri",Kp),Tr.set("json-pointer-uri-fragment",Hp),Tr.set("json-pointer",Wp),Tr.set("regex",zp),Tr.set("relative-json-pointer",Vp),Tr.set("time",ou),Tr.set("uri-reference",Jp),Tr.set("uri-template",Qp),Tr.set("uri",Xp),Tr.set("url",Yp),Tr.set("uuid",Zp)}bA();function EA(e,o,a,u){return Er(It("Format","Test"),[Pe(a.format),u])}function sh(e,o,a,u){return IA(a.format,u)}function SA(e,o,a,u,m,p){return sh(e,o,m,p)||o.AddError({keyword:"format",schemaPath:a,instancePath:u,params:{format:m.format}})}function wA(e,o,a,u){let m=Mc(a)?a.then:!0,p=xc(a)?a.else:!0;return PO(Lt(e,o,a.if,u),Lt(e,o,m,u),Lt(e,o,p,u))}function TA(e,o,a,u){let m=Mc(a)?a.then:!0,p=xc(a)?a.else:!0;return At(e,o,a.if,u)?At(e,o,m,u):At(e,o,p,u)}function RA(e,o,a,u,m,p){let f=Mc(m)?m.then:!0,h=xc(m)?m.else:!0,I=new Dn,E=rr(e,I,`${a}/if`,u,m.if,p)?rr(e,I,`${a}/then`,u,f,p)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"then"}}):rr(e,o,`${a}/else`,u,h,p)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"else"}});if(E)o.Merge([I]);return E}function U1(e,o,a,u){return vn(a.items.map((m,p)=>{let f=Xi(It(u,"length"),Pe(p)),h=Qn(e,o,m,`${u}[${p}]`),I=o.AddIndex(Pe(p));return br(f,Rn(h,I))}))}function B1(e,o,a,u){return vn(a.items.map((m,p)=>{let f=Xi(It(u,"length"),Pe(p)),h=Qn(e,o,m,`${u}[${p}]`);return br(f,h)}))}function G1(e,o,a,u){return o.UseUnevaluated()?U1(e,o,a,u):B1(e,o,a,u)}function K1(e,o,a,u){return mn(a.items,0,(m,p)=>ys(u.length,p)||ko(e,o,m,u[p])&&o.AddIndex(p))}function H1(e,o,a,u,m,p){return $n(m.items,0,(f,h)=>{let I=`${a}/items/${h}`,E=`${u}/${h}`;return ys(p.length,h)||Ao(e,o,I,E,f,p[h])&&o.AddIndex(h)})}function W1(e,o,a,u){let m=us(a)?a.prefixItems.length:0,p=Qn(e,o,a.items,"element"),f=o.AddIndex("index");return xs(u,Pe(m),["element","index"],Rn(p,f))}function z1(e,o,a,u){let m=us(a)?a.prefixItems.length:0,p=Qn(e,o,a.items,"element");return xs(u,Pe(m),["element","index"],p)}function V1(e,o,a,u){return o.UseUnevaluated()?W1(e,o,a,u):z1(e,o,a,u)}function J1(e,o,a,u){let m=us(a)?a.prefixItems.length:0;return mn(u,m,(p,f)=>ko(e,o,a.items,p)&&o.AddIndex(f))}function Q1(e,o,a,u,m,p){let f=us(m)?m.prefixItems.length:0;return $n(p,f,(h,I)=>{let E=`${a}/items`,S=`${u}/${I}`;return Ao(e,o,E,S,m.items,h)&&o.AddIndex(I)})}function kA(e,o,a,u){return Ec(a)?G1(e,o,a,u):V1(e,o,a,u)}function AA(e,o,a,u){return Ec(a)?K1(e,o,a,u):J1(e,o,a,u)}function PA(e,o,a,u,m,p){return Ec(m)?H1(e,o,a,u,m,p):Q1(e,o,a,u,m,p)}function CA(e){return vs(e)}function $A(e,o,a,u){if(!CA(a))return Pe(!0);let[m]=[Jt()],p=pm(u,[m,"_"],Lt(e,o,a.contains,m));return Xi(p,Pe(a.maxContains))}function ih(e,o,a,u){if(!CA(a))return!0;let m=Sd(u,(p)=>At(e,o,a.contains,p));return ys(m,a.maxContains)}function vA(e,o,a,u,m,p){let f=Gs(m)?m.minContains:1;return ih(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:f,maxContains:m.maxContains}})}function MA(e,o,a,u){return Xi(u,Pe(a.maximum))}function ah(e,o,a,u){return ys(u,a.maximum)}function OA(e,o,a,u,m,p){return ah(e,o,m,p)||o.AddError({keyword:"maximum",schemaPath:a,instancePath:u,params:{comparison:"<=",limit:m.maximum}})}function _A(e,o,a,u){return Xi(It(u,"length"),Pe(a.maxItems))}function uh(e,o,a,u){return ys(u.length,a.maxItems)}function LA(e,o,a,u,m,p){return uh(e,o,m,p)||o.AddError({keyword:"maxItems",schemaPath:a,instancePath:u,params:{limit:m.maxItems}})}function NA(e,o,a,u){return TO(u,Pe(a.maxLength))}function ch(e,o,a,u){return Hy(u,a.maxLength)}function DA(e,o,a,u,m,p){return ch(e,o,m,p)||o.AddError({keyword:"maxLength",schemaPath:a,instancePath:u,params:{limit:m.maxLength}})}function qA(e,o,a,u){return Xi(It(Zi(u),"length"),Pe(a.maxProperties))}function mh(e,o,a,u){return ys(Ee(u).length,a.maxProperties)}function FA(e,o,a,u,m,p){return mh(e,o,m,p)||o.AddError({keyword:"maxProperties",schemaPath:a,instancePath:u,params:{limit:m.maxProperties}})}function jA(e){return vs(e)}function X1(e,o,a,u){let[m,p]=[Jt(),Jt()],f=pm(u,[m,p],Rn(Lt(e,o,a.contains,m),o.AddIndex(p)));return $u(f,Pe(a.minContains))}function Y1(e,o,a,u){let[m]=[Jt()],p=pm(u,[m,"_"],Lt(e,o,a.contains,m));return $u(p,Pe(a.minContains))}function UA(e,o,a,u){if(!jA(a))return Pe(!0);return o.UseUnevaluated()?X1(e,o,a,u):Y1(e,o,a,u)}function ph(e,o,a,u){if(!jA(a))return!0;let m=Sd(u,(p,f)=>At(e,o,a.contains,p)&&o.AddIndex(f));return Pa(m,a.minContains)}function BA(e,o,a,u,m,p){return ph(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:m.minContains}})}function GA(e,o,a,u){return $u(u,Pe(a.minimum))}function lh(e,o,a,u){return Pa(u,a.minimum)}function KA(e,o,a,u,m,p){return lh(e,o,m,p)||o.AddError({keyword:"minimum",schemaPath:a,instancePath:u,params:{comparison:">=",limit:m.minimum}})}function HA(e,o,a,u){return $u(It(u,"length"),Pe(a.minItems))}function dh(e,o,a,u){return Pa(u.length,a.minItems)}function WA(e,o,a,u,m,p){return dh(e,o,m,p)||o.AddError({keyword:"minItems",schemaPath:a,instancePath:u,params:{limit:m.minItems}})}function zA(e,o,a,u){return wO(u,Pe(a.minLength))}function fh(e,o,a,u){return Wy(u,a.minLength)}function VA(e,o,a,u,m,p){return fh(e,o,m,p)||o.AddError({keyword:"minLength",schemaPath:a,instancePath:u,params:{limit:m.minLength}})}function JA(e,o,a,u){return $u(It(Zi(u),"length"),Pe(a.minProperties))}function hh(e,o,a,u){return Pa(Ee(u).length,a.minProperties)}function QA(e,o,a,u,m,p){return hh(e,o,m,p)||o.AddError({keyword:"minProperties",schemaPath:a,instancePath:u,params:{limit:m.minProperties}})}function XA(e,o,a,u){return CO(u,Pe(a.multipleOf))}function gh(e,o,a,u){return Gy(u,a.multipleOf)}function YA(e,o,a,u,m,p){return gh(e,o,m,p)||o.AddError({keyword:"multipleOf",schemaPath:a,instancePath:u,params:{multipleOf:m.multipleOf}})}function Z1(e,o,a,u){return wi(e,o,[a.not],u,Un(fo(It("results","length"),Pe(1))))}function ej(e,o,a,u){return Un(Lt(e,o,a.not,u))}function ZA(e,o,a,u){return o.UseUnevaluated()?Z1(e,o,a,u):ej(e,o,a,u)}function yh(e,o,a,u){let m=new Nn;return!At(e,m,a.not,u)&&o.Merge([m])}function eP(e,o,a,u,m,p){return yh(e,o,m,p)||o.AddError({keyword:"not",schemaPath:a,instancePath:u,params:{}})}function tj(e,o,a,u){return wi(e,o,a.oneOf,u,fo(It("results","length"),Pe(1)))}function rj(e,o,a,u){let[m]=[Jt()],p=AO(a.oneOf.map((h)=>Lt(e,o,h,u))),f=pm(p,[m,"_"],fo(m,Pe(!0)));return fo(f,Pe(1))}function tP(e,o,a,u){return o.UseUnevaluated()?tj(e,o,a,u):rj(e,o,a,u)}function rP(e,o,a,u){let m=a.oneOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return M(m.length,1)&&o.Merge(m)}function nP(e,o,a,u,m,p){let f=[],h=[],I=m.oneOf.reduce((S,R,k)=>{let P=new Dn,v=`${a}/oneOf/${k}`,_=rr(e,P,v,u,R,p);if(_)h.push(k);if(!_)f.push(P);return _?[...S,P]:S},[]),E=M(I.length,1)&&o.Merge(I);if(!E&&M(h.length,0))f.forEach((S)=>S.GetErrors().forEach((R)=>o.AddError(R)));return E||o.AddError({keyword:"oneOf",schemaPath:a,instancePath:u,params:{passingSchemas:h}})}function oP(e,o,a,u){let m=_o(dt(a.pattern)?ms(a.pattern):a.pattern);return Er(It(m,"test"),[u])}function xh(e,o,a,u){return(dt(a.pattern)?ms(a.pattern):a.pattern).test(u)}function sP(e,o,a,u,m,p){return xh(e,o,m,p)||o.AddError({keyword:"pattern",schemaPath:a,instancePath:u,params:{pattern:m.pattern}})}function iP(e,o,a,u){return vn(hn(a.patternProperties).map(([m,p])=>{let[f,h]=[Jt(),Jt()],I=_o(ms(m)),E=Un(Er(It(I,"test"),[f])),S=Qn(e,o,p,h),R=o.AddKey(f),k=o.UseUnevaluated()?br(E,Rn(S,R)):br(E,S);return xs(tx(u),Pe(0),[`[${f}, ${h}]`,"_"],k)}))}function aP(e,o,a,u){return mn(hn(a.patternProperties),0,([m,p])=>{let f=ms(m);return mn(hn(u),0,([h,I])=>!f.test(h)||ko(e,o,p,I)&&o.AddKey(h))})}function uP(e,o,a,u,m,p){return $n(hn(m.patternProperties),0,([f,h])=>{let I=`${a}/patternProperties/${f}`,E=ms(f);return $n(hn(p),0,([S,R])=>{let k=`${u}/${S}`;return!E.test(S)||Ao(e,o,I,k,h,R)&&o.AddKey(S)})})}function cP(e,o,a,u){return vn(a.prefixItems.map((m,p)=>{let f=Xi(It(u,"length"),Pe(p)),h=Qn(e,o,m,`${u}[${p}]`),I=o.AddIndex(Pe(p)),E=o.UseUnevaluated()?Rn(h,I):h;return br(f,E)}))}function mP(e,o,a,u){return M(u.length,0)||mn(a.prefixItems,0,(m,p)=>ys(u.length,p)||ko(e,o,m,u[p])&&o.AddIndex(p))}function pP(e,o,a,u,m,p){return M(p.length,0)||$n(m.prefixItems,0,(f,h)=>{let I=`${a}/prefixItems/${h}`,E=`${u}/${h}`;return ys(p.length,h)||Ao(e,o,I,E,f,p[h])&&o.AddIndex(h)})}function el(e,o){return e.includes(o)||Bo().exactOptionalPropertyTypes}function lP(e,o){return Rd(It(e,o))}function Ih(e,o){return Bt(e[o])}function dP(e,o,a,u){let m=cs(a)?a.required:[],p=hn(a.properties).map(([f,h])=>{let I=Un(ea(u,Pe(f))),E=Qn(e,o,h,It(u,f)),S=o.AddKey(Pe(f)),R=o.UseUnevaluated()?Rn(E,S):E,k=m.includes(f)?R:br(I,R);return el(m,f)?k:br(lP(u,f),k)});return vn(p)}function fP(e,o,a,u){let m=cs(a)?a.required:[];return mn(hn(a.properties),0,([f,h])=>{let I=!pe(u,f)||ko(e,o,h,u[f])&&o.AddKey(f);return el(m,f)?I:Ih(u,f)||I})}function hP(e,o,a,u,m,p){let f=cs(m)?m.required:[];return $n(hn(m.properties),0,([I,E])=>{let S=`${a}/properties/${I}`,R=`${u}/${I}`,k=()=>!pe(p,I)||Ao(e,o,S,R,E,p[I])&&o.AddKey(I);return el(f,I)?k():Ih(p,I)||k()})}function gP(e,o,a,u){let[m,p]=[Jt(),Jt()];return xs(Zi(u),Pe(0),[m,p],Lt(e,o,a.propertyNames,m))}function yP(e,o,a,u){return mn(Ee(u),0,(m,p)=>At(e,o,a.propertyNames,m))}function xP(e,o,a,u,m,p){let f=[];return $n(Ee(p),0,(I,E)=>{let S=`${u}/${I}`,R=`${a}/propertyNames`,k=rr(e,o,R,S,m.propertyNames,I);if(!k)f.push(I);return k})||o.AddError({keyword:"propertyNames",schemaPath:a,instancePath:u,params:{propertyNames:f}})}function IP(e,o,a,u){let m=e.RecursiveRef(a)??!1;return Ws(e,o,m,u)}function bP(e,o,a,u){let m=e.RecursiveRef(a)??!1;return Ye(m)&&At(e,o,m,u)}function EP(e,o,a,u,m,p){let f=e.RecursiveRef(m)??!1;return Ye(f)&&rr(e,o,"#",u,f,p)}function nj(e,o,a,u){let m=si(["context","value"],Ws(e,o,a,"value")),p=si(["context","value"],lm([Ds("nextContext",Ad("CheckContext",[])),Ds("result",Er(m,["nextContext","value"])),nx("result",o.Merge("[nextContext]")),dm("result")]));return Er(p,["context",u])}function oj(e,o,a,u){return Ws(e,o,a,u)}function SP(e,o,a,u){let m=e.Ref(a)??!1;return o.UseUnevaluated()?nj(e,o,m,u):oj(e,o,m,u)}function wP(e,o,a,u){let m=e.Ref(a)??!1,p=new Nn,f=Ye(m)&&At(e,p,m,u);if(f)o.Merge([p]);return f}function TP(e,o,a,u,m,p){let f=e.Ref(m)??!1,h=new Dn,I=Ye(f)&&rr(e,h,"#",u,f,p);if(I)o.Merge([h]);if(!I)h.GetErrors().forEach((E)=>o.AddError(E));return I}function RP(e,o,a,u){return vn(a.required.map((m)=>ea(u,Pe(m))))}function kP(e,o,a,u){return mn(a.required,0,(m)=>pe(u,m))}function AP(e,o,a,u,m,p){let f=[];return $n(m.required,0,(I)=>{let E=pe(p,I);if(!E)f.push(I);return E})||o.AddError({keyword:"required",schemaPath:a,instancePath:u,params:{requiredProperties:f}})}function PP(e,o,a,u){return M(a,"object")?Xy(u):M(a,"array")?mm(u):M(a,"boolean")?yO(u):M(a,"integer")?xO(u):M(a,"number")?Qy(u):M(a,"null")?IO(u):M(a,"string")?Zy(u):M(a,"bigint")?Jy(u):M(a,"constructor")?SO(u):M(a,"function")?EO(u):M(a,"symbol")?bO(u):M(a,"undefined")?Rd(u):M(a,"void")?Rd(u):Pe(!0)}function bh(e,o,a,u,m){return M(a,"object")?Uo(m):M(a,"array")?qe(m):M(a,"boolean")?fn(m):M(a,"integer")?cm(m):M(a,"number")?Ot(m):M(a,"null")?bo(m):M(a,"string")?dt(m):M(a,"bigint")?qr(m):M(a,"constructor")?bd(m):M(a,"function")?gs(m):M(a,"symbol")?Ed(m):M(a,"undefined")?Bt(m):M(a,"void")?Bt(m):!0}function sj(e,o,a,u){return Pd(a.map((m)=>PP(e,o,m,u)))}function CP(e,o,a,u,m){return Ca(a,(p)=>bh(e,o,p,u,m))}function $P(e,o,a,u){return qe(a.type)?sj(e,o,a.type,u):PP(e,o,a.type,u)}function vP(e,o,a,u){return qe(a.type)?CP(e,o,a.type,a,u):bh(e,o,a.type,a,u)}function MP(e,o,a,u,m,p){return(qe(m.type)?CP(e,o,m.type,m,p):bh(e,o,m.type,m,p))||o.AddError({keyword:"type",schemaPath:a,instancePath:u,params:{type:m.type}})}function OP(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Er(It("context","GetIndices"),[]),h=Er(It("indices","has"),[m]),I=Lt(e,o,a.unevaluatedItems,p),E=Er(It("context","AddIndex"),[m]),S=xs(u,Pe(0),[p,m],Rn(br(h,I),E));return Er(si(["context"],lm([Ds("indices",f),dm(S)])),["context"])}function _P(e,o,a,u){let m=o.GetIndices();return mn(u,0,(p,f)=>(m.has(f)||At(e,o,a.unevaluatedItems,p))&&o.AddIndex(f))}function LP(e,o,a,u,m,p){let f=o.GetIndices(),h=[];return $n(p,0,(E,S)=>{let R=new Dn,k=(f.has(S)||rr(e,R,a,u,m.unevaluatedItems,E))&&o.AddIndex(S);if(!k)h.push(S);return k})||o.AddError({keyword:"unevaluatedItems",schemaPath:a,instancePath:u,params:{unevaluatedItems:h}})}function NP(e,o,a,u){let[m,p]=[Jt(),Jt()],f=Er(It("context","GetKeys"),[]),h=Er(It("keys","has"),[m]),I=Er(It("context","AddKey"),[m]),E=Lt(e,o,a.unevaluatedProperties,p),S=xs(tx(u),Pe(0),[`[${m}, ${p}]`,"_"],br(h,Rn(E,I)));return Er(si(["context"],lm([Ds("keys",f),dm(S)])),["context"])}function DP(e,o,a,u){let m=o.GetKeys();return mn(hn(u),0,([p,f])=>m.has(p)||At(e,o,a.unevaluatedProperties,f)&&o.AddKey(p))}function qP(e,o,a,u,m,p){let f=o.GetKeys(),h=[];return $n(hn(p),0,([E,S])=>{let R=new Dn,k=f.has(E)||rr(e,R,a,u,m.unevaluatedProperties,S)&&o.AddKey(E);if(!k)h.push(E);return k})||o.AddError({keyword:"unevaluatedProperties",schemaPath:a,instancePath:u,params:{unevaluatedProperties:h}})}function Eh(e){return!M(e.uniqueItems,!1)}function FP(e,o,a,u){if(!Eh(a))return Pe(!0);let m=It(Ad("Set",[Er(It(u,"map"),[It("Hashing","Hash")])]),"size"),p=It(u,"length");return fo(m,p)}function jP(e,o,a,u){if(!Eh(a))return!0;let m=new Set(u.map(vd)).size,p=u.length;return M(m,p)}function UP(e,o,a,u,m,p){if(!Eh(m))return!0;let f=new Set,h=p.reduce((E,S,R)=>{let k=vd(S);if(f.has(k))return[...E,R];return f.add(k),E},[]);return M(h.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:a,instancePath:u,params:{duplicateItems:h}})}function Dc(e,o){return Oc(e)&&(qe(e.type)&&ji(e.type.length,0)&&mn(e.type,0,(a)=>M(a,o))||M(e.type,o))}function ij(e){return Dc(e,"object")}function aj(e){return In(e)&&(Oo(e)||hc(e)||gc(e)||Za(e)||Hs(e)||Ks(e)||tu(e)||xa(e)||Rc(e)||cs(e)||Si(e))}function uj(e){return Dc(e,"array")}function cj(e){return In(e)&&(Ya(e)||Bs(e)||vs(e)||wc(e)||eu(e)||Gs(e)||Ii(e)||us(e)||Ei(e)||bi(e))}function mj(e){return Dc(e,"string")}function pj(e){return In(e)&&(ya(e)||Tc(e)||ga(e)||Ia(e))}function lj(e){return Dc(e,"number")||Dc(e,"bigint")}function dj(e){return In(e)&&(as(e)||Sc(e)||Ic(e)||is(e)||kc(e))}function Qn(e,o,a,u){return o.UseUnevaluated()?Rn(Rn(o.Push(),Lt(e,o,a,u)),o.Pop()):Lt(e,o,a,u)}function Lt(e,o,a,u){e.Push(a);let m=[];if(js(a))return Ek(e,o,a,u);if(Oc(a))m.push($P(e,o,a,u));if(aj(a)){let f=[];if(cs(a))f.push(RP(e,o,a,u));if(Oo(a))f.push(lk(e,o,a,u));if(hc(a))f.push(Pk(e,o,a,u));if(gc(a))f.push(vk(e,o,a,u));if(Za(a))f.push(_k(e,o,a,u));if(Ks(a))f.push(iP(e,o,a,u));if(Hs(a))f.push(dP(e,o,a,u));if(tu(a))f.push(gP(e,o,a,u));if(xa(a))f.push(JA(e,o,a,u));if(Rc(a))f.push(qA(e,o,a,u));let h=vn(f),I=br(Un(Xy(u)),h);m.push(ij(a)?h:I)}if(cj(a)){let f=[];if(Ya(a))f.push(ck(e,o,a,u));if(vs(a))f.push(kk(e,o,a,u));if(Bs(a))f.push(kA(e,o,a,u));if(wc(a))f.push($A(e,o,a,u));if(eu(a))f.push(_A(e,o,a,u));if(Gs(a))f.push(UA(e,o,a,u));if(Ii(a))f.push(HA(e,o,a,u));if(us(a))f.push(cP(e,o,a,u));if(bi(a))f.push(FP(e,o,a,u));let h=vn(f),I=br(Un(mm(u)),h);m.push(uj(a)?h:I)}if(pj(a)){let f=[];if(Tc(a))f.push(NA(e,o,a,u));if(ya(a))f.push(zA(e,o,a,u));if(ga(a))f.push(EA(e,o,a,u));if(Ia(a))f.push(oP(e,o,a,u));let h=vn(f),I=br(Un(Zy(u)),h);m.push(mj(a)?h:I)}if(dj(a)){let f=[];if(Ic(a))f.push(Bk(e,o,a,u));if(is(a))f.push(Kk(e,o,a,u));if(Sc(a))f.push(MA(e,o,a,u));if(as(a))f.push(GA(e,o,a,u));if(kc(a))f.push(XA(e,o,a,u));let h=vn(f),I=br(Un(br(Qy(u),Jy(u))),h);m.push(lj(a)?h:I)}if(vc(a))m.push(SP(e,o,a,u));if($c(a))m.push(IP(e,o,a,u));if(yc(a))m.push(Dk(e,o,a,u));if(Tp(a))m.push(wk(e,o,a,u));if(Rp(a))m.push(jk(e,o,a,u));if(bc(a))m.push(wA(e,o,a,u));if(Ac(a))m.push(ZA(e,o,a,u));if(lc(a))m.push(hk(e,o,a,u));if(fc(a))m.push(xk(e,o,a,u));if(Pc(a))m.push(tP(e,o,a,u));if(Ei(a))m.push(br(Un(mm(u)),OP(e,o,a,u)));if(Si(a))m.push(br(Un(Yy(u)),NP(e,o,a,u)));if(pc(a))m.push(ik(e,o,a,u));let p=vn(m);return e.Pop(a),p}function ko(e,o,a,u){return o.Push()&&At(e,o,a,u)&&o.Pop()}function At(e,o,a,u){e.Push(a);let m=js(a)?zf(e,o,a,u):(!Oc(a)||vP(e,o,a,u))&&(!(ut(u)&&!qe(u))||(!cs(a)||kP(e,o,a,u))&&(!Oo(a)||dk(e,o,a,u))&&(!hc(a)||Ck(e,o,a,u))&&(!gc(a)||Mk(e,o,a,u))&&(!Za(a)||Lk(e,o,a,u))&&(!Ks(a)||aP(e,o,a,u))&&(!Hs(a)||fP(e,o,a,u))&&(!tu(a)||yP(e,o,a,u))&&(!xa(a)||hh(e,o,a,u))&&(!Rc(a)||mh(e,o,a,u)))&&(!qe(u)||(!Ya(a)||mk(e,o,a,u))&&(!vs(a)||Jf(e,o,a,u))&&(!Bs(a)||AA(e,o,a,u))&&(!wc(a)||ih(e,o,a,u))&&(!eu(a)||uh(e,o,a,u))&&(!Gs(a)||ph(e,o,a,u))&&(!Ii(a)||dh(e,o,a,u))&&(!us(a)||mP(e,o,a,u))&&(!bi(a)||jP(e,o,a,u)))&&(!dt(u)||(!Tc(a)||ch(e,o,a,u))&&(!ya(a)||fh(e,o,a,u))&&(!ga(a)||sh(e,o,a,u))&&(!Ia(a)||xh(e,o,a,u)))&&(!(Ot(u)||qr(u))||(!Ic(a)||Yf(e,o,a,u))&&(!is(a)||Zf(e,o,a,u))&&(!Sc(a)||ah(e,o,a,u))&&(!as(a)||lh(e,o,a,u))&&(!kc(a)||gh(e,o,a,u)))&&(!vc(a)||wP(e,o,a,u))&&(!$c(a)||bP(e,o,a,u))&&(!yc(a)||qk(e,o,a,u))&&(!Tp(a)||Vf(e,o,a,u))&&(!Rp(a)||Xf(e,o,a,u))&&(!bc(a)||TA(e,o,a,u))&&(!Ac(a)||yh(e,o,a,u))&&(!lc(a)||gk(e,o,a,u))&&(!fc(a)||Ik(e,o,a,u))&&(!Pc(a)||rP(e,o,a,u))&&(!Ei(a)||(!qe(u)||_P(e,o,a,u)))&&(!Si(a)||(!ut(u)||DP(e,o,a,u)))&&(!pc(a)||ak(e,o,a,u));return e.Pop(a),m}function Ao(e,o,a,u,m,p){return o.Push()&&rr(e,o,a,u,m,p)&&o.Pop()}function rr(e,o,a,u,m,p){if(o.AtCapacity())return!1;e.Push(m);let f=js(m)?Sk(e,o,a,u,m,p):!!(+(!Oc(m)||MP(e,o,a,u,m,p))&+(!(ut(p)&&!qe(p))||!!(+(!cs(m)||AP(e,o,a,u,m,p))&+(!Oo(m)||fk(e,o,a,u,m,p))&+(!hc(m)||$k(e,o,a,u,m,p))&+(!gc(m)||Ok(e,o,a,u,m,p))&+(!Za(m)||Nk(e,o,a,u,m,p))&+(!Ks(m)||uP(e,o,a,u,m,p))&+(!Hs(m)||hP(e,o,a,u,m,p))&+(!tu(m)||xP(e,o,a,u,m,p))&+(!xa(m)||QA(e,o,a,u,m,p))&+(!Rc(m)||FA(e,o,a,u,m,p))))&+(!qe(p)||!!(+(!Ya(m)||pk(e,o,a,u,m,p))&+(!vs(m)||Ak(e,o,a,u,m,p))&+(!Bs(m)||PA(e,o,a,u,m,p))&+(!wc(m)||vA(e,o,a,u,m,p))&+(!eu(m)||LA(e,o,a,u,m,p))&+(!Gs(m)||BA(e,o,a,u,m,p))&+(!Ii(m)||WA(e,o,a,u,m,p))&+(!us(m)||pP(e,o,a,u,m,p))&+(!bi(m)||UP(e,o,a,u,m,p))))&+(!dt(p)||!!(+(!Tc(m)||DA(e,o,a,u,m,p))&+(!ya(m)||VA(e,o,a,u,m,p))&+(!ga(m)||SA(e,o,a,u,m,p))&+(!Ia(m)||sP(e,o,a,u,m,p))))&+(!(Ot(p)||qr(p))||!!(+(!Ic(m)||Gk(e,o,a,u,m,p))&+(!is(m)||Hk(e,o,a,u,m,p))&+(!Sc(m)||OA(e,o,a,u,m,p))&+(!as(m)||KA(e,o,a,u,m,p))&+(!kc(m)||YA(e,o,a,u,m,p))))&+(!vc(m)||TP(e,o,a,u,m,p))&+(!$c(m)||EP(e,o,a,u,m,p))&+(!yc(m)||Fk(e,o,a,u,m,p))&+(!Tp(m)||Tk(e,o,a,u,m,p))&+(!Rp(m)||Uk(e,o,a,u,m,p))&+(!bc(m)||RA(e,o,a,u,m,p))&+(!Ac(m)||eP(e,o,a,u,m,p))&+(!lc(m)||yk(e,o,a,u,m,p))&+(!fc(m)||bk(e,o,a,u,m,p))&+(!Pc(m)||nP(e,o,a,u,m,p))&+(!Ei(m)||(!qe(p)||LP(e,o,a,u,m,p)))&+(!Si(m)||(!ut(p)||qP(e,o,a,u,m,p))))&&(!pc(m)||uk(e,o,a,u,m,p));return e.Pop(m),f}var BP=[0],tl=new Map,qc=new Map;function fj(){return`${BP[0]++}`}function hj(e,o){if(!tl.has(e))tl.set(e,new Map);let a=tl.get(e);if(a.has(o))return a.get(o);let u=fj();return a.set(o,u),u}function gj(e,o,a,u){return e.UseUnevaluated()?Er(`check_${a}`,["context",u]):Er(`check_${a}`,[u])}function yj(e,o,a,u){let m=Lt(e,o,a,"value");return o.UseUnevaluated()?Ds(`check_${u}`,si(["context","value"],m)):Ds(`check_${u}`,si(["value"],m))}function GP(){BP[0]=0,tl.clear(),qc.clear()}function KP(){return[...qc.values()]}function Ws(e,o,a,u){let m=hj(a,e.LexicalBaseURL()),p=gj(o,a,m,u);if(qc.has(m))return p;return qc.set(m,""),qc.set(m,yj(e,o,a,m)),p}function xj(e,o){return ut(o)&&!Cu(e)?o[e]:void 0}function Ij(e,o){return e.reduce((a,u)=>xj(u,a),o)}function bj(e){if(M(e.length,0))return[];let o=e.split("/").map((a)=>a.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function Ej(e,o){let a=bj(o);return Ij(a,e)}var nl="https://json-schema.org";function WP(e,o){if(ut(e)&&Us(e)&&M(e.$dynamicAnchor,o))return e;if(ut(e))for(let a of Ee(e)){let u=WP(e[a],o);if(u)return u}return}function Sh(e,o,a){if(M(e,a))return o.href;let u=In(e)&&Ro(e)?new URL(e.$id,o.href):o;if(qe(e))for(let m of e){let p=Sh(m,u,a);if(!Bt(p))return p}else if(ut(e))for(let m of Ee(e)){let p=Sh(e[m],u,a);if(!Bt(p))return p}return}function Sj(e,o,a){if(M(e.$id,a.hash))return e;let u=new URL(a.href,o.href);if(M(o.pathname,u.pathname))return a.hash.startsWith("#")?zP(e,a):e;return}function wj(e,o,a){let u=new URL(`#${e.$anchor}`,o.href),m=new URL(a.href,o.href);return M(u.href,m.href)?e:void 0}function Tj(e,o,a){let u=new URL(`#${e.$dynamicAnchor}`,o.href),m=new URL(a.href,o.href);return M(u.href,m.href)?e:void 0}function zP(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let a=decodeURIComponent(o.hash.slice(1));if(!a.startsWith("/"))return;return Ej(e,a)}function Rj(e,o,a){if(Ro(e)){let u=Sj(e,o,a);if(!Bt(u))return u}if(dc(e)){let u=wj(e,o,a);if(!Bt(u))return u}if(Us(e)){let u=Tj(e,o,a);if(!Bt(u))return u}return zP(e,a)}function kj(e,o,a){return e.reduce((u,m)=>{let p=ol(m,o,a);return!Bt(p)?p:u},void 0)}function Aj(e){return M(e,"const")||M(e,"enum")}function Pj(e,o,a){return Ee(e).reduce((u,m)=>{if(Aj(m))return u;let p=ol(e[m],o,a);return!Bt(p)?p:u},void 0)}function ol(e,o,a){let u=In(e)&&Ro(e)?new URL(e.$id,o.href):o;if(In(e)){let m=Rj(e,u,a);if(!Bt(m))return m}if(qe(e))return kj(e,u,a);if(ut(e))return Pj(e,u,a);return}function Cj(e,o,a){return Sh(e,new URL(o||".",nl),a)}function $j(e,o,a,u){let m=sl(e,o,a,u,!1);return In(m)&&Ro(m)?m:void 0}function HP(e){return e.href.split("#")[0]}function vj(e,o){return pe(e,o)?e[o]:void 0}function Mj(e,o,a){return ol(e,o,a)}function Oj(e,o,a){let u=HP(a);if(M(u,HP(o)))return;if(!pe(e,u))return;let m=e[u],p=In(m)&&Ro(m)?new URL(m.$id,u):new URL(u);return M(a.hash,"")?m:ol(m,p,a)}function _j(e,o,a,u,m){if(!u.$ref.startsWith("#"))return;if(pe(e,"$schema"))return;let p=Cj(o,a,m);if(Bt(p)||M(p,a))return;return{target:m,base:p,root:o}}function Lj(e,o,a){let u=e[o];if(!In(u))return;return{target:a,base:o,root:u}}function Nj(e,o,a,u,m){let p=m?Lj(e.context,u,a):void 0;if(!Bt(p))return p;return _j(e.root,e.lexicalSchema,e.referenceBase,o,a)}function Dj(e,o,a,u,m,p){if(Ro(m))return;let f=$j(e,o,a,u);if(!f||p.includes(f))return;return{target:m,resource:f}}function sl(e,o,a,u,m=!0){let p=new URL(a||".",nl),f=m&&Ro(o)?new URL(o.$id,p):p,h=new URL(u,f.href);return vj(e,u)??Mj(o,f,h)??Oj(e,f,h)}function qj(e,o,a,u,m,p){let f=new URL(a||".",nl),h=m.$dynamicRef.startsWith("#")?u:o,I=sl(e,h,a,m.$dynamicRef,!1);if(Bt(I)){let R=new URL(m.$dynamicRef,f).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let k=decodeURIComponent(R.slice(1));return p.find((v)=>M(v.$dynamicAnchor,k))??WP(o,k)}return}if(!In(I)||!Us(I))return I;if(new URL(m.$dynamicRef,f).hash.startsWith("#/"))return I;return p.find((R)=>M(R.$dynamicAnchor,I.$dynamicAnchor))??I}function Fj(e,o){let a=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:a,m=sl(e.context,u,e.referenceBase,o.$ref,!1);if(!m||!In(m))return{schema:m};let p=new URL(o.$ref,e.referenceBase).href.split("#")[0],f=!M(p,e.resourceBase),h=Nj(e,o,m,p,f),I=f?Dj(e.context,e.root,e.referenceBase,p,m,e.ids):void 0;return{schema:m,retrievedResource:h,resolvedResource:I}}function jj(e,o){let a=Cc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return sl(e.context,a,e.lexicalBase,o.$recursiveRef,!1)}function Uj(e,o){return qj(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var Nr=function(e,o,a,u){if(a==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?u:a==="a"?u.call(e):u?u.value:o.get(e)},Rr,al,ZP,kh,il,VP,JP,QP,XP,Th,Rh,Ah,Ph,YP,e0;class Ti{constructor(e,o){Rr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return Nr(this,Rr,"m",kh).call(this,this.ids)}Push(e){if(!In(e))return;if(Ro(e))Nr(this,Rr,"m",Ah).call(this,e);if(dc(e))this.anchors.push(e);if(Cc(e))this.recursiveAnchors.push(e);if(Us(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(!In(e))return;if(Ro(e))Nr(this,Rr,"m",Ph).call(this,e);if(dc(e))this.anchors.pop();if(Cc(e))this.recursiveAnchors.pop();if(Us(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Nr(this,Rr,"m",e0).call(this,e)}Ref(e){let o=Fj(Nr(this,Rr,"m",al).call(this),e);return Nr(this,Rr,"m",ZP).call(this,o),o.schema}RecursiveRef(e){let o=jj(Nr(this,Rr,"m",al).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=Uj(Nr(this,Rr,"m",al).call(this),e);if(o)this.pendingResource=!0;return o}}Rr=new WeakSet,al=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Nr(this,Rr,"m",JP).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Nr(this,Rr,"m",VP).call(this),resourceBase:Nr(this,Rr,"m",il).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},ZP=function(o){if(!Bt(o.schema))this.pendingResource=!0;if(!Bt(o.resolvedResource))Nr(this,Rr,"m",YP).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})},kh=function(o){let a=this.retrievedFrames[this.retrievedFrames.length-1],u=a?new URL(a.base):new URL(nl);return(a?o.slice(a.idDepth):o).reduce((p,f)=>new URL(f.$id,p),u).href},il=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return Nr(this,Rr,"m",kh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((a,u)=>new URL(u.$id,a),new URL(o.base)).href},VP=function(){if(this.retrievedFrames.length>0)return Nr(this,Rr,"m",il).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 Nr(this,Rr,"m",il).call(this)},JP=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},QP=function(o){o.forEach((a)=>Nr(this,Rr,"m",Th).call(this,a,!1))},XP=function(o){o.forEach((a)=>Nr(this,Rr,"m",Rh).call(this,a,!1))},Th=function e(o,a=!0){if(js(o))return;if(qe(o))return Nr(this,Rr,"m",QP).call(this,o);if(!In(o))return;let u=o;if(!a&&Ro(u))return;if(!a&&Us(u))this.dynamicAnchors.push(u);for(let m of Ee(u))Nr(this,Rr,"m",e).call(this,u[m],!1)},Rh=function e(o,a=!0){if(js(o))return;if(qe(o))return Nr(this,Rr,"m",XP).call(this,o);if(!In(o))return;let u=o;if(!a&&Ro(u))return;if(!a&&Us(u))this.dynamicAnchors.pop();for(let m of Ee(u))Nr(this,Rr,"m",e).call(this,u[m],!1)},Ah=function(o){this.ids.push(o);let a=this.pendingResource;if(this.pendingResource=!1,a)this.resourceIds.push(o);Nr(this,Rr,"m",Th).call(this,o,!0)},Ph=function(o){if(this.ids.pop(),this.resourceIds.length>0&&M(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();Nr(this,Rr,"m",Rh).call(this,o,!0)},YP=function(o,a){Nr(this,Rr,"m",Ah).call(this,a),this.resolvedResources.set(o,a)},e0=function(o){if(!this.resolvedResources.has(o))return;let a=this.resolvedResources.get(o);Nr(this,Rr,"m",Ph).call(this,a),this.resolvedResources.delete(o)};function Bj(e){let o=e.Functions().join(`;
33
+ `),a=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${a.join("; ")} }`}function Gj(e,o){return Ex("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Nn,B,iu,oa,e.External().variables)}function Kj(e){let o=new Ti(e.Context(),e.Schema()),a=new Nn;return(u)=>At(o,a,e.Schema(),u)}function Hj(e,o){return bx()?Gj(e,o):Kj(e)}class t0{constructor(e,o,a){this.isAccelerated=e,this.code=o,this.check=a}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class r0{constructor(e,o,a,u,m,p){this.context=e,this.schema=o,this.external=a,this.functions=u,this.entry=m,this.useUnevaluated=p}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=Bj(this),o=Hj(this,e);return new t0(bx(),e,o)}}function ul(...e){let[o,a]=kn(e,{2:(I,E)=>[I,E],1:(I)=>[{},I]});ok(),GP();let u=new Ti(o,a),m=new Kf(nk(o,a)),p=Ws(u,m,a,"value"),f=KP(),h=sk();return new r0(o,a,h,f,p,m.UseUnevaluated())}function cl(...e){let[o,a,u]=kn(e,{3:(S,R,k)=>[S,R,k],2:(S,R)=>[{},S,R]}),m=new Ti(o,a),p=new Dn,f=rr(m,p,"#","",a,u),h=p.GetErrors(),I=$x(),E=h.map((S)=>({...S,message:I(S)}));return[f,E]}function $h(...e){let[o,a,u]=kn(e,{3:(f,h,I)=>[f,h,I],2:(f,h)=>[{},f,h]}),m=new Ti(o,a),p=new Nn;return At(m,p,a,u)}function Zt(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return $h(o,a,u)}function Ms(...e){let[o,a,u]=kn(e,{3:(f,h,I)=>[f,h,I],2:(f,h)=>[{},f,h]}),[m,p]=cl(o,a,u);return p}class ba extends Error{constructor(e,o,a){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:a,value:o},writable:!1,configurable:!1,enumerable:!1})}}function n0(e,o,a){if(!qe(a))return a;return a.map((u)=>bn(e,o.items,u))}function o0(e,o,a){return bn({...e,...o.$defs},pn(o.$ref),a)}function Vj(e,o){let a=pe(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Mo(e,o),m=Pn(u);return He(m)?Ip(m,a):m}function s0(e,o,a){let u=Vj(e,o);return bn(e,u,a)}function ml(e){return pe(e,"additionalProperties")?e.additionalProperties:void 0}function i0(e,o,a){if(!ut(a)||qe(a))return a;let u=ml(o);for(let m of Ee(a)){if(pe(o.properties,m)){a[m]=bn(e,o.properties[m],a[m]);continue}if(fn(u)&&M(u,!0)||Mr(u)&&Zt(e,u,a[m])){a[m]=bn(e,u,a[m]);continue}delete a[m]}return a}function a0(e,o,a){if(!ut(a))return a;let u=ml(o),[m,p]=[new RegExp(xn(o)),or(o)];for(let f of Ee(a)){if(m.test(f)){a[f]=bn(e,p,a[f]);continue}if(fn(u)&&M(u,!0)||Mr(u)&&Zt(e,u,a[f])){a[f]=bn(e,u,a[f]);continue}delete a[f]}return a}function u0(e,o,a){return pe(e,o.$ref)?bn(e,e[o.$ref],a):a}function c0(e,o,a){if(!qe(a))return a;let u=Math.min(a.length,o.items.length);for(let m=0;m<u;m++)a[m]=bn(e,o.items[m],a[m]);return ji(a.length,u)?a.slice(0,u):a}function Gr(e){return va(e)}function m0(e,o,a){for(let u of o.anyOf){let m=bn(e,u,Gr(a));if(Zt(e,u,m))return m}return a}function bn(e,o,a){return St(o)?n0(e,o,a):Yt(o)?o0(e,o,a):Ke(o)?s0(e,o,a):He(o)?i0(e,o,a):Kt(o)?a0(e,o,a):Ft(o)?u0(e,o,a):pt(o)?c0(e,o,a):be(o)?m0(e,o,a):a}function Jj(e,o){for(let a of Ee(e)){if(pe(o,a))continue;o[a]=e[a]}return o}function Qj(e){let o={};for(let a of Ee(e))o[a]=Fc(e[a]);return o}function Xj(e){return vh(qR(e))}function vh(e){return e.map((o)=>Fc(o))}function Fc(e){let o=St(e)?F(Fc(e.items),Ma(e)):Ke(e)?Mn(vh(e.allOf)):be(e)?g(Xj(e.anyOf)):He(e)?l(Qj(e.properties)):Kt(e)?ks(di(e),Fc(or(e))):pt(e)?Ur(vh(e.items)):e;return Jj(e,o)}function au(e){return Fc(e)}function Lo(...e){let[o,a,u]=kn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]}),m=Bo().unionPrioritySort?au(a):a;return bn(o,m,u)}function Io(e){return ut(e)&&pe(e,"value")}function Fe(e){return{value:e}}function kr(){return}function Yj(e){return qe(e)?Fe(e):Fe([e])}function Zj(e){return M(e,!0)?Fe(BigInt(1)):Fe(BigInt(0))}var eU=/^-?(0|[1-9]\d*)n$/,tU=/^-?(0|[1-9]\d*)\.\d+$/,rU=/^-?(0|[1-9]\d*)$/;function nU(e){return eU.test(e)}function oU(e){return tU.test(e)}function sU(e){return rU.test(e)}function iU(e){let o=e.toLowerCase();return nU(e)?Fe(BigInt(e.slice(0,e.length-1))):oU(e)?Fe(BigInt(e.split(".")[0])):sU(e)?Fe(BigInt(e)):M(o,"false")?Fe(BigInt(0)):M(o,"true")?Fe(BigInt(1)):kr()}function pl(e){return qr(e)?Fe(e):fn(e)?Zj(e):Ot(e)?Fe(BigInt(Math.trunc(e))):bo(e)?Fe(BigInt(0)):dt(e)?iU(e):Bt(e)?Fe(BigInt(0)):kr()}function aU(e){return M(e,BigInt(0))?Fe(!1):M(e,BigInt(1))?Fe(!0):kr()}function uU(e){return M(e,0)?Fe(!1):M(e,1)?Fe(!0):kr()}function cU(e){return M(e.toLowerCase(),"false")?Fe(!1):M(e.toLowerCase(),"true")?Fe(!0):M(e,"0")?Fe(!1):M(e,"1")?Fe(!0):kr()}function p0(e){return qr(e)?aU(e):fn(e)?Fe(e):Ot(e)?uU(e):bo(e)?Fe(!1):dt(e)?cU(e):Bt(e)?Fe(!1):kr()}function mU(e){return M(e,BigInt(0))?Fe(null):kr()}function pU(e){return M(e,!1)?Fe(null):kr()}function lU(e){return M(e,0)?Fe(null):kr()}function dU(e){let o=e.toLowerCase();return M(o,"undefined")||M(o,"null")||M(e,"")||M(e,"0")?Fe(null):kr()}function fU(e){return qr(e)?mU(e):fn(e)?pU(e):Ot(e)?lU(e):bo(e)?Fe(null):dt(e)?dU(e):Bt(e)?Fe(null):kr()}var l0=BigInt(Number.MAX_SAFE_INTEGER),d0=BigInt(Number.MIN_SAFE_INTEGER);function hU(e){return e<=l0&&e>=d0?Fe(Number(e)):kr()}function gU(e){return Fe(e?1:0)}function yU(e){let o=+e;if(Ot(o))return Fe(o);let a=e.toLowerCase();if(M(a,"false"))return Fe(0);if(M(a,"true"))return Fe(1);let u=pl(e);if(Io(u))return u.value<=l0&&u.value>=d0?Fe(Number(u.value)):kr();return kr()}function Mh(e){return qr(e)?hU(e):fn(e)?gU(e):Ot(e)?Fe(e):bo(e)?Fe(0):dt(e)?yU(e):Bt(e)?Fe(0):kr()}function f0(e){return qr(e)?Fe(e.toString()):fn(e)?Fe(e.toString()):Ot(e)?Fe(e.toString()):bo(e)?Fe("null"):dt(e)?Fe(e):Bt(e)?Fe(""):kr()}function xU(e){return M(e,BigInt(0))?Fe(void 0):kr()}function IU(e){return M(e,!1)?Fe(void 0):kr()}function bU(e){return M(e,0)?Fe(void 0):kr()}function EU(e){let o=e.toLowerCase();return M(o,"undefined")||M(o,"null")||M(e,"")||M(e,"0")?Fe(void 0):kr()}function h0(e){return qr(e)?xU(e):fn(e)?IU(e):Ot(e)?bU(e):bo(e)?Fe(void 0):dt(e)?EU(e):Bt(e)?Fe(e):kr()}function g0(e,o,a){return Yj(a).value.map((m)=>Hr(e,o.items,m))}function y0(e,o,a){let u=pl(a);return Io(u)?u.value:a}function x0(e,o,a){let u=p0(a);return Io(u)?u.value:a}function I0(e,o,a){return Hr({...e,...o.$defs},pn(o.$ref),a)}function b0(e,o,a){return Hr(e,Pn(o),a)}function E0(e,o,a){let u=Mh(a);return Io(u)?Math.trunc(u.value):a}function S0(e,o,a){let u=Mo(e,o),m=Pn(u);return Hr(e,m,a)}function SU(e,o,a){let u=pl(a);return Io(u)&&M(o.const,u.value)?u.value:a}function wU(e,o,a){let u=p0(a);return Io(u)&&M(o.const,u.value)?u.value:a}function TU(e,o,a){let u=Mh(a);return Io(u)&&M(o.const,u.value)?u.value:a}function RU(e,o,a){let u=f0(a);return Io(u)&&M(o.const,u.value)?u.value:a}function w0(e,o,a){if(M(o.const,a))return a;return jx(o)?SU(e,o,a):Ux(o)?wU(e,o,a):wm(o)?TU(e,o,a):Tm(o)?RU(e,o,a):jr()}function T0(e,o,a){let u=fU(a);return Io(u)?u.value:a}function R0(e,o,a){let u=Mh(a);return Io(u)?u.value:a}function ll(e,o,a,u){let m=Ee(u);for(let[p,f]of o)for(let h of m)if(!p.test(h))u[h]=Hr(e,a,u[h]);return u}function jc(e,o,a){return ln(e)&&Bt(a[o])}function kU(e,o,a){let u=wd(o.properties),m=Ee(a);for(let[p,f]of u)for(let h of m){if(!p.test(h)||jc(f,h,a))continue;a[h]=Hr(e,f,a[h])}return pe(o,"additionalProperties")&&ut(o.additionalProperties)?ll(e,u,o.additionalProperties,a):a}function k0(e,o,a){return Uo(a)?kU(e,o,a):a}function AU(e,o,a){let u=wd(o.patternProperties),m=Ee(a);for(let[p,f]of u)for(let h of m)if(p.test(h))a[h]=Hr(e,f,a[h]);return pe(o,"additionalProperties")&&ut(o.additionalProperties)?ll(e,u,o.additionalProperties,a):a}function A0(e,o,a){return Uo(a)?AU(e,o,a):a}function P0(e,o,a){return pe(e,o.$ref)?Hr(e,e[o.$ref],a):a}function C0(e,o,a){let u=f0(a);return Io(u)?u.value:a}function $0(e,o,a){return Hr(e,Pn(o),a)}function v0(e,o,a){if(!qe(a))return a;for(let u=0;u<Math.min(o.items.length,a.length);u++)a[u]=Hr(e,o.items[u],a[u]);return a}function M0(e,o,a){let u=h0(a);return Io(u)?u.value:a}function O0(e,o,a){if(o.anyOf.some((f)=>Zt(e,f,a)))return a;let p=o.anyOf.map((f)=>Hr(e,f,Gr(a))).find((f)=>Zt(e,o,f));return Bt(p)?a:p}function _0(e,o,a){let u=h0(a);return Io(u)?void 0:a}function Hr(e,o,a){return St(o)?g0(e,o,a):go(o)?y0(e,o,a):Vn(o)?x0(e,o,a):Yt(o)?I0(e,o,a):un(o)?b0(e,o,a):yn(o)?E0(e,o,a):Ke(o)?S0(e,o,a):gt(o)?w0(e,o,a):Ts(o)?T0(e,o,a):Cr(o)?R0(e,o,a):He(o)?k0(e,o,a):Kt(o)?A0(e,o,a):Ft(o)?P0(e,o,a):cn(o)?C0(e,o,a):tr(o)?$0(e,o,a):pt(o)?v0(e,o,a):ss(o)?M0(e,o,a):be(o)?O0(e,o,a):yo(o)?_0(e,o,a):a}function ds(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return Hr(o,a,u)}function L0(e,o,a){if(!qe(a))return a;for(let u=0;u<a.length;u++)a[u]=En(e,o.items,a[u]);return a}function N0(e,o,a){return En({...e,...o.$defs},pn(o.$ref),a)}function D0(e,o){if(!Bt(o))return o;return gs(e.default)?e.default():Gr(e.default)}function q0(e,o,a){let u=Mo(e,o),m=Pn(u);return En(e,m,a)}function F0(e,o,a){if(!ut(a))return a;let u=Ee(o.properties);for(let m of u){let p=En(e,o.properties[m],a[m]);if(Bt(p)&&(ln(o.properties[m])||!pe(o.properties[m],"default")))continue;a[m]=p}if(!Oo(o)||fn(o.additionalProperties))return a;for(let m of Ee(a)){if(u.includes(m))continue;a[m]=En(e,o.additionalProperties,a[m])}return a}function j0(e,o,a){if(!ut(a))return a;let[u,m]=[new RegExp(xn(o)),or(o)];for(let p of Ee(a)){if(!(u.test(p)&&To(m)))continue;a[p]=En(e,m,a[p])}if(!Oo(o))return a;for(let p of Ee(a)){if(u.test(p))continue;a[p]=En(e,o.additionalProperties,a[p])}return a}function U0(e,o,a){return pe(e,o.$ref)?En(e,e[o.$ref],a):a}function B0(e,o,a){if(!qe(a))return a;let[u,m]=[o.items,Math.max(o.items.length,a.length)];for(let p=0;p<m;p++)if(p<u.length)a[p]=En(e,u[p],a[p]);return a}function G0(e,o,a){for(let u of o.anyOf){let m=En(e,u,Gr(a));if(Zt(e,u,m))return m}return a}function En(e,o,a){let u=To(o)?D0(o,a):a;return St(o)?L0(e,o,u):Yt(o)?N0(e,o,u):Ke(o)?q0(e,o,u):He(o)?F0(e,o,u):Kt(o)?j0(e,o,u):Ft(o)?U0(e,o,u):pt(o)?B0(e,o,u):be(o)?G0(e,o,u):u}function zs(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return En(o,a,u)}function uu(e){return(...o)=>{let[a,u,m]=kn(o,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return e.reduce((p,f)=>f(a,u,p),m)}}function PU(e,o,a){return o["~codec"].decode(a)}function CU(e,o,a){return o["~codec"].encode(a)}function Ar(e,o,a,u){if(!Kn(a))return u;return M(e,"Decode")?PU(o,a,u):CU(o,a,u)}function $U(e,o,a,u){if(!qe(u))return u;for(let m=0;m<u.length;m++)u[m]=vr(e,o,a.items,u[m]);return Ar(e,o,a,u)}function vU(e,o,a,u){let m=Ar(e,o,a,u);if(!qe(m))return m;for(let p=0;p<m.length;p++)m[p]=vr(e,o,a.items,m[p]);return m}function K0(e,o,a,u){return M(e,"Decode")?$U(e,o,a,u):vU(e,o,a,u)}function H0(e,o,a,u){return u=vr(e,{...o,...a.$defs},pn(a.$ref),u),Ar(e,o,a,u)}function W0(e){return e.reduce((o,a)=>({...o,...a}),{})}function z0(e,o){for(let a of o)if(!$a(e,a))return a;return e}function MU(e,o,a,u){if(M(a.allOf.length,0))return Ar(e,o,a,u);let m=a.allOf.map((h)=>vr(e,o,h,Lo(h,Gr(u)))),f=m.every((h)=>ut(h))?W0(m):z0(u,m);return Ar(e,o,a,f)}function OU(e,o,a,u){if(M(a.allOf.length,0))return Ar(e,o,a,u);let m=Ar(e,o,a,u),p=a.allOf.map((h)=>vr(e,o,h,Lo(h,Gr(m))));if(p.every((h)=>ut(h)))return W0(p);return z0(m,p)}function V0(e,o,a,u){return M(e,"Decode")?MU(e,o,a,u):OU(e,o,a,u)}function _U(e,o,a,u){if(!Uo(u))return u;for(let m of Ee(a.properties)){if(!pe(u,m)||jc(a.properties[m],m,u))continue;u[m]=vr(e,o,a.properties[m],u[m])}return Ar(e,o,a,u)}function LU(e,o,a,u){let m=Ar(e,o,a,u);if(!Uo(m))return m;for(let p of Ee(a.properties)){if(!pe(m,p)||jc(a.properties[p],p,m))continue;m[p]=vr(e,o,a.properties[p],m[p])}return m}function J0(e,o,a,u){return M(e,"Decode")?_U(e,o,a,u):LU(e,o,a,u)}function NU(e,o,a,u){if(!Uo(u))return u;let m=new RegExp(xn(a));for(let p of Ee(u)){if(!m.test(p))continue;u[p]=vr(e,o,or(a),u[p])}return Ar(e,o,a,u)}function DU(e,o,a,u){let m=Ar(e,o,a,u);if(!Uo(m))return m;let p=new RegExp(xn(a));for(let f of Ee(m)){if(!p.test(f))continue;m[f]=vr(e,o,or(a),m[f])}return m}function Q0(e,o,a,u){return M(e,"Decode")?NU(e,o,a,u):DU(e,o,a,u)}function X0(e,o,a,u){return pe(o,a.$ref)?vr(e,o,o[a.$ref],u):u}function Y0(e,o,a,u){return M(e,"Decode")?Ar(e,o,a,X0(e,o,a,u)):X0(e,o,a,Ar(e,o,a,u))}function qU(e,o,a,u){if(!qe(u))return u;for(let m=0;m<Math.min(a.items.length,u.length);m++)u[m]=vr(e,o,a.items[m],u[m]);return Ar(e,o,a,u)}function FU(e,o,a,u){let m=Ar(e,o,a,u);if(!qe(m))return u;for(let p=0;p<Math.min(a.items.length,m.length);p++)m[p]=vr(e,o,a.items[p],m[p]);return m}function Z0(e,o,a,u){return M(e,"Decode")?qU(e,o,a,u):FU(e,o,a,u)}function jU(e,o,a,u){for(let m of a.anyOf){if(!Zt(o,m,u))continue;let p=vr(e,o,m,u);return Ar(e,o,a,p)}return u}function UU(e,o,a,u){let m=Ar(e,o,a,u);for(let p of a.anyOf){let f=vr(e,o,p,Gr(m));if(!Zt(o,p,f))continue;return f}return m}function eC(e,o,a,u){return M(e,"Decode")?jU(e,o,a,u):UU(e,o,a,u)}function vr(e,o,a,u){return St(a)?K0(e,o,a,u):Yt(a)?H0(e,o,a,u):Ke(a)?V0(e,o,a,u):He(a)?J0(e,o,a,u):Kt(a)?Q0(e,o,a,u):Ft(a)?Y0(e,o,a,u):pt(a)?Z0(e,o,a,u):be(a)?eC(e,o,a,u):Ar(e,o,a,u)}class tC extends ba{constructor(e,o){super("Decode",e,o)}}function BU(e,o,a){if(!Zt(e,o,a))throw new tC(a,Ms(e,o,a));return a}function GU(e,o,a){let u=Bo().unionPrioritySort?au(o):o;return vr("Decode",e,u,a)}var KU=uu([(e,o,a)=>Gr(a),(e,o,a)=>zs(e,o,a),(e,o,a)=>ds(e,o,a),(e,o,a)=>Lo(e,o,a),(e,o,a)=>BU(e,o,a),(e,o,a)=>GU(e,o,a)]);function Oh(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return KU(o,a,u)}class rC extends ba{constructor(e,o){super("Encode",e,o)}}function HU(e,o,a){if(!Zt(e,o,a))throw new rC(a,Ms(e,o,a));return a}function WU(e,o,a){let u=Bo().unionPrioritySort?au(o):o;return vr("Encode",e,u,a)}var zU=uu([(e,o,a)=>Gr(a),(e,o,a)=>WU(e,o,a),(e,o,a)=>zs(e,o,a),(e,o,a)=>ds(e,o,a),(e,o,a)=>Lo(e,o,a),(e,o,a)=>HU(e,o,a)]);function _h(...e){let[o,a,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return zU(o,a,u)}function VU(e,o){return Kn(o)||Ri(e,o.items)}function JU(e,o){return Kn(o)||nC({...e,...o.$defs},pn(o.$ref))}function QU(e,o){return Kn(o)||o.allOf.some((a)=>Ri(e,a))}function XU(e,o){return Kn(o)||Ee(o.properties).some((a)=>Ri(e,o.properties[a]))}function YU(e,o){return Kn(o)||Ri(e,or(o))}function nC(e,o){if(Lh.has(o.$ref))return!1;return Lh.add(o.$ref),Kn(o)||pe(e,o.$ref)&&Ri(e,e[o.$ref])}function ZU(e,o){return Kn(o)||o.items.some((a)=>Ri(e,a))}function eB(e,o){return Kn(o)||o.anyOf.some((a)=>Ri(e,a))}function Ri(e,o){return St(o)?VU(e,o):Yt(o)?JU(e,o):Ke(o)?QU(e,o):He(o)?XU(e,o):Kt(o)?YU(e,o):Ft(o)?nC(e,o):pt(o)?ZU(e,o):be(o)?eB(e,o):Kn(o)}var Lh=new Set;function Nh(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Lh.clear(),Ri(o,a)}class fs extends Error{constructor(e,o){super(o);this.type=e}}function oC(e,o){return gs(o.default)?o.default(o):ut(o.default)?Gr(o.default):o.default}function sC(e,o){if(bi(o)&&!To(o))throw new fs(o,"Arrays with uniqueItems constraints must specify a default annotation");let a=Ii(o)?o.minItems:0;return Array.from({length:a},()=>Wr(e,o.items))}function iC(e,o){return is(o)?BigInt(o.exclusiveMinimum)+BigInt(1):as(o)?BigInt(o.minimum):BigInt(0)}function aC(e,o){return!1}function uC(e,o){let a=Wr(e,o.instanceType);return class{constructor(){Object.assign(this,a)}}}function cC(e,o){return Wr({...e,...o.$defs},pn(o.$ref))}function mC(e,o){return Wr(e,Pn(o))}function pC(e,o){let a=Wr(e,o.returnType);return()=>a}function lC(e,o){return is(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:as(o)?o.minimum:0}function dC(e,o){let a=Mo(e,o),u=Pn(a);return Wr(e,u)}function fC(e,o){return o.const}function hC(e,o){throw new fs(o,"Cannot create TNever types")}function gC(e,o){return null}function yC(e,o){return is(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:as(o)?o.minimum:0}function xC(e,o){return(Bt(o.required)?[]:o.required).reduce((u,m)=>({...u,[m]:Wr(e,o.properties[m])}),{})}function IC(e,o){if(xa(o)&&!To(o))throw new fs(o,"Record with the minProperties constraint must have a default annotation");return{}}function bC(e,o){return pe(e,o.$ref)?Wr(e,e[o.$ref]):(()=>{throw new fs(o,"Unable to deref Ref")})()}function EC(e,o){if((Ia(o)||ga(o))&&!To(o))throw Error("Strings with format or pattern constraints must specify default");let u=ya(o)?o.minLength:0;return"".padEnd(u)}function SC(e,o){return Symbol()}function wC(e,o){let a=qu(o.pattern);if(cn(a))throw new fs(o,"Unable to create TemplateLiteral due to infinite type expansion");return Wr(e,a)}function TC(e,o){return Array.from({length:o.minItems},(a,u)=>Wr(e,o.items[u]))}function RC(e,o){return}function kC(e,o){if(M(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Wr(e,o.anyOf[0])}function AC(e,o){return}function Wr(e,o){return To(o)?oC(e,o):St(o)?sC(e,o):go(o)?iC(e,o):Vn(o)?aC(e,o):zr(o)?uC(e,o):Yt(o)?cC(e,o):un(o)?mC(e,o):en(o)?pC(e,o):yn(o)?lC(e,o):Ke(o)?dC(e,o):gt(o)?fC(e,o):ho(o)?hC(e,o):Ts(o)?gC(e,o):Cr(o)?yC(e,o):He(o)?xC(e,o):Kt(o)?IC(e,o):Ft(o)?bC(e,o):cn(o)?EC(e,o):Rs(o)?SC(e,o):tr(o)?wC(e,o):pt(o)?TC(e,o):ss(o)?RC(e,o):be(o)?kC(e,o):yo(o)?AC(e,o):void 0}function Os(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Wr(o,a)}class dl extends ba{constructor(e,o){super("Parse",e,o)}}function tB(e,o,a){if(!Zt(e,o,a))throw new dl(a,Ms(e,o,a));return a}var PC=uu([(e,o,a)=>Gr(a),(e,o,a)=>zs(e,o,a),(e,o,a)=>ds(e,o,a),(e,o,a)=>Lo(e,o,a),(e,o,a)=>tB(e,o,a)]);var nB=l({type:i("insert"),path:s(),value:Pr()}),oB=Object({type:i("update"),path:s(),value:Pr()}),sB=l({type:i("delete"),path:s()}),U_e=g([nB,oB,sB]);class fl{constructor(e,o){this.hasCodec=Nh(e,o),this.buildResult=ul(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(Bo().correctiveParse)return PC(this.Context(),this.Type(),e);throw new dl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Ms(this.Context(),this.Type(),e)}Clean(e){return Lo(this.Context(),this.Type(),e)}Convert(e){return ds(this.Context(),this.Type(),e)}Create(){return Os(this.Context(),this.Type())}Default(e){return zs(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Oh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?_h(this.Context(),this.Type(),e):this.Parse(e)}}function qh(...e){let[o,a]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return new fl(o,a)}var $C=new WeakMap,uB=Symbol.for("TypeBox.Kind");function cB(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function mB(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 Fh(e){try{return MC(e)}catch{return}}function pB(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isFinite(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isInteger(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function lB(e,o){let a=o.properties,u=new Set(a?Object.keys(a):[]);if(a)for(let[m,p]of Object.entries(a)){if(!(m in e))continue;e[m]=Sa(e[m],p)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[m,p]of Object.entries(e)){if(u.has(m))continue;e[m]=Sa(p,o.additionalProperties)}}function dB(e,o){if(Array.isArray(o.items)){for(let a=0;a<e.length;a++){let u=o.items[a];if(!u)continue;e[a]=Sa(e[a],u)}return}if(o.items&&typeof o.items==="object")for(let a=0;a<e.length;a++)e[a]=Sa(e[a],o.items)}function vC(e,o){for(let a of o)if(Fh(a)?.Check(e))return e;for(let a of o){let u=structuredClone(e),m=Sa(u,a);if(Fh(a)?.Check(m))return m}return e}function Sa(e,o){let a=e;if(Array.isArray(o.allOf))for(let p of o.allOf)a=Sa(a,p);if(Array.isArray(o.anyOf))a=vC(a,o.anyOf);if(Array.isArray(o.oneOf))a=vC(a,o.oneOf);let u=cB(o),m=u.length>1&&u.some((p)=>mB(a,p));if(u.length>0&&!m)for(let p of u){let f=pB(a,p);if(f!==a){a=f;break}}if(u.includes("object")&&typeof a==="object"&&a!==null&&!Array.isArray(a))lB(a,o);if(u.includes("array")&&Array.isArray(a))dB(a,o);return a}function hl(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let m=0;m<e.length;m++){let p=o.items[m];if(p)hl(e[m],p)}else if(o.items)for(let m of e)hl(m,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let a=e,u=new Set(o.required??[]);for(let[m,p]of Object.entries(o.properties)){if(!(m in a))continue;if(a[m]===null&&!u.has(m)&&typeof p.$ref!=="string"&&Fh(p)?.Check(null)===!1)delete a[m];else hl(a[m],p)}}function MC(e){let o=e,a=$C.get(o);if(a)return a;let u=qh(e);return $C.set(o,u),u}function fB(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let m=e.instancePath.replace(/^\//,"").replace(/\//g,".");return m?`${m}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function hB(e,o){let a=e.find((u)=>u.name===o.name);if(!a)throw Error(`Tool "${o.name}" not found`);return cu(a,o)}function cu(e,o){let a=structuredClone(o.arguments);hl(a,e.parameters),ds(e.parameters,a);let u=MC(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(uB)){let f=Sa(a,e.parameters);if(f!==a)if(typeof a==="object"&&a!==null&&typeof f==="object"&&f!==null){for(let h of Object.keys(a))delete a[h];Object.assign(a,f)}else return u.Check(f)?f:a}if(u.Check(a))return a;let m=u.Errors(a).map((f)=>` - ${fB(f)}: ${f.message}`).join(`
34
34
  `)||"Unknown validation error",p=`Validation failed for tool "${o.name}":
35
35
  ${m}
36
36
 
37
37
  Received arguments:
38
- ${JSON.stringify(o.arguments,null,2)}`;throw Error(p)}var M0;function Uc(){if(!M0)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return M0}async function O0(e,o,a,u,m,p){let f=N0(o,e),h=[...f],I={...o,messages:[...o.messages,...f]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let E of f)await u({type:"message_start",message:E}),await u({type:"message_end",message:E});return await L0(I,h,a,m,u,p??Uc()),h}async function _0(e,o,a,u,m){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 p=[],f={...e};return await a({type:"agent_start"}),await a({type:"turn_start"}),await L0(f,p,o,u,a,m??Uc()),p}async function L0(e,o,a,u,m,p){let f=e,h=a,I,E=!1,S=await h.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||S.length>0){let P=[];if(I){let J=await h.prepareNextTurn?.(I);if(J)f=J.context??f,P=J.messages??[],h={...h,model:J.model??h.model,reasoning:J.thinkingLevel===void 0?h.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(S.length===0)S=await h.getSteeringMessages?.()||[];await m({type:"turn_start"})}for(let J of N0(f,[...P,...S]))await m({type:"message_start",message:J}),await m({type:"message_end",message:J}),f.messages.push(J),o.push(J);S=[];let v=await h.prepareRequest?.({context:f,model:h.model,thinkingLevel:h.reasoning??"off"},u);if(v)f=v.context??f,h={...h,model:v.model??h.model,reasoning:v.thinkingLevel===void 0?h.reasoning:v.thinkingLevel==="off"?void 0:v.thinkingLevel};let _=await fB(f,h,u,m,p);if(o.push(_),_.stopReason==="error"||_.stopReason==="aborted"){I={message:_,toolResults:[],context:f,newMessages:o},await h.finishTurn?.(I,u),await m({type:"turn_end",message:_,toolResults:[]}),await m({type:"agent_end",messages:o});return}let Q=_.content.filter((J)=>J.type==="toolCall"),L=[];if(R=!1,Q.length>0){let J=_.stopReason==="length"?await hB(Q,m):await gB(f,_,h,u,m);L.push(...J.messages),R=!J.terminate;for(let Z of L)f.messages.push(Z),o.push(Z)}I={message:_,toolResults:L,context:f,newMessages:o};let V=await h.finishTurn?.(I,u);if(await m({type:"turn_end",message:_,toolResults:L}),V?.action==="end"){await m({type:"agent_end",messages:o});return}if(E=V?.action==="continue",S=await h.getSteeringMessages?.()||[],R||S.length>0)E=!1}let k=await h.getFollowUpMessages?.()||[];if(k.length>0){E=!1,S=k;continue}if(E){E=!1;continue}break}await m({type:"agent_end",messages:o})}function N0(e,o){let a=-1;for(let S=o.length-1;S>=0;S--)if(o[S].role==="system"){a=S;break}let u=o[a],m=u?o.map((S,R)=>R===a?jh(u,dB):S):o,p=ni(ae([...e.messages,...m]),(e.tools??[]).map(st)),f=p.toolsAdded.length===0&&p.toolsRemoved.length===0;if(u){if(f&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return m.map((S,R)=>R===a?jh(u,p):S)}if(f)return o;let h=jh({role:"system",content:"",timestamp:Date.now()},p),I=o.findIndex((S)=>S.role!=="system"),E=I===-1?o.length:I;return[...o.slice(0,E),h,...o.slice(E)]}var dB={toolsAdded:[],toolsRemoved:[]};function jh(e,{toolsAdded:o,toolsRemoved:a}){let{toolsAdded:u,toolsRemoved:m,...p}=e;return{...p,...o.length>0?{toolsAdded:o}:{},...a.length>0?{toolsRemoved:a}:{}}}async function fB(e,o,a,u,m){let p=e.messages;if(o.transformContext)p=await o.transformContext(p,a);let f=await o.convertToLlm(p),h=bt({messages:f}),I=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,E=await m(o.model,h,{...o,apiKey:I,signal:a}),S=async()=>Object.assign(await E.result(),{thinkingLevel:o.reasoning??"off"}),R=null,k=!1;for await(let v of E)switch(v.type){case"start":R=v.partial,e.messages.push(R),k=!0,await u({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=v.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:v,message:{...R}});break;case"done":case"error":{let _=await S();if(k)e.messages[e.messages.length-1]=_;else e.messages.push(_);if(!k)await u({type:"message_start",message:{..._}});return await u({type:"message_end",message:_}),_}}let P=await S();if(k)e.messages[e.messages.length-1]=P;else e.messages.push(P),await u({type:"message_start",message:{...P}});return await u({type:"message_end",message:P}),P}async function hB(e,o){let a=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let m={toolCall:u,result:Js(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Bc(m,o);let p=Uh(m);await Bh(p,o),a.push(p)}return{messages:a,terminate:!1}}async function gB(e,o,a,u,m){let p=o.content.filter((h)=>h.type==="toolCall"),f=p.some((h)=>e.tools?.find((I)=>I.name===h.name)?.executionMode==="sequential");if(a.toolExecution==="sequential"||f)return yB(e,o,p,a,u,m);return xB(e,o,p,a,u,m)}async function yB(e,o,a,u,m,p){let f=[],h=[];for(let I of a){await p({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let E=await q0(e,o,I,u,m),S;if(E.kind==="immediate")S={toolCall:I,result:E.result,isError:E.isError};else{let k=await j0(E,m,F0(I,p));S=await U0(e,o,E,k,u,m)}await Bc(S,p);let R=Uh(S);if(await Bh(R,p),f.push(S),h.push(R),m?.aborted)break}return{messages:h,terminate:D0(f)}}async function xB(e,o,a,u,m,p){let f=[];for(let E of a){await p({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await q0(e,o,E,u,m);if(S.kind==="immediate"){let R={toolCall:E,result:S.result,isError:S.isError};if(await Bc(R,p),f.push(R),m?.aborted)break;continue}if(f.push(async()=>{if(m?.aborted){let P={toolCall:E,result:Js("Operation aborted"),isError:!0};return await Bc(P,p),P}let R=await j0(S,m,F0(E,p)),k=await U0(e,o,S,R,u,m);return await Bc(k,p),k}),m?.aborted)break}let h=await Promise.all(f.map((E)=>typeof E==="function"?E():Promise.resolve(E))),I=[];for(let E of h){let S=Uh(E);await Bh(S,p),I.push(S)}return{messages:I,terminate:D0(h)}}function D0(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function IB(e,o){if(!e.prepareArguments)return o;let a=e.prepareArguments(o.arguments);if(a===o.arguments)return o;return{...o,arguments:a}}async function q0(e,o,a,u,m,p=e.tools??[]){let f=p.find((h)=>h.name===a.name);if(!f)return{kind:"immediate",result:Js(`Tool ${a.name} not found`),isError:!0};try{let h=IB(f,a),I=cu(f,h);if(u.beforeToolCall){let E=await u.beforeToolCall({assistantMessage:o,toolCall:a,args:I,context:e},m);if(m?.aborted)return{kind:"immediate",result:Js("Operation aborted"),isError:!0};if(E?.block){let S=Js(E.reason||"Tool execution was blocked");if(E.terminate===!0)S.terminate=!0;return{kind:"immediate",result:S,isError:!0}}}if(m?.aborted)return{kind:"immediate",result:Js("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:a,tool:f,args:I}}catch(h){return{kind:"immediate",result:Js(h instanceof Error?h.message:String(h)),isError:!0}}}function F0(e,o){return(a)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:a})}async function j0(e,o,a){let u=[],m=!0,p=performance.now(),f=()=>Math.round(performance.now()-p);try{let h=await e.tool.execute(e.toolCall.id,e.args,o,(E)=>{if(!m)return;u.push(Promise.resolve(a(E)))}),I=f();return m=!1,await Promise.all(u),{result:h,isError:h.isError===!0,durationMs:I}}catch(h){let I=f();return m=!1,await Promise.all(u),{result:Js(h instanceof Error?h.message:String(h)),isError:!0,durationMs:I}}finally{m=!1}}async function U0(e,o,a,u,m,p){let{result:f,isError:h}=u;if(m.afterToolCall)try{let I=await m.afterToolCall({assistantMessage:o,toolCall:a.toolCall,args:a.args,result:f,isError:h,context:e},p);if(I){let E=I.structuredContent??(I.content?void 0:f.structuredContent);if(f={...f,content:I.content??f.content,details:I.details??f.details,usage:I.usage??f.usage,terminate:I.terminate??f.terminate},E===void 0)delete f.structuredContent;else f.structuredContent=E;h=I.isError??h}}catch(I){f=Js(I instanceof Error?I.message:String(I)),h=!0}return{toolCall:a.toolCall,result:f,isError:h,durationMs:u.durationMs}}function Js(e){return{content:[{type:"text",text:e}],details:{}}}async function Bc(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 Uh(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 Bh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function bB(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var EB={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},SB={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 wB(e){let o=e?.tools?.slice()??[],a=e?.messages?.slice()??[],u=no(e?.systemPrompt,o.map(st));if(a[0]?.role!=="system"&&u)a.unshift(u);return{get systemPrompt(){return ri(a)},model:e?.model??SB,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(m){o=m.slice()},get messages(){return a},set messages(m){a=m.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Gh{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 Kh{_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=wB(o.initialState),this.convertToLlm=o.convertToLlm??bB,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Uc(),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 Gh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Gh(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=on(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let a=this.normalizePromptInput(e,o);await this.runPromptMessages(a)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let a=this.followUpQueue.drain();if(a.length>0){await this.runPromptMessages(a);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let a=[{type:"text",text:e}];if(o&&o.length>0)a.push(...o);return[{role:"user",content:a,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(a)=>{await O0(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),a,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await _0(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(a)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(a,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,a=()=>{},u=new Promise((m)=>{a=m});this.activeRun={promise:u,resolve:a,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(m){await this.handleRunFailure(m,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let a={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:EB,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:a}),await this.processEvents({type:"message_end",message:a}),await this.processEvents({type:"turn_end",message:a,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[a]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let a=new Set(this._state.pendingToolCalls);a.add(e.toolCallId),this._state.pendingToolCalls=a;break}case"tool_execution_end":{let a=new Set(this._state.pendingToolCalls);a.delete(e.toolCallId),this._state.pendingToolCalls=a;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let a of this.listeners)await a(e,o)}}var gl=Symbol("basalt.rebind-fetch");function Te(e,...o){return Object.assign(e,{aliases:o})}function wa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function TB(e){let o=[],a="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(a)o.push(a);a="";continue}if(u>="A"&&u<="Z"&&a&&!/[A-Z]$/.test(a))o.push(a),a="";a+=u}if(a)o.push(a);return o}function B0(e,o){if(e.some((v)=>v.name===o))return o;let a=e.map((v)=>v.name),u=(v)=>a.filter((_)=>wa(_)===v),m=u(wa(o));if(m.length===1&&m[0])return m[0];if(m.length>1)return o;let p=o.split(/[.:/]/).pop()??o,f=p===o?[]:u(wa(p));if(f.length===1&&f[0])return f[0];let h=new Map;for(let v of e)for(let _ of v.aliases??[]){let Q=wa(_);h.set(Q,(h.get(Q)??new Set).add(v.name))}let I=(v)=>[...new Set([...u(v),...h.get(v)??[]])],E=I(wa(p));if(E.length===1&&E[0])return E[0];if(E.length>1)return o;let S=TB(p),R=new Set;S.forEach((v,_)=>{R.add(wa(v));let Q=S[_+1];if(Q)R.add(wa(v+Q))});let k=new Set;for(let v of R)for(let _ of I(v))k.add(_);let P=[...k];return P.length===1&&P[0]?P[0]:o}function T(e){return e}function Tn(e,o){let a=o.indexOf("/");if(a<=0)return;return e.getModel(o.slice(0,a),o.slice(a+1))}function ot(e){return`${e.provider}/${e.id}`}function K0(e,o,a){let u=async(p,f)=>{try{if(o){let I=p instanceof Request?p:void 0;o({at:Date.now(),method:f?.method??I?.method??"GET",url:typeof p==="string"?p:p instanceof URL?p.toString():p.url,headers:G0(f?.headers??I?.headers),body:RB(f?.body!==void 0?f.body:I?.body??void 0)})}}catch{}let h=await e(p,f);if(a)try{let I=Date.now(),{status:E,statusText:S}=h,R=G0(h.headers);if(!h.body)return a({at:I,status:E,statusText:S,headers:R,body:""}),h;let k="",P=new TextDecoder,v=new TransformStream({transform(L,V){V.enqueue(L),k+=P.decode(L,{stream:!0}),a({at:I,status:E,statusText:S,headers:R,body:k})},flush(){k+=P.decode(),a({at:I,status:E,statusText:S,headers:R,body:k})}}),_=h.body.pipeThrough(v),Q=new Response(_,h);try{Object.defineProperty(Q,"url",{value:h.url})}catch{}return Q}catch{}return h},m=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:m,[gl]:(p)=>K0(p,o,a)})}function G0(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,m)=>{o[m]=u}),o;let a=Array.isArray(e)?e:Object.entries(e);for(let u of a)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function RB(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 kB(e,o){return B0(e,o)}function AB(e,o,a){let u=Date.now(),m=new WeakSet,p=(I)=>{if(!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;let E=Date.now(),S=Math.max(10,E-u);I.generationMs=S},f=async(I)=>{if(!a||!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;if(p(I),m.has(I))return;m.add(I),Object.assign(I,await a(I))},h=(I)=>{let E=I?.content;if(!Array.isArray(E))return;for(let S of E)if(S&&S.type==="toolCall"&&typeof S.name==="string")S.name=kB(o(),S.name)};return{async*[Symbol.asyncIterator](){for await(let I of e){let{partial:E,message:S}=I;h(E),await f(S),h(S),yield I}},result:async()=>{let I=await e.result();return p(I),await f(I),h(I),I}}}function Gc(e,o){let a=(o??[]).filter((h)=>h.kind==="path").map((h)=>`<file path=${JSON.stringify(h.data)} />`),u=(o??[]).filter((h)=>h.kind==="text").map((h)=>`<file name=${JSON.stringify(h.name)}>
38
+ ${JSON.stringify(o.arguments,null,2)}`;throw Error(p)}var OC;function Uc(){if(!OC)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return OC}async function _C(e,o,a,u,m,p){let f=DC(o,e),h=[...f],I={...o,messages:[...o.messages,...f]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let E of f)await u({type:"message_start",message:E}),await u({type:"message_end",message:E});return await NC(I,h,a,m,u,p??Uc()),h}async function LC(e,o,a,u,m){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 p=[],f={...e};return await a({type:"agent_start"}),await a({type:"turn_start"}),await NC(f,p,o,u,a,m??Uc()),p}async function NC(e,o,a,u,m,p){let f=e,h=a,I,E=!1,S=await h.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||S.length>0){let P=[];if(I){let J=await h.prepareNextTurn?.(I);if(J)f=J.context??f,P=J.messages??[],h={...h,model:J.model??h.model,reasoning:J.thinkingLevel===void 0?h.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(S.length===0)S=await h.getSteeringMessages?.()||[];await m({type:"turn_start"})}for(let J of DC(f,[...P,...S]))await m({type:"message_start",message:J}),await m({type:"message_end",message:J}),f.messages.push(J),o.push(J);S=[];let v=await h.prepareRequest?.({context:f,model:h.model,thinkingLevel:h.reasoning??"off"},u);if(v)f=v.context??f,h={...h,model:v.model??h.model,reasoning:v.thinkingLevel===void 0?h.reasoning:v.thinkingLevel==="off"?void 0:v.thinkingLevel};let _=await yB(f,h,u,m,p);if(o.push(_),_.stopReason==="error"||_.stopReason==="aborted"){I={message:_,toolResults:[],context:f,newMessages:o},await h.finishTurn?.(I,u),await m({type:"turn_end",message:_,toolResults:[]}),await m({type:"agent_end",messages:o});return}let Q=_.content.filter((J)=>J.type==="toolCall"),L=[];if(R=!1,Q.length>0){let J=_.stopReason==="length"?await xB(Q,m):await IB(f,_,h,u,m);L.push(...J.messages),R=!J.terminate;for(let Z of L)f.messages.push(Z),o.push(Z)}I={message:_,toolResults:L,context:f,newMessages:o};let V=await h.finishTurn?.(I,u);if(await m({type:"turn_end",message:_,toolResults:L}),V?.action==="end"){await m({type:"agent_end",messages:o});return}if(E=V?.action==="continue",S=await h.getSteeringMessages?.()||[],R||S.length>0)E=!1}let k=await h.getFollowUpMessages?.()||[];if(k.length>0){E=!1,S=k;continue}if(E){E=!1;continue}break}await m({type:"agent_end",messages:o})}function DC(e,o){let a=-1;for(let S=o.length-1;S>=0;S--)if(o[S].role==="system"){a=S;break}let u=o[a],m=u?o.map((S,R)=>R===a?jh(u,gB):S):o,p=ni(ae([...e.messages,...m]),(e.tools??[]).map(st)),f=p.toolsAdded.length===0&&p.toolsRemoved.length===0;if(u){if(f&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return m.map((S,R)=>R===a?jh(u,p):S)}if(f)return o;let h=jh({role:"system",content:"",timestamp:Date.now()},p),I=o.findIndex((S)=>S.role!=="system"),E=I===-1?o.length:I;return[...o.slice(0,E),h,...o.slice(E)]}var gB={toolsAdded:[],toolsRemoved:[]};function jh(e,{toolsAdded:o,toolsRemoved:a}){let{toolsAdded:u,toolsRemoved:m,...p}=e;return{...p,...o.length>0?{toolsAdded:o}:{},...a.length>0?{toolsRemoved:a}:{}}}async function yB(e,o,a,u,m){let p=e.messages;if(o.transformContext)p=await o.transformContext(p,a);let f=await o.convertToLlm(p),h=bt({messages:f}),I=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,E=await m(o.model,h,{...o,apiKey:I,signal:a}),S=async()=>Object.assign(await E.result(),{thinkingLevel:o.reasoning??"off"}),R=null,k=!1;for await(let v of E)switch(v.type){case"start":R=v.partial,e.messages.push(R),k=!0,await u({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=v.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:v,message:{...R}});break;case"done":case"error":{let _=await S();if(k)e.messages[e.messages.length-1]=_;else e.messages.push(_);if(!k)await u({type:"message_start",message:{..._}});return await u({type:"message_end",message:_}),_}}let P=await S();if(k)e.messages[e.messages.length-1]=P;else e.messages.push(P),await u({type:"message_start",message:{...P}});return await u({type:"message_end",message:P}),P}async function xB(e,o){let a=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let m={toolCall:u,result:Js(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Bc(m,o);let p=Uh(m);await Bh(p,o),a.push(p)}return{messages:a,terminate:!1}}async function IB(e,o,a,u,m){let p=o.content.filter((h)=>h.type==="toolCall"),f=p.some((h)=>e.tools?.find((I)=>I.name===h.name)?.executionMode==="sequential");if(a.toolExecution==="sequential"||f)return bB(e,o,p,a,u,m);return EB(e,o,p,a,u,m)}async function bB(e,o,a,u,m,p){let f=[],h=[];for(let I of a){await p({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let E=await FC(e,o,I,u,m),S;if(E.kind==="immediate")S={toolCall:I,result:E.result,isError:E.isError};else{let k=await UC(E,m,jC(I,p));S=await BC(e,o,E,k,u,m)}await Bc(S,p);let R=Uh(S);if(await Bh(R,p),f.push(S),h.push(R),m?.aborted)break}return{messages:h,terminate:qC(f)}}async function EB(e,o,a,u,m,p){let f=[];for(let E of a){await p({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await FC(e,o,E,u,m);if(S.kind==="immediate"){let R={toolCall:E,result:S.result,isError:S.isError};if(await Bc(R,p),f.push(R),m?.aborted)break;continue}if(f.push(async()=>{if(m?.aborted){let P={toolCall:E,result:Js("Operation aborted"),isError:!0};return await Bc(P,p),P}let R=await UC(S,m,jC(E,p)),k=await BC(e,o,S,R,u,m);return await Bc(k,p),k}),m?.aborted)break}let h=await Promise.all(f.map((E)=>typeof E==="function"?E():Promise.resolve(E))),I=[];for(let E of h){let S=Uh(E);await Bh(S,p),I.push(S)}return{messages:I,terminate:qC(h)}}function qC(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function SB(e,o){if(!e.prepareArguments)return o;let a=e.prepareArguments(o.arguments);if(a===o.arguments)return o;return{...o,arguments:a}}async function FC(e,o,a,u,m,p=e.tools??[]){let f=p.find((h)=>h.name===a.name);if(!f)return{kind:"immediate",result:Js(`Tool ${a.name} not found`),isError:!0};try{let h=SB(f,a),I=cu(f,h);if(u.beforeToolCall){let E=await u.beforeToolCall({assistantMessage:o,toolCall:a,args:I,context:e},m);if(m?.aborted)return{kind:"immediate",result:Js("Operation aborted"),isError:!0};if(E?.block){let S=Js(E.reason||"Tool execution was blocked");if(E.terminate===!0)S.terminate=!0;return{kind:"immediate",result:S,isError:!0}}}if(m?.aborted)return{kind:"immediate",result:Js("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:a,tool:f,args:I}}catch(h){return{kind:"immediate",result:Js(h instanceof Error?h.message:String(h)),isError:!0}}}function jC(e,o){return(a)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:a})}async function UC(e,o,a){let u=[],m=!0,p=performance.now(),f=()=>Math.round(performance.now()-p);try{let h=await e.tool.execute(e.toolCall.id,e.args,o,(E)=>{if(!m)return;u.push(Promise.resolve(a(E)))}),I=f();return m=!1,await Promise.all(u),{result:h,isError:h.isError===!0,durationMs:I}}catch(h){let I=f();return m=!1,await Promise.all(u),{result:Js(h instanceof Error?h.message:String(h)),isError:!0,durationMs:I}}finally{m=!1}}async function BC(e,o,a,u,m,p){let{result:f,isError:h}=u;if(m.afterToolCall)try{let I=await m.afterToolCall({assistantMessage:o,toolCall:a.toolCall,args:a.args,result:f,isError:h,context:e},p);if(I){let E=I.structuredContent??(I.content?void 0:f.structuredContent);if(f={...f,content:I.content??f.content,details:I.details??f.details,usage:I.usage??f.usage,terminate:I.terminate??f.terminate},E===void 0)delete f.structuredContent;else f.structuredContent=E;h=I.isError??h}}catch(I){f=Js(I instanceof Error?I.message:String(I)),h=!0}return{toolCall:a.toolCall,result:f,isError:h,durationMs:u.durationMs}}function Js(e){return{content:[{type:"text",text:e}],details:{}}}async function Bc(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 Uh(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 Bh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function wB(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var TB={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},RB={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 kB(e){let o=e?.tools?.slice()??[],a=e?.messages?.slice()??[],u=no(e?.systemPrompt,o.map(st));if(a[0]?.role!=="system"&&u)a.unshift(u);return{get systemPrompt(){return ri(a)},model:e?.model??RB,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(m){o=m.slice()},get messages(){return a},set messages(m){a=m.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Gh{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 Kh{_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=kB(o.initialState),this.convertToLlm=o.convertToLlm??wB,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Uc(),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 Gh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Gh(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=on(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let a=this.normalizePromptInput(e,o);await this.runPromptMessages(a)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let a=this.followUpQueue.drain();if(a.length>0){await this.runPromptMessages(a);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let a=[{type:"text",text:e}];if(o&&o.length>0)a.push(...o);return[{role:"user",content:a,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(a)=>{await _C(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),a,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await LC(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(a)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(a,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,a=()=>{},u=new Promise((m)=>{a=m});this.activeRun={promise:u,resolve:a,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(m){await this.handleRunFailure(m,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let a={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:TB,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:a}),await this.processEvents({type:"message_end",message:a}),await this.processEvents({type:"turn_end",message:a,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[a]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let a=new Set(this._state.pendingToolCalls);a.add(e.toolCallId),this._state.pendingToolCalls=a;break}case"tool_execution_end":{let a=new Set(this._state.pendingToolCalls);a.delete(e.toolCallId),this._state.pendingToolCalls=a;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let a of this.listeners)await a(e,o)}}var gl=Symbol("basalt.rebind-fetch");function Te(e,...o){return Object.assign(e,{aliases:o})}function wa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function AB(e){let o=[],a="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(a)o.push(a);a="";continue}if(u>="A"&&u<="Z"&&a&&!/[A-Z]$/.test(a))o.push(a),a="";a+=u}if(a)o.push(a);return o}function GC(e,o){if(e.some((v)=>v.name===o))return o;let a=e.map((v)=>v.name),u=(v)=>a.filter((_)=>wa(_)===v),m=u(wa(o));if(m.length===1&&m[0])return m[0];if(m.length>1)return o;let p=o.split(/[.:/]/).pop()??o,f=p===o?[]:u(wa(p));if(f.length===1&&f[0])return f[0];let h=new Map;for(let v of e)for(let _ of v.aliases??[]){let Q=wa(_);h.set(Q,(h.get(Q)??new Set).add(v.name))}let I=(v)=>[...new Set([...u(v),...h.get(v)??[]])],E=I(wa(p));if(E.length===1&&E[0])return E[0];if(E.length>1)return o;let S=AB(p),R=new Set;S.forEach((v,_)=>{R.add(wa(v));let Q=S[_+1];if(Q)R.add(wa(v+Q))});let k=new Set;for(let v of R)for(let _ of I(v))k.add(_);let P=[...k];return P.length===1&&P[0]?P[0]:o}function T(e){return e}function Tn(e,o){let a=o.indexOf("/");if(a<=0)return;return e.getModel(o.slice(0,a),o.slice(a+1))}function ot(e){return`${e.provider}/${e.id}`}function HC(e,o,a){let u=async(p,f)=>{try{if(o){let I=p instanceof Request?p:void 0;o({at:Date.now(),method:f?.method??I?.method??"GET",url:typeof p==="string"?p:p instanceof URL?p.toString():p.url,headers:KC(f?.headers??I?.headers),body:PB(f?.body!==void 0?f.body:I?.body??void 0)})}}catch{}let h=await e(p,f);if(a)try{let I=Date.now(),{status:E,statusText:S}=h,R=KC(h.headers);if(!h.body)return a({at:I,status:E,statusText:S,headers:R,body:""}),h;let k="",P=new TextDecoder,v=new TransformStream({transform(L,V){V.enqueue(L),k+=P.decode(L,{stream:!0}),a({at:I,status:E,statusText:S,headers:R,body:k})},flush(){k+=P.decode(),a({at:I,status:E,statusText:S,headers:R,body:k})}}),_=h.body.pipeThrough(v),Q=new Response(_,h);try{Object.defineProperty(Q,"url",{value:h.url})}catch{}return Q}catch{}return h},m=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:m,[gl]:(p)=>HC(p,o,a)})}function KC(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,m)=>{o[m]=u}),o;let a=Array.isArray(e)?e:Object.entries(e);for(let u of a)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function PB(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 CB(e,o){return GC(e,o)}function $B(e,o,a){let u=Date.now(),m=new WeakSet,p=(I)=>{if(!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;let E=Date.now(),S=Math.max(10,E-u);I.generationMs=S},f=async(I)=>{if(!a||!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;if(p(I),m.has(I))return;m.add(I),Object.assign(I,await a(I))},h=(I)=>{let E=I?.content;if(!Array.isArray(E))return;for(let S of E)if(S&&S.type==="toolCall"&&typeof S.name==="string")S.name=CB(o(),S.name)};return{async*[Symbol.asyncIterator](){for await(let I of e){let{partial:E,message:S}=I;h(E),await f(S),h(S),yield I}},result:async()=>{let I=await e.result();return p(I),await f(I),h(I),I}}}function Gc(e,o){let a=(o??[]).filter((h)=>h.kind==="path").map((h)=>`<file path=${JSON.stringify(h.data)} />`),u=(o??[]).filter((h)=>h.kind==="text").map((h)=>`<file name=${JSON.stringify(h.name)}>
39
39
  ${h.data}
40
40
  </file>`),m=(o??[]).filter((h)=>h.kind==="image").map((h)=>({type:"image",data:h.data,mimeType:h.mimeType})),p=(o??[]).filter((h)=>h.kind==="image"&&h.id).map((h)=>`<image id=${JSON.stringify(h.id)} name=${JSON.stringify(h.name)} />`);return{merged:[...a,...u,...p,...e.trim()?[e]:[]].join(`
41
41
 
42
- `),images:m}}function Hh(e,o){let{merged:a,images:u}=Gc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:a},...u]:a,timestamp:Date.now()}}function H0(e){let o=new Set;for(let h of e.tools){let I=h.name.toLowerCase();if(o.has(I))throw Error(`Tool names collide ignoring case: ${h.name}`);o.add(I)}let a=new Kh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(h,I,E)=>{let{captureRequest:S,captureResponse:R}=e,k=S||R?{...E,fetch:K0(E?.fetch??globalThis.fetch,S?(v)=>S({...v,model:ot(h)}):void 0,R?(v)=>R({...v,model:ot(h)}):void 0)}:E,P=h.api==="openai-completions"||h.api==="openai-responses"?{...h,compat:{...h.compat,supportsDeveloperRole:!1}}:h;return AB(e.models.streamSimple(P,I,k),()=>a.state.tools,e.hooks.response)},convertToLlm:(h)=>h,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:h,model:I})=>{let E=h.messages.findIndex((P)=>P.role!=="system"),S=h.messages.slice(0,E===-1?h.messages.length:E),R=e.hooks.prepare,k=e.hooks.tools?.()??h.tools;if(k){a.state.tools=k;let P=S[0];if(P?.role==="system")S[0]={...P,toolsAdded:k.map(st),toolsRemoved:void 0}}return{context:{...h,tools:k,messages:await R(S,k,I)}}}:void 0}),u=new Map,m=new Map,p=new WeakSet,f;return a.subscribe((h)=>{if(h.type==="message_update"&&h.message.role==="assistant"){m.clear(),e.hooks.draft(W0(h.message));return}if(h.type==="tool_execution_update"){let E=u.get(h.toolCallId)??We(h.toolName,h.args),S=Array.isArray(h.partialResult?.content)?h.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";m.set(h.toolCallId,{type:"tool_call",id:h.toolCallId,name:E.name,input:E.input,...E.source?{source:E.source}:{},output:S}),e.hooks.draft([...m.values()]);return}if(h.type==="tool_execution_end"){if(m.delete(h.toolCallId))e.hooks.draft(m.size>0?[...m.values()]:null);return}if(h.type!=="message_end")return;if(p.has(h.message)){e.steerConsumed?.(h.message);return}let I=h.message.role==="user"&&f?{type:"user",text:f.text,...f.attachments?.length?{attachments:f.attachments}:{}}:PB(h.message);if(h.message.role==="user")f=void 0;if(I?.type==="assistant"){for(let E of I.parts)if(E.type==="tool_call")u.set(E.id,E)}if(I?.type==="tool_result"){let E=u.get(I.callID);if(E?.source)Object.assign(I,{name:E.name,source:E.source})}if(I)e.hooks.message(I,h.message);if(h.message.role==="assistant")e.hooks.draft(null)}),{agent:a,prompt:(h,I)=>{f={text:h,attachments:I};let{merged:E,images:S}=Gc(h,I);return a.prompt(E,S.length>0?S:void 0)},retry:async()=>{let h=a.state.messages;if(h.at(-1)?.role==="assistant")a.state.messages=h.slice(0,-1);await a.continue()},resume:()=>a.continue(),steer:(h)=>{p.add(h),a.steer(h)},unsteer:(h)=>{let E=a.steeringQueue?.messages;if(!E)return!1;let S=E.indexOf(h);if(S<0){let k=JSON.stringify(h);S=E.findIndex((P)=>JSON.stringify(P)===k)}if(S<0)return!1;let[R]=E.splice(S,1);if(R)p.delete(R);return!0},abort:()=>a.abort()}}function Wh(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 yl(e,o="\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"){let{name:a,source:u}=We(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:a,...u?{source:u}:{},output:o,isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:o}],isError:!0,timestamp:Date.now()}}}function W0(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,...We(o.name,o.arguments)}})}function PB(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:W0(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((a)=>a.type==="image").map((a)=>({mimeType:a.mimeType,data:a.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((a)=>a.type==="text"?a.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class ht extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function C(e){return e}import{createHash as z0}from"crypto";import{existsSync as CB}from"fs";import{readFile as V0,realpath as xl}from"fs/promises";import{dirname as $B,isAbsolute as J0,relative as Q0,resolve as X0,sep as Y0}from"path";var Z0=[...ty];class Il extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class bl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let a=$B(X0(e)),u=X0(a,o??"web.tsx");if(!o&&!CB(u))return;let m=Q0(await xl(a),await xl(u));if(J0(m)||m===".."||m.startsWith(`..${Y0}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let a=this.pending.get(e);if(a)return a;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let a=this.cache.get(e);if(a){let E=!0;for(let[S,R]of a.inputs){let k=await V0(S).catch(()=>{return});if(!k||z0("sha256").update(k).digest("hex")!==R){E=!1;break}}if(E)return a.source;this.cache.delete(e)}let u=await xl(o),m=new Map,p=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:Z0,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(E){E.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(S)=>{if(!Z0.includes(S.path))throw Error(`Unsupported shared web import: ${S.path}`);return{path:S.path,external:!0}}),E.onLoad({filter:/.*/},async(S)=>{let R=Q0(u,await xl(S.path));if(J0(R)||R===".."||R.startsWith(`..${Y0}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await V0(S.path);m.set(S.path,z0("sha256").update(k).digest("hex"));return})}}]}).catch((E)=>{let R=(E instanceof AggregateError?E.errors:[E]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:E})});if(!p.success)throw new Il(p.logs.filter((E)=>E.level==="error").map((E)=>({file:E.position?.file??null,line:E.position?.line??null,message:E.message})));let f=p.outputs.find((E)=>E.kind==="entry-point"&&E.path.endsWith(".js")),h=p.outputs.find((E)=>E.path.endsWith(".css"));if(!f||p.outputs.some((E)=>E!==f&&E!==h))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let I=await f.text();return this.cache.set(e,{source:I,css:await h?.text(),inputs:m}),I}}function No(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function _s(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((a)=>a.type==="text"?a.text:"[image]").join("")}function El(e){return e.content.flatMap((a)=>a.type==="text"&&a.text.trim()?[a.text.trim()]:[]).join(`
42
+ `),images:m}}function Hh(e,o){let{merged:a,images:u}=Gc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:a},...u]:a,timestamp:Date.now()}}function WC(e){let o=new Set;for(let h of e.tools){let I=h.name.toLowerCase();if(o.has(I))throw Error(`Tool names collide ignoring case: ${h.name}`);o.add(I)}let a=new Kh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(h,I,E)=>{let{captureRequest:S,captureResponse:R}=e,k=S||R?{...E,fetch:HC(E?.fetch??globalThis.fetch,S?(v)=>S({...v,model:ot(h)}):void 0,R?(v)=>R({...v,model:ot(h)}):void 0)}:E,P=h.api==="openai-completions"||h.api==="openai-responses"?{...h,compat:{...h.compat,supportsDeveloperRole:!1}}:h;return $B(e.models.streamSimple(P,I,k),()=>a.state.tools,e.hooks.response)},convertToLlm:(h)=>h,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:h,model:I})=>{let E=h.messages.findIndex((P)=>P.role!=="system"),S=h.messages.slice(0,E===-1?h.messages.length:E),R=e.hooks.prepare,k=e.hooks.tools?.()??h.tools;if(k){a.state.tools=k;let P=S[0];if(P?.role==="system")S[0]={...P,toolsAdded:k.map(st),toolsRemoved:void 0}}return{context:{...h,tools:k,messages:await R(S,k,I)}}}:void 0}),u=new Map,m=new Map,p=new WeakSet,f;return a.subscribe((h)=>{if(h.type==="message_update"&&h.message.role==="assistant"){m.clear(),e.hooks.draft(zC(h.message));return}if(h.type==="tool_execution_update"){let E=u.get(h.toolCallId)??We(h.toolName,h.args),S=Array.isArray(h.partialResult?.content)?h.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";m.set(h.toolCallId,{type:"tool_call",id:h.toolCallId,name:E.name,input:E.input,...E.source?{source:E.source}:{},output:S}),e.hooks.draft([...m.values()]);return}if(h.type==="tool_execution_end"){if(m.delete(h.toolCallId))e.hooks.draft(m.size>0?[...m.values()]:null);return}if(h.type!=="message_end")return;if(p.has(h.message)){e.steerConsumed?.(h.message);return}let I=h.message.role==="user"&&f?{type:"user",text:f.text,...f.attachments?.length?{attachments:f.attachments}:{}}:vB(h.message);if(h.message.role==="user")f=void 0;if(I?.type==="assistant"){for(let E of I.parts)if(E.type==="tool_call")u.set(E.id,E)}if(I?.type==="tool_result"){let E=u.get(I.callID);if(E?.source)Object.assign(I,{name:E.name,source:E.source})}if(I)e.hooks.message(I,h.message);if(h.message.role==="assistant")e.hooks.draft(null)}),{agent:a,prompt:(h,I)=>{f={text:h,attachments:I};let{merged:E,images:S}=Gc(h,I);return a.prompt(E,S.length>0?S:void 0)},retry:async()=>{let h=a.state.messages;if(h.at(-1)?.role==="assistant")a.state.messages=h.slice(0,-1);await a.continue()},resume:()=>a.continue(),steer:(h)=>{p.add(h),a.steer(h)},unsteer:(h)=>{let E=a.steeringQueue?.messages;if(!E)return!1;let S=E.indexOf(h);if(S<0){let k=JSON.stringify(h);S=E.findIndex((P)=>JSON.stringify(P)===k)}if(S<0)return!1;let[R]=E.splice(S,1);if(R)p.delete(R);return!0},abort:()=>a.abort()}}function Wh(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 yl(e,o="\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"){let{name:a,source:u}=We(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:a,...u?{source:u}:{},output:o,isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:o}],isError:!0,timestamp:Date.now()}}}function zC(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,...We(o.name,o.arguments)}})}function vB(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:zC(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((a)=>a.type==="image").map((a)=>({mimeType:a.mimeType,data:a.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((a)=>a.type==="text"?a.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class ht extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function C(e){return e}import{createHash as VC}from"crypto";import{existsSync as MB}from"fs";import{readFile as JC,realpath as xl}from"fs/promises";import{dirname as OB,isAbsolute as QC,relative as XC,resolve as YC,sep as ZC}from"path";var e$=[...ry];class Il extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class bl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let a=OB(YC(e)),u=YC(a,o??"web.tsx");if(!o&&!MB(u))return;let m=XC(await xl(a),await xl(u));if(QC(m)||m===".."||m.startsWith(`..${ZC}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let a=this.pending.get(e);if(a)return a;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let a=this.cache.get(e);if(a){let E=!0;for(let[S,R]of a.inputs){let k=await JC(S).catch(()=>{return});if(!k||VC("sha256").update(k).digest("hex")!==R){E=!1;break}}if(E)return a.source;this.cache.delete(e)}let u=await xl(o),m=new Map,p=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:e$,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(E){E.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(S)=>{if(!e$.includes(S.path))throw Error(`Unsupported shared web import: ${S.path}`);return{path:S.path,external:!0}}),E.onLoad({filter:/.*/},async(S)=>{let R=XC(u,await xl(S.path));if(QC(R)||R===".."||R.startsWith(`..${ZC}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await JC(S.path);m.set(S.path,VC("sha256").update(k).digest("hex"));return})}}]}).catch((E)=>{let R=(E instanceof AggregateError?E.errors:[E]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:E})});if(!p.success)throw new Il(p.logs.filter((E)=>E.level==="error").map((E)=>({file:E.position?.file??null,line:E.position?.line??null,message:E.message})));let f=p.outputs.find((E)=>E.kind==="entry-point"&&E.path.endsWith(".js")),h=p.outputs.find((E)=>E.path.endsWith(".css"));if(!f||p.outputs.some((E)=>E!==f&&E!==h))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let I=await f.text();return this.cache.set(e,{source:I,css:await h?.text(),inputs:m}),I}}function No(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function _s(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((a)=>a.type==="text"?a.text:"[image]").join("")}function El(e){return e.content.flatMap((a)=>a.type==="text"&&a.text.trim()?[a.text.trim()]:[]).join(`
43
43
 
44
- `)}function mu(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function pu(e){return e.role==="assistant"&&e.content.length>0}function Po(e){let o=[],a=new Map,u=0;for(let m of e){let p=m.raw;if(p.role==="assistant"){if(pu(p))u++;for(let f of p.content){if(f.type!=="toolCall")continue;let h={call:f,step:u,message:p};o.push(h),a.set(f.id,h)}}else if(p.role==="toolResult"){let f=a.get(p.toolCallId);if(f)f.result=p}}return o}var Sl=new Set(["edit","write"]),e$=new Set(["grep","glob"]);function po(e,o){let a=We(e.name,e.arguments).input?.[o];return typeof a==="string"?a:void 0}function t$(e){return[...new Set(Po(e).flatMap((o)=>Sl.has(We(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&po(o.call,"path")?[po(o.call,"path")]:[]))]}function zh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function wl(e){let o=[{source:"ASSISTANT_TOOL",text:`${We(e.call.name,e.call.arguments).name}(${No(We(e.call.name,e.call.arguments).input)}) [${zh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:mu(e.result)});return o}function F(e){let o=0,a=0,u=0;for(let m of e){let p=m.codePointAt(0);if(p<=127)o++;else if(p>=19968&&p<=40959||p>=12288&&p<=12351||p>=65280&&p<=65519||p>=131072&&p<=173791)a++;else u++}return Math.max(0,Math.ceil(o/4+a+u/2))}var Vh=8192;function q(e){let o=e,a=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let m of o.content)if(m.type==="text")u+=m.text;else a++;else if(o.role==="assistant")for(let m of o.content)if(m.type==="text")u+=m.text;else if(m.type==="thinking")u+=m.thinking;else u+=`${m.name}${No(m.arguments)}`;else if(o.role==="toolResult")for(let m of o.content)if(m.type==="text")u+=m.text;else a++;else u=No(e);return F(u)+16+a*Vh}function ki(e=[]){return e.reduce((o,a)=>o+F(a.name+a.description+No(a.parameters))+16,0)}function Fn(e,o){let a=e.replace(/\s+/g," ").trim();if(F(a)<=o)return a;let u=Math.min(a.length,o*4);while(u>0&&F(a.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${a.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Co(e,o,a=Number.POSITIVE_INFINITY){if(F(e)<=o&&e.length<=a)return e;let u=`
44
+ `)}function mu(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function pu(e){return e.role==="assistant"&&e.content.length>0}function Po(e){let o=[],a=new Map,u=0;for(let m of e){let p=m.raw;if(p.role==="assistant"){if(pu(p))u++;for(let f of p.content){if(f.type!=="toolCall")continue;let h={call:f,step:u,message:p};o.push(h),a.set(f.id,h)}}else if(p.role==="toolResult"){let f=a.get(p.toolCallId);if(f)f.result=p}}return o}var Sl=new Set(["edit","write"]),t$=new Set(["grep","glob"]);function po(e,o){let a=We(e.name,e.arguments).input?.[o];return typeof a==="string"?a:void 0}function r$(e){return[...new Set(Po(e).flatMap((o)=>Sl.has(We(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&po(o.call,"path")?[po(o.call,"path")]:[]))]}function zh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function wl(e){let o=[{source:"ASSISTANT_TOOL",text:`${We(e.call.name,e.call.arguments).name}(${No(We(e.call.name,e.call.arguments).input)}) [${zh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:mu(e.result)});return o}function W(e){let o=0,a=0,u=0;for(let m of e){let p=m.codePointAt(0);if(p<=127)o++;else if(p>=19968&&p<=40959||p>=12288&&p<=12351||p>=65280&&p<=65519||p>=131072&&p<=173791)a++;else u++}return Math.max(0,Math.ceil(o/4+a+u/2))}var Vh=8192;function j(e){let o=e,a=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let m of o.content)if(m.type==="text")u+=m.text;else a++;else if(o.role==="assistant")for(let m of o.content)if(m.type==="text")u+=m.text;else if(m.type==="thinking")u+=m.thinking;else u+=`${m.name}${No(m.arguments)}`;else if(o.role==="toolResult")for(let m of o.content)if(m.type==="text")u+=m.text;else a++;else u=No(e);return W(u)+16+a*Vh}function ki(e=[]){return e.reduce((o,a)=>o+W(a.name+a.description+No(a.parameters))+16,0)}function Fn(e,o){let a=e.replace(/\s+/g," ").trim();if(W(a)<=o)return a;let u=Math.min(a.length,o*4);while(u>0&&W(a.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${a.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Co(e,o,a=Number.POSITIVE_INFINITY){if(W(e)<=o&&e.length<=a)return e;let u=`
45
45
  [... omitted; use history tools for the full text ...]
46
- `,m=Math.floor((o-F(u))/2);if(m<=0)return"";let p=(f)=>{let h=0,I=Math.max(0,Math.min(e.length,m*4,Math.floor((a-u.length)/2)));while(h<I){let E=Math.ceil((h+I)/2),S=f?e.slice(-E):e.slice(0,E);if(F(S)<=m)h=E;else I=E-1}if(!h)return"";return f?e.slice(-h).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,h).replace(/[\uD800-\uDBFF]$/,"")};return`${p(!1)}${u}${p(!0)}`}function Tl(e,o){if(F(e.join(`
47
- `))<=o)return e;let a=(S)=>`- [... ${S} steps omitted; use history tools for the full text ...]`,u=o-F(a(e.length)),m=[],p=[],f=0,h=0,I=e.length-1;while(h<=I){let S=m.length<=p.length,R=S?e[h]:e[I],k=F(`${R}
48
- `);if(f+k>u)break;if(f+=k,S)m.push(e[h++]);else p.unshift(e[I--])}let E=I-h+1;return[...m,...E>0?[a(E)]:[],...p]}function Qs(e){let o=[],a;for(let u of e){let m=u.entry;if(m.type==="run"&&m.state==="start"){a={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(a);continue}if(m.type==="run"&&m.state==="end"){if(a)a.end=m.seq,a.status=vB(m.reason,a.records);a=void 0;continue}if(m.type==="extension"||!u.raw)continue;if(!a&&m.type==="user"&&m.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!a)a={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(a);a.records.push(u)}for(let u of o)u.records=Jh(u.records);return o}function Jh(e){if(e.length<=1)return[...e];let o=[],a=[],u=new Set;for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;let f=p.raw?.role;if(f==="assistant"){let I=p.raw.content?.filter((E)=>E.type==="toolCall")??[];if(I.length>0)for(let E of I)u.add(E.id);if(o.push(p),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(f==="toolResult"){let h=p.raw;if(h.toolCallId)u.delete(h.toolCallId);if(o.push(p),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(f==="user"){if(o.length===0){o.push(p);continue}let h=e.slice(m+1).some((I)=>I.raw?.role==="assistant");if(u.size>0||h){a.push(p);continue}o.push(p);continue}o.push(p)}if(a.length>0)o.push(...a);return o}function vB(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let a=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return a?.stopReason==="error"&&ha(a)?"interrupted":"failed";if(!a)return"completed";switch(a.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ha(a)?"interrupted":"failed";default:return"interrupted"}}function Ta(e){for(let o=e.length-1;o>=0;o--){let a=e[o]?.entry;if(a?.type==="compaction")return a.through}return 0}function Rl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((a)=>a.entry.seq<=o)}function Qh(e,o){return e.find((a)=>a.start<o&&!Rl(a,o)&&a.records.some((u)=>u.entry.seq<=o))}function lu(e){let o=Ta(e),u=Qs(e).findLast((m)=>m.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function kl(e){let o=Ta(e);return Qh(Qs(e),o)?.end}function Kc(e,o){let a=Ta(e),u=Qs(e).at(-1);if(!u||u.end!==void 0)return;let m=u.records.filter((S)=>S.entry.seq>a),p=[],f=new Set;for(let S of m){let R=S.raw,k=q(S.raw);if(R.role==="assistant"){for(let P of R.content)if(P.type==="toolCall")f.add(P.id)}else if(R.role==="toolResult")f.delete(R.toolCallId);if(pu(R)||!p.length||R.role==="user"&&p.at(-1)?.assistant)p.push({end:S.entry.seq,tokens:k,assistant:pu(R),pending:f.size});else{let P=p.at(-1);P.end=S.entry.seq,P.tokens+=k,P.pending=f.size}}let h=p.findLastIndex((S)=>S.assistant),I=0,E;for(let S=p.length-1;S>=0;S--){let R=p[S];if(S<h&&R.assistant&&R.pending===0&&(I<=o||E===void 0))E=R.end;if(I+=R.tokens,I>o&&E!==void 0)break}if(I<=o)return;return E}var r$=2000;function Ai(e,o){let a=F(o);if(a<=r$)return o;let u=new TextEncoder().encode(o).length,m=o.split(`
46
+ `,m=Math.floor((o-W(u))/2);if(m<=0)return"";let p=(f)=>{let h=0,I=Math.max(0,Math.min(e.length,m*4,Math.floor((a-u.length)/2)));while(h<I){let E=Math.ceil((h+I)/2),S=f?e.slice(-E):e.slice(0,E);if(W(S)<=m)h=E;else I=E-1}if(!h)return"";return f?e.slice(-h).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,h).replace(/[\uD800-\uDBFF]$/,"")};return`${p(!1)}${u}${p(!0)}`}function Tl(e,o){if(W(e.join(`
47
+ `))<=o)return e;let a=(S)=>`- [... ${S} steps omitted; use history tools for the full text ...]`,u=o-W(a(e.length)),m=[],p=[],f=0,h=0,I=e.length-1;while(h<=I){let S=m.length<=p.length,R=S?e[h]:e[I],k=W(`${R}
48
+ `);if(f+k>u)break;if(f+=k,S)m.push(e[h++]);else p.unshift(e[I--])}let E=I-h+1;return[...m,...E>0?[a(E)]:[],...p]}function Qs(e){let o=[],a;for(let u of e){let m=u.entry;if(m.type==="run"&&m.state==="start"){a={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(a);continue}if(m.type==="run"&&m.state==="end"){if(a)a.end=m.seq,a.status=_B(m.reason,a.records);a=void 0;continue}if(m.type==="extension"||!u.raw)continue;if(!a&&m.type==="user"&&m.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!a)a={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(a);a.records.push(u)}for(let u of o)u.records=Jh(u.records);return o}function Jh(e){if(e.length<=1)return[...e];let o=[],a=[],u=new Set;for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;let f=p.raw?.role;if(f==="assistant"){let I=p.raw.content?.filter((E)=>E.type==="toolCall")??[];if(I.length>0)for(let E of I)u.add(E.id);if(o.push(p),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(f==="toolResult"){let h=p.raw;if(h.toolCallId)u.delete(h.toolCallId);if(o.push(p),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(f==="user"){if(o.length===0){o.push(p);continue}let h=e.slice(m+1).some((I)=>I.raw?.role==="assistant");if(u.size>0||h){a.push(p);continue}o.push(p);continue}o.push(p)}if(a.length>0)o.push(...a);return o}function _B(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let a=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return a?.stopReason==="error"&&ha(a)?"interrupted":"failed";if(!a)return"completed";switch(a.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ha(a)?"interrupted":"failed";default:return"interrupted"}}function Ta(e){for(let o=e.length-1;o>=0;o--){let a=e[o]?.entry;if(a?.type==="compaction")return a.through}return 0}function Rl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((a)=>a.entry.seq<=o)}function Qh(e,o){return e.find((a)=>a.start<o&&!Rl(a,o)&&a.records.some((u)=>u.entry.seq<=o))}function lu(e){let o=Ta(e),u=Qs(e).findLast((m)=>m.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function kl(e){let o=Ta(e);return Qh(Qs(e),o)?.end}function Kc(e,o){let a=Ta(e),u=Qs(e).at(-1);if(!u||u.end!==void 0)return;let m=u.records.filter((S)=>S.entry.seq>a),p=[],f=new Set;for(let S of m){let R=S.raw,k=j(S.raw);if(R.role==="assistant"){for(let P of R.content)if(P.type==="toolCall")f.add(P.id)}else if(R.role==="toolResult")f.delete(R.toolCallId);if(pu(R)||!p.length||R.role==="user"&&p.at(-1)?.assistant)p.push({end:S.entry.seq,tokens:k,assistant:pu(R),pending:f.size});else{let P=p.at(-1);P.end=S.entry.seq,P.tokens+=k,P.pending=f.size}}let h=p.findLastIndex((S)=>S.assistant),I=0,E;for(let S=p.length-1;S>=0;S--){let R=p[S];if(S<h&&R.assistant&&R.pending===0&&(I<=o||E===void 0))E=R.end;if(I+=R.tokens,I>o&&E!==void 0)break}if(I<=o)return;return E}var n$=2000;function Ai(e,o){let a=W(o);if(a<=n$)return o;let u=new TextEncoder().encode(o).length,m=o.split(`
49
49
  `).length,p=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${m} lines, approximately ${a} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
50
- `),f="</user-text-reference>",h=r$-F(`${p}
50
+ `),f="</user-text-reference>",h=n$-W(`${p}
51
51
 
52
52
  ${f}`);if(h<=0)return o;let I=`${p}
53
53
  ${Co(o,h,o.length-p.length-f.length-3)}
54
- ${f}`;return I.length<o.length&&F(I)<a?I:o}function n$(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let m=Ai(e.entry.seq,o.content);return m===o.content?o:{...o,content:m}}let a=!1,u=o.content.map((m)=>{if(m.type!=="text")return m;let p=Ai(e.entry.seq,m.text);if(p!==m.text)a=!0;return p===m.text?m:{...m,text:p}});return a?{...o,content:u}:o}function Xh(e,o=!1){let a=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),u=a.flatMap((P)=>{let v=P.raw.content;return typeof v==="string"?[]:v.filter((_)=>_.type==="image")}),m=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,p=e.status==="open"?"interrupted":e.status,f="";if(a.length){let P=o?Co(a.map((v)=>_s(v.raw)).join(`
54
+ ${f}`;return I.length<o.length&&W(I)<a?I:o}function o$(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let m=Ai(e.entry.seq,o.content);return m===o.content?o:{...o,content:m}}let a=!1,u=o.content.map((m)=>{if(m.type!=="text")return m;let p=Ai(e.entry.seq,m.text);if(p!==m.text)a=!0;return p===m.text?m:{...m,text:p}});return a?{...o,content:u}:o}function Xh(e,o=!1){let a=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),u=a.flatMap((P)=>{let v=P.raw.content;return typeof v==="string"?[]:v.filter((_)=>_.type==="image")}),m=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,p=e.status==="open"?"interrupted":e.status,f="";if(a.length){let P=o?Co(a.map((v)=>_s(v.raw)).join(`
55
55
 
56
56
  `),600):a.map((v,_)=>`<user-message sequence="${_+1}">
57
57
  ${Ai(v.entry.seq,_s(v.raw))}
@@ -60,63 +60,63 @@ ${Ai(v.entry.seq,_s(v.raw))}
60
60
  `);f=[`<chunk-input id="${e.id}" status="${p}"${o?' excerpt="true"':""}>`,P,...o?[m]:[],"</chunk-input>"].join(`
61
61
  `)}let I=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,E=I?El(I):"",S=[];if(p!=="completed"){let P=Po(e.records),v=new Map(P.map((J)=>[J.call,J])),_=P.slice(-3),Q=new Set(_.map((J)=>J.message)),L=[],V=[];for(let J of e.records){let Z=J.raw;if(Z.role!=="assistant")continue;let ne=Q.has(Z);for(let z of Z.content)if(z.type==="text"&&Z!==I&&z.text.trim())if(ne)V.push(`ASSISTANT: ${Fn(z.text,50)}`);else L.push(`- ASSISTANT: ${Fn(z.text,50)}`);else if(z.type==="toolCall"){let oe=v.get(z);if(!oe)continue;if(ne){if(_.includes(oe))for(let fe of wl(oe))V.push(`${fe.source}: ${Co(fe.text,fe.source==="ASSISTANT_TOOL"?180:360)}`)}else L.push(`- ${z.name}(${Fn(No(z.arguments),40)}) [${zh(oe)}]`)}}S.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",m,...L.length?[`Earlier steps, oldest first:
62
62
  ${Tl(L,o?300:800).join(`
63
- `)}`]:[],...V)}let R=t$(e.records),k=[`<chunk-summary id="${e.id}" status="${p}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,E?o?Co(E,600):E:"No final assistant response was recorded.",...S,...R.length?[`Recorded file changes:
63
+ `)}`]:[],...V)}let R=r$(e.records),k=[`<chunk-summary id="${e.id}" status="${p}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,E?o?Co(E,600):E:"No final assistant response was recorded.",...S,...R.length?[`Recorded file changes:
64
64
  ${Co(R.join(`
65
65
  `),250)}`]:[],...o&&p==="completed"?[m]:[],"</chunk-summary>"].join(`
66
- `);return{input:f,images:u,summary:k,tokens:MB(f,k,u.length)}}function MB(e,o,a){return(e?F(e)+16:0)+F(o)+16+a*Vh}var OB=["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."],_B="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.",LB=1500,NB=80,DB=240;function o$(e,o,a){let u=[],m=0,p=Math.min(o.target,o.hard);for(let h=e.length-1;h>=0;h--){let I=e[h],E=Xh(I),S=m+E.tokens>p?Xh(I,!0):void 0,R=S&&S.tokens<E.tokens?S:E;if(!(!a&&h===e.length-1&&I.status!=="completed")&&m+R.tokens>o.hard)break;m+=R.tokens,u.push({run:I,content:R})}u.reverse();let f=e.slice(0,e.length-u.length);return{visible:u,archived:f,tokens:m}}function s$(e){let{runs:o,visible:a,archived:u,partial:m}=e,p=u.flatMap((I)=>{let E=I.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>_s(R.raw));if(!E.length)return[];let S=I===o[0]?DB:NB;return[`- ${I.id} [${I.status}]: ${Fn(E.join(" / "),S)}`]}),f=new Map(o.map((I,E)=>[I,E+1])),h=[...a.map((I)=>f.get(I)??0),...m?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...OB,...m?[_B]:[],"",`visible chunks: ${a.length+(m?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((I)=>I.id).join(", "):"none"}`,`visible sequences: ${h.length?`${h[0]}..${h.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...p.length?["archived requests, oldest first:",Co(p.join(`
67
- `),LB)]:[],"</conversation-checkpoint>"].join(`
68
- `)}function i$(e,o){let a=e.split(`
66
+ `);return{input:f,images:u,summary:k,tokens:LB(f,k,u.length)}}function LB(e,o,a){return(e?W(e)+16:0)+W(o)+16+a*Vh}var NB=["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."],DB="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.",qB=1500,FB=80,jB=240;function s$(e,o,a){let u=[],m=0,p=Math.min(o.target,o.hard);for(let h=e.length-1;h>=0;h--){let I=e[h],E=Xh(I),S=m+E.tokens>p?Xh(I,!0):void 0,R=S&&S.tokens<E.tokens?S:E;if(!(!a&&h===e.length-1&&I.status!=="completed")&&m+R.tokens>o.hard)break;m+=R.tokens,u.push({run:I,content:R})}u.reverse();let f=e.slice(0,e.length-u.length);return{visible:u,archived:f,tokens:m}}function i$(e){let{runs:o,visible:a,archived:u,partial:m}=e,p=u.flatMap((I)=>{let E=I.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>_s(R.raw));if(!E.length)return[];let S=I===o[0]?jB:FB;return[`- ${I.id} [${I.status}]: ${Fn(E.join(" / "),S)}`]}),f=new Map(o.map((I,E)=>[I,E+1])),h=[...a.map((I)=>f.get(I)??0),...m?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...NB,...m?[DB]:[],"",`visible chunks: ${a.length+(m?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((I)=>I.id).join(", "):"none"}`,`visible sequences: ${h.length?`${h[0]}..${h.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...p.length?["archived requests, oldest first:",Co(p.join(`
67
+ `),qB)]:[],"</conversation-checkpoint>"].join(`
68
+ `)}function a$(e,o){let a=e.split(`
69
69
  `),u=o.split(`
70
- `),m=new Set(a),p=new Set(u),f=[...a.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`- ${Fn(I,40)}`),...u.filter((I)=>I.trim()&&!m.has(I)).map((I)=>`+ ${Fn(I,40)}`)],h=a.find((I)=>I.trim()&&p.has(I));return[...f.slice(0,6),...f.length>6?[`\u2026 ${f.length-6} more changed lines`]:[],...h&&f.every((I)=>I.startsWith("+"))?[`@ ${Fn(h,40)}`]:[]]}function Al(e,o){if(!o)return e;let a=o.endsWith("/")?o:`${o}/`;return e.startsWith(a)?e.slice(a.length):e}function qB(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((a)=>{let u=a&&typeof a==="object"?a.path:void 0;return typeof u==="string"?[u]:[]})}function FB(e,o){let a=po(e,"path");if(Sl.has(e.name)&&a)return`file:${Al(a,o)}`;let u=po(e,"command");if(u)return`command:${u}`;return`${e.name}:${No(e.arguments)}`}function jB(e,o){let a={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let p of Po(e)){let f=u.get(p.step)??[];f.push(p),u.set(p.step,f)}let m=new Map;for(let p of e){let f=p.raw;if(!pu(f))continue;let h=++a.steps,I=El(f);if(I)a.narration.push({step:h,text:Fn(I,60)});for(let{call:E,result:S}of u.get(h)??[]){if(!S)continue;let R=We(E.name,E.arguments),k={...E,name:R.name,arguments:R.input},P=FB(k,o),v=mu(S);if(S.isError){let Z=po(k,"command"),ne=Z?`${k.name} \`${Fn(Z,40)}\``:`${k.name} ${P.startsWith("file:")?P.slice(5):Fn(No(k.arguments),40)}`,z={step:h,key:P,what:ne,detail:Co(v.trim().split(`
70
+ `),m=new Set(a),p=new Set(u),f=[...a.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`- ${Fn(I,40)}`),...u.filter((I)=>I.trim()&&!m.has(I)).map((I)=>`+ ${Fn(I,40)}`)],h=a.find((I)=>I.trim()&&p.has(I));return[...f.slice(0,6),...f.length>6?[`\u2026 ${f.length-6} more changed lines`]:[],...h&&f.every((I)=>I.startsWith("+"))?[`@ ${Fn(h,40)}`]:[]]}function Al(e,o){if(!o)return e;let a=o.endsWith("/")?o:`${o}/`;return e.startsWith(a)?e.slice(a.length):e}function UB(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((a)=>{let u=a&&typeof a==="object"?a.path:void 0;return typeof u==="string"?[u]:[]})}function BB(e,o){let a=po(e,"path");if(Sl.has(e.name)&&a)return`file:${Al(a,o)}`;let u=po(e,"command");if(u)return`command:${u}`;return`${e.name}:${No(e.arguments)}`}function GB(e,o){let a={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let p of Po(e)){let f=u.get(p.step)??[];f.push(p),u.set(p.step,f)}let m=new Map;for(let p of e){let f=p.raw;if(!pu(f))continue;let h=++a.steps,I=El(f);if(I)a.narration.push({step:h,text:Fn(I,60)});for(let{call:E,result:S}of u.get(h)??[]){if(!S)continue;let R=We(E.name,E.arguments),k={...E,name:R.name,arguments:R.input},P=BB(k,o),v=mu(S);if(S.isError){let Z=po(k,"command"),ne=Z?`${k.name} \`${Fn(Z,40)}\``:`${k.name} ${P.startsWith("file:")?P.slice(5):Fn(No(k.arguments),40)}`,z={step:h,key:P,what:ne,detail:Co(v.trim().split(`
71
71
  `).slice(0,8).join(`
72
- `),200)};a.errors.push(z);let oe=m.get(P)??[];oe.push(z),m.set(P,oe);continue}for(let Z of m.get(P)??[])Z.resolved=h;m.delete(P);let _=po(k,"path");if(Sl.has(k.name)&&_){let Z=Al(_,o),ne=a.files.get(Z)??{count:0,first:h,last:h,diffs:[]};if(ne.count++,ne.last=h,ne.diffs.push({step:h,lines:k.name==="edit"?po(k,"old_string")!==void 0?i$(po(k,"old_string")??"",po(k,"new_string")??""):[]:i$("",po(k,"content")??"")}),ne.diffs.length>3)ne.diffs.shift();a.files.set(Z,ne);continue}let Q=k.name==="read"?[..._?[_]:[],...qB(k)]:[];if(Q.length){for(let Z of Q){let ne=Al(Z,o),z=a.reads.get(ne)??[];z.push(h),a.reads.set(ne,z)}continue}if(e$.has(k.name)){let Z=_?` in ${Al(_,o)}`:"",ne=k.name==="grep"&&po(k,"glob")?` (${po(k,"glob")})`:"",z=`${k.name} ${po(k,"pattern")??""}${Z}${ne}`.replace(/\s+/g," "),oe=a.searches.get(z)??{steps:[],head:""};oe.steps.push(h),oe.head=Fn(v.trim().split(`
72
+ `),200)};a.errors.push(z);let oe=m.get(P)??[];oe.push(z),m.set(P,oe);continue}for(let Z of m.get(P)??[])Z.resolved=h;m.delete(P);let _=po(k,"path");if(Sl.has(k.name)&&_){let Z=Al(_,o),ne=a.files.get(Z)??{count:0,first:h,last:h,diffs:[]};if(ne.count++,ne.last=h,ne.diffs.push({step:h,lines:k.name==="edit"?po(k,"old_string")!==void 0?a$(po(k,"old_string")??"",po(k,"new_string")??""):[]:a$("",po(k,"content")??"")}),ne.diffs.length>3)ne.diffs.shift();a.files.set(Z,ne);continue}let Q=k.name==="read"?[..._?[_]:[],...UB(k)]:[];if(Q.length){for(let Z of Q){let ne=Al(Z,o),z=a.reads.get(ne)??[];z.push(h),a.reads.set(ne,z)}continue}if(t$.has(k.name)){let Z=_?` in ${Al(_,o)}`:"",ne=k.name==="grep"&&po(k,"glob")?` (${po(k,"glob")})`:"",z=`${k.name} ${po(k,"pattern")??""}${Z}${ne}`.replace(/\s+/g," "),oe=a.searches.get(z)??{steps:[],head:""};oe.steps.push(h),oe.head=Fn(v.trim().split(`
73
73
  `)[0]??"",25),a.searches.set(z,oe);continue}let L=po(k,"command");if(L){let Z=v.trim().split(`
74
- `);a.commands.push({step:h,command:Fn(L,40),exit:"0",lines:Z.length,tail:Z.slice(-3).map((ne)=>Fn(ne,40))});continue}let V=`${k.name} ${Fn(No(k.arguments),40)}`,J=a.other.get(V)??[];J.push(h),a.other.set(V,J)}}return a}function a$(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Hc(e,o,a){let u=(E,S)=>S===void 0||!E.length?E:Tl(E,S),m=[`<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).`],p=[...e.files];m.push("",`## Modified files (${p.length})`),p.forEach(([E,S],R)=>{if(m.push(`- ${E}: ${S.count} change${S.count>1?"s":""} (step ${S.first}${S.last!==S.first?`-${S.last}`:""})`),R<p.length-a.diffFiles)return;for(let k of S.diffs)m.push(` step ${k.step}:`,...k.lines.map((P)=>` ${P}`))}),m.push("",`## Errors (${e.errors.length})`,...e.errors.map((E)=>E.resolved?`- step ${E.step} ${E.what} (resolved at step ${E.resolved})${a.lists===void 0?`: ${E.detail.replace(/\n/g,`
74
+ `);a.commands.push({step:h,command:Fn(L,40),exit:"0",lines:Z.length,tail:Z.slice(-3).map((ne)=>Fn(ne,40))});continue}let V=`${k.name} ${Fn(No(k.arguments),40)}`,J=a.other.get(V)??[];J.push(h),a.other.set(V,J)}}return a}function u$(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Hc(e,o,a){let u=(E,S)=>S===void 0||!E.length?E:Tl(E,S),m=[`<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).`],p=[...e.files];m.push("",`## Modified files (${p.length})`),p.forEach(([E,S],R)=>{if(m.push(`- ${E}: ${S.count} change${S.count>1?"s":""} (step ${S.first}${S.last!==S.first?`-${S.last}`:""})`),R<p.length-a.diffFiles)return;for(let k of S.diffs)m.push(` step ${k.step}:`,...k.lines.map((P)=>` ${P}`))}),m.push("",`## Errors (${e.errors.length})`,...e.errors.map((E)=>E.resolved?`- step ${E.step} ${E.what} (resolved at step ${E.resolved})${a.lists===void 0?`: ${E.detail.replace(/\n/g,`
75
75
  `)}`:""}`:`- step ${E.step} ${E.what} (UNRESOLVED): ${E.detail.replace(/\n/g,`
76
- `)}`)),m.push("","## Steps",...u(e.narration.map((E)=>`- ${E.step}. ${E.text}`),a.narration));let f=[...e.reads].map(([E,S])=>`- ${E} @ ${S.join(",")}`);m.push("",`## Files read (${f.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(f,a.lists));let h=[...e.searches].map(([E,S])=>`- ${E} \u2192 ${S.head||"(no output)"} (${a$(S.steps)})`);m.push("",`## Searches (${h.length})`,...u(h,a.lists));let I=e.commands.map((E)=>[`- ${E.step}. \`${E.command}\` exit=${E.exit}, ${E.lines} output lines, last ${E.tail.length}:`,...E.tail.map((S)=>` ${S}`)].join(`
77
- `));if(m.push("",`## Commands (${I.length})`,...u(I,a.lists)),e.other.size){let E=[...e.other].map(([S,R])=>`- ${S} (${a$(R)})`);m.push("",`## Other tool calls (${E.length})`,...u(E,a.lists))}return m.push("</work-state>"),m.join(`
78
- `)}function Pl(e,o,a,u){let m=jB(e,u),p=Hc(m,o,{diffFiles:Number.POSITIVE_INFINITY});if(F(p)<=a)return p;let f={...m,narration:[]};for(let E of[Number.POSITIVE_INFINITY,20,10,5]){let S=F(Hc(f,o,{diffFiles:E}));if(S>a*0.7)continue;return Hc(m,o,{narration:Math.max(500,a-S),diffFiles:E})}let h=Math.max(300,Math.floor(a*0.1)),I=F(Hc(f,o,{diffFiles:0,lists:h}));return Hc(m,o,{narration:Math.max(500,a-I),diffFiles:0,lists:h})}function Cl(e){return{role:"user",content:e,timestamp:0}}function Yh(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 u$(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:Cl(e.input)}function du(e){let o=[];for(let a of e){let u=o.at(-1),m=a;if(u?.role==="user"&&m.role==="user"){let p=(f)=>typeof f.content==="string"?[{type:"text",text:f.content}]:f.content;o[o.length-1]={...m,content:[...p(u),{type:"text",text:`
76
+ `)}`)),m.push("","## Steps",...u(e.narration.map((E)=>`- ${E.step}. ${E.text}`),a.narration));let f=[...e.reads].map(([E,S])=>`- ${E} @ ${S.join(",")}`);m.push("",`## Files read (${f.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(f,a.lists));let h=[...e.searches].map(([E,S])=>`- ${E} \u2192 ${S.head||"(no output)"} (${u$(S.steps)})`);m.push("",`## Searches (${h.length})`,...u(h,a.lists));let I=e.commands.map((E)=>[`- ${E.step}. \`${E.command}\` exit=${E.exit}, ${E.lines} output lines, last ${E.tail.length}:`,...E.tail.map((S)=>` ${S}`)].join(`
77
+ `));if(m.push("",`## Commands (${I.length})`,...u(I,a.lists)),e.other.size){let E=[...e.other].map(([S,R])=>`- ${S} (${u$(R)})`);m.push("",`## Other tool calls (${E.length})`,...u(E,a.lists))}return m.push("</work-state>"),m.join(`
78
+ `)}function Pl(e,o,a,u){let m=GB(e,u),p=Hc(m,o,{diffFiles:Number.POSITIVE_INFINITY});if(W(p)<=a)return p;let f={...m,narration:[]};for(let E of[Number.POSITIVE_INFINITY,20,10,5]){let S=W(Hc(f,o,{diffFiles:E}));if(S>a*0.7)continue;return Hc(m,o,{narration:Math.max(500,a-S),diffFiles:E})}let h=Math.max(300,Math.floor(a*0.1)),I=W(Hc(f,o,{diffFiles:0,lists:h}));return Hc(m,o,{narration:Math.max(500,a-I),diffFiles:0,lists:h})}function Cl(e){return{role:"user",content:e,timestamp:0}}function Yh(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 c$(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:Cl(e.input)}function du(e){let o=[];for(let a of e){let u=o.at(-1),m=a;if(u?.role==="user"&&m.role==="user"){let p=(f)=>typeof f.content==="string"?[{type:"text",text:f.content}]:f.content;o[o.length-1]={...m,content:[...p(u),{type:"text",text:`
79
79
 
80
- `},...p(m)]};continue}o.push(a)}return o}function c$(e){let o=[],a=new Map;for(let u of e){let m=u;if(m.role==="toolResult"){if(!a.has(m.toolCallId))continue;let p=a.get(m.toolCallId);if(p===void 0)a.set(m.toolCallId,o.length),o.push(u);else o[p]=u;continue}if(m.role==="assistant"){if(a=new Map,m.stopReason!=="error"&&m.stopReason!=="aborted"){for(let p of m.content)if(p.type==="toolCall")a.set(p.id,void 0)}}else if(m.role==="user")a=new Map;o.push(u)}return o}function UB(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 Me(e,o,a,u={}){let m=Ta(e),p=Qs(e),f=p.filter((Ee)=>Rl(Ee,m)),h=Qh(p,m),I=[],E=[],S=0;for(let Ee of p){if(Rl(Ee,m))continue;let ee=[];for(let ue of Ee.records){if(Ee===h&&ue.entry.seq<=m)continue;let $e=ue.raw.role==="user"?n$(ue):ue.raw;S+=q($e),I.push($e),ee.push($e)}if(u.inspect&&ee.length)E.push({id:`recent-${Ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Ee.id}`,tokens:ee.reduce((ue,$e)=>ue+q($e),0),detail:JSON.stringify(ee,UB,2)})}if(!f.length&&!h)return{items:E,messages:du(I),visible:0,archived:0,open:S,tokens:S,untrimmed:S};let R=o$(f,a,!!h),{visible:k,archived:P}=R,v=R.tokens,_=[],Q="",L="";if(h){let Ee=h.records.filter((ue)=>ue.entry.seq<=m),ee=Ee.filter((ue)=>ue.entry.type==="user"&&!ue.entry.notices&&ue.raw.role==="user");if(ee.length){Q=[`<chunk-input id="${h.id}" status="partial">`,...ee.map(($e,gt)=>`<user-message sequence="${gt+1}">
81
- ${Ai($e.entry.seq,_s($e.raw))}
80
+ `},...p(m)],timestamp:Math.max(u.timestamp,m.timestamp)};continue}o.push(a)}return o}function m$(e){let o=[],a=new Map;for(let u of e){let m=u;if(m.role==="toolResult"){if(!a.has(m.toolCallId))continue;let p=a.get(m.toolCallId);if(p===void 0)a.set(m.toolCallId,o.length),o.push(u);else o[p]=u;continue}if(m.role==="assistant"){if(m.content.length===0)continue;if(a=new Map,m.stopReason!=="error"&&m.stopReason!=="aborted"){for(let p of m.content)if(p.type==="toolCall")a.set(p.id,void 0)}}else if(m.role==="user")a=new Map;o.push(u)}return o}function KB(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 Me(e,o,a,u={}){let m=Ta(e),p=Qs(e),f=p.filter((ee)=>Rl(ee,m)),h=Qh(p,m),I=[],E=[],S=0;for(let ee of p){if(Rl(ee,m))continue;let ue=[];for(let we of ee.records){if(ee===h&&we.entry.seq<=m)continue;let Ve=we.raw.role==="user"?o$(we):we.raw;S+=j(Ve),I.push(Ve),ue.push(Ve)}if(u.inspect&&ue.length)E.push({id:`recent-${ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${ee.id}`,tokens:ue.reduce((we,Ve)=>we+j(Ve),0),detail:JSON.stringify(ue,KB,2)})}if(!f.length&&!h)return{items:E,messages:du(I),visible:0,archived:0,open:S,tokens:S,untrimmed:S};let R=s$(f,a,!!h),{visible:k,archived:P}=R,v=R.tokens,_=[],Q="",L="";if(h){let ee=h.records.filter((we)=>we.entry.seq<=m),ue=ee.filter((we)=>we.entry.type==="user"&&!we.entry.notices&&we.raw.role==="user");if(ue.length){Q=[`<chunk-input id="${h.id}" status="partial">`,...ue.map((Ve,je)=>`<user-message sequence="${je+1}">
81
+ ${Ai(Ve.entry.seq,_s(Ve.raw))}
82
82
  </user-message>`),"</chunk-input>"].join(`
83
- `);let ue=ee.flatMap(($e)=>{let gt=$e.raw.content;return typeof gt==="string"?[]:gt.filter((Ke)=>Ke.type==="image")});_.push(ue.length?{role:"user",content:[{type:"text",text:Q},...ue],timestamp:0}:Cl(Q))}L=Pl(Ee,h,a.index,u.cwd),_.push(Yh(L,o))}let V=e.flatMap((Ee)=>{let ee=Ee.raw;if(Ee.entry.seq>m||ee?.role!=="toolResult"||ee.toolName!=="skill")return[];return[Cl(ee.content.filter((ue)=>ue.type==="text").map((ue)=>ue.text).join(`
84
- `))]}),J="",Z=()=>{J=s$({runs:f,visible:k.map((ee)=>ee.run),archived:P,partial:!!h,tokens:v,budget:a});let Ee=[Cl(J)];for(let{content:ee}of k){if(ee.input)Ee.push(u$(ee));Ee.push(Yh(ee.summary,o))}return[...Ee,...V,..._]},ne=(Ee)=>Ee.reduce((ee,ue)=>ee+q(ue),0),z=Z(),oe=ne(z)+S,fe=oe,{trim:ke}=u;while(ke&&ke.fixed+oe>ke.limit){let Ee=h||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!Ee.length)break;let ee=0,ue=0;for(let $e of Ee)if(ue++,ee+=$e.content.tokens,ee>=ke.fixed+oe-ke.limit)break;P=[...P,...k.slice(0,ue).map(($e)=>$e.run)],k=k.slice(ue),v-=ee,z=Z(),oe=ne(z)+S}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:q(z[0]),detail:J},...k.map(({run:Ee,content:ee})=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"sealed",tokens:(ee.input?q(u$(ee)):0)+q(Yh(ee.summary,o)),detail:[ee.input,ee.summary].filter(Boolean).join(`
83
+ `);let we=ue.flatMap((Ve)=>{let je=Ve.raw.content;return typeof je==="string"?[]:je.filter((Qt)=>Qt.type==="image")});_.push(we.length?{role:"user",content:[{type:"text",text:Q},...we],timestamp:0}:Cl(Q))}L=Pl(ee,h,a.index,u.cwd),_.push(Yh(L,o))}let V=e.flatMap((ee)=>{let ue=ee.raw;if(ee.entry.seq>m||ue?.role!=="toolResult"||ue.toolName!=="skill")return[];return[Cl(ue.content.filter((we)=>we.type==="text").map((we)=>we.text).join(`
84
+ `))]}),J="",Z=e.findLast((ee)=>ee.entry.type==="compaction")?.entry.time??0,ne=()=>{J=i$({runs:f,visible:k.map((ue)=>ue.run),archived:P,partial:!!h,tokens:v,budget:a});let ee=[Cl(J)];for(let{content:ue}of k){if(ue.input)ee.push(c$(ue));ee.push(Yh(ue.summary,o))}return[...ee,...V,..._].map((ue)=>({...ue,timestamp:Z}))},z=(ee)=>ee.reduce((ue,we)=>ue+j(we),0),oe=ne(),fe=z(oe)+S,Ae=fe,{trim:Ge}=u;while(Ge&&Ge.fixed+fe>Ge.limit){let ee=h||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!ee.length)break;let ue=0,we=0;for(let Ve of ee)if(we++,ue+=Ve.content.tokens,ue>=Ge.fixed+fe-Ge.limit)break;P=[...P,...k.slice(0,we).map((Ve)=>Ve.run)],k=k.slice(we),v-=ue,oe=ne(),fe=z(oe)+S}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:j(oe[0]),detail:J},...k.map(({run:ee,content:ue})=>({id:ee.id,label:`Chunk ${ee.id}`,state:"sealed",tokens:(ue.input?j(c$(ue)):0)+j(Yh(ue.summary,o)),detail:[ue.input,ue.summary].filter(Boolean).join(`
85
85
 
86
- `)})),...P.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"})),...h?[{id:h.id,label:`Chunk ${h.id}`,state:"folded",tokens:ne(_),detail:[Q,L].filter(Boolean).join(`
86
+ `)})),...P.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"})),...h?[{id:h.id,label:`Chunk ${h.id}`,state:"folded",tokens:z(_),detail:[Q,L].filter(Boolean).join(`
87
87
 
88
- `)}]:[],...E]:[],messages:du([...z,...I]),visible:k.length,archived:P.length,open:S,tokens:oe,untrimmed:fe}}function me(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Zh=0.97,BB=0.97,m$=0.5,GB=0.05,KB=20000,HB=24000;function Wc(e){return{target:KB,hard:HB,index:Math.floor(me(e)*GB)}}function eg(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class zc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,a=()=>{return}){this.records=e;this.fold=o;this.cwd=a}budget(e){return Wc(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(me(e)*Zh/this.ratio)}prepare(e,o,a,u){let m=me(a),p=Wc(a),f=e.reduce((z,oe)=>z+q(oe),0)+ki(o),h=this.records().at(-1)?.entry.seq??0,I=()=>u?[...u,...this.records().filter((z)=>z.entry.seq>h)]:this.records(),E=()=>Me(I(),a,p,{cwd:this.cwd(),trim:{fixed:f,limit:Math.floor(m*Zh/this.ratio)}}),S=I().findLast((z)=>z.raw?.role==="assistant"),R=S?I().filter((z)=>z.entry.seq>S.entry.seq&&z.raw):[],k=S?.raw,P=()=>S!==void 0&&(S.entry.seq===this.reshapedAfter||I().some((z)=>z.entry.type==="compaction"&&z.entry.seq>S.entry.seq)),v=this.dueSeal(a);if(v!==void 0)this.fold(v,!1),this.reshapedAfter=S?.entry.seq??-1;let _=E(),Q=R.reduce((z,oe)=>z+q(oe.raw),0);if(this.lastEstimate===0&&S&&k&&!P()){let z=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,oe=f+_.untrimmed-q(k)-Q;if(z>0&&oe>0)this.ratio=Math.min(2,Math.max(0.5,z/oe))}let V=((z)=>{let oe=f+z.untrimmed,fe=f+z.tokens;return((S&&k&&!P()&&eg(k)>0?eg(k)+Math.round(this.ratio*Q):void 0)??Math.round(oe*this.ratio))-Math.round((oe-fe)*this.ratio)})(_);if(V>m*BB){let z=V-_.open*this.ratio,oe=Math.max(1000,Math.floor((m*m$-z-p.index)/this.ratio)),fe=S?.entry.seq??-1,ke=I().findLast(($e)=>$e.entry.type==="compaction"&&$e.entry.partial)?.entry.seq??-1,Ee=Math.max(this.lastFoldSeq,ke),ue=(Ee>0?I().filter(($e)=>$e.entry.seq>Ee&&$e.raw?.role==="assistant").length:999)<=1;if(!ue||this.consecutivePartialFolds<2){let $e=Kc(I(),oe);if($e!==void 0)this.fold($e,!0),this.reshapedAfter=fe,this.lastFoldSeq=fe,this.consecutivePartialFolds=ue?this.consecutivePartialFolds+1:1,_=E()}}else this.consecutivePartialFolds=0;this.lastEstimate=f+_.tokens;let J=_.messages,Z=f+_.tokens;if(Math.round(Z*this.ratio)>m)J=WB(J,Math.floor((m-f)/this.ratio)),Z=f+J.reduce((z,oe)=>z+q(oe),0);return this.lastEstimate=Z,{messages:du([...e,...J]),estimate:Z}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((a)=>a.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(kl(o)===void 0){let a=o.findLast((h)=>h.raw?.role==="assistant"),u=a?.raw,m=a!==void 0&&(a.entry.seq===this.reshapedAfter||o.some((h)=>h.entry.type==="compaction"&&h.entry.seq>a.entry.seq)),f=(a?o.filter((h)=>h.entry.seq>a.entry.seq&&h.raw):[]).reduce((h,I)=>h+q(I.raw),0);if(m||!u||eg(u)+f<Math.floor(me(e)*Zh))return}return lu(o)}recover(e){let o=me(e),a=Wc(e),u=Me(this.records(),e,a,{cwd:this.cwd()}),m=Math.floor((o*m$-(o-u.open*this.ratio)-a.index)/this.ratio),p=Kc(this.records(),m);if(p===void 0)return!1;return this.fold(p,!0),this.reshapedAfter=this.records().findLast((f)=>f.raw?.role==="assistant")?.entry.seq??-1,!0}}function WB(e,o){let a=e.reduce((m,p)=>m+q(p),0);if(a<=o)return e;let u=[];for(let m of e){let p=m;if(p.role!=="toolResult"||a<=o){u.push(m);continue}let f=q(m);if(f<=1500){u.push(m);continue}let h=Math.max(500,Math.floor(f/2)),I=p.content.map((R)=>{if(R.type!=="text")return R;return{...R,text:Co(R.text,h)}}),E={...p,content:I},S=q(E);a-=f-S,u.push(E)}return u}var zB=2000;function fu(e,o){let a=[];for(let u of o.replace(/\r\n/g,`
88
+ `)}]:[],...E]:[],messages:du([...oe,...I]),visible:k.length,archived:P.length,open:S,tokens:fe,untrimmed:Ae}}function me(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Zh=0.97,HB=0.97,p$=0.5,WB=0.05,zB=20000,VB=24000;function Wc(e){return{target:zB,hard:VB,index:Math.floor(me(e)*WB)}}function eg(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class zc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,a=()=>{return}){this.records=e;this.fold=o;this.cwd=a}budget(e){return Wc(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(me(e)*Zh/this.ratio)}prepare(e,o,a,u){let m=me(a),p=Wc(a),f=e.reduce((z,oe)=>z+j(oe),0)+ki(o),h=this.records().at(-1)?.entry.seq??0,I=()=>u?[...u,...this.records().filter((z)=>z.entry.seq>h)]:this.records(),E=()=>Me(I(),a,p,{cwd:this.cwd(),trim:{fixed:f,limit:Math.floor(m*Zh/this.ratio)}}),S=I().findLast((z)=>z.raw?.role==="assistant"),R=S?I().filter((z)=>z.entry.seq>S.entry.seq&&z.raw):[],k=S?.raw,P=()=>S!==void 0&&(S.entry.seq===this.reshapedAfter||I().some((z)=>z.entry.type==="compaction"&&z.entry.seq>S.entry.seq)),v=this.dueSeal(a);if(v!==void 0)this.fold(v,!1),this.reshapedAfter=S?.entry.seq??-1;let _=E(),Q=R.reduce((z,oe)=>z+j(oe.raw),0);if(this.lastEstimate===0&&S&&k&&!P()){let z=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,oe=f+_.untrimmed-j(k)-Q;if(z>0&&oe>0)this.ratio=Math.min(2,Math.max(0.5,z/oe))}let V=((z)=>{let oe=f+z.untrimmed,fe=f+z.tokens;return((S&&k&&!P()&&eg(k)>0?eg(k)+Math.round(this.ratio*Q):void 0)??Math.round(oe*this.ratio))-Math.round((oe-fe)*this.ratio)})(_);if(V>m*HB){let z=V-_.open*this.ratio,oe=Math.max(1000,Math.floor((m*p$-z-p.index)/this.ratio)),fe=S?.entry.seq??-1,Ae=I().findLast((we)=>we.entry.type==="compaction"&&we.entry.partial)?.entry.seq??-1,Ge=Math.max(this.lastFoldSeq,Ae),ue=(Ge>0?I().filter((we)=>we.entry.seq>Ge&&we.raw?.role==="assistant").length:999)<=1;if(!ue||this.consecutivePartialFolds<2){let we=Kc(I(),oe);if(we!==void 0)this.fold(we,!0),this.reshapedAfter=fe,this.lastFoldSeq=fe,this.consecutivePartialFolds=ue?this.consecutivePartialFolds+1:1,_=E()}}else this.consecutivePartialFolds=0;this.lastEstimate=f+_.tokens;let J=_.messages,Z=f+_.tokens;if(Math.round(Z*this.ratio)>m)J=JB(J,Math.floor((m-f)/this.ratio)),Z=f+J.reduce((z,oe)=>z+j(oe),0);return this.lastEstimate=Z,{messages:du([...e,...J]),estimate:Z}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((a)=>a.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(kl(o)===void 0){let a=o.findLast((h)=>h.raw?.role==="assistant"),u=a?.raw,m=a!==void 0&&(a.entry.seq===this.reshapedAfter||o.some((h)=>h.entry.type==="compaction"&&h.entry.seq>a.entry.seq)),f=(a?o.filter((h)=>h.entry.seq>a.entry.seq&&h.raw):[]).reduce((h,I)=>h+j(I.raw),0);if(m||!u||eg(u)+f<Math.floor(me(e)*Zh))return}return lu(o)}recover(e){let o=me(e),a=Wc(e),u=Me(this.records(),e,a,{cwd:this.cwd()}),m=Math.floor((o*p$-(o-u.open*this.ratio)-a.index)/this.ratio),p=Kc(this.records(),m);if(p===void 0)return!1;return this.fold(p,!0),this.reshapedAfter=this.records().findLast((f)=>f.raw?.role==="assistant")?.entry.seq??-1,!0}}var tg=500;function JB(e,o){let a=[...e],u=a.map((p)=>j(p)),m=u.reduce((p,f)=>p+f,0);while(m>o){let p=-1;for(let[R,k]of a.entries()){if(k.role!=="toolResult"||(u[R]??0)<=tg)continue;if(p<0||(u[R]??0)>(u[p]??0))p=R}if(p<0)break;let f=a[p],h=u[p]??0,I=Math.max(tg,Math.floor(h/2)),E={...f,content:f.content.map((R)=>R.type==="text"?{...R,text:Co(R.text,I)}:R)},S=j(E);u[p]=S<h?S:tg,a[p]=E,m-=h-S}return a}var QB=2000;function fu(e,o){let a=[];for(let u of o.replace(/\r\n/g,`
89
89
  `).split(`
90
- `))for(let m=0;m<Math.max(u.length,1);){let p=Math.min(u.length,m+zB);if(p<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(p-1)))p--;a.push({source:e,text:u.slice(m,p)}),m=p>m?p:m+1}return a}function hu(e){let o=[],a=Po(e.records),u=new Map(a.map((p)=>[p.call,p])),m=new Set(a.flatMap((p)=>p.result?[p.result]:[]));for(let p of e.records){let f=p.raw;if(f.role==="user")o.push(...fu(p.entry.type==="user"&&p.entry.notices?"NOTICE":"USER",_s(f)));else if(f.role==="assistant"){for(let h of f.content)if(h.type==="text"&&h.text.trim())o.push(...fu("ASSISTANT",h.text));else if(h.type==="toolCall"){let I=u.get(h);if(I)for(let E of wl(I))o.push(...fu(E.source,E.text))}}else if(f.role==="toolResult"&&!m.has(f))o.push(...fu(f.isError?"TOOL_ERROR":"TOOL_OUTPUT",mu(f)))}return o.map((p,f)=>({chunk:e.id,line:f,...p}))}function $l(e,o){let a=e.find((u)=>u.entry.seq===o);if(a?.entry.type!=="user"||a.entry.notices||!a.raw||a.raw.role!=="user")return;return fu("USER",_s(a.raw)).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function vl(e,o){let a=e.find((u)=>u.entry.seq===o)?.entry;if(a?.type!=="extension"||!a.display)return;return fu("EXTENSION",a.display.text).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function Vc(e,o=""){return e.map((a,u)=>{let m=e[u-1],p=m&&m.source===a.source&&m.chunk===a.chunk&&m.line===a.line-1;return`${o}${p?`${a.line}:`:`${a.line} ${a.source}:`} ${a.text}`}).join(`
91
- `)}import{AsyncLocalStorage as VB}from"async_hooks";import{chmodSync as f$,existsSync as JB,mkdirSync as QB,readFileSync as XB,renameSync as YB,writeFileSync as ZB}from"fs";import{dirname as eG,join as tG}from"path";function p$(){let e=Bun.version.split(".").map(Number);if(!((e[0]??0)>1||e[0]===1&&(e[1]??0)>4||e[0]===1&&e[1]===4&&(e[2]??0)>=3))throw Error("\u4EE3\u7406\u4F20\u8F93\u9700\u8981 Bun 1.4.3 \u6216\u66F4\u65B0\u7248\u672C\uFF0C\u8BF7\u5148\u5347\u7EA7 Bun")}function l$(e=process.env){let o={...e};for(let a of["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY"])delete o[a],delete o[a.toLowerCase()];return o}function Jc(e){let o=e.hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1]??o;return u==="localhost"||u.endsWith(".localhost")||u==="::1"||u==="::"||/^(?:0\.|127\.)/.test(u)}function d$(e,o){let a=async(m,p,f)=>{let h=await e(m,{...p,...o.proxy?{proxy:o.proxy}:{proxy:!1},...o.tls==="insecure"?{tls:{rejectUnauthorized:!1}}:{},redirect:"manual"});if(![301,302,303,307,308].includes(h.status))return h;let I=h.headers.get("location");if(!I)return h;if(f>=10)throw Error("\u4EE3\u7406\u8BF7\u6C42\u91CD\u5B9A\u5411\u6B21\u6570\u8FC7\u591A");let E=m instanceof Request?m:void 0,S=new URL(E?.url??String(m)),R=new URL(I,S);if(R.protocol!=="http:"&&R.protocol!=="https:")throw Error("\u62D2\u7EDD\u91CD\u5B9A\u5411\u5230\u975E HTTP \u5730\u5740");if(Jc(R)&&!Jc(S))throw Error("\u62D2\u7EDD\u4ECE\u516C\u7F51\u91CD\u5B9A\u5411\u5230\u56DE\u73AF\u5730\u5740");let k=new Headers(E?.headers);if(new Headers(p?.headers).forEach((_,Q)=>{k.set(Q,_)}),S.origin!==R.origin)k.delete("authorization"),k.delete("cookie"),k.delete("proxy-authorization");let P=(p?.method??E?.method??"GET").toUpperCase(),v={...p,method:P,headers:k};if(h.status===303||(h.status===301||h.status===302)&&P==="POST")v.method="GET",delete v.body,k.delete("content-length"),k.delete("content-type");else if(P!=="GET"&&P!=="HEAD"&&p?.body===void 0&&E?.body)throw Error("\u65E0\u6CD5\u5B89\u5168\u91CD\u5B9A\u5411\u5E26\u6D41\u5F0F\u8BF7\u6C42\u4F53\u7684\u8BF7\u6C42");return await h.body?.cancel(),a(R,v,f+1)};return Object.assign((m,p)=>a(m,p,0),{preconnect:e.preconnect})}var tg=ny,g$=Xr,h$=new VB;class Gn{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;p$(),this.path=tG(e,"proxy.json");let a=async(u,m)=>{let p=h$.getStore();if(!p)return this.baseFetch(u,m);return this.createFetch(p)(u,m)};globalThis.fetch=Object.assign(a,{preconnect:o.preconnect})}load(){if(!JB(this.path))return;this.config=this.validate(JSON.parse(XB(this.path,"utf8")))}settings(){return{...this.config,defaultProfileID:this.config.defaultProfileID,routes:{...this.config.routes},profiles:this.config.profiles.map((e)=>{let{password:o,...a}=e;return{...a,hasPassword:Boolean(o)}})}}save(e){let o=this.validate(e);for(let a of o.profiles)a.password||=this.config.profiles.find((u)=>u.id===a.id)?.password;try{QB(eG(this.path),{recursive:!0});let a=`${this.path}.tmp-${process.pid}`;ZB(a,`${JSON.stringify(o,null,2)}
92
- `,{mode:384}),f$(a,384),YB(a,this.path),f$(this.path,384)}catch(a){throw Error("\u4FDD\u5B58\u4EE3\u7406\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:a})}return this.config=o,this.settings()}createFetch(e,o=this.baseFetch){let a=(m,p="verify")=>d$(o,{proxy:m,tls:p});return Object.assign(async(m,p)=>{let f=m instanceof Request?m.url:String(m),I=this.profileFor(e)?.noProxy?.some((S)=>oG(f,S))??!1;if(Jc(new URL(f))||I)return a()(m,p);let E=this.proxyURL(e);return a(E,this.profileFor(e)?.tls)(m,p)},{preconnect:o.preconnect})}models(e){return new y$(e,this)}providerOptions(e,o,a){let u=Object.assign({},e),m=e?.fetch,f=m?.[gl]?.call(m,this.baseFetch)??m??this.baseFetch;u.fetch=this.createFetch(o,f);let h=l$({...process.env,...e?.env}),I=!1;if(a)try{I=Jc(new URL(a))}catch{}let E=I?void 0:this.proxyURL(o),S=this.profileFor(o);return u.env={...h,...E?{HTTP_PROXY:E,HTTPS_PROXY:E,ALL_PROXY:E}:{},...S?.noProxy?.length?{NO_PROXY:S.noProxy.join(",")}:{}},u}run(e,o){return h$.run(e,o)}wrapProvider(e){let o=ar(e.id),a={...e.auth},u=e.auth.oauth;if(u){let S=e.id==="openai"||e.id===kt?tg:o;a.oauth={...u,login:(R,k)=>this.run(S,()=>u.login(R,k)),refresh:(R,k)=>this.run(S,()=>u.refresh(R,k)),toAuth:(R)=>this.run(S,()=>u.toAuth(R))}}let m={...e,auth:a},p=e.refreshModels;if(p)m.refreshModels=(S)=>this.run(o,()=>p(S));m.stream=(S,R,k)=>this.run(o,()=>e.stream(S,R,this.providerOptions(k,o,S.baseUrl))),m.streamSimple=(S,R,k)=>this.run(o,()=>e.streamSimple(S,R,this.providerOptions(k,o,S.baseUrl)));let f=e.fetchDeferred;if(f)m.fetchDeferred=(S,R,k)=>this.run(o,()=>f(S,R,this.providerOptions(k,o,S.baseUrl)));let h=e.cancelDeferred;if(h)m.cancelDeferred=(S,R,k)=>this.run(o,()=>h(S,R,this.providerOptions(k,o,S.baseUrl)));let I=e.generateImages;if(I)m.generateImages=(S,R,k)=>this.run(o,()=>I(S,R,this.providerOptions(k,o,S.baseUrl)));let E=e.classify;if(E)m.classify=(S,R,k)=>this.run(o,()=>E(S,R,this.providerOptions(k,o,S.baseUrl)));return m}proxyURL(e){let o=this.profileFor(e);if(!o)return;let a=sd(o.address),u=o.username?`${encodeURIComponent(o.username)}:${encodeURIComponent(o.password??"")}@`:"",m=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return`${a.protocol}://${u}${m}:${a.port}`}profileFor(e){let o=e?this.config.routes[e]:this.config.defaultProfileID,a=e&&o!==void 0?o:this.config.defaultProfileID;if(!a)return;let u=this.config.profiles.find((m)=>m.id===a);if(!u)throw Error(`\u4EE3\u7406\u7EBF\u8DEF ${a} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u9875\u91CD\u65B0\u9009\u62E9`);return u}validate(e){let o=rg(e);if(o?.version!==1)throw new t("\u4EE3\u7406\u914D\u7F6E\u7248\u672C\u65E0\u6548");let u=(Array.isArray(o.profiles)?o.profiles:[]).map(rG),m=new Set(u.map((I)=>I.id));if(m.size!==u.length)throw new t("\u4EE3\u7406\u914D\u7F6E ID \u4E0D\u80FD\u91CD\u590D");let p=nG(o.defaultProfileID);if(p&&!m.has(p))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let f=rg(o.routes)??{},h={};for(let[I,E]of Object.entries(f)){if(I!==tg&&I!==g$&&!oy(I))throw new t(`\u4EE3\u7406\u7528\u9014\u65E0\u6548\uFF1A${I}`);if(E!==null&&(typeof E!=="string"||!m.has(E)))throw new t(`\u7528\u9014 ${I} \u7684\u7EBF\u8DEF\u4E0D\u5B58\u5728`);h[I]=E}return{version:1,defaultProfileID:p,routes:h,profiles:u}}}class y${source;manager;wrapped=new Map;constructor(e,o){this.source=e;this.manager=o;for(let a of e.getProviders())this.install(a)}getProviders(){return this.source.getProviders().map((e)=>this.wrap(e))}getProvider(e){let o=this.source.getProvider(e);return o?this.wrap(o):void 0}getModels(...e){return this.source.getModels(...e)}getModel(...e){return this.source.getModel(...e)}getModelsOfType(e,o){return this.source.getModelsOfType(e,o)}getModelOfType(e,o,a){return this.source.getModelOfType(e,o,a)}getAllModels(...e){return this.source.getAllModels(...e)}refresh(...e){return this.source.refresh(...e)}checkAuth(...e){return this.source.checkAuth(...e)}getAvailable(...e){return this.source.getAvailable(...e)}getAvailableOfType(e,o,a){return this.source.getAvailableOfType(e,o,a)}getAllAvailable(...e){return this.source.getAllAvailable(...e)}getAuth(e,o){if(typeof e==="string")return this.source.getAuth(e,o);return this.source.getAuth(e,o)}login(...e){return this.source.login(...e)}logout(...e){return this.source.logout(...e)}stream(e,o,a){return this.source.stream(e,o,a)}complete(e,o,a){return this.source.complete(e,o,a)}streamSimple(...e){return this.source.streamSimple(...e)}completeSimple(...e){return this.source.completeSimple(...e)}streamDeferred(...e){return this.source.streamDeferred(...e)}fetchDeferred(...e){return this.source.fetchDeferred(...e)}cancelDeferred(...e){return this.source.cancelDeferred(...e)}generateImages(...e){return this.source.generateImages(...e)}classify(...e){return this.source.classify(...e)}setProvider(e){this.install(e)}deleteProvider(e){this.source.deleteProvider(e),this.wrapped.delete(e)}clearProviders(){this.source.clearProviders(),this.wrapped.clear()}wrap(e){return this.wrapped.get(e.id)??this.install(e)}install(e){if(this.wrapped.get(e.id)===e)return this.source.setProvider(e),e;let o=this.manager.wrapProvider(e);return this.wrapped.set(e.id,o),this.source.setProvider(o),o}}function ar(e){return`${ry}${e}`}function Xo(e){return[{id:tg,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:g$,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:ar(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function rG(e){let o=rg(e);if(!o)throw new t("\u4EE3\u7406\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof o.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(o.id))throw new t("\u4EE3\u7406\u914D\u7F6E ID \u65E0\u6548");let a;try{a=sd(String(o.address??""))}catch(p){throw new t(p instanceof Error?p.message:"\u4EE3\u7406\u5730\u5740\u65E0\u6548")}let u=Array.isArray(o.noProxy)?o.noProxy:[];if(!u.every((p)=>typeof p==="string"&&p.trim()))throw new t("\u76F4\u8FDE\u4F8B\u5916\u5FC5\u987B\u662F\u975E\u7A7A\u4E3B\u673A");let m=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return{id:o.id,name:typeof o.name==="string"&&o.name.trim()?o.name.trim():a.hostname,address:`${a.protocol}://${m}:${a.port}`,username:typeof o.username==="string"&&o.username?o.username:void 0,password:typeof o.password==="string"&&o.password?o.password:void 0,tls:o.tls==="insecure"?"insecure":"verify",noProxy:u.map((p)=>String(p).trim())}}function nG(e){if(e===void 0||e===null||e==="")return;if(typeof e!=="string")throw new t("\u4EE3\u7406\u7EBF\u8DEF ID \u65E0\u6548");return e}function rg(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function oG(e,o){try{let a=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/^\./,"");return a===u||a.endsWith(`.${u}`)}catch{return!1}}import{join as Wg}from"path";import{existsSync as N$}from"fs";import{realpath as D$}from"fs/promises";import{dirname as q$,isAbsolute as EG,join as F$,relative as SG,resolve as cg,sep as wG}from"path";import{existsSync as sG,watch as iG}from"fs";import{readdir as aG,stat as uG}from"fs/promises";import{basename as ng,dirname as cG,join as x$,resolve as mG}from"path";class og{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,a,u=150){this.host=e;this.slots=o;this.watching=a;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let a=[],u=[];for(let h of[...new Set(e)]){let I;try{I=await aG(h)}catch(E){if(E instanceof Error&&"code"in E&&E.code==="ENOENT")continue;throw E}for(let E of I.sort()){let S=x$(h,E),R=(await uG(S)).isDirectory()?x$(S,"index.ts"):S;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(k){let P=ng(R)==="index.ts"?ng(cG(R)):ng(R,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let v={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};a.push({definition:v,path:R}),this.slots.set(P,{definition:v,path:R,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let m=o.filter((h)=>![...u,...a].some((I)=>I.definition.id===h.definition.id)),p=[...m,...u],f=this.order(p.map(({definition:h})=>h));for(let h of f){let I=p.find((S)=>S.definition===h)?.path,E=m.some((S)=>S.definition===h);try{await this.host.install(h,I,E)}catch(S){this.slots.set(h.id,{definition:h,path:I,builtin:E,enabled:!0,error:S instanceof Error?S.message:String(S)})}}if(this.watching())for(let h of[...p,...a]){if(!sG(h.path))continue;let I=iG(h.path,()=>{let E=h.definition.id,S=this.debounceTimers.get(E);if(S)clearTimeout(S);let R=setTimeout(()=>{this.debounceTimers.delete(E),this.host.reload(E).catch((k)=>{let P=this.slots.get(E);if(P)P.error=k instanceof Error?k.message:String(k)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(E,R)});I.on("error",(E)=>{let S=this.slots.get(h.definition.id);if(S)S.error=E.message,this.host.changed()}),this.watchers.push(I)}}order(e,o=!1){let a=new Map;for(let h of e){if(this.validate(h),a.has(h.id)||!o&&this.slots.has(h.id))throw Error(`Duplicate plugin: ${h.id}`);a.set(h.id,h)}let u=[],m=new Set,p=new Set,f=(h)=>{if(p.has(h.id))return;if(m.has(h.id))throw Error(`Plugin dependency cycle: ${h.id}`);m.add(h.id);for(let I of h.deps??[]){let E=a.get(I);if(E)f(E);else if(!this.slots.has(I))throw Error(`Missing plugin dependency: ${I}`)}m.delete(h.id),p.add(h.id),u.push(h)};for(let h of e)f(h);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${mG(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 I$(e,o,a=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,m;try{return await Promise.race([a?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((p,f)=>{m=setTimeout(()=>{u.abort(),f(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(m)}}import{AsyncLocalStorage as pG}from"async_hooks";import{isDeepStrictEqual as b$}from"util";var Ra=new pG;function Ls(){let e=Ra.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function gu(e){let o=structuredClone(e),a=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let m of Object.values(u))a(m)};return a(o),o}function E$(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let I of["seq","time","session_id","raw"])if(I in o)throw Error(`Entry replacement contains protected field: ${I}`);let a=JSON.parse(JSON.stringify(o,(I,E)=>{if(typeof E==="function"||typeof E==="symbol"||typeof E==="number"&&!Number.isFinite(E))throw Error("Entry replacement must contain JSON values");return E}));if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Entry replacement must serialize to a body");let u=a,m=[];switch(e.type){case"user":m.push("text","attachments");break;case"assistant":m.push("parts","error");break;case"tool_result":m.push("output","images");break;case"extension":m.push("payload","display");break;case"notice_pending":m.push("notice");break;case"run":if(e.state==="end")m.push("error");break;case"compaction":break}let p={...e};for(let I of new Set([...Object.keys(e),...Object.keys(u)])){if(!m.includes(I)&&!b$(p[I],u[I]))throw Error(`Entry replacement changed protected field: ${I}`);if(["seq","time","session_id","raw"].includes(I))throw Error(`Entry replacement contains protected field: ${I}`)}let f=(I)=>I===void 0||typeof I==="string",h=!0;switch(e.type){case"user":h=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((I)=>I&&typeof I.name==="string"&&typeof I.mimeType==="string"&&nm.includes(I.kind)&&typeof I.data==="string"));break;case"assistant":h=f(u.error)&&Array.isArray(u.parts)&&u.parts.every((I)=>I&&(["text","thinking"].includes(I.type)&&typeof I.text==="string"||I.type==="tool_call"&&typeof I.id==="string"&&typeof I.name==="string"&&("input"in I)));break;case"tool_result":h=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((I)=>I&&typeof I.mimeType==="string"&&typeof I.data==="string"));break;case"extension":{let I=u.display;h="payload"in u&&(I===void 0||I!==null&&typeof I==="object"&&("text"in I)&&typeof I.text==="string"&&(!("title"in I)||f(I.title)));break}case"notice_pending":{let E=["text"],S=p.notice,R=u.notice;if(h=!!R&&typeof R==="object"&&!Array.isArray(R),!h)break;let k=R;for(let P of new Set([...Object.keys(S),...Object.keys(k)]))if(E.includes(P)){if(typeof k[P]!=="string")h=!1}else if(!b$(S[P],k[P]))h=!1;break}case"run":h=f(u.error);break;case"compaction":break}if(!h)throw Error("Invalid entry replacement content");return a}function S$(e,o,a,u,m,p){let f=u;for(let h of a.generations)for(let I of h.hooks.get("entry.before_append")??[]){if(h.disabled)break;let E={phase:"before",violated:!1};try{let S=Ra.run(E,()=>{let R=gu(f),k=performance.now(),P=I(R,{sessionID:m,seq:p});if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")throw Promise.resolve(P).catch(()=>{}),Error("entry.before_append must be synchronous");let v=P===void 0?void 0:E$(f,P);if(E.violated)throw Error("entry.before_append attempted a database write");return{validated:v,slow:performance.now()-k>e}});if(S.validated&&JSON.stringify(S.validated)!==JSON.stringify(f))f=S.validated;if(S.slow)throw Error("entry.before_append exceeded budget");h.beforeFailures=0,h.failures=0}catch(S){h.failures=h.beforeFailures++,o(h,S)}}return f}function lG(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return gu(o);return structuredClone(o)}async function w$(e,o,a,u,m,p,f,h,I="end"){let E=p;for(let S of u){if(S.disabled)continue;let R=S.hooks.get(m)??[];for(let k of R){if(S.disabled)break;let P=S.hookOptions.get(k);if(m==="prompt.fragments"&&(P?.promptPosition??"end")!==I)continue;let v=m==="prompt.fragments"?JSON.stringify([f?.id,E]):void 0,_=v===void 0?void 0:S.promptCache.get(k)?.get(v);try{let Q=lG(m,E),L=P?.timeoutMs,V=typeof L==="function"?L({runtime:e.runtime,session:f,connection:h}):L,J=await o((Z)=>k(Q,{runtime:e.runtime,session:f,connection:h,signal:Z}),V);if(v!==void 0){let Z=J===void 0?E:J;if(!Array.isArray(Z)||Z.some((z)=>typeof z!=="string"))throw Error("Prompt fragments must be strings");if(_&&JSON.stringify(_)!==JSON.stringify(Z))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let ne=S.promptCache.get(k)??new Map;ne.set(v,[...Z]),S.promptCache.set(k,ne)}if(S.failures=0,J!==void 0&&m!=="entry.after_append")E=J}catch(Q){if(_)E=structuredClone(_);if(a(S,Q),P?.errorMode==="propagate")throw Q}}}return E}class Qc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,a,u,m="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,a,u,m)}has(e,o){return this.generations.some((a)=>!a.disabled&&(a.hooks.get(e)??[]).some((u)=>o===void 0||(a.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...a)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...a)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((a)=>a(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let a of this.generations){if(a.disabled)continue;for(let u of a.historyResolvers){let m=u(e,o);if(m)return m}}}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 dG}from"fs";import{dirname as fG,resolve as T$}from"path";var sg=new WeakMap;function R$(e){return[...e].map((o)=>{let a=Boolean(o.path&&(Boolean(o.definition.webEntry)||dG(T$(fG(T$(o.path)),"web.tsx"))));if(o.current&&!sg.has(o.current))sg.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:a,webRevision:o.current?sg.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class ig{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,a){this.host=e;this.deadline=o;this.fail=a}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,a){let u=this.host.pin(),m=(async()=>{try{let p=[];for(let f of u.generations){if(f.disabled)continue;for(let h of f.hooks.get(e)??[]){let I=f.hookOptions.get(h)?.timeoutMs,E=typeof I==="function"?I({runtime:this.host.runtime,session:o,connection:a}):I;p.push(this.deadline((S)=>h(o,{runtime:this.host.runtime,session:o,connection:a,signal:S}),E,!0).catch((S)=>this.fail(f,S)))}}await Promise.all(p)}finally{await u.release()}})();this.pending.add(m),m.then(()=>this.pending.delete(m),()=>this.pending.delete(m))}finishEntry(e,o,a){let u=a===void 0?void 0:gu(a),m=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Ra.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,m),this.pending.add(m);let p=()=>{if(this.pending.delete(m),this.entryQueues.get(o)===m)this.entryQueues.delete(o)};m.then(p,p)}}function k$(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 hG(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 gG(e,o){let a=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!a)throw Error("Completion session not found");let u=o.model??a?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let m=Tn(e.options.models,u);if(!m&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!m){let p=(await e.models()).models.filter((h)=>h.available===!0),f=m?ot(m):u;if(!p.some((h)=>h.id===f)){let h=p[0];if(h)m=Tn(e.options.models,h.id)}}if(!m)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return m}async function A$(e,o){hG(o);let a=await gG(e,o),u=o.maxTokens??Math.min(a.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>a.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let m="",p=!1;try{let f=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],h=e.options.models.streamSimple(a,{messages:f},{maxTokens:u,signal:o.signal});for await(let I of h){if(o.signal?.aborted)throw Error("cancelled");if(I.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${k$(I.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(I.type==="text_delta")m+=I.delta;if(I.type==="done"){if(I.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(I.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${I.reason}\uFF09`);p=!0}}}catch(f){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${k$(f instanceof Error?f.message:String(f))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!p)throw Error("Model completion ended without a stop response; retry");return{text:m,model:ot(a)}}var yG=["active","archived","all"];function P$(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function xG(e){let{projectID:o,children:a,archive:u,since:m}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(a!==void 0&&typeof a!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!yG.includes(u))throw Error("sessions archive must be active, archived or all");if(m!==void 0&&!Number.isFinite(m))throw Error("sessions since must be a finite timestamp in milliseconds")}function IG(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function C$(e){function o(a,u={}){let{types:m,bodies:p}=u;if(m!==void 0&&!Array.isArray(m))throw Error("sessions types must be an array");let f=P$(u.limit),h=u.after??0;if(!Number.isSafeInteger(h)||h<0)throw Error("sessions after must be a non-negative integer");let I=(e.get(a)?.entries(h,m,p!==!1)??[]).slice(0,f);return structuredClone(p===!1?I.map(IG):I)}return{list(a={}){xG(a);let u=a.limit===void 0?void 0:P$(a.limit),m=e.list(a.children??!1,{archive:a.archive}).filter((p)=>a.projectID===void 0||p.projectID===a.projectID).filter((p)=>a.since===void 0||p.created>=a.since);return structuredClone(u===void 0?m:m.slice(0,u))},get(a){return structuredClone(e.get(a)?.info())},entries:o}}async function $$(e,o,a,u,m,p){let f={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},h=e.runtime.store.db,I=new Map,E=!1,S=!0,R=()=>{if(!S||f.disposed)throw Error("Plugin registration scope is closed")},k=(L,V)=>{if(R(),!E){I.set(L,V);return}if(V===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,L);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,L,V)},P={get:(L)=>{R();let V=I.has(L)?I.get(L):h.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,L)?.value;return V==null?void 0:JSON.parse(V)},set:(L,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");k(L,J)},delete:(L)=>k(L,null)},v=()=>{if(R(),E)throw Error("Register resources during setup only")},_=[...o.migrations??[]].sort((L,V)=>L.version-V.version),Q=new Set;try{for(let L of _){if(!Number.isSafeInteger(L.version)||L.version<1||Q.has(L.version))throw Error("Plugin migration versions must be unique positive integers");if(Q.add(L.version),h.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,L.version))continue;h.transaction(()=>{if(L.sql!==void 0)h.run(L.sql);else L.up({...P,db:h});for(let[V,J]of I)if(J===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,J);h.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,L.version)})(),e.runtime.store.invalidateEntryCache(),I.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:C$(e.runtime),complete:(L)=>A$(e.runtime,L),kv:P,database:h,broadcast:(L)=>{e.runtime.emitEvent(L)},registerInputGate:(L)=>{v(),f.gates.push(L)},registerNoticeSource:(L,V)=>{if(v(),!L||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");f.noticeSources.set(L,{...V})},provide:(L,V)=>{if(v(),L.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(f.services.has(L.name))throw Error(`Duplicate plugin service: ${L.name}`);if(!L.validate(V))throw Error(`Invalid plugin service: ${L.name}`);f.services.set(L.name,V)},on:(L,V,J)=>{if(v(),J?.promptPosition&&L!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let Z=f.hooks.get(L)??[];if(Z.push(V),f.hooks.set(L,Z),J)f.hookOptions.set(V,J)},registerHistoryResolver:(L)=>{v(),f.historyResolvers.push(L)},registerTool:(L,V)=>{if(v(),!L.name||["toolsearch","tool_search","tool_call"].includes(L.name.toLowerCase())||bG(e,m,o.id).has(L.name.toLowerCase())||f.tools.some((Z)=>Z.name.toLowerCase()===L.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${L.name}`);let J=a?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;f.tools.push({...L,defer:J,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:a})},registerRoute:(L)=>{if(v(),!(L.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>L.path===V||L.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(L.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(f.routes.some((V)=>V.path===L.path&&V.method===L.method))throw Error("Duplicate plugin route");f.routes.push(L)},registerWebSocket:(L)=>{if(v(),!L.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(f.websockets.some((V)=>V.path===L.path))throw Error("Duplicate plugin WebSocket route");f.websockets.push(L)},registerCommand:(L)=>{v(),f.commands.push(L)},registerWebContribution:(L)=>{v(),f.web.push(L)},registerToolPolicy:(L,V)=>{v(),f.policies.set(L,V)},appendExtension:(L,V)=>{if(Ls(),R(),!E)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(L,V)},onDeactivate:(L)=>{v(),f.deactivators.push(L)},onDispose:(L)=>{v(),f.disposers.push(L)}})),h.transaction(()=>{for(let[L,V]of I)if(V===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,L);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,L,V)})(),I.clear(),E=!0,f}catch(L){throw S=!1,await p(f),L}}function bG(e,o,a){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((m)=>m.name)].map((m)=>m.toLowerCase()));for(let[m,p]of o){if(m===a)continue;for(let f of p.current?.tools??[])u.add(f.name.toLowerCase())}return u}class ag{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function v$(e,o,a,u){for(let m of o){let p=m.current;if(!p||p.disabled||p.retired)continue;let f=p.websockets.find((h)=>h.path===u);if(!f)continue;return{connect:(h)=>{let I=!1;p.references++,p.connections.add(h);let E={send:(R)=>{if(I||p.retired||p.disabled)return;h.send(R)},close:(R,k)=>h.close(R,k)},S=async(R)=>{if(I||p.retired||p.disabled){h.close(1012,"Plugin unavailable");return}try{await a(R),p.failures=0}catch(k){if(p.failures++,p.error=k instanceof Error?k.message:String(k),h.close(1011,"Plugin callback failed"),p.failures>=e.failureThreshold){p.disabled=!0;for(let P of p.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>S(()=>f.open?.(E)),message:(R)=>S(()=>f.message(E,R)),close:async()=>{if(I)return;I=!0,p.connections.delete(h);try{await a(()=>f.close?.(E))}catch(R){p.error=R instanceof Error?R.message:String(R)}finally{p.references--,await e.collect(p)}}}}}}return}function ug(e,o){let a=e.split("/"),u=new URL(o.url).pathname.split("/");if(a.length!==u.length)return;let m={};return a.every((f,h)=>{let I=u[h];if(I===void 0)return!1;if(!f.startsWith(":"))return I===f;try{m[f.slice(1)]=decodeURIComponent(I)}catch{return!1}return I.length>0})?m:void 0}async function M$(e,o,a,u,m){let p=e.pin();try{let f=p.generations.find((h)=>h.definition.id===a)?.commands.find((h)=>h.id===u);if(!f)throw new y("Plugin command is unavailable");return await o(()=>f.execute(m))}finally{await p.release()}}function O$(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((m)=>m.method===o.method&&ug(m.path,o)!==void 0))}finally{a.release()}}function _$(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((m)=>m.public===!0&&m.method===o.method&&ug(m.path,o)!==void 0))}finally{a.release()}}async function L$(e,o,a){let u=e.pin(),m=!0;try{for(let p of u.generations)for(let f of p.routes){if(f.method!==a.method)continue;let h=ug(f.path,a);if(h){let I=await o(()=>f.handler(a,h),f.timeoutMs);if(!I)return;if(I.body&&I.body instanceof ReadableStream){m=!1;let E=!1,S=()=>{if(E)return;E=!0,u.release()},R=I.body.getReader(),k=new ReadableStream({async pull(P){try{let{done:v,value:_}=await R.read();if(v)P.close(),S();else P.enqueue(_)}catch(v){P.error(v),S()}},async cancel(P){try{await R.cancel(P)}finally{S()}}});return new Response(k,{status:I.status,statusText:I.statusText,headers:I.headers})}return I}}return}finally{if(m)await u.release()}}class mg{runtime;options;slots=new Map;retirement=new ag(this.deadline.bind(this));observers=new ig(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new bl;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 og(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 y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let a=o.current.services.get(e.name);if(!e.validate(a))throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return a}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((a)=>a(e)))}noticeSource(e){return[...this.slots.values()].findLast((a)=>a.enabled&&a.current&&!a.current.disabled&&a.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let a=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==a)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let a of e)this.directories.add(cg(a));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await D$(e),a=[...this.directories,F$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>F$(u.directory,".basalt","plugins"))];for(let u of a){if(!N$(u))continue;let m=SG(await D$(u),o);if(m&&m!==".."&&!m.startsWith(`..${wG}`)&&!EG(m)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),a=await this.checkEntry(o);if(!a.ok)throw new ht(a.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((a)=>a.level==="error").map((a)=>({file:a.position?.file??null,line:a.position?.line??null,column:a.position?.column??null,message:a.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,a=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,a)})}async installDefinition(e,o,a=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),m={definition:e,path:o,builtin:a,enabled:u?.enabled!==0};if(m.enabled)m.current=await this.stage(e,a);this.slots.set(e.id,m)}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 h=await this.checkEntry(o.path);if(!h.ok)throw new ht(h.errors)}let a=o.builtin&&!N$(o.path)?o.definition:await this.catalog.read(o.path);if(a.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((h)=>h.definition.id===e?a:h.definition),!0),m=await this.stage(a),p=o.current;o.definition=a,o.current=m,o.error=void 0,o.discoveryFailed=!1;let f=new Map(this.slots);this.slots.clear();for(let h of u){let I=f.get(h.id);if(I)this.slots.set(h.id,I)}if(p)await this.retirement.retire(p)}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}})}setEnabled(e,o){return this.exclusive(async()=>{let a=this.require(e);if(o===a.enabled&&(!o||a.current&&!a.current.disabled))return;if(!o){for(let f of this.slots.values())if(f.enabled&&f.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${f.definition.id}`)}let u=o&&a.discoveryFailed&&a.path?await this.catalog.read(a.path):a.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let m=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let p=a.current;if(a.definition=u,o)a.discoveryFailed=!1;if(a.enabled=o,a.current=m,a.error=void 0,p)await this.retirement.retire(p)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let a of e.deps??[])if(a===e.id||!this.slots.get(a)?.current||this.slots.get(a)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${a}`);return $$(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,a){this.observers.notify(e,o,a)}resolveHistory(e,o){for(let a of this.slots.values()){if(!a.enabled||!a.current||a.current.disabled)continue;for(let u of a.current.historyResolvers){let m=u(e,o);if(m)return m}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Qc(this,e)}async invoke(e,o,a,u,m,p="end"){return w$(this,this.deadline.bind(this),this.fail.bind(this),e,o,a,u,m,p)}pinEntry(e){if(Ra.getStore()?.phase==="after")return;let o;for(let a of this.slots.values()){let u=a.current;if(!a.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Qc(this,o)}beforeEntry(e,o,a,u){return S$(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,a,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let a of e.connections)a.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,a){this.observers.finishEntry(e,o,a)}deadline(e,o=this.timeoutMs,a=!1){return I$(e,o,a)}appendExtension(e,o){return Ls(),new Promise((a)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let m=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),a(m)})}list(){return R$(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(a&&o.path)await this.webBuilder.build(a,q$(cg(o.path)));return{ok:!0}}catch(o){if(o instanceof Il)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!a)return;return this.webBuilder.build(a,q$(cg(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);return a?this.webBuilder.cache.get(a)?.css:void 0}command(e,o,a){return M$(this,this.deadline.bind(this),e,o,a)}hasRoute(e){return O$(this,e)}isPublicRoute(e){return _$(this,e)}route(e){return L$(this,this.deadline.bind(this),e)}websocket(e){return v$(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 j$}from"fs";import{join as TG}from"path";var RG=500,kG=1000,AG=3600000,PG=5000,CG=2000,$G=3,vG=1073741824;class pg{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=TG(e.dataDir,Gi),this.features={...zi(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,a=o?.backfill;if(!o||!a)return{...e,state:"backfilling"};if(a.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(a.total,a.done),indexed:a.done,state:a.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=j$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=j$(this.options.store.path).size}catch{}return Math.max(vG,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(),lo(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,ze,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Rt,0,PG);try{return e()}finally{Atomics.store(this.flags,ze,0),Atomics.notify(this.flags,ze)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=Vi(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,ze,0),Atomics.store(this.flags,Rt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,a=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),a&&this.restarts<$G&&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,ze,0),Atomics.notify(this.flags,ze);let o=new Promise((a)=>{this.stopped=a});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(CG)]),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,RG-(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)lo(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),AG),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,kG-(performance.now()-this.lastPush)),a=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),m=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(m===this.lastPushed)return;this.lastPushed=m,this.lastPush=performance.now(),e(u)};if(o===0)a();else this.statusTimer=setTimeout(a,o),this.statusTimer.unref?.()}}import{existsSync as Iu,mkdirSync as qG,readdirSync as V$,readFileSync as K$,realpathSync as lg,statSync as Nl,writeFileSync as dg}from"fs";import{dirname as Ll,isAbsolute as fg,relative as J$,resolve as FG}from"path";import{existsSync as Xc}from"fs";import{dirname as NG,join as xu}from"path";import{mkdirSync as MG,writeFileSync as OG}from"fs";import{tmpdir as _G}from"os";import{join as U$}from"path";var Ml=2000,Ce=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function yu(e,o){return e.map((a,u)=>{let m=a.length>Ml?`${a.slice(0,Ml)}\u2026 [line truncated]`:a;return`${String(o+u).padStart(6)} ${m}`}).join(`
90
+ `))for(let m=0;m<Math.max(u.length,1);){let p=Math.min(u.length,m+QB);if(p<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(p-1)))p--;a.push({source:e,text:u.slice(m,p)}),m=p>m?p:m+1}return a}function hu(e){let o=[],a=Po(e.records),u=new Map(a.map((p)=>[p.call,p])),m=new Set(a.flatMap((p)=>p.result?[p.result]:[]));for(let p of e.records){let f=p.raw;if(f.role==="user")o.push(...fu(p.entry.type==="user"&&p.entry.notices?"NOTICE":"USER",_s(f)));else if(f.role==="assistant"){for(let h of f.content)if(h.type==="text"&&h.text.trim())o.push(...fu("ASSISTANT",h.text));else if(h.type==="toolCall"){let I=u.get(h);if(I)for(let E of wl(I))o.push(...fu(E.source,E.text))}}else if(f.role==="toolResult"&&!m.has(f))o.push(...fu(f.isError?"TOOL_ERROR":"TOOL_OUTPUT",mu(f)))}return o.map((p,f)=>({chunk:e.id,line:f,...p}))}function $l(e,o){let a=e.find((u)=>u.entry.seq===o);if(a?.entry.type!=="user"||a.entry.notices||!a.raw||a.raw.role!=="user")return;return fu("USER",_s(a.raw)).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function vl(e,o){let a=e.find((u)=>u.entry.seq===o)?.entry;if(a?.type!=="extension"||!a.display)return;return fu("EXTENSION",a.display.text).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function Vc(e,o=""){return e.map((a,u)=>{let m=e[u-1],p=m&&m.source===a.source&&m.chunk===a.chunk&&m.line===a.line-1;return`${o}${p?`${a.line}:`:`${a.line} ${a.source}:`} ${a.text}`}).join(`
91
+ `)}import{AsyncLocalStorage as XB}from"async_hooks";import{chmodSync as h$,existsSync as YB,mkdirSync as ZB,readFileSync as eG,renameSync as tG,writeFileSync as rG}from"fs";import{dirname as nG,join as oG}from"path";function l$(){let e=Bun.version.split(".").map(Number);if(!((e[0]??0)>1||e[0]===1&&(e[1]??0)>4||e[0]===1&&e[1]===4&&(e[2]??0)>=3))throw Error("\u4EE3\u7406\u4F20\u8F93\u9700\u8981 Bun 1.4.3 \u6216\u66F4\u65B0\u7248\u672C\uFF0C\u8BF7\u5148\u5347\u7EA7 Bun")}function d$(e=process.env){let o={...e};for(let a of["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY"])delete o[a],delete o[a.toLowerCase()];return o}function Jc(e){let o=e.hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1]??o;return u==="localhost"||u.endsWith(".localhost")||u==="::1"||u==="::"||/^(?:0\.|127\.)/.test(u)}function f$(e,o){let a=async(m,p,f)=>{let h=await e(m,{...p,...o.proxy?{proxy:o.proxy}:{proxy:!1},...o.tls==="insecure"?{tls:{rejectUnauthorized:!1}}:{},redirect:"manual"});if(![301,302,303,307,308].includes(h.status))return h;let I=h.headers.get("location");if(!I)return h;if(f>=10)throw Error("\u4EE3\u7406\u8BF7\u6C42\u91CD\u5B9A\u5411\u6B21\u6570\u8FC7\u591A");let E=m instanceof Request?m:void 0,S=new URL(E?.url??String(m)),R=new URL(I,S);if(R.protocol!=="http:"&&R.protocol!=="https:")throw Error("\u62D2\u7EDD\u91CD\u5B9A\u5411\u5230\u975E HTTP \u5730\u5740");if(Jc(R)&&!Jc(S))throw Error("\u62D2\u7EDD\u4ECE\u516C\u7F51\u91CD\u5B9A\u5411\u5230\u56DE\u73AF\u5730\u5740");let k=new Headers(E?.headers);if(new Headers(p?.headers).forEach((_,Q)=>{k.set(Q,_)}),S.origin!==R.origin)k.delete("authorization"),k.delete("cookie"),k.delete("proxy-authorization");let P=(p?.method??E?.method??"GET").toUpperCase(),v={...p,method:P,headers:k};if(h.status===303||(h.status===301||h.status===302)&&P==="POST")v.method="GET",delete v.body,k.delete("content-length"),k.delete("content-type");else if(P!=="GET"&&P!=="HEAD"&&p?.body===void 0&&E?.body)throw Error("\u65E0\u6CD5\u5B89\u5168\u91CD\u5B9A\u5411\u5E26\u6D41\u5F0F\u8BF7\u6C42\u4F53\u7684\u8BF7\u6C42");return await h.body?.cancel(),a(R,v,f+1)};return Object.assign((m,p)=>a(m,p,0),{preconnect:e.preconnect})}var rg=oy,y$=Xr,g$=new XB;class Gn{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;l$(),this.path=oG(e,"proxy.json");let a=async(u,m)=>{let p=g$.getStore();if(!p)return this.baseFetch(u,m);return this.createFetch(p)(u,m)};globalThis.fetch=Object.assign(a,{preconnect:o.preconnect})}load(){if(!YB(this.path))return;this.config=this.validate(JSON.parse(eG(this.path,"utf8")))}settings(){return{...this.config,defaultProfileID:this.config.defaultProfileID,routes:{...this.config.routes},profiles:this.config.profiles.map((e)=>{let{password:o,...a}=e;return{...a,hasPassword:Boolean(o)}})}}save(e){let o=this.validate(e);for(let a of o.profiles)a.password||=this.config.profiles.find((u)=>u.id===a.id)?.password;try{ZB(nG(this.path),{recursive:!0});let a=`${this.path}.tmp-${process.pid}`;rG(a,`${JSON.stringify(o,null,2)}
92
+ `,{mode:384}),h$(a,384),tG(a,this.path),h$(this.path,384)}catch(a){throw Error("\u4FDD\u5B58\u4EE3\u7406\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:a})}return this.config=o,this.settings()}createFetch(e,o=this.baseFetch){let a=(m,p="verify")=>f$(o,{proxy:m,tls:p});return Object.assign(async(m,p)=>{let f=m instanceof Request?m.url:String(m),I=this.profileFor(e)?.noProxy?.some((S)=>aG(f,S))??!1;if(Jc(new URL(f))||I)return a()(m,p);let E=this.proxyURL(e);return a(E,this.profileFor(e)?.tls)(m,p)},{preconnect:o.preconnect})}models(e){return new x$(e,this)}providerOptions(e,o,a){let u=Object.assign({},e),m=e?.fetch,f=m?.[gl]?.call(m,this.baseFetch)??m??this.baseFetch;u.fetch=this.createFetch(o,f);let h=d$({...process.env,...e?.env}),I=!1;if(a)try{I=Jc(new URL(a))}catch{}let E=I?void 0:this.proxyURL(o),S=this.profileFor(o);return u.env={...h,...E?{HTTP_PROXY:E,HTTPS_PROXY:E,ALL_PROXY:E}:{},...S?.noProxy?.length?{NO_PROXY:S.noProxy.join(",")}:{}},u}run(e,o){return g$.run(e,o)}wrapProvider(e){let o=ar(e.id),a={...e.auth},u=e.auth.oauth;if(u){let S=e.id==="openai"||e.id===kt?rg:o;a.oauth={...u,login:(R,k)=>this.run(S,()=>u.login(R,k)),refresh:(R,k)=>this.run(S,()=>u.refresh(R,k)),toAuth:(R)=>this.run(S,()=>u.toAuth(R))}}let m={...e,auth:a},p=e.refreshModels;if(p)m.refreshModels=(S)=>this.run(o,()=>p(S));m.stream=(S,R,k)=>this.run(o,()=>e.stream(S,R,this.providerOptions(k,o,S.baseUrl))),m.streamSimple=(S,R,k)=>this.run(o,()=>e.streamSimple(S,R,this.providerOptions(k,o,S.baseUrl)));let f=e.fetchDeferred;if(f)m.fetchDeferred=(S,R,k)=>this.run(o,()=>f(S,R,this.providerOptions(k,o,S.baseUrl)));let h=e.cancelDeferred;if(h)m.cancelDeferred=(S,R,k)=>this.run(o,()=>h(S,R,this.providerOptions(k,o,S.baseUrl)));let I=e.generateImages;if(I)m.generateImages=(S,R,k)=>this.run(o,()=>I(S,R,this.providerOptions(k,o,S.baseUrl)));let E=e.classify;if(E)m.classify=(S,R,k)=>this.run(o,()=>E(S,R,this.providerOptions(k,o,S.baseUrl)));return m}proxyURL(e){let o=this.profileFor(e);if(!o)return;let a=sd(o.address),u=o.username?`${encodeURIComponent(o.username)}:${encodeURIComponent(o.password??"")}@`:"",m=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return`${a.protocol}://${u}${m}:${a.port}`}profileFor(e){let o=e?this.config.routes[e]:this.config.defaultProfileID,a=e&&o!==void 0?o:this.config.defaultProfileID;if(!a)return;let u=this.config.profiles.find((m)=>m.id===a);if(!u)throw Error(`\u4EE3\u7406\u7EBF\u8DEF ${a} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u9875\u91CD\u65B0\u9009\u62E9`);return u}validate(e){let o=ng(e);if(o?.version!==1)throw new t("\u4EE3\u7406\u914D\u7F6E\u7248\u672C\u65E0\u6548");let u=(Array.isArray(o.profiles)?o.profiles:[]).map(sG),m=new Set(u.map((I)=>I.id));if(m.size!==u.length)throw new t("\u4EE3\u7406\u914D\u7F6E ID \u4E0D\u80FD\u91CD\u590D");let p=iG(o.defaultProfileID);if(p&&!m.has(p))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let f=ng(o.routes)??{},h={};for(let[I,E]of Object.entries(f)){if(I!==rg&&I!==y$&&!sy(I))throw new t(`\u4EE3\u7406\u7528\u9014\u65E0\u6548\uFF1A${I}`);if(E!==null&&(typeof E!=="string"||!m.has(E)))throw new t(`\u7528\u9014 ${I} \u7684\u7EBF\u8DEF\u4E0D\u5B58\u5728`);h[I]=E}return{version:1,defaultProfileID:p,routes:h,profiles:u}}}class x${source;manager;wrapped=new Map;constructor(e,o){this.source=e;this.manager=o;for(let a of e.getProviders())this.install(a)}getProviders(){return this.source.getProviders().map((e)=>this.wrap(e))}getProvider(e){let o=this.source.getProvider(e);return o?this.wrap(o):void 0}getModels(...e){return this.source.getModels(...e)}getModel(...e){return this.source.getModel(...e)}getModelsOfType(e,o){return this.source.getModelsOfType(e,o)}getModelOfType(e,o,a){return this.source.getModelOfType(e,o,a)}getAllModels(...e){return this.source.getAllModels(...e)}refresh(...e){return this.source.refresh(...e)}checkAuth(...e){return this.source.checkAuth(...e)}getAvailable(...e){return this.source.getAvailable(...e)}getAvailableOfType(e,o,a){return this.source.getAvailableOfType(e,o,a)}getAllAvailable(...e){return this.source.getAllAvailable(...e)}getAuth(e,o){if(typeof e==="string")return this.source.getAuth(e,o);return this.source.getAuth(e,o)}login(...e){return this.source.login(...e)}logout(...e){return this.source.logout(...e)}stream(e,o,a){return this.source.stream(e,o,a)}complete(e,o,a){return this.source.complete(e,o,a)}streamSimple(...e){return this.source.streamSimple(...e)}completeSimple(...e){return this.source.completeSimple(...e)}streamDeferred(...e){return this.source.streamDeferred(...e)}fetchDeferred(...e){return this.source.fetchDeferred(...e)}cancelDeferred(...e){return this.source.cancelDeferred(...e)}generateImages(...e){return this.source.generateImages(...e)}classify(...e){return this.source.classify(...e)}setProvider(e){this.install(e)}deleteProvider(e){this.source.deleteProvider(e),this.wrapped.delete(e)}clearProviders(){this.source.clearProviders(),this.wrapped.clear()}wrap(e){return this.wrapped.get(e.id)??this.install(e)}install(e){if(this.wrapped.get(e.id)===e)return this.source.setProvider(e),e;let o=this.manager.wrapProvider(e);return this.wrapped.set(e.id,o),this.source.setProvider(o),o}}function ar(e){return`${ny}${e}`}function Xo(e){return[{id:rg,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:y$,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:ar(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function sG(e){let o=ng(e);if(!o)throw new t("\u4EE3\u7406\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof o.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(o.id))throw new t("\u4EE3\u7406\u914D\u7F6E ID \u65E0\u6548");let a;try{a=sd(String(o.address??""))}catch(p){throw new t(p instanceof Error?p.message:"\u4EE3\u7406\u5730\u5740\u65E0\u6548")}let u=Array.isArray(o.noProxy)?o.noProxy:[];if(!u.every((p)=>typeof p==="string"&&p.trim()))throw new t("\u76F4\u8FDE\u4F8B\u5916\u5FC5\u987B\u662F\u975E\u7A7A\u4E3B\u673A");let m=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return{id:o.id,name:typeof o.name==="string"&&o.name.trim()?o.name.trim():a.hostname,address:`${a.protocol}://${m}:${a.port}`,username:typeof o.username==="string"&&o.username?o.username:void 0,password:typeof o.password==="string"&&o.password?o.password:void 0,tls:o.tls==="insecure"?"insecure":"verify",noProxy:u.map((p)=>String(p).trim())}}function iG(e){if(e===void 0||e===null||e==="")return;if(typeof e!=="string")throw new t("\u4EE3\u7406\u7EBF\u8DEF ID \u65E0\u6548");return e}function ng(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function aG(e,o){try{let a=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/^\./,"");return a===u||a.endsWith(`.${u}`)}catch{return!1}}import{join as zg}from"path";import{existsSync as D$}from"fs";import{realpath as q$}from"fs/promises";import{dirname as F$,isAbsolute as TG,join as j$,relative as RG,resolve as mg,sep as kG}from"path";import{existsSync as uG,watch as cG}from"fs";import{readdir as mG,stat as pG}from"fs/promises";import{basename as og,dirname as lG,join as I$,resolve as dG}from"path";class sg{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,a,u=150){this.host=e;this.slots=o;this.watching=a;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let a=[],u=[];for(let h of[...new Set(e)]){let I;try{I=await mG(h)}catch(E){if(E instanceof Error&&"code"in E&&E.code==="ENOENT")continue;throw E}for(let E of I.sort()){let S=I$(h,E),R=(await pG(S)).isDirectory()?I$(S,"index.ts"):S;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(k){let P=og(R)==="index.ts"?og(lG(R)):og(R,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let v={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};a.push({definition:v,path:R}),this.slots.set(P,{definition:v,path:R,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let m=o.filter((h)=>![...u,...a].some((I)=>I.definition.id===h.definition.id)),p=[...m,...u],f=this.order(p.map(({definition:h})=>h));for(let h of f){let I=p.find((S)=>S.definition===h)?.path,E=m.some((S)=>S.definition===h);try{await this.host.install(h,I,E)}catch(S){this.slots.set(h.id,{definition:h,path:I,builtin:E,enabled:!0,error:S instanceof Error?S.message:String(S)})}}if(this.watching())for(let h of[...p,...a]){if(!uG(h.path))continue;let I=cG(h.path,()=>{let E=h.definition.id,S=this.debounceTimers.get(E);if(S)clearTimeout(S);let R=setTimeout(()=>{this.debounceTimers.delete(E),this.host.reload(E).catch((k)=>{let P=this.slots.get(E);if(P)P.error=k instanceof Error?k.message:String(k)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(E,R)});I.on("error",(E)=>{let S=this.slots.get(h.definition.id);if(S)S.error=E.message,this.host.changed()}),this.watchers.push(I)}}order(e,o=!1){let a=new Map;for(let h of e){if(this.validate(h),a.has(h.id)||!o&&this.slots.has(h.id))throw Error(`Duplicate plugin: ${h.id}`);a.set(h.id,h)}let u=[],m=new Set,p=new Set,f=(h)=>{if(p.has(h.id))return;if(m.has(h.id))throw Error(`Plugin dependency cycle: ${h.id}`);m.add(h.id);for(let I of h.deps??[]){let E=a.get(I);if(E)f(E);else if(!this.slots.has(I))throw Error(`Missing plugin dependency: ${I}`)}m.delete(h.id),p.add(h.id),u.push(h)};for(let h of e)f(h);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${dG(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 b$(e,o,a=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,m;try{return await Promise.race([a?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((p,f)=>{m=setTimeout(()=>{u.abort(),f(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(m)}}import{AsyncLocalStorage as fG}from"async_hooks";import{isDeepStrictEqual as E$}from"util";var Ra=new fG;function Ls(){let e=Ra.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function gu(e){let o=structuredClone(e),a=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let m of Object.values(u))a(m)};return a(o),o}function S$(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let I of["seq","time","session_id","raw"])if(I in o)throw Error(`Entry replacement contains protected field: ${I}`);let a=JSON.parse(JSON.stringify(o,(I,E)=>{if(typeof E==="function"||typeof E==="symbol"||typeof E==="number"&&!Number.isFinite(E))throw Error("Entry replacement must contain JSON values");return E}));if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Entry replacement must serialize to a body");let u=a,m=[];switch(e.type){case"user":m.push("text","attachments");break;case"assistant":m.push("parts","error");break;case"tool_result":m.push("output","images");break;case"extension":m.push("payload","display");break;case"notice_pending":m.push("notice");break;case"run":if(e.state==="end")m.push("error");break;case"compaction":break}let p={...e};for(let I of new Set([...Object.keys(e),...Object.keys(u)])){if(!m.includes(I)&&!E$(p[I],u[I]))throw Error(`Entry replacement changed protected field: ${I}`);if(["seq","time","session_id","raw"].includes(I))throw Error(`Entry replacement contains protected field: ${I}`)}let f=(I)=>I===void 0||typeof I==="string",h=!0;switch(e.type){case"user":h=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((I)=>I&&typeof I.name==="string"&&typeof I.mimeType==="string"&&nm.includes(I.kind)&&typeof I.data==="string"));break;case"assistant":h=f(u.error)&&Array.isArray(u.parts)&&u.parts.every((I)=>I&&(["text","thinking"].includes(I.type)&&typeof I.text==="string"||I.type==="tool_call"&&typeof I.id==="string"&&typeof I.name==="string"&&("input"in I)));break;case"tool_result":h=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((I)=>I&&typeof I.mimeType==="string"&&typeof I.data==="string"));break;case"extension":{let I=u.display;h="payload"in u&&(I===void 0||I!==null&&typeof I==="object"&&("text"in I)&&typeof I.text==="string"&&(!("title"in I)||f(I.title)));break}case"notice_pending":{let E=["text"],S=p.notice,R=u.notice;if(h=!!R&&typeof R==="object"&&!Array.isArray(R),!h)break;let k=R;for(let P of new Set([...Object.keys(S),...Object.keys(k)]))if(E.includes(P)){if(typeof k[P]!=="string")h=!1}else if(!E$(S[P],k[P]))h=!1;break}case"run":h=f(u.error);break;case"compaction":break}if(!h)throw Error("Invalid entry replacement content");return a}function w$(e,o,a,u,m,p){let f=u;for(let h of a.generations)for(let I of h.hooks.get("entry.before_append")??[]){if(h.disabled)break;let E={phase:"before",violated:!1};try{let S=Ra.run(E,()=>{let R=gu(f),k=performance.now(),P=I(R,{sessionID:m,seq:p});if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")throw Promise.resolve(P).catch(()=>{}),Error("entry.before_append must be synchronous");let v=P===void 0?void 0:S$(f,P);if(E.violated)throw Error("entry.before_append attempted a database write");return{validated:v,slow:performance.now()-k>e}});if(S.validated&&JSON.stringify(S.validated)!==JSON.stringify(f))f=S.validated;if(S.slow)throw Error("entry.before_append exceeded budget");h.beforeFailures=0,h.failures=0}catch(S){h.failures=h.beforeFailures++,o(h,S)}}return f}function hG(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return gu(o);return structuredClone(o)}async function T$(e,o,a,u,m,p,f,h,I="end"){let E=p;for(let S of u){if(S.disabled)continue;let R=S.hooks.get(m)??[];for(let k of R){if(S.disabled)break;let P=S.hookOptions.get(k);if(m==="prompt.fragments"&&(P?.promptPosition??"end")!==I)continue;let v=m==="prompt.fragments"?JSON.stringify([f?.id,E]):void 0,_=v===void 0?void 0:S.promptCache.get(k)?.get(v);try{let Q=hG(m,E),L=P?.timeoutMs,V=typeof L==="function"?L({runtime:e.runtime,session:f,connection:h}):L,J=await o((Z)=>k(Q,{runtime:e.runtime,session:f,connection:h,signal:Z}),V);if(v!==void 0){let Z=J===void 0?E:J;if(!Array.isArray(Z)||Z.some((z)=>typeof z!=="string"))throw Error("Prompt fragments must be strings");if(_&&JSON.stringify(_)!==JSON.stringify(Z))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let ne=S.promptCache.get(k)??new Map;ne.set(v,[...Z]),S.promptCache.set(k,ne)}if(S.failures=0,J!==void 0&&m!=="entry.after_append")E=J}catch(Q){if(_)E=structuredClone(_);if(a(S,Q),P?.errorMode==="propagate")throw Q}}}return E}class Qc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,a,u,m="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,a,u,m)}has(e,o){return this.generations.some((a)=>!a.disabled&&(a.hooks.get(e)??[]).some((u)=>o===void 0||(a.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...a)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...a)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((a)=>a(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let a of this.generations){if(a.disabled)continue;for(let u of a.historyResolvers){let m=u(e,o);if(m)return m}}}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 gG}from"fs";import{dirname as yG,resolve as R$}from"path";var ig=new WeakMap;function k$(e){return[...e].map((o)=>{let a=Boolean(o.path&&(Boolean(o.definition.webEntry)||gG(R$(yG(R$(o.path)),"web.tsx"))));if(o.current&&!ig.has(o.current))ig.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:a,webRevision:o.current?ig.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class ag{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,a){this.host=e;this.deadline=o;this.fail=a}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,a){let u=this.host.pin(),m=(async()=>{try{let p=[];for(let f of u.generations){if(f.disabled)continue;for(let h of f.hooks.get(e)??[]){let I=f.hookOptions.get(h)?.timeoutMs,E=typeof I==="function"?I({runtime:this.host.runtime,session:o,connection:a}):I;p.push(this.deadline((S)=>h(o,{runtime:this.host.runtime,session:o,connection:a,signal:S}),E,!0).catch((S)=>this.fail(f,S)))}}await Promise.all(p)}finally{await u.release()}})();this.pending.add(m),m.then(()=>this.pending.delete(m),()=>this.pending.delete(m))}finishEntry(e,o,a){let u=a===void 0?void 0:gu(a),m=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Ra.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,m),this.pending.add(m);let p=()=>{if(this.pending.delete(m),this.entryQueues.get(o)===m)this.entryQueues.delete(o)};m.then(p,p)}}function A$(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 xG(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 IG(e,o){let a=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!a)throw Error("Completion session not found");let u=o.model??a?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let m=Tn(e.options.models,u);if(!m&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!m){let p=(await e.models()).models.filter((h)=>h.available===!0),f=m?ot(m):u;if(!p.some((h)=>h.id===f)){let h=p[0];if(h)m=Tn(e.options.models,h.id)}}if(!m)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return m}async function P$(e,o){xG(o);let a=await IG(e,o),u=o.maxTokens??Math.min(a.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>a.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let m="",p=!1;try{let f=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],h=e.options.models.streamSimple(a,{messages:f},{maxTokens:u,signal:o.signal});for await(let I of h){if(o.signal?.aborted)throw Error("cancelled");if(I.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${A$(I.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(I.type==="text_delta")m+=I.delta;if(I.type==="done"){if(I.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(I.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${I.reason}\uFF09`);p=!0}}}catch(f){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${A$(f instanceof Error?f.message:String(f))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!p)throw Error("Model completion ended without a stop response; retry");return{text:m,model:ot(a)}}var bG=["active","archived","all"];function C$(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function EG(e){let{projectID:o,children:a,archive:u,since:m}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(a!==void 0&&typeof a!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!bG.includes(u))throw Error("sessions archive must be active, archived or all");if(m!==void 0&&!Number.isFinite(m))throw Error("sessions since must be a finite timestamp in milliseconds")}function SG(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function $$(e){function o(a,u={}){let{types:m,bodies:p}=u;if(m!==void 0&&!Array.isArray(m))throw Error("sessions types must be an array");let f=C$(u.limit),h=u.after??0;if(!Number.isSafeInteger(h)||h<0)throw Error("sessions after must be a non-negative integer");let I=(e.get(a)?.entries(h,m,p!==!1)??[]).slice(0,f);return structuredClone(p===!1?I.map(SG):I)}return{list(a={}){EG(a);let u=a.limit===void 0?void 0:C$(a.limit),m=e.list(a.children??!1,{archive:a.archive}).filter((p)=>a.projectID===void 0||p.projectID===a.projectID).filter((p)=>a.since===void 0||p.created>=a.since);return structuredClone(u===void 0?m:m.slice(0,u))},get(a){return structuredClone(e.get(a)?.info())},entries:o}}async function v$(e,o,a,u,m,p){let f={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},h=e.runtime.store.db,I=new Map,E=!1,S=!0,R=()=>{if(!S||f.disposed)throw Error("Plugin registration scope is closed")},k=(L,V)=>{if(R(),!E){I.set(L,V);return}if(V===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,L);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,L,V)},P={get:(L)=>{R();let V=I.has(L)?I.get(L):h.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,L)?.value;return V==null?void 0:JSON.parse(V)},set:(L,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");k(L,J)},delete:(L)=>k(L,null)},v=()=>{if(R(),E)throw Error("Register resources during setup only")},_=[...o.migrations??[]].sort((L,V)=>L.version-V.version),Q=new Set;try{for(let L of _){if(!Number.isSafeInteger(L.version)||L.version<1||Q.has(L.version))throw Error("Plugin migration versions must be unique positive integers");if(Q.add(L.version),h.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,L.version))continue;h.transaction(()=>{if(L.sql!==void 0)h.run(L.sql);else L.up({...P,db:h});for(let[V,J]of I)if(J===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,J);h.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,L.version)})(),e.runtime.store.invalidateEntryCache(),I.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:$$(e.runtime),complete:(L)=>P$(e.runtime,L),kv:P,database:h,broadcast:(L)=>{e.runtime.emitEvent(L)},registerInputGate:(L)=>{v(),f.gates.push(L)},registerNoticeSource:(L,V)=>{if(v(),!L||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");f.noticeSources.set(L,{...V})},provide:(L,V)=>{if(v(),L.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(f.services.has(L.name))throw Error(`Duplicate plugin service: ${L.name}`);if(!L.validate(V))throw Error(`Invalid plugin service: ${L.name}`);f.services.set(L.name,V)},on:(L,V,J)=>{if(v(),J?.promptPosition&&L!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let Z=f.hooks.get(L)??[];if(Z.push(V),f.hooks.set(L,Z),J)f.hookOptions.set(V,J)},registerHistoryResolver:(L)=>{v(),f.historyResolvers.push(L)},registerTool:(L,V)=>{if(v(),!L.name||["toolsearch","tool_search","tool_call"].includes(L.name.toLowerCase())||wG(e,m,o.id).has(L.name.toLowerCase())||f.tools.some((Z)=>Z.name.toLowerCase()===L.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${L.name}`);let J=a?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;f.tools.push({...L,defer:J,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:a})},registerRoute:(L)=>{if(v(),!(L.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>L.path===V||L.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(L.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(f.routes.some((V)=>V.path===L.path&&V.method===L.method))throw Error("Duplicate plugin route");f.routes.push(L)},registerWebSocket:(L)=>{if(v(),!L.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(f.websockets.some((V)=>V.path===L.path))throw Error("Duplicate plugin WebSocket route");f.websockets.push(L)},registerCommand:(L)=>{v(),f.commands.push(L)},registerWebContribution:(L)=>{v(),f.web.push(L)},registerToolPolicy:(L,V)=>{v(),f.policies.set(L,V)},appendExtension:(L,V)=>{if(Ls(),R(),!E)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(L,V)},onDeactivate:(L)=>{v(),f.deactivators.push(L)},onDispose:(L)=>{v(),f.disposers.push(L)}})),h.transaction(()=>{for(let[L,V]of I)if(V===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,L);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,L,V)})(),I.clear(),E=!0,f}catch(L){throw S=!1,await p(f),L}}function wG(e,o,a){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((m)=>m.name)].map((m)=>m.toLowerCase()));for(let[m,p]of o){if(m===a)continue;for(let f of p.current?.tools??[])u.add(f.name.toLowerCase())}return u}class ug{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function M$(e,o,a,u){for(let m of o){let p=m.current;if(!p||p.disabled||p.retired)continue;let f=p.websockets.find((h)=>h.path===u);if(!f)continue;return{connect:(h)=>{let I=!1;p.references++,p.connections.add(h);let E={send:(R)=>{if(I||p.retired||p.disabled)return;h.send(R)},close:(R,k)=>h.close(R,k)},S=async(R)=>{if(I||p.retired||p.disabled){h.close(1012,"Plugin unavailable");return}try{await a(R),p.failures=0}catch(k){if(p.failures++,p.error=k instanceof Error?k.message:String(k),h.close(1011,"Plugin callback failed"),p.failures>=e.failureThreshold){p.disabled=!0;for(let P of p.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>S(()=>f.open?.(E)),message:(R)=>S(()=>f.message(E,R)),close:async()=>{if(I)return;I=!0,p.connections.delete(h);try{await a(()=>f.close?.(E))}catch(R){p.error=R instanceof Error?R.message:String(R)}finally{p.references--,await e.collect(p)}}}}}}return}function cg(e,o){let a=e.split("/"),u=new URL(o.url).pathname.split("/");if(a.length!==u.length)return;let m={};return a.every((f,h)=>{let I=u[h];if(I===void 0)return!1;if(!f.startsWith(":"))return I===f;try{m[f.slice(1)]=decodeURIComponent(I)}catch{return!1}return I.length>0})?m:void 0}async function O$(e,o,a,u,m){let p=e.pin();try{let f=p.generations.find((h)=>h.definition.id===a)?.commands.find((h)=>h.id===u);if(!f)throw new y("Plugin command is unavailable");return await o(()=>f.execute(m))}finally{await p.release()}}function _$(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((m)=>m.method===o.method&&cg(m.path,o)!==void 0))}finally{a.release()}}function L$(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((m)=>m.public===!0&&m.method===o.method&&cg(m.path,o)!==void 0))}finally{a.release()}}async function N$(e,o,a){let u=e.pin(),m=!0;try{for(let p of u.generations)for(let f of p.routes){if(f.method!==a.method)continue;let h=cg(f.path,a);if(h){let I=await o(()=>f.handler(a,h),f.timeoutMs);if(!I)return;if(I.body&&I.body instanceof ReadableStream){m=!1;let E=!1,S=()=>{if(E)return;E=!0,u.release()},R=I.body.getReader(),k=new ReadableStream({async pull(P){try{let{done:v,value:_}=await R.read();if(v)P.close(),S();else P.enqueue(_)}catch(v){P.error(v),S()}},async cancel(P){try{await R.cancel(P)}finally{S()}}});return new Response(k,{status:I.status,statusText:I.statusText,headers:I.headers})}return I}}return}finally{if(m)await u.release()}}class pg{runtime;options;slots=new Map;retirement=new ug(this.deadline.bind(this));observers=new ag(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new bl;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 sg(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 y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let a=o.current.services.get(e.name);if(!e.validate(a))throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return a}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((a)=>a(e)))}noticeSource(e){return[...this.slots.values()].findLast((a)=>a.enabled&&a.current&&!a.current.disabled&&a.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let a=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==a)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let a of e)this.directories.add(mg(a));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await q$(e),a=[...this.directories,j$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>j$(u.directory,".basalt","plugins"))];for(let u of a){if(!D$(u))continue;let m=RG(await q$(u),o);if(m&&m!==".."&&!m.startsWith(`..${kG}`)&&!TG(m)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),a=await this.checkEntry(o);if(!a.ok)throw new ht(a.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((a)=>a.level==="error").map((a)=>({file:a.position?.file??null,line:a.position?.line??null,column:a.position?.column??null,message:a.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,a=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,a)})}async installDefinition(e,o,a=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),m={definition:e,path:o,builtin:a,enabled:u?.enabled!==0};if(m.enabled)m.current=await this.stage(e,a);this.slots.set(e.id,m)}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 h=await this.checkEntry(o.path);if(!h.ok)throw new ht(h.errors)}let a=o.builtin&&!D$(o.path)?o.definition:await this.catalog.read(o.path);if(a.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((h)=>h.definition.id===e?a:h.definition),!0),m=await this.stage(a),p=o.current;o.definition=a,o.current=m,o.error=void 0,o.discoveryFailed=!1;let f=new Map(this.slots);this.slots.clear();for(let h of u){let I=f.get(h.id);if(I)this.slots.set(h.id,I)}if(p)await this.retirement.retire(p)}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}})}setEnabled(e,o){return this.exclusive(async()=>{let a=this.require(e);if(o===a.enabled&&(!o||a.current&&!a.current.disabled))return;if(!o){for(let f of this.slots.values())if(f.enabled&&f.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${f.definition.id}`)}let u=o&&a.discoveryFailed&&a.path?await this.catalog.read(a.path):a.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let m=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let p=a.current;if(a.definition=u,o)a.discoveryFailed=!1;if(a.enabled=o,a.current=m,a.error=void 0,p)await this.retirement.retire(p)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let a of e.deps??[])if(a===e.id||!this.slots.get(a)?.current||this.slots.get(a)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${a}`);return v$(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,a){this.observers.notify(e,o,a)}resolveHistory(e,o){for(let a of this.slots.values()){if(!a.enabled||!a.current||a.current.disabled)continue;for(let u of a.current.historyResolvers){let m=u(e,o);if(m)return m}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Qc(this,e)}async invoke(e,o,a,u,m,p="end"){return T$(this,this.deadline.bind(this),this.fail.bind(this),e,o,a,u,m,p)}pinEntry(e){if(Ra.getStore()?.phase==="after")return;let o;for(let a of this.slots.values()){let u=a.current;if(!a.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Qc(this,o)}beforeEntry(e,o,a,u){return w$(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,a,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let a of e.connections)a.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,a){this.observers.finishEntry(e,o,a)}deadline(e,o=this.timeoutMs,a=!1){return b$(e,o,a)}appendExtension(e,o){return Ls(),new Promise((a)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let m=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),a(m)})}list(){return k$(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(a&&o.path)await this.webBuilder.build(a,F$(mg(o.path)));return{ok:!0}}catch(o){if(o instanceof Il)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!a)return;return this.webBuilder.build(a,F$(mg(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);return a?this.webBuilder.cache.get(a)?.css:void 0}command(e,o,a){return O$(this,this.deadline.bind(this),e,o,a)}hasRoute(e){return _$(this,e)}isPublicRoute(e){return L$(this,e)}route(e){return N$(this,this.deadline.bind(this),e)}websocket(e){return M$(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 U$}from"fs";import{join as AG}from"path";var PG=500,CG=1000,$G=3600000,vG=5000,MG=2000,OG=3,_G=1073741824;class lg{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=AG(e.dataDir,Gi),this.features={...zi(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,a=o?.backfill;if(!o||!a)return{...e,state:"backfilling"};if(a.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(a.total,a.done),indexed:a.done,state:a.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=U$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=U$(this.options.store.path).size}catch{}return Math.max(_G,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(),lo(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,ze,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Rt,0,vG);try{return e()}finally{Atomics.store(this.flags,ze,0),Atomics.notify(this.flags,ze)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=Vi(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,ze,0),Atomics.store(this.flags,Rt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,a=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),a&&this.restarts<OG&&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,ze,0),Atomics.notify(this.flags,ze);let o=new Promise((a)=>{this.stopped=a});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(MG)]),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,PG-(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)lo(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),$G),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,CG-(performance.now()-this.lastPush)),a=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),m=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(m===this.lastPushed)return;this.lastPushed=m,this.lastPush=performance.now(),e(u)};if(o===0)a();else this.statusTimer=setTimeout(a,o),this.statusTimer.unref?.()}}import{existsSync as Iu,mkdirSync as UG,readdirSync as J$,readFileSync as H$,realpathSync as dg,statSync as Nl,writeFileSync as fg}from"fs";import{dirname as Ll,isAbsolute as hg,relative as Q$,resolve as BG}from"path";import{existsSync as Xc}from"fs";import{dirname as FG,join as xu}from"path";import{mkdirSync as LG,writeFileSync as NG}from"fs";import{tmpdir as DG}from"os";import{join as B$}from"path";var Ml=2000,Ce=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function yu(e,o){return e.map((a,u)=>{let m=a.length>Ml?`${a.slice(0,Ml)}\u2026 [line truncated]`:a;return`${String(o+u).padStart(6)} ${m}`}).join(`
93
93
  `)}function le(e,o){if(e.length<=o)return e;let a=Math.floor(o*0.4),u=o-a,m=e.length-a-u,p=e.slice(a,e.length-u).split(`
94
94
  `).length-1;return`${e.slice(0,a)}
95
95
 
96
96
  \u2026 [${m} characters, ~${p} lines omitted] \u2026
97
97
 
98
- ${e.slice(-u)}`}var LG=0;function it(e,o,a){if(e.length<=o)return e;let u=le(e,o);try{let m=a?xd(a):U$(_G(),"basalt-output");MG(m,{recursive:!0});let p=U$(m,`${process.pid}-${Date.now().toString(36)}-${LG++}.txt`);return OG(p,e),`${u}
99
- [Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var B$=120000,G$=600000,ka;function DG(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function lr(){if(ka!==void 0)return ka||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let m=xu(u,"bash.exe");if(DG(m))continue;if(Xc(m))return ka=m,m}for(let u of o){let m=xu(u,"git.exe");if(Xc(m)){let p=NG(u),f=xu(p,"bin","bash.exe");if(Xc(f))return ka=f,f;let h=xu(p,"usr","bin","bash.exe");if(Xc(h))return ka=h,h}}let a=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?xu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?xu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of a)if(Xc(u))return ka=u,u;ka="";return}class Ol{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let a=0;while(a<o.length){if(o[a]<128){a+=1;continue}let m=o[a+1];if(m===void 0)break;let p=m>=48&&m<=57?4:2;if(a+p>o.length)break;a+=p}return this.gbkPending=o.slice(a),this.gbk.decode(o.subarray(0,a))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let a=new Uint8Array(this.sniffPending.length+e.length);if(a.set(this.sniffPending),a.set(e,this.sniffPending.length),a.length<2)return this.sniffPending=a,"";this.sniffPending=void 0;let u=a[0]===255&&a[1]===254,m=!1;for(let p=1;p<a.length;p+=2)if(a[p]===0){m=!0;break}this.isUtf16=u||m,o=a}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Aa(e,o){let a=process.platform==="win32",u=o??"auto";if(!a)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[lr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let m=lr();if(m)return{argv:[m,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function cr(e,o){let a=await Qe(e,o.signal);if(a)return{output:a,code:126,timedOut:!1};let{argv:u,isWindows:m}=Aa(e,o.shell),p=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!m,windowsHide:!0,env:{...process.env,...am(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...m?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((Z)=>Z.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),f=!1,h=()=>{try{if(m)p.kill();else process.kill(-p.pid,"SIGKILL")}catch{}},I=setTimeout(()=>{f=!0,h()},o.timeout);o.signal?.addEventListener("abort",h,{once:!0});let E=Ce*2,S="",R="",k=0,P=0,v="",_=(Z=!1)=>{let ne=k-S.length-R.length,z=ne>0?`${S}
98
+ ${e.slice(-u)}`}var qG=0;function it(e,o,a){if(e.length<=o)return e;let u=le(e,o);try{let m=a?xd(a):B$(DG(),"basalt-output");LG(m,{recursive:!0});let p=B$(m,`${process.pid}-${Date.now().toString(36)}-${qG++}.txt`);return NG(p,e),`${u}
99
+ [Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var G$=120000,K$=600000,ka;function jG(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function lr(){if(ka!==void 0)return ka||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let m=xu(u,"bash.exe");if(jG(m))continue;if(Xc(m))return ka=m,m}for(let u of o){let m=xu(u,"git.exe");if(Xc(m)){let p=FG(u),f=xu(p,"bin","bash.exe");if(Xc(f))return ka=f,f;let h=xu(p,"usr","bin","bash.exe");if(Xc(h))return ka=h,h}}let a=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?xu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?xu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of a)if(Xc(u))return ka=u,u;ka="";return}class Ol{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let a=0;while(a<o.length){if(o[a]<128){a+=1;continue}let m=o[a+1];if(m===void 0)break;let p=m>=48&&m<=57?4:2;if(a+p>o.length)break;a+=p}return this.gbkPending=o.slice(a),this.gbk.decode(o.subarray(0,a))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let a=new Uint8Array(this.sniffPending.length+e.length);if(a.set(this.sniffPending),a.set(e,this.sniffPending.length),a.length<2)return this.sniffPending=a,"";this.sniffPending=void 0;let u=a[0]===255&&a[1]===254,m=!1;for(let p=1;p<a.length;p+=2)if(a[p]===0){m=!0;break}this.isUtf16=u||m,o=a}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Aa(e,o){let a=process.platform==="win32",u=o??"auto";if(!a)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[lr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let m=lr();if(m)return{argv:[m,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function cr(e,o){let a=await Qe(e,o.signal);if(a)return{output:a,code:126,timedOut:!1};let{argv:u,isWindows:m}=Aa(e,o.shell),p=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!m,windowsHide:!0,env:{...process.env,...am(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...m?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((Z)=>Z.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),f=!1,h=()=>{try{if(m)p.kill();else process.kill(-p.pid,"SIGKILL")}catch{}},I=setTimeout(()=>{f=!0,h()},o.timeout);o.signal?.addEventListener("abort",h,{once:!0});let E=Ce*2,S="",R="",k=0,P=0,v="",_=(Z=!1)=>{let ne=k-S.length-R.length,z=ne>0?`${S}
100
100
  \u2026 [${ne} characters omitted] \u2026
101
- ${R}`:S+R;if(!Z)return le(z,Ce);return it(v.length===k?v:z,Ce,o.cwd)},Q=()=>{let Z=new Ol;return async(ne)=>{for await(let oe of ne){let fe=Z.decode(oe);if(k+=fe.length,v.length<4000000)v+=fe;if(S.length<E)S+=fe;else R=(R+fe).slice(-E);if(o.onOutput){let ke=performance.now();if(ke-P>=80)P=ke,o.onOutput(_())}}let z=Z.flush();if(z){if(k+=z.length,v.length<4000000)v+=z;if(S.length<E)S+=z;else R=(R+z).slice(-E)}}},L=Promise.all([Q()(p.stdout),Q()(p.stderr)]),V=await p.exited;if(clearTimeout(I),o.signal?.removeEventListener("abort",h),await Promise.race([L.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
102
- [background processes are still running; their later output is not captured]`;return{output:_(!0),code:f?null:V,timedOut:f}}class hg{seen=new Map;mark(e,o=Nl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Nl(e).mtimeMs!==o?"changed":void 0}}var H$=2000,jG=500,UG=10485760,_l=20,BG=6,GG=40000,KG=80000;function HG(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 Q$(e,o,a=[],u){let m=(v)=>fg(v)?v:FG(e,v),p=(v)=>{let _=J$(e,v);return _&&!_.startsWith("..")&&!fg(_)?_:v},f=(v)=>{let _=v;while(!Iu(_)&&Ll(_)!==_)_=Ll(_);let Q=lg(_);if(a.some((L)=>Iu(L)&&z$(lg(L),Q))&&!z$(lg(e),Q))throw Error("External directories are read-only")},h=(v,_,Q)=>{let L=m(v);if(!Iu(L))throw Error(`No such file or directory: ${L}${JG(L)}`);let V=Nl(L);if(V.isDirectory()){let ue=V$(L,{withFileTypes:!0}).map((Ke)=>Ke.isDirectory()?`${Ke.name}/`:Ke.name).sort(),$e=ue.slice(0,jG),gt=ue.length-$e.length;return c(`${$e.join(`
103
- `)}${gt>0?`
104
- \u2026 and ${gt} more entries`:""}`||"(empty directory)").content}let J=K$(L),Z=HG(J);if(Z){if(V.size>UG)throw Error(`${L} exceeds the 10 MB image limit (${V.size} bytes)`);return o.mark(L),[{type:"text",text:`Read image ${p(L)} (${Z}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:Z}]}if(J.subarray(0,8192).includes(0))throw Error(`${L} looks like a binary file (${V.size} bytes)`);o.mark(L);let ne=J.toString("utf8");if(!ne)return c("(empty file)").content;let z=ne.replace(/\r?\n$/,"").split(/\r?\n/),oe=(_??1)-1;if(oe>=z.length)throw Error(`offset ${_} is past the end of the file (${z.length} lines)`);let fe=Math.min(z.length,oe+(Q??H$)),ke=0,Ee=oe;while(Ee<fe){let ue=z[Ee]?.length??0;if(Ee>oe&&ke+ue>GG)break;ke+=ue,Ee++}let ee=yu(z.slice(oe,Ee),oe+1);if(Ee<fe)ee+=`
101
+ ${R}`:S+R;if(!Z)return le(z,Ce);return it(v.length===k?v:z,Ce,o.cwd)},Q=()=>{let Z=new Ol;return async(ne)=>{for await(let oe of ne){let fe=Z.decode(oe);if(k+=fe.length,v.length<4000000)v+=fe;if(S.length<E)S+=fe;else R=(R+fe).slice(-E);if(o.onOutput){let Ae=performance.now();if(Ae-P>=80)P=Ae,o.onOutput(_())}}let z=Z.flush();if(z){if(k+=z.length,v.length<4000000)v+=z;if(S.length<E)S+=z;else R=(R+z).slice(-E)}}},L=Promise.all([Q()(p.stdout),Q()(p.stderr)]),V=await p.exited;if(clearTimeout(I),o.signal?.removeEventListener("abort",h),await Promise.race([L.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
102
+ [background processes are still running; their later output is not captured]`;return{output:_(!0),code:f?null:V,timedOut:f}}class gg{seen=new Map;mark(e,o=Nl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Nl(e).mtimeMs!==o?"changed":void 0}}var W$=2000,GG=500,KG=10485760,_l=20,HG=6,WG=40000,zG=80000;function VG(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 X$(e,o,a=[],u){let m=(v)=>hg(v)?v:BG(e,v),p=(v)=>{let _=Q$(e,v);return _&&!_.startsWith("..")&&!hg(_)?_:v},f=(v)=>{let _=v;while(!Iu(_)&&Ll(_)!==_)_=Ll(_);let Q=dg(_);if(a.some((L)=>Iu(L)&&V$(dg(L),Q))&&!V$(dg(e),Q))throw Error("External directories are read-only")},h=(v,_,Q)=>{let L=m(v);if(!Iu(L))throw Error(`No such file or directory: ${L}${YG(L)}`);let V=Nl(L);if(V.isDirectory()){let ue=J$(L,{withFileTypes:!0}).map((je)=>je.isDirectory()?`${je.name}/`:je.name).sort(),we=ue.slice(0,GG),Ve=ue.length-we.length;return c(`${we.join(`
103
+ `)}${Ve>0?`
104
+ \u2026 and ${Ve} more entries`:""}`||"(empty directory)").content}let J=H$(L),Z=VG(J);if(Z){if(V.size>KG)throw Error(`${L} exceeds the 10 MB image limit (${V.size} bytes)`);return o.mark(L),[{type:"text",text:`Read image ${p(L)} (${Z}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:Z}]}if(J.subarray(0,8192).includes(0))throw Error(`${L} looks like a binary file (${V.size} bytes)`);o.mark(L);let ne=J.toString("utf8");if(!ne)return c("(empty file)").content;let z=ne.replace(/\r?\n$/,"").split(/\r?\n/),oe=(_??1)-1;if(oe>=z.length)throw Error(`offset ${_} is past the end of the file (${z.length} lines)`);let fe=Math.min(z.length,oe+(Q??W$)),Ae=0,Ge=oe;while(Ge<fe){let ue=z[Ge]?.length??0;if(Ge>oe&&Ae+ue>WG)break;Ae+=ue,Ge++}let ee=yu(z.slice(oe,Ge),oe+1);if(Ge<fe)ee+=`
105
105
 
106
- (Showing lines ${oe+1}-${Ee} of ${z.length} (truncated at line ${Ee} due to safety budget). Use offset/limit to read specific windows.)`;else if(oe>0||Ee<z.length)ee+=`
106
+ (Showing lines ${oe+1}-${Ge} of ${z.length} (truncated at line ${Ge} due to safety budget). Use offset/limit to read specific windows.)`;else if(oe>0||Ge<z.length)ee+=`
107
107
 
108
- (Showing lines ${oe+1}-${Ee} of ${z.length}. Use offset/limit to read other parts.)`;return c(ee).content},I=T({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
108
+ (Showing lines ${oe+1}-${Ge} of ${z.length}. Use offset/limit to read other parts.)`;return c(ee).content},I=T({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
109
109
  - path may be absolute or relative to the working directory.
110
- - By default reads up to ${H$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
110
+ - By default reads up to ${W$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
111
111
  - Lines longer than ${Ml} characters are truncated.
112
112
  - Reading a directory lists its entries (directories end with /).
113
113
  - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
114
114
  - To read several files at once, give paths instead of path (up to ${_l}, 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.
115
- - Always read a file before editing or overwriting it.`,parameters:l({path:n(s({description:"File or directory path"})),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"})),paths:n(H(l({path:s({description:"File or directory path"}),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:_l,description:"Several files or directories to read in one call, instead of path"}))}),async execute(v,_){let Q=[..._.path!==void 0?[{path:_.path,offset:_.offset,limit:_.limit}]:[],..._.paths??[]];if(Q.length===0)throw Error("Give path, or paths to read several files");if(Q.length===1){let ne=Q[0];return{content:h(ne.path,ne.offset,ne.limit),details:void 0}}if(Q.length>_l)throw Error(`Read at most ${_l} paths per call`);let L=[],V=[],J=0,Z=(ne)=>{let z=L.at(-1);if(ne.type==="text"&&z?.type==="text")z.text+=`
115
+ - Always read a file before editing or overwriting it.`,parameters:l({path:n(s({description:"File or directory path"})),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"})),paths:n(F(l({path:s({description:"File or directory path"}),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:_l,description:"Several files or directories to read in one call, instead of path"}))}),async execute(v,_){let Q=[..._.path!==void 0?[{path:_.path,offset:_.offset,limit:_.limit}]:[],..._.paths??[]];if(Q.length===0)throw Error("Give path, or paths to read several files");if(Q.length===1){let ne=Q[0];return{content:h(ne.path,ne.offset,ne.limit),details:void 0}}if(Q.length>_l)throw Error(`Read at most ${_l} paths per call`);let L=[],V=[],J=0,Z=(ne)=>{let z=L.at(-1);if(ne.type==="text"&&z?.type==="text")z.text+=`
116
116
 
117
- ${ne.text}`;else L.push(ne)};for(let ne of Q){let z=`==> ${p(m(ne.path))} <==`;if(J>=KG){Z({type:"text",text:`${z}
118
- (Skipped due to total read safety budget; read in separate calls)`});continue}try{let oe=h(ne.path,ne.offset,ne.limit);for(let fe=0;fe<oe.length;fe++){let ke=oe[fe];if(!ke)continue;if(ke.type==="text")J+=ke.text.length,Z(fe===0?{...ke,text:`${z}
119
- ${ke.text}`}:ke);else Z(ke)}}catch(oe){let fe=oe instanceof Error?oe.message:String(oe);V.push(fe),Z({type:"text",text:`${z}
117
+ ${ne.text}`;else L.push(ne)};for(let ne of Q){let z=`==> ${p(m(ne.path))} <==`;if(J>=zG){Z({type:"text",text:`${z}
118
+ (Skipped due to total read safety budget; read in separate calls)`});continue}try{let oe=h(ne.path,ne.offset,ne.limit);for(let fe=0;fe<oe.length;fe++){let Ae=oe[fe];if(!Ae)continue;if(Ae.type==="text")J+=Ae.text.length,Z(fe===0?{...Ae,text:`${z}
119
+ ${Ae.text}`}:Ae);else Z(Ae)}}catch(oe){let fe=oe instanceof Error?oe.message:String(oe);V.push(fe),Z({type:"text",text:`${z}
120
120
  Error: ${fe}`})}}if(V.length===Q.length)throw Error(V.join(`
121
121
  `));return{content:L,details:void 0}}}),E=async(v,_,Q,L)=>{let V=L?.update,J=await cr(v,{cwd:e,timeout:120000,signal:Q,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:V?(fe)=>V(c(`${L.prefix}
122
122
 
@@ -130,68 +130,68 @@ ${Z}
130
130
  - An existing file is replaced whole, including changes made since you last read it.
131
131
  - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
132
132
  - 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.
133
- - Do not create documentation or README files unless asked.`,parameters:l({path:s({description:"File path"}),content:s({description:"The full file content"}),then_run:n(s({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(v,_,Q,L){let V=m(_.path);f(V);let J=Iu(V),Z;if(J){if(Nl(V).isDirectory())throw Error(`${V} is a directory`);Z=S(V,!0)}qG(Ll(V),{recursive:!0}),dg(V,_.content),o.mark(V);let ne=_.content?_.content.split(`
133
+ - Do not create documentation or README files unless asked.`,parameters:l({path:s({description:"File path"}),content:s({description:"The full file content"}),then_run:n(s({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(v,_,Q,L){let V=m(_.path);f(V);let J=Iu(V),Z;if(J){if(Nl(V).isDirectory())throw Error(`${V} is a directory`);Z=S(V,!0)}UG(Ll(V),{recursive:!0}),fg(V,_.content),o.mark(V);let ne=_.content?_.content.split(`
134
134
  `).length:0,z=`${J?"Overwrote":"Created"} ${p(V)} (${ne} lines)${Z?`
135
- ${Z}`:""}`;if(_.then_run){let oe=await E(_.then_run,`${p(V)} was written as given`,Q,{prefix:z,update:L});if(z+=oe.out,oe.failed)return{...c(z),isError:!0}}return c(z)}}),k=(v,_,Q,L)=>{let V=m(v);if(!Iu(V))throw Error(`File not found: ${V} (use write to create it)`);f(V);let J=S(V),Z=K$(V,"utf8"),ne=Z,z=ne.includes(`\r
136
- `),oe=[],fe=[],ke=0,Ee=0;return _.forEach((ee,ue)=>{let $e=L?`edits[${Q+ue}]: `:"";try{if(ee.old_string===ee.new_string)throw Error(`${$e}old_string and new_string are identical`);if(!ee.old_string)throw Error(`${$e}old_string is empty (use write to create or replace a whole file)`);let gt=z&&!ee.old_string.includes(`\r
137
- `),Ke=gt?ee.old_string.replace(/\n/g,`\r
138
- `):ee.old_string,Zt=gt?ee.new_string.replace(/\n/g,`\r
139
- `):ee.new_string,_e=WG(ne,Ke).map((Pt)=>[Pt,Pt+Ke.length]);if(_e.length===0)_e=zG(ne,Ke);if(_e.length===0)throw Error(`${$e}old_string not found in ${p(V)}; read the relevant lines and copy the exact text.${VG(ne,Ke)}`);if(_e.length>1&&!ee.replace_all){let Pt=_e.map(([tt])=>W$(ne,tt)).join(", ");throw Error(`${$e}old_string occurs ${_e.length} times (lines ${Pt}); add surrounding lines to make it unique, or set replace_all.`)}let qe=W$(ne,_e[0][0]),Dt=ee.replace_all?_e:[_e[0]],pt="",Mt=0;for(let[Pt,tt]of Dt)pt+=ne.slice(Mt,Pt)+Zt,Mt=tt;ne=pt+ne.slice(Mt),ke++,Ee+=Dt.length;let Ir=ne.split(/\r?\n/),nr=qe+Zt.split(/\r?\n/).length-1,Ut=Math.max(1,qe-1),et=Math.min(Ir.length,nr+1);if(et-Ut+1<=BG+2)oe.push(yu(Ir.slice(Ut-1,et),Ut));else oe.push(`${yu(Ir.slice(Ut-1,qe+1),Ut)}
140
- \u2026 (${nr-qe-3} lines as given)
141
- ${yu(Ir.slice(nr-2,et),nr-1)}`)}catch(gt){fe.push(gt instanceof Error?gt.message:String(gt))}}),{path:V,original:Z,content:ne,echoes:oe,applied:ke,total:Ee,count:_.length,note:J,failed:fe}},P=T({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
135
+ ${Z}`:""}`;if(_.then_run){let oe=await E(_.then_run,`${p(V)} was written as given`,Q,{prefix:z,update:L});if(z+=oe.out,oe.failed)return{...c(z),isError:!0}}return c(z)}}),k=(v,_,Q,L)=>{let V=m(v);if(!Iu(V))throw Error(`File not found: ${V} (use write to create it)`);f(V);let J=S(V),Z=H$(V,"utf8"),ne=Z,z=ne.includes(`\r
136
+ `),oe=[],fe=[],Ae=0,Ge=0;return _.forEach((ee,ue)=>{let we=L?`edits[${Q+ue}]: `:"";try{if(ee.old_string===ee.new_string)throw Error(`${we}old_string and new_string are identical`);if(!ee.old_string)throw Error(`${we}old_string is empty (use write to create or replace a whole file)`);let Ve=z&&!ee.old_string.includes(`\r
137
+ `),je=Ve?ee.old_string.replace(/\n/g,`\r
138
+ `):ee.old_string,Qt=Ve?ee.new_string.replace(/\n/g,`\r
139
+ `):ee.new_string,$e=JG(ne,je).map((Pt)=>[Pt,Pt+je.length]);if($e.length===0)$e=QG(ne,je);if($e.length===0)throw Error(`${we}old_string not found in ${p(V)}; read the relevant lines and copy the exact text.${XG(ne,je)}`);if($e.length>1&&!ee.replace_all){let Pt=$e.map(([rt])=>z$(ne,rt)).join(", ");throw Error(`${we}old_string occurs ${$e.length} times (lines ${Pt}); add surrounding lines to make it unique, or set replace_all.`)}let _e=z$(ne,$e[0][0]),Dt=ee.replace_all?$e:[$e[0]],lt="",Mt=0;for(let[Pt,rt]of Dt)lt+=ne.slice(Mt,Pt)+Qt,Mt=rt;ne=lt+ne.slice(Mt),Ae++,Ge+=Dt.length;let Ir=ne.split(/\r?\n/),nr=_e+Qt.split(/\r?\n/).length-1,Ut=Math.max(1,_e-1),tt=Math.min(Ir.length,nr+1);if(tt-Ut+1<=HG+2)oe.push(yu(Ir.slice(Ut-1,tt),Ut));else oe.push(`${yu(Ir.slice(Ut-1,_e+1),Ut)}
140
+ \u2026 (${nr-_e-3} lines as given)
141
+ ${yu(Ir.slice(nr-2,tt),nr-1)}`)}catch(Ve){fe.push(Ve instanceof Error?Ve.message:String(Ve))}}),{path:V,original:Z,content:ne,echoes:oe,applied:Ae,total:Ge,count:_.length,note:J,failed:fe}},P=T({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
142
142
  - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
143
143
  - 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.
144
144
  - 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.
145
145
  - 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.
146
146
  - To create a file use write; to delete or move files use bash.
147
147
  - 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.
148
- - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(s({description:"File path (the default for edits items without their own path)"})),old_string:n(s({description:"The exact text to replace (only when edits is absent)"})),new_string:n(s({description:"The replacement text (only when edits is absent)"})),replace_all:n(N({description:"Replace every occurrence (default false)"})),edits:n(H(l({path:n(s({description:"The file of this replacement, when it is not path"})),old_string:s({description:"The exact text to replace"}),new_string:s({description:"The replacement text"}),replace_all:n(N({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(s({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(v,_,Q,L){let V=_.edits&&_.edits.length>0?_.edits.map((ee)=>({path:ee.path??_.path,step:ee})):_.old_string!==void 0&&_.new_string!==void 0?[{path:_.path,step:{old_string:_.old_string,new_string:_.new_string,replace_all:_.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,Z=new Map;V.forEach((ee,ue)=>{if(!ee.path)throw Error(`${J?`edits[${ue}]: `:""}path is required`);let $e=m(ee.path),gt=Z.get($e)??{raw:ee.path,steps:[],offset:ue};gt.steps.push(ee.step),Z.set($e,gt)});let ne=[],z=[];for(let ee of Z.values())try{let ue=k(ee.raw,ee.steps,ee.offset,J);if(ue.applied>0)ne.push(ue);z.push(...ue.failed)}catch(ue){let $e=ue instanceof Error?ue.message:String(ue);z.push(`${J?`edits[${ee.offset}]: `:""}${$e}`)}if(ne.length===0)throw Error(z.join(`
149
- `));let oe=[];try{for(let ee of ne)dg(ee.path,ee.content),oe.push(ee)}catch(ee){for(let ue of oe)dg(ue.path,ue.original);throw ee}for(let ee of ne)o.mark(ee.path);let ke=ne.map((ee)=>{let ue=ee.total===1?"1 occurrence":`${ee.total} occurrences`,$e=ee.note?`
150
- ${ee.note}`:"";if(!J)return`Edited ${p(ee.path)} (${ue}).${$e}
151
- ${ee.echoes[0]}`;let gt=ee.failed.length>0?`, ${ee.failed.length} failed`:"";return`Edited ${p(ee.path)} (${ee.applied} edits${gt}, ${ue}). Regions are shown as they were right after each edit; later edits may shift line numbers.${$e}
152
- ${ee.echoes.map((Ke,Zt)=>`--- edit ${Zt+1}
153
- ${Ke}`).join(`
148
+ - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(s({description:"File path (the default for edits items without their own path)"})),old_string:n(s({description:"The exact text to replace (only when edits is absent)"})),new_string:n(s({description:"The replacement text (only when edits is absent)"})),replace_all:n(N({description:"Replace every occurrence (default false)"})),edits:n(F(l({path:n(s({description:"The file of this replacement, when it is not path"})),old_string:s({description:"The exact text to replace"}),new_string:s({description:"The replacement text"}),replace_all:n(N({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(s({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(v,_,Q,L){let V=_.edits&&_.edits.length>0?_.edits.map((ee)=>({path:ee.path??_.path,step:ee})):_.old_string!==void 0&&_.new_string!==void 0?[{path:_.path,step:{old_string:_.old_string,new_string:_.new_string,replace_all:_.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,Z=new Map;V.forEach((ee,ue)=>{if(!ee.path)throw Error(`${J?`edits[${ue}]: `:""}path is required`);let we=m(ee.path),Ve=Z.get(we)??{raw:ee.path,steps:[],offset:ue};Ve.steps.push(ee.step),Z.set(we,Ve)});let ne=[],z=[];for(let ee of Z.values())try{let ue=k(ee.raw,ee.steps,ee.offset,J);if(ue.applied>0)ne.push(ue);z.push(...ue.failed)}catch(ue){let we=ue instanceof Error?ue.message:String(ue);z.push(`${J?`edits[${ee.offset}]: `:""}${we}`)}if(ne.length===0)throw Error(z.join(`
149
+ `));let oe=[];try{for(let ee of ne)fg(ee.path,ee.content),oe.push(ee)}catch(ee){for(let ue of oe)fg(ue.path,ue.original);throw ee}for(let ee of ne)o.mark(ee.path);let Ae=ne.map((ee)=>{let ue=ee.total===1?"1 occurrence":`${ee.total} occurrences`,we=ee.note?`
150
+ ${ee.note}`:"";if(!J)return`Edited ${p(ee.path)} (${ue}).${we}
151
+ ${ee.echoes[0]}`;let Ve=ee.failed.length>0?`, ${ee.failed.length} failed`:"";return`Edited ${p(ee.path)} (${ee.applied} edits${Ve}, ${ue}). Regions are shown as they were right after each edit; later edits may shift line numbers.${we}
152
+ ${ee.echoes.map((je,Qt)=>`--- edit ${Qt+1}
153
+ ${je}`).join(`
154
154
  `)}`}).join(`
155
155
 
156
- `),Ee=!1;if(_.then_run){let ee=await E(_.then_run,"The edits above were applied",Q,{prefix:ke,update:L});if(ke+=ee.out,ee.failed)Ee=!0}if(z.length>0)ke+=`
156
+ `),Ge=!1;if(_.then_run){let ee=await E(_.then_run,"The edits above were applied",Q,{prefix:Ae,update:L});if(Ae+=ee.out,ee.failed)Ge=!0}if(z.length>0)Ae+=`
157
157
 
158
158
  ${z.length===1?"1 edit":`${z.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
159
159
  - ${z.join(`
160
- - `)}`,Ee=!0;return Ee?{...c(ke),isError:!0}:c(ke)}});return[Te(I,"cat","view","read_file","view_file","open_file","open"),Te(R,"write_file","create_file","new_file","save_file"),Te(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function WG(e,o){let a=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))a.push(u);return a}function W$(e,o){let a=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)a++;return a}function zG(e,o){let a=o.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),u=[],m=e.split(`
160
+ - `)}`,Ge=!0;return Ge?{...c(Ae),isError:!0}:c(Ae)}});return[Te(I,"cat","view","read_file","view_file","open_file","open"),Te(R,"write_file","create_file","new_file","save_file"),Te(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function JG(e,o){let a=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))a.push(u);return a}function z$(e,o){let a=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)a++;return a}function QG(e,o){let a=o.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),u=[],m=e.split(`
161
161
  `),p=0;for(let I of m)u.push(p),p+=I.length+1;let f=m.map((I)=>I.replace(/\r$/,"").trimEnd()),h=[];for(let I=0;I+a.length<=f.length;I++)if(a.every((E,S)=>f[I+S]===E)){let E=I+a.length-1,S=u[E]+m[E].replace(/\r$/,"").length,R=o.endsWith(`
162
- `)&&S<e.length?e[S]==="\r"?2:1:0;h.push([u[I],S+R]),I+=a.length-1}return h}function VG(e,o){let a=(h)=>h.replace(/\s+/g," ").trim(),u=a(o);if(!u)return"";let m=e.split(/\r?\n/),p=o.split(/\r?\n/).length;for(let h=0;h+p<=m.length;h++)if(a(m.slice(h,h+p).join(`
162
+ `)&&S<e.length?e[S]==="\r"?2:1:0;h.push([u[I],S+R]),I+=a.length-1}return h}function XG(e,o){let a=(h)=>h.replace(/\s+/g," ").trim(),u=a(o);if(!u)return"";let m=e.split(/\r?\n/),p=o.split(/\r?\n/).length;for(let h=0;h+p<=m.length;h++)if(a(m.slice(h,h+p).join(`
163
163
  `))===u)return` A match ignoring whitespace exists at line ${h+1}; copy the exact indentation and line breaks from the read output:
164
- ${le(yu(m.slice(h,h+p),h+1),4000)}`;let f=o.split(/\r?\n/).find((h)=>h.trim())?.trim();if(f){let h=m.findIndex((I)=>I.includes(f));if(h!==-1)return` Its first line appears at line ${h+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 JG(e){let o=Ll(e);if(!Iu(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let m=V$(o).filter((p)=>{let f=p.toLowerCase().replace(/\.[^.]*$/,"");return f&&(f.includes(u)||u.includes(f))}).slice(0,5);return m.length?`. Did you mean: ${m.join(", ")}?`:""}function z$(e,o){let a=J$(e,o);return a===""||!a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&a!==".."&&!fg(a)}var gg=20,yg=80,QG=5,XG=(e)=>e!==void 0&&e>0?e:void 0;function X$(e,o){let a=$l(e,o)??vl(e,o);if(!a)throw Error(`No user message with seq ${o}`);return a}function Dl(e,o){let a=(f)=>{if(o)return o(f);if(f.source&&f.source!=="self"||f.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(f)=>{let h=a(f),I=XG(f.seq);return{scope:h,seq:I,runs:()=>Qs(h.records),reference:`session_id=${h.sessionID}`,both:I!==void 0&&f.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
164
+ ${le(yu(m.slice(h,h+p),h+1),4000)}`;let f=o.split(/\r?\n/).find((h)=>h.trim())?.trim();if(f){let h=m.findIndex((I)=>I.includes(f));if(h!==-1)return` Its first line appears at line ${h+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 YG(e){let o=Ll(e);if(!Iu(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let m=J$(o).filter((p)=>{let f=p.toLowerCase().replace(/\.[^.]*$/,"");return f&&(f.includes(u)||u.includes(f))}).slice(0,5);return m.length?`. Did you mean: ${m.join(", ")}?`:""}function V$(e,o){let a=Q$(e,o);return a===""||!a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&a!==".."&&!hg(a)}var yg=20,xg=80,ZG=5,eK=(e)=>e!==void 0&&e>0?e:void 0;function Y$(e,o){let a=$l(e,o)??vl(e,o);if(!a)throw Error(`No user message with seq ${o}`);return a}function Dl(e,o){let a=(f)=>{if(o)return o(f);if(f.source&&f.source!=="self"||f.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(f)=>{let h=a(f),I=eK(f.seq);return{scope:h,seq:I,runs:()=>Qs(h.records),reference:`session_id=${h.sessionID}`,both:I!==void 0&&f.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
165
165
  `:""}},m=T({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
166
166
  - 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).
167
- - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),pattern:s({minLength:1,description:"Text to search for"}),also:n(H(s({minLength:1}),{maxItems:QG,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(s({description:"Only search this chunk"})),seq:n(x({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(N({description:"Default false"})),head_limit:n(x({minimum:1,maximum:gg,description:`Hits to return (default ${gg})`})),offset:n(x({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(f,h){let{scope:I,seq:E,runs:S,reference:R,both:k}=u(h),P;if(E!==void 0)P=[X$(I.records,E)];else{let oe=S(),fe=h.chunk_id?oe.filter((ke)=>ke.id===h.chunk_id):oe;if(h.chunk_id&&!fe.length)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);P=fe.map(hu)}let v=(oe)=>h.case_sensitive?oe:oe.toLowerCase(),_=[h.pattern,...(h.also??[]).filter(Boolean)].map(v),Q=h.head_limit??gg,L=h.offset??0,V=[],J=new Map,Z=0;for(let oe of P)oe.forEach((fe,ke)=>{let Ee=v(fe.text);if(!_.every((ue)=>Ee.includes(ue)))return;if(J.set(fe.chunk,(J.get(fe.chunk)??0)+1),Z++,Z<=L||V.length>=Q)return;let ee=oe.slice(Math.max(0,ke-2),ke+3);V.push(`${R} chunk ${fe.chunk} line ${fe.line}:
167
+ - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),pattern:s({minLength:1,description:"Text to search for"}),also:n(F(s({minLength:1}),{maxItems:ZG,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(s({description:"Only search this chunk"})),seq:n(x({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(N({description:"Default false"})),head_limit:n(x({minimum:1,maximum:yg,description:`Hits to return (default ${yg})`})),offset:n(x({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(f,h){let{scope:I,seq:E,runs:S,reference:R,both:k}=u(h),P;if(E!==void 0)P=[Y$(I.records,E)];else{let oe=S(),fe=h.chunk_id?oe.filter((Ae)=>Ae.id===h.chunk_id):oe;if(h.chunk_id&&!fe.length)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);P=fe.map(hu)}let v=(oe)=>h.case_sensitive?oe:oe.toLowerCase(),_=[h.pattern,...(h.also??[]).filter(Boolean)].map(v),Q=h.head_limit??yg,L=h.offset??0,V=[],J=new Map,Z=0;for(let oe of P)oe.forEach((fe,Ae)=>{let Ge=v(fe.text);if(!_.every((ue)=>Ge.includes(ue)))return;if(J.set(fe.chunk,(J.get(fe.chunk)??0)+1),Z++,Z<=L||V.length>=Q)return;let ee=oe.slice(Math.max(0,Ae-2),Ae+3);V.push(`${R} chunk ${fe.chunk} line ${fe.line}:
168
168
  ${Vc(ee," ")}`)});if(!Z)return c(`${k}No matches`);if(!V.length)return c(`${k}No matches at offset ${L} (total ${Z})`);let ne=Z-L-V.length,z=J.size>1?` (all matches by chunk: ${[...J].map(([oe,fe])=>`${oe} ${fe}`).join(", ")})`:"";return c(`${k}${V.join(`
169
169
 
170
170
  `)}${ne>0?`
171
171
 
172
- \u2026 ${ne} more matches${z}; continue with offset=${L+V.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=T({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),chunk_id:n(s({description:"Chunk to read"})),seq:n(x({description:"User message to read (from a user-text-reference)"})),offset:n(x({minimum:0,description:"First line (default 0)"})),limit:n(x({minimum:1,maximum:yg,description:`Lines to return (default ${yg})`}))}),async execute(f,h){let{scope:I,seq:E,runs:S,reference:R,both:k}=u(h),P;if(E!==void 0)P=X$(I.records,E);else if(h.chunk_id){let L=S().find((V)=>V.id===h.chunk_id);if(!L)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);P=hu(L)}else{let L=S().map((V)=>`${R} ${V.id} (${V.status}, ${hu(V).length} lines)`);return c(L.length?`Pass chunk_id or seq. Chunks in this session:
172
+ \u2026 ${ne} more matches${z}; continue with offset=${L+V.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=T({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),chunk_id:n(s({description:"Chunk to read"})),seq:n(x({description:"User message to read (from a user-text-reference)"})),offset:n(x({minimum:0,description:"First line (default 0)"})),limit:n(x({minimum:1,maximum:xg,description:`Lines to return (default ${xg})`}))}),async execute(f,h){let{scope:I,seq:E,runs:S,reference:R,both:k}=u(h),P;if(E!==void 0)P=Y$(I.records,E);else if(h.chunk_id){let L=S().find((V)=>V.id===h.chunk_id);if(!L)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);P=hu(L)}else{let L=S().map((V)=>`${R} ${V.id} (${V.status}, ${hu(V).length} lines)`);return c(L.length?`Pass chunk_id or seq. Chunks in this session:
173
173
  ${L.join(`
174
- `)}`:"This session has no history yet")}let v=h.offset??0,_=P.slice(v,v+(h.limit??yg));if(!_.length)return c(`No lines at offset ${v} (total ${P.length})`);let Q=P.length-v-_.length;return c(`${k}${R} ${E!==void 0?`seq=${E}`:h.chunk_id}
174
+ `)}`:"This session has no history yet")}let v=h.offset??0,_=P.slice(v,v+(h.limit??xg));if(!_.length)return c(`No lines at offset ${v} (total ${P.length})`);let Q=P.length-v-_.length;return c(`${k}${R} ${E!==void 0?`seq=${E}`:h.chunk_id}
175
175
  ${Vc(_)}${Q>0?`
176
176
 
177
- \u2026 ${Q} more lines; continue with offset=${v+_.length}`:""}`)}});return[m,p]}import{existsSync as YG,statSync as Y$}from"fs";import{isAbsolute as Z$,relative as ZG,resolve as ev}from"path";var ql=200,eK=30000,Fl=Bun.which("rg");async function xg(e,o,a){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:a,windowsHide:!0}),[m,p,f]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(f>1)throw Error(p.trim()||`${e[0]} exited with ${f}`);return m}function tv(e){let o=(p)=>p?Z$(p)?p:ev(e,p):e,a=(p)=>{let f=ZG(e,p);return f&&!f.startsWith("..")&&!Z$(f)?f:p},u=T({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
177
+ \u2026 ${Q} more lines; continue with offset=${v+_.length}`:""}`)}});return[m,p]}import{existsSync as tK,statSync as Z$}from"fs";import{isAbsolute as ev,relative as rK,resolve as tv}from"path";var ql=200,nK=30000,Fl=Bun.which("rg");async function Ig(e,o,a){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:a,windowsHide:!0}),[m,p,f]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(f>1)throw Error(p.trim()||`${e[0]} exited with ${f}`);return m}function rv(e){let o=(p)=>p?ev(p)?p:tv(e,p):e,a=(p)=>{let f=rK(e,p);return f&&!f.startsWith("..")&&!ev(f)?f:p},u=T({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
178
178
  - Respects .gitignore and skips .git. Use it instead of find or ls -R.
179
- - To search file contents, use grep.`,parameters:l({pattern:s({description:"Glob pattern, matched relative to path"}),path:n(s({description:"Directory to search (default: working directory)"}))}),async execute(p,f,h){let I=o(f.path),E=!1;try{E=Y$(I).isDirectory()}catch{}if(!E)throw Error(`Directory not found: ${a(I)}`);let S;if(Fl)S=(await xg([Fl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",f.pattern],I,h)).split(`
180
- `).filter(Boolean);else{S=[];for await(let v of new Bun.Glob(f.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(v))S.push(v)}if(!S.length)return c("No files found");let R=S.map((v)=>{let _=ev(I,v);try{return{path:_,time:Y$(_).mtimeMs}}catch{return{path:_,time:0}}});R.sort((v,_)=>_.time-v.time);let k=R.slice(0,ql).map((v)=>a(v.path)),P=S.length-k.length;return c(`${k.join(`
179
+ - To search file contents, use grep.`,parameters:l({pattern:s({description:"Glob pattern, matched relative to path"}),path:n(s({description:"Directory to search (default: working directory)"}))}),async execute(p,f,h){let I=o(f.path),E=!1;try{E=Z$(I).isDirectory()}catch{}if(!E)throw Error(`Directory not found: ${a(I)}`);let S;if(Fl)S=(await Ig([Fl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",f.pattern],I,h)).split(`
180
+ `).filter(Boolean);else{S=[];for await(let v of new Bun.Glob(f.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(v))S.push(v)}if(!S.length)return c("No files found");let R=S.map((v)=>{let _=tv(I,v);try{return{path:_,time:Z$(_).mtimeMs}}catch{return{path:_,time:0}}});R.sort((v,_)=>_.time-v.time);let k=R.slice(0,ql).map((v)=>a(v.path)),P=S.length-k.length;return c(`${k.join(`
181
181
  `)}${P>0?`
182
182
  \u2026 ${P} more files; narrow the pattern`:""}`)}}),m=T({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
183
183
  - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
184
184
  - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
185
185
  - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
186
- - Use this instead of running grep or rg through bash.`,parameters:l({pattern:s({description:"Regular expression"}),path:n(s({description:"File or directory to search (default: working directory)"})),glob:n(s({description:"Only search files matching this glob"})),output:n(g([i("files"),i("content"),i("count")],{description:"Output mode (default files)"})),ignore_case:n(N()),context:n(x({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(p,f,h){let I=o(f.path);if(!YG(I))throw Error(`Path not found: ${a(I)}`);let E=f.output??"files",S;if(Fl){let P=[Fl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(f.ignore_case)P.push("-i");if(f.glob)P.push("--glob",f.glob);if(E==="files")P.push("-l");else if(E==="count")P.push("-c");else if(P.push("-n","--no-heading"),f.context)P.push("-C",String(f.context));P.push("--",f.pattern,I),S=await xg(P,e,h)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(f.ignore_case)P.push("-i");if(f.glob)P.push(`--include=${f.glob}`);if(E==="files")P.push("-l");else if(E==="count")P.push("-c");else if(P.push("-n"),f.context)P.push(`-C${f.context}`);P.push("--",f.pattern,I),S=await xg(P,e,h)}let R=`${e}/`,k=S.split(`
186
+ - Use this instead of running grep or rg through bash.`,parameters:l({pattern:s({description:"Regular expression"}),path:n(s({description:"File or directory to search (default: working directory)"})),glob:n(s({description:"Only search files matching this glob"})),output:n(g([i("files"),i("content"),i("count")],{description:"Output mode (default files)"})),ignore_case:n(N()),context:n(x({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(p,f,h){let I=o(f.path);if(!tK(I))throw Error(`Path not found: ${a(I)}`);let E=f.output??"files",S;if(Fl){let P=[Fl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(f.ignore_case)P.push("-i");if(f.glob)P.push("--glob",f.glob);if(E==="files")P.push("-l");else if(E==="count")P.push("-c");else if(P.push("-n","--no-heading"),f.context)P.push("-C",String(f.context));P.push("--",f.pattern,I),S=await Ig(P,e,h)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(f.ignore_case)P.push("-i");if(f.glob)P.push(`--include=${f.glob}`);if(E==="files")P.push("-l");else if(E==="count")P.push("-c");else if(P.push("-n"),f.context)P.push(`-C${f.context}`);P.push("--",f.pattern,I),S=await Ig(P,e,h)}let R=`${e}/`,k=S.split(`
187
187
  `).filter(Boolean).map((P)=>P.startsWith(R)?P.slice(R.length):P).filter((P)=>E!=="count"||!P.endsWith(":0"));if(!k.length)return c("No matches");if(E==="files"&&k.length>ql)return c(`${k.slice(0,ql).join(`
188
188
  `)}
189
189
  \u2026 ${k.length-ql} more files; narrow the search`);return c(it(k.join(`
190
- `),eK,e))}});return[Te(u,"find","find_files","list_files","file_search","ls","list","list_dir"),Te(m,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function rv(e){return Te(T({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
190
+ `),nK,e))}});return[Te(u,"find","find_files","list_files","file_search","ls","list","list_dir"),Te(m,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function nv(e){return Te(T({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
191
191
  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.
192
192
  - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
193
193
  - 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.
194
- - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:H(l({content:s({minLength:1,description:"What to do, in imperative form"}),status:g(sy.map((o)=>i(o)))}))}),async execute(o,a){let u=a.todos.map((f)=>({content:f.content,status:f.status}));e(u);let m=u.filter((f)=>f.status==="completed").length,p=u.find((f)=>f.status==="in_progress");return c(`Todo list updated (${m}/${u.length} completed${p?`; in progress: ${p.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function nv(e){let o=me(e);return{target:o,hard:o,index:o}}class jl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},a){this.records=e;this.cwd=o;if(a)this.defaultPolicy=new zc(e,a,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??nv(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??me(e)}prepare(e,o,a,u,m=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,a,u);let p=e.reduce((E,S)=>E+q(S),0)+ki(o),f=Math.max(0,me(a)*this.recoveryRatio-p),h=Me(u??this.records(),a,nv(a),{cwd:this.cwd()}).messages,I=h.reduce((E,S)=>E+q(S),0);if(m&&I>f)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(I>f&&h.length>1){let E=h.shift();if(E)I-=q(E);while(h[0]?.role==="toolResult"){let S=h.shift();if(S)I-=q(S)}}if(I>f){let E=h.at(-1),S=E&&"content"in E&&typeof E.content==="string"?E.content:"[Context omitted: use history tools to retrieve earlier messages.]";h.length=0;let R=S;while(R&&q({role:"user",content:R,timestamp:0})>f)R=R.slice(Math.ceil(R.length/2));if(R)h.push({role:"user",content:R,timestamp:0});I=h.reduce((k,P)=>k+q(P),0)}return this.lastMessageCount=h.length,{messages:[...e,...h],estimate:p+I}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as bg,readFileSync as tK}from"fs";import{homedir as rK}from"os";import{dirname as ov,join as Eg,resolve as nK}from"path";var oK=`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.
194
+ - 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:F(l({content:s({minLength:1,description:"What to do, in imperative form"}),status:g(iy.map((o)=>i(o)))}))}),async execute(o,a){let u=a.todos.map((f)=>({content:f.content,status:f.status}));e(u);let m=u.filter((f)=>f.status==="completed").length,p=u.find((f)=>f.status==="in_progress");return c(`Todo list updated (${m}/${u.length} completed${p?`; in progress: ${p.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function ov(e){let o=me(e);return{target:o,hard:o,index:o}}class jl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},a){this.records=e;this.cwd=o;if(a)this.defaultPolicy=new zc(e,a,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??ov(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??me(e)}prepare(e,o,a,u,m=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,a,u);let p=e.reduce((E,S)=>E+j(S),0)+ki(o),f=Math.max(0,me(a)*this.recoveryRatio-p),h=Me(u??this.records(),a,ov(a),{cwd:this.cwd()}).messages,I=h.reduce((E,S)=>E+j(S),0);if(m&&I>f)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(I>f&&h.length>1){let E=h.shift();if(E)I-=j(E);while(h[0]?.role==="toolResult"){let S=h.shift();if(S)I-=j(S)}}if(I>f){let E=h.at(-1),S=E&&"content"in E&&typeof E.content==="string"?E.content:"[Context omitted: use history tools to retrieve earlier messages.]";h.length=0;let R=S;while(R&&j({role:"user",content:R,timestamp:0})>f)R=R.slice(Math.ceil(R.length/2));if(R)h.push({role:"user",content:R,timestamp:0});I=h.reduce((k,P)=>k+j(P),0)}return this.lastMessageCount=h.length,{messages:[...e,...h],estimate:p+I}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as Eg,readFileSync as oK}from"fs";import{homedir as sK}from"os";import{dirname as sv,join as Sg,resolve as iK}from"path";var aK=`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.
195
195
 
196
196
  # How to work
197
197
 
@@ -249,7 +249,7 @@ Do not use it for a single deliverable, even a complex one (a feature, a bug fix
249
249
  - 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.
250
250
  - Do not use emojis unless the user does or asks for them.
251
251
  - 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.
252
- - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,sK=`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.
252
+ - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,uK=`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.
253
253
 
254
254
  # Tools
255
255
 
@@ -263,7 +263,7 @@ Do not use it for a single deliverable, even a complex one (a feature, a bug fix
263
263
 
264
264
  - Reply in the same language the user writes in.
265
265
  - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
266
- - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,iK=["AGENTS.md","CLAUDE.md"],aK=20000;function sv(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?oK:sK}],a=[];if(e.globalInstructions?.trim())a.push(Ig("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of uK(e.project.directory))a.push(Ig(u.path,u.content));if(e.project.instructions.trim())a.push(Ig(`Project "${e.project.name}" instructions`,e.project.instructions))}if(a.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
266
+ - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,cK=["AGENTS.md","CLAUDE.md"],mK=20000;function iv(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?aK:uK}],a=[];if(e.globalInstructions?.trim())a.push(bg("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of pK(e.project.directory))a.push(bg(u.path,u.content));if(e.project.instructions.trim())a.push(bg(`Project "${e.project.name}" instructions`,e.project.instructions))}if(a.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
267
267
 
268
268
  # Instructions from the user and project
269
269
 
@@ -273,30 +273,30 @@ ${a.join(`
273
273
 
274
274
  `)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
275
275
 
276
- ${cK(e)}`}),o}function Ig(e,o){return`<instructions source="${e}">
277
- ${le(o.trim(),aK)}
278
- </instructions>`}function uK(e){let o=[],a=e;for(let u=0;u<20;u++){for(let p of iK){let f=Eg(a,p);if(bg(f)){try{o.unshift({path:f,content:tK(f,"utf8")})}catch{}break}}if(bg(Eg(a,".git"))||a===rK())break;let m=ov(a);if(m===a)break;a=m}return o}function cK(e){let o=e.now??new Date,a=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),m=e.project?.directory??process.cwd(),{shellName:p}=Aa("",e.shell),f=[`Working directory: ${m}`,`Shell: ${p}`,`Date: ${a} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)f.push(e.git??"Git: not a git repository");return`<environment>
276
+ ${lK(e)}`}),o}function bg(e,o){return`<instructions source="${e}">
277
+ ${le(o.trim(),mK)}
278
+ </instructions>`}function pK(e){let o=[],a=e;for(let u=0;u<20;u++){for(let p of cK){let f=Sg(a,p);if(Eg(f)){try{o.unshift({path:f,content:oK(f,"utf8")})}catch{}break}}if(Eg(Sg(a,".git"))||a===sK())break;let m=sv(a);if(m===a)break;a=m}return o}function lK(e){let o=e.now??new Date,a=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),m=e.project?.directory??process.cwd(),{shellName:p}=Aa("",e.shell),f=[`Working directory: ${m}`,`Shell: ${p}`,`Date: ${a} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)f.push(e.git??"Git: not a git repository");return`<environment>
279
279
  ${f.join(`
280
280
  `)}
281
- </environment>`}function mK(e){let o=nK(e);while(!0){if(bg(Eg(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let a=ov(o);if(a===o)return!1;o=a}}async function iv(e,o){if(o?.aborted||mK(e))return;let a=async(...I)=>{try{let E=Bun.spawn(["git",...I],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[S,R]=await Promise.all([new Response(E.stdout).text(),E.exited]);return R===0?S.trim():void 0}catch{return}},u=await a("rev-parse","--abbrev-ref","HEAD");if(u===void 0)return;let[m="",p=""]=await Promise.all([a("status","--short"),a("log","--oneline","-5")]),f=m?m.split(`
281
+ </environment>`}function dK(e){let o=iK(e);while(!0){if(Eg(Sg(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let a=sv(o);if(a===o)return!1;o=a}}async function av(e,o){if(o?.aborted||dK(e))return;let a=async(...I)=>{try{let E=Bun.spawn(["git",...I],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[S,R]=await Promise.all([new Response(E.stdout).text(),E.exited]);return R===0?S.trim():void 0}catch{return}},u=await a("rev-parse","--abbrev-ref","HEAD");if(u===void 0)return;let[m="",p=""]=await Promise.all([a("status","--short"),a("log","--oneline","-5")]),f=m?m.split(`
282
282
  `):[],h=f.length>30?[...f.slice(0,30),`\u2026 ${f.length-30} more`]:f;return[`Git branch: ${u}`,`Git status at session start:${h.length?`
283
283
  ${h.join(`
284
284
  `)}`:" clean"}`,p?`Recent commits:
285
285
  ${p}`:"Recent commits: none"].join(`
286
- `)}function ur(e){let a=(e.hasCompacted?e.hasCompacted():e.records().some((m)=>m.entry.type==="compaction"))?Dl(e.records,e.history):[],u=e.directory??process.cwd();return[...Q$(u,new hg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...tv(u),rv(e.onTodos),...a]}class Pi{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||!ay.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!iy.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let a=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete a[u];else a[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let m=u,p=m.source??"core",f=u.name.toLowerCase(),h=m.defer??"always",I="suggestion";if(o.global)h=o.global,I="global";if(Object.hasOwn(o.sources,p))h=o.sources[p]??h,I="source";if(Object.hasOwn(o.tools,f))h=o.tools[f]??h,I="tool";if(p==="core"||m.builtin&&m.defer!=="defer")h="always",I="suggestion";return{name:u.name,source:p,mode:h,origin:I,deferred:h==="defer"}})}}function Sg(e){return{name:e.name,description:e.description,parameters:e.parameters}}function wg(e,o){if(!o)return e;let a=Array.isArray(o.type)?o.type:[o.type],u=e;if(a.includes("number")||a.includes("integer")){let m=typeof u==="string"&&u.trim()?Number(u):u;if(typeof m!=="number"||!Number.isFinite(m))return u;let p=m;if(typeof o.maximum==="number"&&p>o.maximum)p=o.maximum;if(typeof o.minimum==="number"&&p<o.minimum)p=o.minimum;return p===m?u:p}if(typeof u==="string"&&(a.includes("object")||a.includes("array")))try{let m=JSON.parse(u),p=Array.isArray(m);if(typeof m==="object"&&m!==null&&!p&&a.includes("object")||p&&a.includes("array"))u=m}catch{}if(Array.isArray(u)){let m=o.items;if(!m||typeof m!=="object"||Array.isArray(m))return u;return u.map((p)=>wg(p,m))}if(typeof u==="object"&&u!==null&&o.properties){let m={...u};for(let[p,f]of Object.entries(o.properties))if(p in m)m[p]=wg(m[p],f);return m}return u}function pK(e){let o=e.prepareArguments;return{...e,prepareArguments:(a)=>{let u=wg(a,e.parameters);return o?o(u):u}}}function lK(e,o,a){let u=e.prepareArguments?e.prepareArguments(a):a;return cu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class Tg{retrieved=new Map;stub(e,o){let a=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${a}
287
- (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,m,p,f)=>{let h=JSON.stringify(Sg(e)),I;try{I=lK(e,u,m??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
288
- Schema: ${h}`),isError:!0}}let E=await e.execute(u,I,p,f),S=E.content.map((R)=>R.type==="text"?{...R,text:it(R.text,Ce,o)}:R);return{...E,content:S}}}}assemble(e,o,a,u){let m=e.map(pK),p=new Set(o.filter((h)=>h.deferred).map((h)=>h.name));if(!p.size)return m;let f=m.filter((h)=>p.has(h.name)&&a(h.name)).sort((h,I)=>h.name<I.name?-1:h.name>I.name?1:0);return[...m.filter((h)=>!p.has(h.name)),...f.map((h)=>this.stub(h,u)),Te(T({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:s(),max_results:n(x({minimum:1,maximum:100}))}),execute:async(h,I)=>{let E=I.query.trim().toLowerCase(),S=E.startsWith("select:")?E.slice(7).split(",").map((k)=>k.trim()):void 0,R=f.filter((k)=>a(k.name)&&(S?S.includes(k.name.toLowerCase()):`${k.name} ${k.description}`.toLowerCase().includes(E))).slice(0,I.max_results??5);return c(JSON.stringify(R.map((k)=>{let P=JSON.stringify(Sg(k)),v=this.retrieved.get(k.name);if(v?.schema===P)return{name:k.name,status:"\u5DF2\u53D6\u56DE",callID:v.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(k.name,{schema:P,callID:h}),Sg(k)})))}}),"tool_search")]}}async function Ul(e,o,a,u){let m=await o.setup(e,u),p=a?.has("projection.policy")?await a.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!a)return m;if(a.has("session.setup"))m=await a.invoke("session.setup",m,e);if(a.has("tools.configure"))m=await a.invoke("tools.configure",m,e);let f=m.systemPrompt,h=m.systemParts?.at(-1);if(h?.label==="\u8FD0\u884C\u73AF\u5883"&&a.has("prompt.fragments","before-environment")){let R=await a.invoke("prompt.fragments",[],e,void 0,"before-environment"),k=f.length-h.detail.length;f=f.slice(0,k)+R.join("")+h.detail}let I=await a.invoke("prompt.fragments",[],e),E=[...m.tools,...a.tools()],S=a.has("tools.visible")?await a.invoke("tools.visible",E,e):E;return{...m,systemPrompt:f+I.join(""),tools:S}}var dK=3,av={attempts:10,delayMs:2000},fK=/\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 hK(e,o){if(e.stopReason!=="error")return!1;if(ha(e,o))return!1;return!fK.test(e.errorMessage??"")}function uv(e,o,a){if(ha(e,o))return!0;if(a?.preserveHistory!==!0)return!1;return e.errorMessage===(a.overflowError??"Context exceeds the request budget")}function gK(e,o){return new Promise((a,u)=>{if(o.aborted)return u(o.reason);let m=setTimeout(()=>{o.removeEventListener("abort",p),a()},e),p=()=>{clearTimeout(m),u(o.reason)};o.addEventListener("abort",p,{once:!0})})}async function cv(e,o,a,u,m,p,f,h,I=!1){let E=I?void 0:await o?.invoke("run.start",{text:p},e);if(E)p=E.text;if(h.throwIfAborted(),p===void 0)await u.resume();else await u.prompt(p,f);let S=0,R=0;while(S<dK){let _=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(_?.stopReason!=="error")return;if(!uv(_,m.contextWindow,a)){if(!hK(_,m.contextWindow)||R>=av.attempts)return;R++,await gK(av.delayMs,h),await u.retry();continue}if(!e.context.recover(m)){if(a?.preserveHistory===!0)throw Error(a.overflowError??"Context exceeds the request budget");return}h.throwIfAborted(),S++,await u.retry()}let P=e.records.findLast((v)=>v.raw?.role==="assistant")?.raw;if(a?.preserveHistory===!0&&P?.stopReason==="error"&&uv(P,m.contextWindow,a))throw Error(a.overflowError??"Context exceeds the request budget")}async function mv(e,o,a,u,m,p){p.throwIfAborted();let f,h;try{h=await Promise.race([Ul(e,o,a(),p),new Promise((k,P)=>{f=()=>P(p.reason),p.addEventListener("abort",f,{once:!0})})])}finally{if(f)p.removeEventListener("abort",f)}p.throwIfAborted();let I=a(),E=(k)=>{if(!I)return k;return{...k,execute:async(P,v,_,Q)=>{let L=u()??h.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=L?I.policy(L):void 0;if(L&&!V?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${L}`);let J=await I.invoke("tool.before_call",{name:k.name,callID:P,args:v},e);if(J.block)throw Error(J.block);let Z=await j.run(e,()=>k.execute(P,J.args,_,Q));return I.invoke("tool.after_result",Z,e)}}};if(I)h.tools=h.tools.map(E);let S=h.tools,R=()=>{if(!S.some((P)=>P.name==="history_grep")){if(e.records.some((v)=>v.entry.type==="compaction")){let _=Dl(()=>e.records,(Q)=>e.resolveHistory(Q)).map(E);for(let Q of _)if(!S.some((L)=>L.name===Q.name))S.push(Q)}}let k=new Pi(o.store).partition(S);return h.tools=m.assemble(S,k,(P)=>e.permitsTool(P),h.cwd),h.tools};return h.tools=R(),{setup:h,executionTools:S,assemble:R}}function pv(e,o,a,u,m,p,f){return{response:async(h)=>{let I=await o()?.invoke("model.after_response",h,e)??h;if(I.role==="assistant")for(let E of I.content){if(E.type!=="toolCall"||E.name.toLowerCase()!=="tool_call")continue;let S=E.arguments.name;if(typeof S==="string"){let R=f.find((k)=>k.name.toLowerCase()===S.toLowerCase());E.arguments.name=R?.name??S}}return I},payload:(h)=>o()?.invoke("model.before_request",h,e)??Promise.resolve(h),transformContext:(h)=>o()?.invoke("transformContext",h,e)??Promise.resolve(h),boundary:async()=>{if(u())return!0;let h=await o()?.invoke("step.after",{notices:[]},e);for(let E of h?.notices??[])e.notice(E);await p.work;let I=await p.flushNotices();if(I&&!m())e.agent?.steer(I)},prepare:async(h,I,E)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let S=await o()?.invoke("model.check",{},e);if(S?.error)throw Error(S.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let L of R?.notices??[])e.notice(L);await p.work,await p.flushNotices();let k=await o()?.invoke("projection.before",e.records,e),P=await o()?.invoke("projection.prefix",[],e)??[],v=e.context.prepare([...h,...P],I,E,k,a()?.preserveHistory===!0);if(a()?.preserveHistory===!0&&v.estimate>me(E))throw Error(a()?.overflowError??"Context exceeds the request budget");let _=v.messages,Q=await o()?.invoke("projection.after",_,e)??_;return du(c$(Q))}}}async function lv(e,o,a){let u=o.store.pendingNotices(e.id);if(!u.length)return;let m=u,p=o.plugins?.pin();try{if(p){let P=await p.invoke("notice.deliver",u,e);m=u.map((v,_)=>({...v,text:P[_]?.text??v.text}))}}finally{await p?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let f=m.map((P)=>P.text).join(`
286
+ `)}function ur(e){let a=(e.hasCompacted?e.hasCompacted():e.records().some((m)=>m.entry.type==="compaction"))?Dl(e.records,e.history):[],u=e.directory??process.cwd();return[...X$(u,new gg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...rv(u),nv(e.onTodos),...a]}class Pi{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||!uy.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!ay.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let a=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete a[u];else a[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let m=u,p=m.source??"core",f=u.name.toLowerCase(),h=m.defer??"always",I="suggestion";if(o.global)h=o.global,I="global";if(Object.hasOwn(o.sources,p))h=o.sources[p]??h,I="source";if(Object.hasOwn(o.tools,f))h=o.tools[f]??h,I="tool";if(p==="core"||m.builtin&&m.defer!=="defer")h="always",I="suggestion";return{name:u.name,source:p,mode:h,origin:I,deferred:h==="defer"}})}}function wg(e){return{name:e.name,description:e.description,parameters:e.parameters}}function Tg(e,o){if(!o)return e;let a=Array.isArray(o.type)?o.type:[o.type],u=e;if(a.includes("number")||a.includes("integer")){let m=typeof u==="string"&&u.trim()?Number(u):u;if(typeof m!=="number"||!Number.isFinite(m))return u;let p=m;if(typeof o.maximum==="number"&&p>o.maximum)p=o.maximum;if(typeof o.minimum==="number"&&p<o.minimum)p=o.minimum;return p===m?u:p}if(typeof u==="string"&&(a.includes("object")||a.includes("array")))try{let m=JSON.parse(u),p=Array.isArray(m);if(typeof m==="object"&&m!==null&&!p&&a.includes("object")||p&&a.includes("array"))u=m}catch{}if(Array.isArray(u)){let m=o.items;if(!m||typeof m!=="object"||Array.isArray(m))return u;return u.map((p)=>Tg(p,m))}if(typeof u==="object"&&u!==null&&o.properties){let m={...u};for(let[p,f]of Object.entries(o.properties))if(p in m)m[p]=Tg(m[p],f);return m}return u}function fK(e){let o=e.prepareArguments;return{...e,prepareArguments:(a)=>{let u=Tg(a,e.parameters);return o?o(u):u}}}function hK(e,o,a){let u=e.prepareArguments?e.prepareArguments(a):a;return cu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class Rg{retrieved=new Map;stub(e,o){let a=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${a}
287
+ (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,m,p,f)=>{let h=JSON.stringify(wg(e)),I;try{I=hK(e,u,m??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
288
+ Schema: ${h}`),isError:!0}}let E=await e.execute(u,I,p,f),S=E.content.map((R)=>R.type==="text"?{...R,text:it(R.text,Ce,o)}:R);return{...E,content:S}}}}assemble(e,o,a,u){let m=e.map(fK),p=new Set(o.filter((h)=>h.deferred).map((h)=>h.name));if(!p.size)return m;let f=m.filter((h)=>p.has(h.name)&&a(h.name)).sort((h,I)=>h.name<I.name?-1:h.name>I.name?1:0);return[...m.filter((h)=>!p.has(h.name)),...f.map((h)=>this.stub(h,u)),Te(T({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:s(),max_results:n(x({minimum:1,maximum:100}))}),execute:async(h,I)=>{let E=I.query.trim().toLowerCase(),S=E.startsWith("select:")?E.slice(7).split(",").map((k)=>k.trim()):void 0,R=f.filter((k)=>a(k.name)&&(S?S.includes(k.name.toLowerCase()):`${k.name} ${k.description}`.toLowerCase().includes(E))).slice(0,I.max_results??5);return c(JSON.stringify(R.map((k)=>{let P=JSON.stringify(wg(k)),v=this.retrieved.get(k.name);if(v?.schema===P)return{name:k.name,status:"\u5DF2\u53D6\u56DE",callID:v.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(k.name,{schema:P,callID:h}),wg(k)})))}}),"tool_search")]}}async function Ul(e,o,a,u){let m=await o.setup(e,u),p=a?.has("projection.policy")?await a.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!a)return m;if(a.has("session.setup"))m=await a.invoke("session.setup",m,e);if(a.has("tools.configure"))m=await a.invoke("tools.configure",m,e);let f=m.systemPrompt,h=m.systemParts?.at(-1);if(h?.label==="\u8FD0\u884C\u73AF\u5883"&&a.has("prompt.fragments","before-environment")){let R=await a.invoke("prompt.fragments",[],e,void 0,"before-environment"),k=f.length-h.detail.length;f=f.slice(0,k)+R.join("")+h.detail}let I=await a.invoke("prompt.fragments",[],e),E=[...m.tools,...a.tools()],S=a.has("tools.visible")?await a.invoke("tools.visible",E,e):E;return{...m,systemPrompt:f+I.join(""),tools:S}}var gK=3,uv={attempts:10,delayMs:2000},yK=/\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 xK(e,o){if(e.stopReason!=="error")return!1;if(ha(e,o))return!1;return!yK.test(e.errorMessage??"")}function cv(e,o,a){if(ha(e,o))return!0;if(a?.preserveHistory!==!0)return!1;return e.errorMessage===(a.overflowError??"Context exceeds the request budget")}var mv="\u4E0A\u4E0B\u6587\u5DF2\u6EE1\uFF0C\u6A21\u578B\u6CA1\u6709\u5269\u4F59\u7684\u8F93\u51FA\u7A7A\u95F4\uFF0C\u56DE\u590D\u88AB\u622A\u65AD\uFF1B\u8BF7\u538B\u7F29\u4F1A\u8BDD\u6216\u6362\u7528\u4E0A\u4E0B\u6587\u66F4\u5927\u7684\u6A21\u578B";function pv(e){if(e.stopReason!=="length")return!1;return!e.content.some((o)=>o.type==="text"&&o.text.trim()||o.type==="toolCall")}function IK(e,o){return new Promise((a,u)=>{if(o.aborted)return u(o.reason);let m=setTimeout(()=>{o.removeEventListener("abort",p),a()},e),p=()=>{clearTimeout(m),u(o.reason)};o.addEventListener("abort",p,{once:!0})})}async function lv(e,o,a,u,m,p,f,h,I=!1){let E=I?void 0:await o?.invoke("run.start",{text:p},e);if(E)p=E.text;if(h.throwIfAborted(),p===void 0)await u.resume();else await u.prompt(p,f);let S=0,R=0;while(S<gK){let _=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(_&&pv(_)){if(!e.context.recover(m))throw Error(mv);h.throwIfAborted(),S++,await u.retry();continue}if(_?.stopReason!=="error")return;if(!cv(_,m.contextWindow,a)){if(!xK(_,m.contextWindow)||R>=uv.attempts)return;R++,await IK(uv.delayMs,h),await u.retry();continue}if(!e.context.recover(m)){if(a?.preserveHistory===!0)throw Error(a.overflowError??"Context exceeds the request budget");return}h.throwIfAborted(),S++,await u.retry()}let P=e.records.findLast((v)=>v.raw?.role==="assistant")?.raw;if(P&&pv(P))throw Error(mv);if(a?.preserveHistory===!0&&P?.stopReason==="error"&&cv(P,m.contextWindow,a))throw Error(a.overflowError??"Context exceeds the request budget")}async function dv(e,o,a,u,m,p){p.throwIfAborted();let f,h;try{h=await Promise.race([Ul(e,o,a(),p),new Promise((k,P)=>{f=()=>P(p.reason),p.addEventListener("abort",f,{once:!0})})])}finally{if(f)p.removeEventListener("abort",f)}p.throwIfAborted();let I=a(),E=(k)=>{if(!I)return k;return{...k,execute:async(P,v,_,Q)=>{let L=u()??h.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=L?I.policy(L):void 0;if(L&&!V?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${L}`);let J=await I.invoke("tool.before_call",{name:k.name,callID:P,args:v},e);if(J.block)throw Error(J.block);let Z=await q.run(e,()=>k.execute(P,J.args,_,Q));return I.invoke("tool.after_result",Z,e)}}};if(I)h.tools=h.tools.map(E);let S=h.tools,R=()=>{if(!S.some((P)=>P.name==="history_grep")){if(e.records.some((v)=>v.entry.type==="compaction")){let _=Dl(()=>e.records,(Q)=>e.resolveHistory(Q)).map(E);for(let Q of _)if(!S.some((L)=>L.name===Q.name))S.push(Q)}}let k=new Pi(o.store).partition(S);return h.tools=m.assemble(S,k,(P)=>e.permitsTool(P),h.cwd),h.tools};return h.tools=R(),{setup:h,executionTools:S,assemble:R}}function fv(e,o,a,u,m,p,f){return{response:async(h)=>{let I=await o()?.invoke("model.after_response",h,e)??h;if(I.role==="assistant")for(let E of I.content){if(E.type!=="toolCall"||E.name.toLowerCase()!=="tool_call")continue;let S=E.arguments.name;if(typeof S==="string"){let R=f.find((k)=>k.name.toLowerCase()===S.toLowerCase());E.arguments.name=R?.name??S}}return I},payload:(h)=>o()?.invoke("model.before_request",h,e)??Promise.resolve(h),transformContext:(h)=>o()?.invoke("transformContext",h,e)??Promise.resolve(h),boundary:async()=>{if(u())return!0;let h=await o()?.invoke("step.after",{notices:[]},e);for(let E of h?.notices??[])e.notice(E);await p.work;let I=await p.flushNotices();if(I&&!m())e.agent?.steer(I)},prepare:async(h,I,E)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let S=await o()?.invoke("model.check",{},e);if(S?.error)throw Error(S.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let L of R?.notices??[])e.notice(L);await p.work,await p.flushNotices();let k=await o()?.invoke("projection.before",e.records,e),P=await o()?.invoke("projection.prefix",[],e)??[],v=e.context.prepare([...h,...P],I,E,k,a()?.preserveHistory===!0);if(a()?.preserveHistory===!0&&v.estimate>me(E))throw Error(a()?.overflowError??"Context exceeds the request budget");let _=v.messages,Q=await o()?.invoke("projection.after",_,e)??_;return du(m$(Q))}}}async function hv(e,o,a){let u=o.store.pendingNotices(e.id);if(!u.length)return;let m=u,p=o.plugins?.pin();try{if(p){let P=await p.invoke("notice.deliver",u,e);m=u.map((v,_)=>({...v,text:P[_]?.text??v.text}))}}finally{await p?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let f=m.map((P)=>P.text).join(`
289
289
  `),h=m.map((P)=>o.plugins?.noticeSource(P.sourceKind)),I=Math.max(800,...h.map((P)=>P?.summaryLimit??800)),E=f.length>I?`
290
290
  [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${h.find((P)=>P?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
291
- ${f.slice(0,I)}${E}`,k={role:"user",content:R,timestamp:Date.now()};return a({type:"user",text:R,notices:u.map(({text:P,...v})=>v)},k),k}class Rg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,a,u,m,p,f,h){this.session=e;this.context=o;this.isStopped=a;this.isRunning=u;this.waiting=m;this.start=p;this.invalidateAgent=f;this.append=h}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let a of e){if(a.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:a.dedupeKey,sourceKind:a.sourceKind,sourceID:a.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((a)=>a.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((a)=>{this.failure=a}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=lv(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 yK=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 kg(e){let o={};for(let[a,u]of Object.entries(e)){if(!yK.has(a.toLowerCase())){o[a]=u;continue}let m=/^bearer\s+/i.exec(u)?.[0];o[a]=m?`${m}***`:"***"}return o}function dv(e,o,a,u){let p=(a.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:a.systemPrompt}]).map((z,oe)=>({id:`system-${oe}`,label:z.label,detail:z.detail,tokens:F(z.detail)+(oe===0?16:0)})),f=a.tools.map((z)=>{let oe=z,fe=oe.defer==="defer"||z.description.includes("(Parameters not inlined: use toolsearch");return{name:z.name,description:z.description,group:oe.group??"\u5185\u7F6E",schema:z.parameters,deferred:fe}});p.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:ki(a.tools),detail:JSON.stringify(f,null,2)});let h=p.reduce((z,oe)=>z+oe.tokens,0),I=u!==void 0?e.records.filter((z)=>z.entry.seq<=u):e.records,E=Me(I,o,e.context.budget(o),{inspect:!0,cwd:a.cwd,trim:{fixed:h,limit:e.context.previewLimit(o)}}),S,R=0,k=0;for(let z of I){if(z.raw?.role!=="assistant")continue;let oe=z.raw.usage;S??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},S.input+=oe.input,S.output+=oe.output,S.cacheRead+=oe.cacheRead,S.cacheWrite+=oe.cacheWrite,S.cost+=oe.cost.total;let fe=z.entry.generationMs??z.raw.generationMs;if(typeof fe==="number"&&fe>0&&oe.output>0)R+=fe,k+=oe.output}if(S){let z=S.input+S.cacheRead+S.cacheWrite;if(z>0)S.cacheHitRate=S.cacheRead/z}if(S&&R>0&&k>0)S.generationMs=R,S.tps=Number((k/(R/1000)).toFixed(1));let P=h+E.tokens,v=e.context.calibrationRatio??1,_=Math.round(P*v),Q=I.findLast((z)=>z.raw?.role==="assistant"),L=Q?.raw,J=(Q?I.filter((z)=>z.entry.seq>Q.entry.seq&&z.raw):I.filter((z)=>z.raw)).length>0,Z,ne;if(L){let z=L.usage,oe=z.input+z.cacheRead+z.cacheWrite;if(oe>0)Z=oe,ne=z.cacheRead/oe}return{contextWindow:o.contextWindow,usableWindow:me(o),items:[...p,...E.items],calibratedTokens:_,calibrationRatio:v,lastInputTokens:Z,lastCacheHitRate:ne,hasPendingOutput:J,tools:f,usage:S}}class ft extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class ce extends Error{constructor(e="session"){super(`${e} is busy`)}}var Ag="medium",xK=1e6;class Bl{row;ctx;events;notices;lease;policyID;discovery=new Tg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Ul(this,this.ctx,e);return new Pi(this.ctx.store).partition(o.tools).filter((a)=>this.permitsTool(a.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new ce;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,a){this.row=e;this.ctx=o;this.events=a;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new Rg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let m=this.entries(0,["extension","run"],!1),p=m.findLast((h)=>h.type==="extension"&&h.namespace==="session"&&h.kind==="stop_requested"),f=m.findLast((h)=>h.type==="run"&&h.state==="start");if(p&&p.seq>(f?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let h=this.entries(u.seq,["user"],!1).length>0,I=o.store.pendingNotices(e.id).some((E)=>E.wake&&E.recovery!=="discard");if(!this.stopped&&(h||I))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new jl(()=>this.records,()=>this.cwd,(h,I)=>this.appendCompaction(h,I)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=Tn(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:kg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:kg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??Ag}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get runningTools(){return this.agent?.agent.state.pendingToolCalls.size??0}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:a,model:u,thinking:m,metadata:p,created:f,updated:h,todos:I}=this.row;return{id:e,title:o,projectID:a,model:u,thinking:m??Ag,metadata:p,created:f,updated:h,archivedAt:this.row.archivedAt,status:this.status,todos:I,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5,xK);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let a=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,a,e)}entriesAround(e,o,a){return this.ctx.store.entriesAround(this.row.id,e,o,a)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,a=!0){return this.ctx.store.entries(this.row.id,e,o,a)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let a=Tn(this.ctx.models,this.row.model);if(!a)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),m;try{m=this.setup??await Ul(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)m.tools=this.discovery.assemble(m.tools,new Pi(this.ctx.store).partition(m.tools),(f)=>this.permitsTool(f),m.cwd);let p=dv(this,a,m,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:p};return p})();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 ft}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"||!Tn(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,ud(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let a=ud(o),u=Hh(e,a),m=this.append({type:"user",text:e,...a?.length?{attachments:a}:{}},u);if(this.recallableSteers.set(m.seq,u),this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((p)=>p.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let a=o.raw,u=this.pendingSteers.indexOf(a);if(u<0){let p=JSON.stringify(a);u=this.pendingSteers.findIndex((f)=>JSON.stringify(f)===p)}let m=!1;if(u>=0)this.pendingSteers.splice(u,1),m=!0;else m=this.agent?.unsteer(a)??!1;if(!m)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,a]of this.recallableSteers){if(a!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,a){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&a===void 0)throw new ce;if(e!==void 0)this.stopped=!1;let u=Tn(this.ctx.models,this.row.model);if(!u&&a===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let m=new AbortController;if(this.starting=m,!this.row.title&&e!==void 0)this.row={...this.row,title:IK(e,o)},this.ctx.store.updateSession(this.row);let p=a??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let f=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=f.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(m.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(a!==void 0){let h=this.records.filter((R)=>R.entry.seq>p),I=h.filter((R)=>R.entry.type==="user"&&!R.raw);if(I.length>1)return{reason:"interrupted"};let E=I[0];if(E?.entry.type==="user"){if(h.some((R)=>R.entry.seq>E.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=E.entry.text,o=E.entry.attachments,this.pendingUserSeq=E.entry.seq}for(let R of Po(h.filter((k)=>k.raw))){if(R.result)continue;let k=R.message.stopReason;if(k==="error"||k==="aborted")continue;let{body:P,raw:v}=yl(R.call);this.append(P,v)}if(!E&&this.waitingForInput())return{reason:"waiting_user"};let S=this.records.findLast((R)=>R.entry.seq>p&&R.raw)?.raw;if(!E&&S?.role==="assistant")return Wh(S);if(!E&&!S&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let f=await this.prepareAgent(u,m.signal);m.signal.throwIfAborted();while(this.pendingSteers.length>0){let h=this.pendingSteers.shift();if(h)f.steer(h)}return await cv(this,this.lease,this.setup,f,u,e,o,m.signal,a!==void 0&&e===void 0),Wh(this.records.findLast((h)=>h.entry.seq>p&&h.raw?.role==="assistant")?.raw)}).then((f)=>m.signal.aborted?{reason:"aborted"}:f,(f)=>m.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(f)}).then(async(f)=>{try{if(!this.suspended&&f.reason!=="interrupted"){if(!m.signal.aborted&&this.waitingForInput())f={reason:"waiting_user"};if(f.reason!=="interrupted")f=await this.lease?.invoke("run.end",{reason:f.reason,error:f.error},this)??f}}catch(h){f={reason:"error",error:String(h)}}finally{try{await this.lease?.release()}catch(h){f={reason:"error",error:String(h)}}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",...f});let h=Tn(this.ctx.models,this.row.model);if(h)this.context.settle(h)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:a,executionTools:u,assemble:m}=await mv(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=a,this.row.parentID&&(!a.toolPolicy||!this.lease?.policy(a.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=a.cwd,this.agent=H0({models:this.ctx.models,model:e,systemPrompt:a.systemPrompt,tools:a.tools,history:this.records.filter((p)=>!this.pendingSteers.includes(p.raw)).flatMap((p)=>p.raw?[p.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??Ag,captureRequest:(p)=>{this.lastRequestSnapshot=p},captureResponse:(p)=>{this.lastResponseSnapshot=p},steerConsumed:(p)=>this.markSteerConsumed(p),hooks:{tools:m,...pv(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(p,f)=>{if(this.suspended&&f.role==="assistant"&&(f.stopReason==="aborted"||f.stopReason==="error"))return;if(f.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,f);let h=this.loaded?.find((I)=>I.entry.seq===this.pendingUserSeq);if(h)h.raw=f;this.pendingUserSeq=void 0;return}if(f.role==="assistant")this.context.calibrate(f);this.append(p,f)},draft:(p)=>{this.draftParts=p,this.events.draft(p)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let a=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...a?{saved:a}:{}})}measureCompactionSavings(e,o){let a=Tn(this.ctx.models,this.row.model);if(!a)return;let u=this.context.budget(a),m=Me(this.records,a,u,{cwd:this.cwd}).tokens,p={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},f=Me([...this.records,p],a,u,{cwd:this.cwd}).tokens;return{before:m,after:f}}compact(){this.assertWritable();let e=lu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let a=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(a.type==="user"&&!(("notices"in a)&&a.notices))this.row={...this.row,updated:a.time};return this.refreshEntries(),a}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function IK(e,o){let u=(e.trim()||o?.map((m)=>m.name).join(" ")||"").split(`
292
- `)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var hv=new Set(["user","assistant","tool_result","run","compaction"]),bK=new Set(["user","assistant","toolResult"]);function gv(e,o,a){return{format:ad,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...a?{project:a}:{},records:o.filter((u)=>hv.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function Jo(e){if(!xr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===ad)return EK(e);if(xr(e.info)&&Array.isArray(e.messages))return wK(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 EK(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(!xr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let a=0,u=e.records.flatMap((m,p)=>{let f=`records[${p}]`;if(!xr(m)||!xr(m.entry))throw new t(`${f} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let h=m.entry;if(h.type==="notice_pending"||h.type==="extension")return[];if(typeof h.type!=="string"||!hv.has(h.type))throw new t(`${f} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(h.type)}`);let{seq:I,time:E}=h;if(typeof I!=="number"||!Number.isSafeInteger(I)||I<=a)throw new t(`${f} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof E!=="number"||!Number.isFinite(E))throw new t(`${f} \u7F3A\u5C11\u6709\u6548\u7684 time`);a=I,SK(h,f);let S=m.raw;if(S!==void 0&&!(xr(S)&&typeof S.role==="string"&&bK.has(S.role)))throw new t(`${f} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:h,...S===void 0?{}:{raw:S}}]});return{title:Dr(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(xv):[],created:Xs(o.created)??Date.now(),updated:Xs(o.updated)??Date.now(),needsRaw:!1,records:u}}function SK(e,o){let a=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);switch(e.type){case"user":if(typeof e.text!=="string")throw a("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw a("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw a("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&Xg.includes(e.reason)))throw a("\u7684 state/reason \u4E0D\u5408\u6CD5");return;case"compaction":if(typeof e.through!=="number"||typeof e.partial!=="boolean")throw a("\u7F3A\u5C11 through \u6216 partial");return}}function wK(e){let o=e.info,a=xr(o.time)?o.time:{},u=xr(o.model)?o.model:void 0,m=e.messages.filter(xr).sort(TK),p=[],f=0,h=0,I=(Q,L)=>{h=Math.max(h,L??h),f+=1,p.push({entry:{...Q,seq:f,time:h}})},E=!1,S=(Q,L)=>{if(!E)return;E=!1,I({type:"run",state:"end",reason:Q,...L?{error:L}:{}},void 0)};for(let Q of m){let L=xr(Q.info)?Q.info:{},V=Array.isArray(Q.parts)?Q.parts.filter(xr):[],J=Xs(xr(L.time)?L.time.created:void 0);if(L.role==="user"){S("done");let Z=RK(V);if(!Z)continue;I({type:"run",state:"start"},J),I(Z,J),E=!0}else if(L.role==="assistant"){if(!E)I({type:"run",state:"start"},J),E=!0;PK(L,V,I);let Z=yv(L.error);if(Z)S(Z.aborted?"aborted":"error",Z.aborted?void 0:Z.message)}}S("done");let R=m.findLast((Q)=>xr(Q.info)&&Q.info.role==="assistant"),k=xr(R?.info)?R.info:void 0,P=Dr(u?.providerID)||Dr(k?.providerID),v=Dr(u?.id)||Dr(k?.modelID),_=P&&v?`${P}/${v}`:void 0;return{title:Dr(o.title),model:_,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(xv):[],created:Xs(a.created)??p[0]?.entry.time??Date.now(),updated:Xs(a.updated)??p.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:p}}function TK(e,o){let a=(m)=>(xr(m.info)&&xr(m.info.time)?Xs(m.info.time.created):void 0)??0,u=(m)=>xr(m.info)?Dr(m.info.id):"";return a(e)-a(o)||u(e).localeCompare(u(o))}function RK(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Dr(u.text)).join(`
291
+ ${f.slice(0,I)}${E}`,k={role:"user",content:R,timestamp:Date.now()};return a({type:"user",text:R,notices:u.map(({text:P,...v})=>v)},k),k}class kg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,a,u,m,p,f,h){this.session=e;this.context=o;this.isStopped=a;this.isRunning=u;this.waiting=m;this.start=p;this.invalidateAgent=f;this.append=h}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let a of e){if(a.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:a.dedupeKey,sourceKind:a.sourceKind,sourceID:a.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((a)=>a.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((a)=>{this.failure=a}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=hv(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 bK=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 Ag(e){let o={};for(let[a,u]of Object.entries(e)){if(!bK.has(a.toLowerCase())){o[a]=u;continue}let m=/^bearer\s+/i.exec(u)?.[0];o[a]=m?`${m}***`:"***"}return o}function gv(e,o,a,u){let p=(a.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:a.systemPrompt}]).map((z,oe)=>({id:`system-${oe}`,label:z.label,detail:z.detail,tokens:W(z.detail)+(oe===0?16:0)})),f=a.tools.map((z)=>{let oe=z,fe=oe.defer==="defer"||z.description.includes("(Parameters not inlined: use toolsearch");return{name:z.name,description:z.description,group:oe.group??"\u5185\u7F6E",schema:z.parameters,deferred:fe}});p.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:ki(a.tools),detail:JSON.stringify(f,null,2)});let h=p.reduce((z,oe)=>z+oe.tokens,0),I=u!==void 0?e.records.filter((z)=>z.entry.seq<=u):e.records,E=Me(I,o,e.context.budget(o),{inspect:!0,cwd:a.cwd,trim:{fixed:h,limit:e.context.previewLimit(o)}}),S,R=0,k=0;for(let z of I){if(z.raw?.role!=="assistant")continue;let oe=z.raw.usage;S??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},S.input+=oe.input,S.output+=oe.output,S.cacheRead+=oe.cacheRead,S.cacheWrite+=oe.cacheWrite,S.cost+=oe.cost.total;let fe=z.entry.generationMs??z.raw.generationMs;if(typeof fe==="number"&&fe>0&&oe.output>0)R+=fe,k+=oe.output}if(S){let z=S.input+S.cacheRead+S.cacheWrite;if(z>0)S.cacheHitRate=S.cacheRead/z}if(S&&R>0&&k>0)S.generationMs=R,S.tps=Number((k/(R/1000)).toFixed(1));let P=h+E.tokens,v=e.context.calibrationRatio??1,_=Math.round(P*v),Q=I.findLast((z)=>z.raw?.role==="assistant"),L=Q?.raw,J=(Q?I.filter((z)=>z.entry.seq>Q.entry.seq&&z.raw):I.filter((z)=>z.raw)).length>0,Z,ne;if(L){let z=L.usage,oe=z.input+z.cacheRead+z.cacheWrite;if(oe>0)Z=oe,ne=z.cacheRead/oe}return{contextWindow:o.contextWindow,usableWindow:me(o),items:[...p,...E.items],calibratedTokens:_,calibrationRatio:v,lastInputTokens:Z,lastCacheHitRate:ne,hasPendingOutput:J,tools:f,usage:S}}class ft extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class ce extends Error{constructor(e="session"){super(`${e} is busy`)}}var Pg="medium",EK=1e6;class Bl{row;ctx;events;notices;lease;policyID;discovery=new Rg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Ul(this,this.ctx,e);return new Pi(this.ctx.store).partition(o.tools).filter((a)=>this.permitsTool(a.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new ce;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;steerWaiter;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,a){this.row=e;this.ctx=o;this.events=a;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new kg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let m=this.entries(0,["extension","run"],!1),p=m.findLast((h)=>h.type==="extension"&&h.namespace==="session"&&h.kind==="stop_requested"),f=m.findLast((h)=>h.type==="run"&&h.state==="start");if(p&&p.seq>(f?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let h=this.entries(u.seq,["user"],!1).length>0,I=o.store.pendingNotices(e.id).some((E)=>E.wake&&E.recovery!=="discard");if(!this.stopped&&(h||I))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new jl(()=>this.records,()=>this.cwd,(h,I)=>this.appendCompaction(h,I)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=Tn(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:Ag(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:Ag(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??Pg}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get runningTools(){return this.agent?.agent.state.pendingToolCalls.size??0}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:a,model:u,thinking:m,metadata:p,created:f,updated:h,todos:I}=this.row;return{id:e,title:o,projectID:a,model:u,thinking:m??Pg,metadata:p,created:f,updated:h,archivedAt:this.row.archivedAt,status:this.status,todos:I,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5,EK);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let a=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,a,e)}entriesAround(e,o,a){return this.ctx.store.entriesAround(this.row.id,e,o,a)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,a=!0){return this.ctx.store.entries(this.row.id,e,o,a)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let a=Tn(this.ctx.models,this.row.model);if(!a)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),m;try{m=this.setup??await Ul(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)m.tools=this.discovery.assemble(m.tools,new Pi(this.ctx.store).partition(m.tools),(f)=>this.permitsTool(f),m.cwd);let p=gv(this,a,m,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:p};return p})();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 ft}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"||!Tn(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,ud(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let a=ud(o),u=Hh(e,a),m=this.append({type:"user",text:e,...a?.length?{attachments:a}:{}},u);if(this.recallableSteers.set(m.seq,u),this.steerWaiter?.abort(Error("user steered")),this.steerWaiter=void 0,this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}userSteered(){if(this.recallableSteers.size>0)return AbortSignal.abort(Error("user steered"));return this.steerWaiter??=new AbortController,this.steerWaiter.signal}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((p)=>p.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let a=o.raw,u=this.pendingSteers.indexOf(a);if(u<0){let p=JSON.stringify(a);u=this.pendingSteers.findIndex((f)=>JSON.stringify(f)===p)}let m=!1;if(u>=0)this.pendingSteers.splice(u,1),m=!0;else m=this.agent?.unsteer(a)??!1;if(!m)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,a]of this.recallableSteers){if(a!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,a){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&a===void 0)throw new ce;if(e!==void 0)this.stopped=!1;let u=Tn(this.ctx.models,this.row.model);if(!u&&a===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let m=new AbortController;if(this.starting=m,!this.row.title&&e!==void 0)this.row={...this.row,title:SK(e,o)},this.ctx.store.updateSession(this.row);let p=a??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let f=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=f.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(m.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(a!==void 0){let h=this.records.filter((R)=>R.entry.seq>p),I=h.filter((R)=>R.entry.type==="user"&&!R.raw);if(I.length>1)return{reason:"interrupted"};let E=I[0];if(E?.entry.type==="user"){if(h.some((R)=>R.entry.seq>E.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=E.entry.text,o=E.entry.attachments,this.pendingUserSeq=E.entry.seq}for(let R of Po(h.filter((k)=>k.raw))){if(R.result)continue;let k=R.message.stopReason;if(k==="error"||k==="aborted")continue;let{body:P,raw:v}=yl(R.call);this.append(P,v)}if(!E&&this.waitingForInput())return{reason:"waiting_user"};let S=this.records.findLast((R)=>R.entry.seq>p&&R.raw)?.raw;if(!E&&S?.role==="assistant")return Wh(S);if(!E&&!S&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let f=await this.prepareAgent(u,m.signal);m.signal.throwIfAborted();while(this.pendingSteers.length>0){let h=this.pendingSteers.shift();if(h)f.steer(h)}return await lv(this,this.lease,this.setup,f,u,e,o,m.signal,a!==void 0&&e===void 0),Wh(this.records.findLast((h)=>h.entry.seq>p&&h.raw?.role==="assistant")?.raw)}).then((f)=>m.signal.aborted?{reason:"aborted"}:f,(f)=>m.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(f)}).then(async(f)=>{try{if(!this.suspended&&f.reason!=="interrupted"){if(!m.signal.aborted&&this.waitingForInput())f={reason:"waiting_user"};if(f.reason!=="interrupted")f=await this.lease?.invoke("run.end",{reason:f.reason,error:f.error},this)??f}}catch(h){f={reason:"error",error:String(h)}}finally{try{await this.lease?.release()}catch(h){f={reason:"error",error:String(h)}}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",...f});let h=Tn(this.ctx.models,this.row.model);if(h)this.context.settle(h)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:a,executionTools:u,assemble:m}=await dv(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=a,this.row.parentID&&(!a.toolPolicy||!this.lease?.policy(a.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=a.cwd,this.agent=WC({models:this.ctx.models,model:e,systemPrompt:a.systemPrompt,tools:a.tools,history:this.records.filter((p)=>!this.pendingSteers.includes(p.raw)).flatMap((p)=>p.raw?[p.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??Pg,captureRequest:(p)=>{this.lastRequestSnapshot=p},captureResponse:(p)=>{this.lastResponseSnapshot=p},steerConsumed:(p)=>this.markSteerConsumed(p),hooks:{tools:m,...fv(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(p,f)=>{if(this.suspended&&f.role==="assistant"&&(f.stopReason==="aborted"||f.stopReason==="error"))return;if(f.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,f);let h=this.loaded?.find((I)=>I.entry.seq===this.pendingUserSeq);if(h)h.raw=f;this.pendingUserSeq=void 0;return}if(f.role==="assistant")this.context.calibrate(f);this.append(p,f)},draft:(p)=>{this.draftParts=p,this.events.draft(p)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let a=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...a?{saved:a}:{}})}measureCompactionSavings(e,o){let a=Tn(this.ctx.models,this.row.model);if(!a)return;let u=this.context.budget(a),m=Me(this.records,a,u,{cwd:this.cwd}).tokens,p={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},f=Me([...this.records,p],a,u,{cwd:this.cwd}).tokens;return{before:m,after:f}}compact(){this.assertWritable();let e=lu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let a=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(a.type==="user"&&!(("notices"in a)&&a.notices))this.row={...this.row,updated:a.time};return this.refreshEntries(),a}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function SK(e,o){let u=(e.trim()||o?.map((m)=>m.name).join(" ")||"").split(`
292
+ `)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var xv=new Set(["user","assistant","tool_result","run","compaction"]),wK=new Set(["user","assistant","toolResult"]);function Iv(e,o,a){return{format:ad,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...a?{project:a}:{},records:o.filter((u)=>xv.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function Jo(e){if(!xr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===ad)return TK(e);if(xr(e.info)&&Array.isArray(e.messages))return kK(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 TK(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(!xr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let a=0,u=e.records.flatMap((m,p)=>{let f=`records[${p}]`;if(!xr(m)||!xr(m.entry))throw new t(`${f} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let h=m.entry;if(h.type==="notice_pending"||h.type==="extension")return[];if(typeof h.type!=="string"||!xv.has(h.type))throw new t(`${f} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(h.type)}`);let{seq:I,time:E}=h;if(typeof I!=="number"||!Number.isSafeInteger(I)||I<=a)throw new t(`${f} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof E!=="number"||!Number.isFinite(E))throw new t(`${f} \u7F3A\u5C11\u6709\u6548\u7684 time`);a=I,RK(h,f);let S=m.raw;if(S!==void 0&&!(xr(S)&&typeof S.role==="string"&&wK.has(S.role)))throw new t(`${f} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:h,...S===void 0?{}:{raw:S}}]});return{title:Dr(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(Ev):[],created:Xs(o.created)??Date.now(),updated:Xs(o.updated)??Date.now(),needsRaw:!1,records:u}}function RK(e,o){let a=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);switch(e.type){case"user":if(typeof e.text!=="string")throw a("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw a("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw a("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&Yg.includes(e.reason)))throw a("\u7684 state/reason \u4E0D\u5408\u6CD5");return;case"compaction":if(typeof e.through!=="number"||typeof e.partial!=="boolean")throw a("\u7F3A\u5C11 through \u6216 partial");return}}function kK(e){let o=e.info,a=xr(o.time)?o.time:{},u=xr(o.model)?o.model:void 0,m=e.messages.filter(xr).sort(AK),p=[],f=0,h=0,I=(Q,L)=>{h=Math.max(h,L??h),f+=1,p.push({entry:{...Q,seq:f,time:h}})},E=!1,S=(Q,L)=>{if(!E)return;E=!1,I({type:"run",state:"end",reason:Q,...L?{error:L}:{}},void 0)};for(let Q of m){let L=xr(Q.info)?Q.info:{},V=Array.isArray(Q.parts)?Q.parts.filter(xr):[],J=Xs(xr(L.time)?L.time.created:void 0);if(L.role==="user"){S("done");let Z=PK(V);if(!Z)continue;I({type:"run",state:"start"},J),I(Z,J),E=!0}else if(L.role==="assistant"){if(!E)I({type:"run",state:"start"},J),E=!0;vK(L,V,I);let Z=bv(L.error);if(Z)S(Z.aborted?"aborted":"error",Z.aborted?void 0:Z.message)}}S("done");let R=m.findLast((Q)=>xr(Q.info)&&Q.info.role==="assistant"),k=xr(R?.info)?R.info:void 0,P=Dr(u?.providerID)||Dr(k?.providerID),v=Dr(u?.id)||Dr(k?.modelID),_=P&&v?`${P}/${v}`:void 0;return{title:Dr(o.title),model:_,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(Ev):[],created:Xs(a.created)??p[0]?.entry.time??Date.now(),updated:Xs(a.updated)??p.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:p}}function AK(e,o){let a=(m)=>(xr(m.info)&&xr(m.info.time)?Xs(m.info.time.created):void 0)??0,u=(m)=>xr(m.info)?Dr(m.info.id):"";return a(e)-a(o)||u(e).localeCompare(u(o))}function PK(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Dr(u.text)).join(`
293
293
 
294
- `),a=e.flatMap((u)=>u.type==="file"?kK(u):[]);if(!o.trim()&&a.length===0)return;return{type:"user",text:o,...a.length?{attachments:a}:{}}}function kK(e){let o=Dr(e.mime)||"application/octet-stream",a=Dr(e.filename)||"file",u=Dr(e.url),m=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(m){let p=m[3]??"";if(o.startsWith("image/"))return[{name:a,mimeType:o,kind:"image",data:m[2]?p:btoa(p)}];if(o.startsWith("text/")||o==="application/json"){let f=m[2]?new TextDecoder().decode(Uint8Array.from(atob(p),(h)=>h.charCodeAt(0))):p;return[{name:a,mimeType:o,kind:"text",data:f}]}return[]}if(u.startsWith("file://"))try{return[{name:a,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function AK(e){let o=[[]];for(let a of e){if(a.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(a.type==="reasoning"||a.type==="text"||a.type==="tool")o.at(-1)?.push(a)}return o.filter((a)=>a.length>0)}function PK(e,o,a){let u=`${Dr(e.providerID)}/${Dr(e.modelID)}`,m=yv(e.error),p=AK(o);p.forEach((f,h)=>{let I=f.flatMap((R)=>{if(R.type==="reasoning")return Dr(R.text).trim()?[{type:"thinking",text:Dr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Dr(R.text).trim()?[{type:"text",text:Dr(R.text)}]:[];return[{type:"tool_call",id:fv(R.callID),name:Dr(R.tool),input:xr(R.state)&&xr(R.state.input)?R.state.input:{}}]}),E=h===p.length-1,S=CK(f);a({type:"assistant",parts:I,model:u,...E&&m&&!m.aborted?{error:m.message}:{}},S);for(let R of f){if(R.type!=="tool")continue;let k=xr(R.state)?R.state:{},P=k.status==="error",v=k.status==="pending"||k.status==="running",_=P?[Dr(k.output),Dr(k.error)].filter(Boolean).join(`
295
- `):v?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Dr(k.output);a({type:"tool_result",callID:fv(R.callID),name:Dr(R.tool),output:_,isError:P||v},Xs(xr(k.time)?k.time.end:void 0))}})}function fv(e){return Dr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function yv(e){if(!xr(e))return;let o=xr(e.data)?e.data:{};return{message:Dr(o.message)||Dr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function CK(e){for(let o of e){let a=xr(o.time)?Xs(o.time.start):xr(o.state)?$K(o.state):void 0;if(a!==void 0)return a}return}function $K(e){return xr(e.time)?Xs(e.time.start):void 0}function xv(e){if(!xr(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 Iv(e,o){let a={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let m=u.time;switch(u.type){case"user":return{entry:u,raw:vK(u,m)};case"assistant":{let p=u.parts.flatMap((h)=>{if(h.type==="text")return[{type:"text",text:h.text}];if(h.type==="thinking")return[];return[{type:"toolCall",id:h.id,name:h.name,arguments:MK(h.input)}]}),f=p.some((h)=>h.type==="toolCall");return{entry:u,raw:{role:"assistant",content:p,api:o.api,provider:o.provider,model:o.id,usage:a,stopReason:u.error?"error":f?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:m}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:m}};default:return{entry:u}}})}function vK(e,o){let a=(e.attachments??[]).flatMap((p)=>p.kind==="path"?[`<file path=${JSON.stringify(p.data)} />`]:p.kind==="text"?[`<file name=${JSON.stringify(p.name)}>
294
+ `),a=e.flatMap((u)=>u.type==="file"?CK(u):[]);if(!o.trim()&&a.length===0)return;return{type:"user",text:o,...a.length?{attachments:a}:{}}}function CK(e){let o=Dr(e.mime)||"application/octet-stream",a=Dr(e.filename)||"file",u=Dr(e.url),m=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(m){let p=m[3]??"";if(o.startsWith("image/"))return[{name:a,mimeType:o,kind:"image",data:m[2]?p:btoa(p)}];if(o.startsWith("text/")||o==="application/json"){let f=m[2]?new TextDecoder().decode(Uint8Array.from(atob(p),(h)=>h.charCodeAt(0))):p;return[{name:a,mimeType:o,kind:"text",data:f}]}return[]}if(u.startsWith("file://"))try{return[{name:a,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function $K(e){let o=[[]];for(let a of e){if(a.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(a.type==="reasoning"||a.type==="text"||a.type==="tool")o.at(-1)?.push(a)}return o.filter((a)=>a.length>0)}function vK(e,o,a){let u=`${Dr(e.providerID)}/${Dr(e.modelID)}`,m=bv(e.error),p=$K(o);p.forEach((f,h)=>{let I=f.flatMap((R)=>{if(R.type==="reasoning")return Dr(R.text).trim()?[{type:"thinking",text:Dr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Dr(R.text).trim()?[{type:"text",text:Dr(R.text)}]:[];return[{type:"tool_call",id:yv(R.callID),name:Dr(R.tool),input:xr(R.state)&&xr(R.state.input)?R.state.input:{}}]}),E=h===p.length-1,S=MK(f);a({type:"assistant",parts:I,model:u,...E&&m&&!m.aborted?{error:m.message}:{}},S);for(let R of f){if(R.type!=="tool")continue;let k=xr(R.state)?R.state:{},P=k.status==="error",v=k.status==="pending"||k.status==="running",_=P?[Dr(k.output),Dr(k.error)].filter(Boolean).join(`
295
+ `):v?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Dr(k.output);a({type:"tool_result",callID:yv(R.callID),name:Dr(R.tool),output:_,isError:P||v},Xs(xr(k.time)?k.time.end:void 0))}})}function yv(e){return Dr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function bv(e){if(!xr(e))return;let o=xr(e.data)?e.data:{};return{message:Dr(o.message)||Dr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function MK(e){for(let o of e){let a=xr(o.time)?Xs(o.time.start):xr(o.state)?OK(o.state):void 0;if(a!==void 0)return a}return}function OK(e){return xr(e.time)?Xs(e.time.start):void 0}function Ev(e){if(!xr(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 Sv(e,o){let a={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let m=u.time;switch(u.type){case"user":return{entry:u,raw:_K(u,m)};case"assistant":{let p=u.parts.flatMap((h)=>{if(h.type==="text")return[{type:"text",text:h.text}];if(h.type==="thinking")return[];return[{type:"toolCall",id:h.id,name:h.name,arguments:LK(h.input)}]}),f=p.some((h)=>h.type==="toolCall");return{entry:u,raw:{role:"assistant",content:p,api:o.api,provider:o.provider,model:o.id,usage:a,stopReason:u.error?"error":f?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:m}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:m}};default:return{entry:u}}})}function _K(e,o){let a=(e.attachments??[]).flatMap((p)=>p.kind==="path"?[`<file path=${JSON.stringify(p.data)} />`]:p.kind==="text"?[`<file name=${JSON.stringify(p.name)}>
296
296
  ${p.data}
297
297
  </file>`]:[]),u=(e.attachments??[]).filter((p)=>p.kind==="image").map((p)=>({type:"image",data:p.data,mimeType:p.mimeType})),m=[...a,...e.text.trim()?[e.text]:[]].join(`
298
298
 
299
- `);return{role:"user",content:u.length?[{type:"text",text:m},...u]:m,timestamp:o}}function xr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Dr(e){return typeof e==="string"?e:""}function Xs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function MK(e){return xr(e)?e:{}}function pr(e,o){let a=e.at(-1)?.entry.seq??0,u,m,p;for(let{entry:E}of e){if(E.type==="run"&&E.state==="start")u=E.seq;if(E.seq===o)if(E.type==="user"&&!E.notices)a=(u??E.seq)-1;else m=u;if(E.type==="run"&&E.state==="end"){if(m!==void 0&&u===m)p=E.seq;u=void 0}}let f=e.find((E)=>E.entry.seq===o)?.entry;if(o!==void 0&&!f)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(f&&!(f.type==="user"&&!f.notices)){if(m!==void 0&&p===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");a=p??f.seq}else if(o===void 0&&u!==void 0)a=e.findLast(({entry:E})=>E.type==="run"&&E.state==="end")?.entry.seq??0;let h=e.filter(({entry:E})=>E.seq<=a&&(E.type!=="compaction"||E.through<=a)),I=new Map(h.map(({entry:E},S)=>[E.seq,S+1]));return h.map((E,S)=>{let R=structuredClone(E);if(R.entry.seq=S+1,R.entry.type==="compaction"){let k=R.entry.through,P=h.findLast(({entry:v})=>v.seq<=k);R.entry.through=P?I.get(P.entry.seq)??0:0}return R})}function dr(e){let o=new Map,a=[];for(let u of e){if(u.type==="assistant"){for(let f of u.parts)if(f.type==="tool_call"&&f.name==="todo")o.set(f.id,f.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let m=o.get(u.callID);if(!m||typeof m!=="object"||!("todos"in m)||!Array.isArray(m.todos))continue;let p=[];for(let f of m.todos){if(!f||typeof f!=="object"||!("content"in f)||typeof f.content!=="string"||!("status"in f)||f.status!=="pending"&&f.status!=="in_progress"&&f.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");p.push({content:f.content,status:f.status})}a=p}return a}import{Buffer as Sv}from"buffer";import{createHash as OK}from"crypto";import{isDeepStrictEqual as Gl}from"util";var Kl="@blob:";function bu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function bv(e,o,a){if(typeof e!=="string"||e.length<256||e.startsWith(Kl))return;let u=Sv.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let m=OK("sha256").update(u).digest("hex");return a.put(m,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Kl}${m}`}function Ev(e,o){if(typeof e!=="string"||!e.startsWith(Kl))return;let a=o.get(e.slice(Kl.length));if(a===void 0)return;return Sv.from(a.buffer,a.byteOffset,a.byteLength).toString("base64")}function Hl(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=bv(m.data,m.mimeType,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((m)=>{let p=bv(m.data,m.mimeType,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,images:u}}return e}function Ys(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=Ev(m.data,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((m)=>{let p=Ev(m.data,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,images:u}}return e}function Yc(e,o){if(!bu(o))return o;if(e.type==="user"){let{merged:a,images:u}=Gc(e.text,e.attachments),m=u.length>0?[{type:"text",text:a},...u]:a,p=Object.keys(o),{role:f,timestamp:h,content:I}=o;if(p.length===3&&f==="user"&&typeof h==="number"&&"content"in o&&Gl(I,m))return{role:"user",timestamp:h};return o}if(e.type==="tool_result"){let{role:a,toolCallId:u,toolName:m,isError:p,timestamp:f,content:h}=o;if(a!=="toolResult"||u!==e.callID||typeof m!=="string"||p!==e.isError||typeof f!=="number")return o;let I=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!Gl(o.details,e.meta):e.meta!==void 0)return o;let{role:S,toolCallId:R,toolName:k,content:P,details:v,isError:_,timestamp:Q,...L}=o;if(Gl(h,I))return{role:"toolResult",...m!==e.name?{toolName:m}:{},...L,timestamp:f};if(Array.isArray(h)){let V=e.images??[],J=0,Z=!0,ne=h.map((z)=>{if(bu(z)&&z.type==="image"){let oe=V[J++],fe=Object.keys(z);if(oe&&fe.length===3&&z.mimeType===oe.mimeType&&z.data===oe.data)return{type:"image",mimeType:z.mimeType};Z=!1}return z});if(Z&&J===V.length)return{role:"toolResult",...m!==e.name?{toolName:m}:{},content:ne,...L,timestamp:f}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let m=!1,p=u.map((f,h)=>{let I=e.parts[h];if(bu(f)){if(f.type==="text"&&I?.type==="text"&&f.text===I.text){m=!0;let E={...f};return delete E.text,E}if(f.type==="thinking"&&I?.type==="thinking"&&f.thinking===I.text){m=!0;let E={...f};return delete E.thinking,E}if(f.type==="toolCall"&&I?.type==="tool_call"&&f.id===I.id&&f.name===I.name&&"arguments"in f&&Gl(f.arguments,I.input)){m=!0;let E={...f};return delete E.id,delete E.name,delete E.arguments,E}}return f});if(!m)return o;return{...o,content:p}}return o}function Pg(e,o){if(!bu(o))return o;if(e.type==="user"){let{role:a,timestamp:u}=o;if(a==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:m,images:p}=Gc(e.text,e.attachments);return{role:"user",content:p.length>0?[{type:"text",text:m},...p]:m,timestamp:u}}return o}if(e.type==="tool_result"){let{role:a,timestamp:u}=o;if(a==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:p,toolName:f,content:h,timestamp:I,...E}=o,S;if(Array.isArray(h)){let R=e.images??[],k=0;S=h.map((P)=>{if(bu(P)&&P.type==="image"&&!("data"in P)){let v=R[k++];if(v)return{type:"image",mimeType:P.mimeType,data:v.data}}return P})}else S=[{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 f==="string"?f:e.name,content:S,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...E,timestamp:u}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u))return o;let m=!1,p=u.map((f,h)=>{let I=e.parts[h];if(bu(f)){if(f.type==="text"&&!("text"in f)&&I?.type==="text"){m=!0;let{type:E,...S}=f;return{type:E,text:I.text,...S}}if(f.type==="thinking"&&!("thinking"in f)&&I?.type==="thinking"){m=!0;let{type:E,...S}=f;return{type:E,thinking:I.text,...S}}if(f.type==="toolCall"&&!("arguments"in f)&&I?.type==="tool_call"){m=!0;let{type:E,...S}=f;return{type:E,id:I.id,name:I.name,arguments:structuredClone(I.input),...S}}}return f});if(!m)return o;return{...o,content:p}}return o}function wv(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),a=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(I,E,S){o.run(I,E,S)},get(I){return a.get(I)?.data}},m=e.query("SELECT session_id, seq, body, raw FROM entries").all(),p=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),f=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),h=0;return e.transaction(()=>{for(let I of m){let E;try{E=JSON.parse(I.body)}catch{continue}let S=Ys(E,u),R=Hl(S,u),k=R===E?I.body:JSON.stringify(R),P=I.raw;if(I.raw!==null)try{let v=JSON.parse(I.raw),_=Pg(S,v),Q=Yc(S,_);P=JSON.stringify(Q)}catch{P=I.raw}if(k!==I.body)p.run(k,P,I.session_id,I.seq),h++;else if(P!==I.raw)f.run(P,I.session_id,I.seq),h++}})(),h}import{Database as _K}from"bun:sqlite";import{chmodSync as Tv,existsSync as LK,mkdirSync as NK}from"fs";import{dirname as DK}from"path";var Cg=[`
299
+ `);return{role:"user",content:u.length?[{type:"text",text:m},...u]:m,timestamp:o}}function xr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Dr(e){return typeof e==="string"?e:""}function Xs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function LK(e){return xr(e)?e:{}}function pr(e,o){let a=e.at(-1)?.entry.seq??0,u,m,p;for(let{entry:E}of e){if(E.type==="run"&&E.state==="start")u=E.seq;if(E.seq===o)if(E.type==="user"&&!E.notices)a=(u??E.seq)-1;else m=u;if(E.type==="run"&&E.state==="end"){if(m!==void 0&&u===m)p=E.seq;u=void 0}}let f=e.find((E)=>E.entry.seq===o)?.entry;if(o!==void 0&&!f)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(f&&!(f.type==="user"&&!f.notices)){if(m!==void 0&&p===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");a=p??f.seq}else if(o===void 0&&u!==void 0)a=e.findLast(({entry:E})=>E.type==="run"&&E.state==="end")?.entry.seq??0;let h=e.filter(({entry:E})=>E.seq<=a&&(E.type!=="compaction"||E.through<=a)),I=new Map(h.map(({entry:E},S)=>[E.seq,S+1]));return h.map((E,S)=>{let R=structuredClone(E);if(R.entry.seq=S+1,R.entry.type==="compaction"){let k=R.entry.through,P=h.findLast(({entry:v})=>v.seq<=k);R.entry.through=P?I.get(P.entry.seq)??0:0}return R})}function dr(e){let o=new Map,a=[];for(let u of e){if(u.type==="assistant"){for(let f of u.parts)if(f.type==="tool_call"&&f.name==="todo")o.set(f.id,f.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let m=o.get(u.callID);if(!m||typeof m!=="object"||!("todos"in m)||!Array.isArray(m.todos))continue;let p=[];for(let f of m.todos){if(!f||typeof f!=="object"||!("content"in f)||typeof f.content!=="string"||!("status"in f)||f.status!=="pending"&&f.status!=="in_progress"&&f.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");p.push({content:f.content,status:f.status})}a=p}return a}import{Buffer as Rv}from"buffer";import{createHash as NK}from"crypto";import{isDeepStrictEqual as Gl}from"util";var Kl="@blob:";function bu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function wv(e,o,a){if(typeof e!=="string"||e.length<256||e.startsWith(Kl))return;let u=Rv.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let m=NK("sha256").update(u).digest("hex");return a.put(m,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Kl}${m}`}function Tv(e,o){if(typeof e!=="string"||!e.startsWith(Kl))return;let a=o.get(e.slice(Kl.length));if(a===void 0)return;return Rv.from(a.buffer,a.byteOffset,a.byteLength).toString("base64")}function Hl(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=wv(m.data,m.mimeType,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((m)=>{let p=wv(m.data,m.mimeType,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,images:u}}return e}function Ys(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=Tv(m.data,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((m)=>{let p=Tv(m.data,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,images:u}}return e}function Yc(e,o){if(!bu(o))return o;if(e.type==="user"){let{merged:a,images:u}=Gc(e.text,e.attachments),m=u.length>0?[{type:"text",text:a},...u]:a,p=Object.keys(o),{role:f,timestamp:h,content:I}=o;if(p.length===3&&f==="user"&&typeof h==="number"&&"content"in o&&Gl(I,m))return{role:"user",timestamp:h};return o}if(e.type==="tool_result"){let{role:a,toolCallId:u,toolName:m,isError:p,timestamp:f,content:h}=o;if(a!=="toolResult"||u!==e.callID||typeof m!=="string"||p!==e.isError||typeof f!=="number")return o;let I=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!Gl(o.details,e.meta):e.meta!==void 0)return o;let{role:S,toolCallId:R,toolName:k,content:P,details:v,isError:_,timestamp:Q,...L}=o;if(Gl(h,I))return{role:"toolResult",...m!==e.name?{toolName:m}:{},...L,timestamp:f};if(Array.isArray(h)){let V=e.images??[],J=0,Z=!0,ne=h.map((z)=>{if(bu(z)&&z.type==="image"){let oe=V[J++],fe=Object.keys(z);if(oe&&fe.length===3&&z.mimeType===oe.mimeType&&z.data===oe.data)return{type:"image",mimeType:z.mimeType};Z=!1}return z});if(Z&&J===V.length)return{role:"toolResult",...m!==e.name?{toolName:m}:{},content:ne,...L,timestamp:f}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let m=!1,p=u.map((f,h)=>{let I=e.parts[h];if(bu(f)){if(f.type==="text"&&I?.type==="text"&&f.text===I.text){m=!0;let E={...f};return delete E.text,E}if(f.type==="thinking"&&I?.type==="thinking"&&f.thinking===I.text){m=!0;let E={...f};return delete E.thinking,E}if(f.type==="toolCall"&&I?.type==="tool_call"&&f.id===I.id&&f.name===I.name&&"arguments"in f&&Gl(f.arguments,I.input)){m=!0;let E={...f};return delete E.id,delete E.name,delete E.arguments,E}}return f});if(!m)return o;return{...o,content:p}}return o}function Cg(e,o){if(!bu(o))return o;if(e.type==="user"){let{role:a,timestamp:u}=o;if(a==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:m,images:p}=Gc(e.text,e.attachments);return{role:"user",content:p.length>0?[{type:"text",text:m},...p]:m,timestamp:u}}return o}if(e.type==="tool_result"){let{role:a,timestamp:u}=o;if(a==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:p,toolName:f,content:h,timestamp:I,...E}=o,S;if(Array.isArray(h)){let R=e.images??[],k=0;S=h.map((P)=>{if(bu(P)&&P.type==="image"&&!("data"in P)){let v=R[k++];if(v)return{type:"image",mimeType:P.mimeType,data:v.data}}return P})}else S=[{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 f==="string"?f:e.name,content:S,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...E,timestamp:u}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u))return o;let m=!1,p=u.map((f,h)=>{let I=e.parts[h];if(bu(f)){if(f.type==="text"&&!("text"in f)&&I?.type==="text"){m=!0;let{type:E,...S}=f;return{type:E,text:I.text,...S}}if(f.type==="thinking"&&!("thinking"in f)&&I?.type==="thinking"){m=!0;let{type:E,...S}=f;return{type:E,thinking:I.text,...S}}if(f.type==="toolCall"&&!("arguments"in f)&&I?.type==="tool_call"){m=!0;let{type:E,...S}=f;return{type:E,id:I.id,name:I.name,arguments:structuredClone(I.input),...S}}}return f});if(!m)return o;return{...o,content:p}}return o}function kv(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),a=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(I,E,S){o.run(I,E,S)},get(I){return a.get(I)?.data}},m=e.query("SELECT session_id, seq, body, raw FROM entries").all(),p=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),f=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),h=0;return e.transaction(()=>{for(let I of m){let E;try{E=JSON.parse(I.body)}catch{continue}let S=Ys(E,u),R=Hl(S,u),k=R===E?I.body:JSON.stringify(R),P=I.raw;if(I.raw!==null)try{let v=JSON.parse(I.raw),_=Cg(S,v),Q=Yc(S,_);P=JSON.stringify(Q)}catch{P=I.raw}if(k!==I.body)p.run(k,P,I.session_id,I.seq),h++;else if(P!==I.raw)f.run(P,I.session_id,I.seq),h++}})(),h}import{Database as DK}from"bun:sqlite";import{chmodSync as Av,existsSync as qK,mkdirSync as FK}from"fs";import{dirname as jK}from"path";var $g=[`
300
300
  CREATE TABLE projects (
301
301
  id TEXT PRIMARY KEY,
302
302
  name TEXT NOT NULL,
@@ -373,8 +373,8 @@ ${p.data}
373
373
  mime TEXT NOT NULL,
374
374
  data BLOB NOT NULL
375
375
  ) WITHOUT ROWID;
376
- 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 qK=[20,50,100,200,400,800];function FK(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function $g(e){let o=0;while(!0)try{return e()}catch(a){let u=qK[o];if(u===void 0||!FK(a))throw a;o++,Bun.sleepSync(u)}}function Rv(e,o){if(e!==":memory:")NK(DK(e),{recursive:!0});let a=new _K(e,{create:!0,strict:!0}),u=(p,f=!0)=>new Proxy(function(...h){return Reflect.apply(p,this,h)},{apply(h,I,E){Ls();let S=o.length===0&&!a.inTransaction,R=f?Reflect.get(p,"immediate"):void 0,k=()=>{let P=[];o.push(P);let v=!1;try{let _=typeof R==="function"?Reflect.apply(R,p,E):Reflect.apply(h,I,E);return v=!0,_}finally{o.pop();let _=o.at(-1);if(v&&_)_.push(...P);else for(let Q of P)if(v)Q.commit();else Q.rollback()}};return S?$g(k):k()},get(h,I){let E=Reflect.get(p,I);if(["deferred","immediate","exclusive"].includes(String(I))&&typeof E==="function")return u(E,!1);return E}}),m=new Proxy(a,{get(p,f){let h=Reflect.get(p,f,p);if(typeof h!=="function")return h;return(...I)=>{Ls();let R=(f==="run"||f==="exec")&&o.length===0&&!a.inTransaction?$g(()=>Reflect.apply(h,p,I)):Reflect.apply(h,p,I);if(f==="transaction"&&typeof R==="function")return u(R,!0);if(f!=="query"&&f!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(k,P,v){let _=Reflect.get(k,P,k);if(typeof _!=="function")return _;return(...Q)=>{Ls();let J=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!a.inTransaction?$g(()=>Reflect.apply(_,k,Q)):Reflect.apply(_,k,Q);return J===k?v:J}}})}}});if(e!==":memory:")Tv(e,384);if(m.run("PRAGMA journal_mode = WAL"),m.run("PRAGMA synchronous = FULL"),m.run("PRAGMA foreign_keys = ON"),m.run("PRAGMA busy_timeout = 10000"),m.run("PRAGMA mmap_size = 268435456"),jK(m),m.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),m.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let p of["-wal","-shm"]){let f=e+p;if(LK(f))Tv(f,384)}return m}function jK(e,o=Cg){let{user_version:a}=e.query("PRAGMA user_version").get();if(a>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${a} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=a;u<o.length;u++)e.transaction(()=>{let m=o[u]??"",p=Array.isArray(m)?m:u>=4?UK(m):[m];for(let f of p)try{if(f.trim())e.run(f)}catch(h){if(!(h instanceof Error)||!/already exists|duplicate column name/i.test(h.message))throw h}e.run(`PRAGMA user_version = ${u+1}`)})()}function UK(e){let o=[],a=0,u=0,m=[],p=!1,f=0,h=(I)=>{let E=e.slice(a,I).trim();if(E)o.push(E);a=I+1,m=[],p=!1,f=0};while(u<e.length){let I=e[u];if(I==="'"||I==='"'||I==="`"||I==="["){let E=I==="["?"]":I;u++;while(u<e.length)if(e[u]===E)if(E!=="]"&&e[u+1]===E)u+=2;else break;else u++;u++;continue}if(I==="-"&&e[u+1]==="-"){let E=e.indexOf(`
377
- `,u);u=E===-1?e.length:E+1;continue}if(I==="/"&&e[u+1]==="*"){let E=e.indexOf("*/",u+2);u=E===-1?e.length:E+2;continue}if(/[A-Za-z_]/.test(I)){let E=u+1;while(E<e.length&&/[A-Za-z0-9_$]/.test(e[E]))E++;let S=e.slice(u,E).toUpperCase();if(m.length<3)m.push(S),p=m[0]==="CREATE"&&(m[1]==="TRIGGER"||m[2]==="TRIGGER");if(p){if(S==="BEGIN"||S==="CASE"&&f>0)f++;else if(S==="END"&&f>0)f--}u=E;continue}if(I===";"&&f===0)h(u);u++}return h(e.length),o}var Wl=({position:e,closed_at:o,...a})=>({...a,closedAt:o??null}),zl=(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 Vl=new Set(["user","run","extension","notice_pending","compaction"]);class Jl{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=Rv(e,this.entryTransactions),this.blobs={put:(o,a,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,a,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Wl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Wl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Wl(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[a,u]of e.entries())o.run(a,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){let o=this.sessionIDs(e);for(let a of o)this.invalidateEntryCache(a);this.db.transaction(()=>{let a=new Set;for(let u of o)for(let m of this.collectSessionBlobHashes(u))a.add(m);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(a)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(zl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(zl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(zl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,a){this.insertSessionWithRecords(o,pr(this.records(e),a))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let a=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:m}of o){let{seq:p,time:f,...h}=u,I=h,E=Hl(I,this.blobs),S=m===void 0?null:JSON.stringify(Yc(I,m));a.run(e.id,p,f,JSON.stringify(E),S)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{let a=this.collectSessionBlobHashes(e.id,o);this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e),this.pruneCandidateBlobs(a)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let a=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)a.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.transaction(()=>{let o=new Set,a=[e];while(a.length>0){let u=a.pop();if(!u)continue;for(let m of this.collectSessionBlobHashes(u))o.add(m);for(let m of this.childSessions(u))a.push(m.id)}this.db.query("DELETE FROM sessions WHERE id = ?").run(e),this.pruneCandidateBlobs(o)})()}collectSessionBlobHashes(e,o=1){let a=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq >= ? AND body LIKE '%@blob:%'").all(e,o),u=new Set;for(let m of a)for(let p of m.body.matchAll(/@blob:([0-9a-f]{64})/g))if(p[1])u.add(p[1]);return u}pruneCandidateBlobs(e){if(e.size===0)return;let o=this.db.query("SELECT 1 AS one FROM entries WHERE body LIKE ? LIMIT 1"),a=this.db.query("DELETE FROM blobs WHERE hash = ?");for(let u of e)if(!o.get(`%@blob:${u}%`))a.run(u)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,a,u){Ls();let m=this.plugins,p=m?.pinEntry(a),f;try{return f=this.db.transaction(()=>{let h=Math.max(o??0,this.lastSeq(e)+1),E=(p&&m?m.beforeEntry(p,a,e,h):void 0)??a,S=JSON.stringify(E),R=p?JSON.parse(S):E,k={...R,seq:h,time:Date.now()},P=Hl(R,this.blobs),v=P===R&&!p?S:JSON.stringify(P),_=u===void 0?null:JSON.stringify(Yc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,h,k.time,v,_),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return this.cacheAppended(e,k,v),k})(),f}finally{if(p&&m){let h={commit:()=>m.finishEntry(p,e,f),rollback:()=>m.finishEntry(p,e)},I=this.entryTransactions.at(-1);if(I)I.push(h);else h.commit()}}}setEntryRaw(e,o,a){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let m=Ys(JSON.parse(u.body),this.blobs),p=Yc(m,a);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(p),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,a,u=!0){if(a&&a.length===0)return[];let m=a?.every((f)=>Vl.has(f))?this.cachedEntries(e):void 0;if(m&&a)return m.filter((h)=>h.seq>o&&a.includes(h.type)).map((h)=>({...u?Ys(h,this.blobs):h}));return(a?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...a):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((f)=>({...Ys(JSON.parse(f.body),u?this.blobs:void 0),seq:f.seq,time:f.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let a=[...Vl],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...a).map((m)=>({...JSON.parse(m.body),seq:m.seq,time:m.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,a){let u=this.smallEntries.get(e);if(!u||!Vl.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(a),seq:o.seq,time:o.time})}entriesRange(e,o,a=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,a).map((u)=>({...Ys(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let a=this.lastSeq(e),u=(I)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,I),m=u(o),p=m?.type==="run"&&m.state==="start"?o+1:o;if(p>=a)return a;let f=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,p,p);if(!f)return a;if(f.end)return f.seq;let h=u(f.seq-1);return h?.type==="run"&&h.state==="start"&&f.seq-1>p?f.seq-2:f.seq-1}entriesAround(e,o,a,u){let m=this.lastSeq(e);if(m===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let p=Math.min(Math.max(1,o),m),f=this.alignToUser(e,Math.max(1,p-a)),h=this.alignToTurnEnd(e,Math.min(m,p+u));return this.window(e,f,h,m)}entriesFrom(e,o,a){let u=this.lastSeq(e),m=Math.max(1,o);if(m>u)return{entries:[],from:m,to:u,hasBefore:u>0,hasAfter:!1};let p=this.alignToTurnEnd(e,Math.min(u,m+a-1));return this.window(e,m,p,u)}window(e,o,a,u){let m=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,a+1),from:o,to:a,hasBefore:m!==null,hasAfter:a<u}}replayStart(e,o,a,u=Number.POSITIVE_INFINITY){let m=this.lastSeq(e),p=this.lastEntry(e,"compaction"),f=p?.type==="compaction"?p.through+1:1,h=Math.max(1,m-o+1),I=Math.max(1,m-a+1,Math.min(f,h));return this.alignToUser(e,I<h?Math.min(h,this.budgetStart(e,I,u)):I)}budgetStart(e,o,a){let u=this.db.query("SELECT seq, length(body) AS size FROM entries WHERE session_id = ? AND seq >= ? ORDER BY seq DESC").all(e,o),m=0;for(let p of u)if(m+=p.size,m>a)return p.seq+1;return o}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((a)=>{let u=Ys(JSON.parse(a.body),this.blobs);return{entry:{...u,seq:a.seq,time:a.time},...a.raw===null?{}:{raw:Pg(u,JSON.parse(a.raw))}}})}lastEntry(e,o){if(Vl.has(o)){let u=this.cachedEntries(e);if(u){let m=u.findLast((p)=>p.type===o);return m?{...Ys(m,this.blobs)}:void 0}}let a=this.db.query("SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return a?{...Ys(JSON.parse(a.body),this.blobs),seq:a.seq,time:a.time}:void 0}async enqueueNotice(e,o){let a=this.truncationEpoch(e),u=o;if(this.plugins){let m=this.plugins.pin();try{let p=await m.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(p===null)return!1;o={...p,dedupeKey:u.dedupeKey,wake:u.wake&&p.wake,recovery:u.recovery}}finally{await m.release()}}return this.db.transaction(()=>{let m=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!m||m.truncation_epoch!==a)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((h)=>h.type==="notice_pending"&&h.notice.dedupeKey===o.dedupeKey||h.type==="user"&&h.notices?.some((I)=>I.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,a=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let p of a)if(p.type==="user"&&p.notices)for(let f of p.notices)u.add(f.dedupeKey);else if(p.type==="extension"&&p.namespace==="basalt.notice"&&p.kind==="discarded"&&p.payload&&typeof p.payload==="object"&&"dedupeKey"in p.payload&&typeof p.payload.dedupeKey==="string")u.add(p.payload.dedupeKey);let m=[];for(let p of a)if(p.type==="notice_pending"&&!u.has(p.notice.dedupeKey))m.push(p.notice);return m}}function re(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as BK,readdirSync as Pv,statSync as Cv}from"fs";import{join as $v}from"path";function Zc(e){try{return Cv(e).size}catch{return 0}}function vv(e){try{return Math.round(Cv(e).mtimeMs)}catch{return}}function Mv(e){let o=0,a=0;try{let u=Pv(e,{withFileTypes:!0});for(let m of u){let p=$v(e,m.name);if(m.isDirectory()){let f=Mv(p);o+=f.bytes,a+=f.files}else if(m.isFile())o+=Zc(p),a+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:a}}function GK(e){if(!BK(e))return[];try{return Pv(e,{withFileTypes:!0}).flatMap((o)=>{let a=$v(KK(e),o.name),u=vv(a);if(o.isDirectory()){let m=Mv(a);return[{name:o.name,kind:"directory",bytes:m.bytes,files:m.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Zc(a),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,a)=>a.bytes-o.bytes||o.name.localeCompare(a.name))}catch{return[]}}function KK(e){return e}function Zs(e,o){let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return 0;let u=Object.values(a)[0];return typeof u==="number"?u:0}function kv(e,o){try{let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return;let u=Object.values(a)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var HK={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},WK={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function zK(e){let o=new Map;try{let a=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let p of u)a.set(p.name,p.tbl_name);let m=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let p of m){let f=a.get(p.name)??p.name;if(f.startsWith("sqlite_autoindex_")){let I=f.slice(17),E=I.lastIndexOf("_");if(E>0)f=I.slice(0,E)}let h=o.get(f)??{bytes:0,pages:0};o.set(f,{bytes:h.bytes+(Number(p.bytes)||0),pages:h.pages+(Number(p.pages)||0)})}}catch{}return o}function VK(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,a=e.db.query(`SELECT
376
+ 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 UK=[20,50,100,200,400,800];function BK(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function vg(e){let o=0;while(!0)try{return e()}catch(a){let u=UK[o];if(u===void 0||!BK(a))throw a;o++,Bun.sleepSync(u)}}function Pv(e,o){if(e!==":memory:")FK(jK(e),{recursive:!0});let a=new DK(e,{create:!0,strict:!0}),u=(p,f=!0)=>new Proxy(function(...h){return Reflect.apply(p,this,h)},{apply(h,I,E){Ls();let S=o.length===0&&!a.inTransaction,R=f?Reflect.get(p,"immediate"):void 0,k=()=>{let P=[];o.push(P);let v=!1;try{let _=typeof R==="function"?Reflect.apply(R,p,E):Reflect.apply(h,I,E);return v=!0,_}finally{o.pop();let _=o.at(-1);if(v&&_)_.push(...P);else for(let Q of P)if(v)Q.commit();else Q.rollback()}};return S?vg(k):k()},get(h,I){let E=Reflect.get(p,I);if(["deferred","immediate","exclusive"].includes(String(I))&&typeof E==="function")return u(E,!1);return E}}),m=new Proxy(a,{get(p,f){let h=Reflect.get(p,f,p);if(typeof h!=="function")return h;return(...I)=>{Ls();let R=(f==="run"||f==="exec")&&o.length===0&&!a.inTransaction?vg(()=>Reflect.apply(h,p,I)):Reflect.apply(h,p,I);if(f==="transaction"&&typeof R==="function")return u(R,!0);if(f!=="query"&&f!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(k,P,v){let _=Reflect.get(k,P,k);if(typeof _!=="function")return _;return(...Q)=>{Ls();let J=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!a.inTransaction?vg(()=>Reflect.apply(_,k,Q)):Reflect.apply(_,k,Q);return J===k?v:J}}})}}});if(e!==":memory:")Av(e,384);if(m.run("PRAGMA journal_mode = WAL"),m.run("PRAGMA synchronous = FULL"),m.run("PRAGMA foreign_keys = ON"),m.run("PRAGMA busy_timeout = 10000"),m.run("PRAGMA mmap_size = 268435456"),GK(m),m.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),m.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let p of["-wal","-shm"]){let f=e+p;if(qK(f))Av(f,384)}return m}function GK(e,o=$g){let{user_version:a}=e.query("PRAGMA user_version").get();if(a>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${a} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=a;u<o.length;u++)e.transaction(()=>{let m=o[u]??"",p=Array.isArray(m)?m:u>=4?KK(m):[m];for(let f of p)try{if(f.trim())e.run(f)}catch(h){if(!(h instanceof Error)||!/already exists|duplicate column name/i.test(h.message))throw h}e.run(`PRAGMA user_version = ${u+1}`)})()}function KK(e){let o=[],a=0,u=0,m=[],p=!1,f=0,h=(I)=>{let E=e.slice(a,I).trim();if(E)o.push(E);a=I+1,m=[],p=!1,f=0};while(u<e.length){let I=e[u];if(I==="'"||I==='"'||I==="`"||I==="["){let E=I==="["?"]":I;u++;while(u<e.length)if(e[u]===E)if(E!=="]"&&e[u+1]===E)u+=2;else break;else u++;u++;continue}if(I==="-"&&e[u+1]==="-"){let E=e.indexOf(`
377
+ `,u);u=E===-1?e.length:E+1;continue}if(I==="/"&&e[u+1]==="*"){let E=e.indexOf("*/",u+2);u=E===-1?e.length:E+2;continue}if(/[A-Za-z_]/.test(I)){let E=u+1;while(E<e.length&&/[A-Za-z0-9_$]/.test(e[E]))E++;let S=e.slice(u,E).toUpperCase();if(m.length<3)m.push(S),p=m[0]==="CREATE"&&(m[1]==="TRIGGER"||m[2]==="TRIGGER");if(p){if(S==="BEGIN"||S==="CASE"&&f>0)f++;else if(S==="END"&&f>0)f--}u=E;continue}if(I===";"&&f===0)h(u);u++}return h(e.length),o}var Wl=({position:e,closed_at:o,...a})=>({...a,closedAt:o??null}),zl=(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 Vl=new Set(["user","run","extension","notice_pending","compaction"]);class Jl{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=Pv(e,this.entryTransactions),this.blobs={put:(o,a,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,a,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Wl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Wl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Wl(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[a,u]of e.entries())o.run(a,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){let o=this.sessionIDs(e);for(let a of o)this.invalidateEntryCache(a);this.db.transaction(()=>{let a=new Set;for(let u of o)for(let m of this.collectSessionBlobHashes(u))a.add(m);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(a)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(zl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(zl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(zl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,a){this.insertSessionWithRecords(o,pr(this.records(e),a))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let a=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:m}of o){let{seq:p,time:f,...h}=u,I=h,E=Hl(I,this.blobs),S=m===void 0?null:JSON.stringify(Yc(I,m));a.run(e.id,p,f,JSON.stringify(E),S)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{let a=this.collectSessionBlobHashes(e.id,o);this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e),this.pruneCandidateBlobs(a)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let a=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)a.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.transaction(()=>{let o=new Set,a=[e];while(a.length>0){let u=a.pop();if(!u)continue;for(let m of this.collectSessionBlobHashes(u))o.add(m);for(let m of this.childSessions(u))a.push(m.id)}this.db.query("DELETE FROM sessions WHERE id = ?").run(e),this.pruneCandidateBlobs(o)})()}collectSessionBlobHashes(e,o=1){let a=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq >= ? AND body LIKE '%@blob:%'").all(e,o),u=new Set;for(let m of a)for(let p of m.body.matchAll(/@blob:([0-9a-f]{64})/g))if(p[1])u.add(p[1]);return u}pruneCandidateBlobs(e){if(e.size===0)return;let o=this.db.query("SELECT 1 AS one FROM entries WHERE body LIKE ? LIMIT 1"),a=this.db.query("DELETE FROM blobs WHERE hash = ?");for(let u of e)if(!o.get(`%@blob:${u}%`))a.run(u)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,a,u){Ls();let m=this.plugins,p=m?.pinEntry(a),f;try{return f=this.db.transaction(()=>{let h=Math.max(o??0,this.lastSeq(e)+1),E=(p&&m?m.beforeEntry(p,a,e,h):void 0)??a,S=JSON.stringify(E),R=p?JSON.parse(S):E,k={...R,seq:h,time:Date.now()},P=Hl(R,this.blobs),v=P===R&&!p?S:JSON.stringify(P),_=u===void 0?null:JSON.stringify(Yc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,h,k.time,v,_),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return this.cacheAppended(e,k,v),k})(),f}finally{if(p&&m){let h={commit:()=>m.finishEntry(p,e,f),rollback:()=>m.finishEntry(p,e)},I=this.entryTransactions.at(-1);if(I)I.push(h);else h.commit()}}}setEntryRaw(e,o,a){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let m=Ys(JSON.parse(u.body),this.blobs),p=Yc(m,a);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(p),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,a,u=!0){if(a&&a.length===0)return[];let m=a?.every((f)=>Vl.has(f))?this.cachedEntries(e):void 0;if(m&&a)return m.filter((h)=>h.seq>o&&a.includes(h.type)).map((h)=>({...u?Ys(h,this.blobs):h}));return(a?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...a):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((f)=>({...Ys(JSON.parse(f.body),u?this.blobs:void 0),seq:f.seq,time:f.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let a=[...Vl],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...a).map((m)=>({...JSON.parse(m.body),seq:m.seq,time:m.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,a){let u=this.smallEntries.get(e);if(!u||!Vl.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(a),seq:o.seq,time:o.time})}entriesRange(e,o,a=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,a).map((u)=>({...Ys(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let a=this.lastSeq(e),u=(I)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,I),m=u(o),p=m?.type==="run"&&m.state==="start"?o+1:o;if(p>=a)return a;let f=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,p,p);if(!f)return a;if(f.end)return f.seq;let h=u(f.seq-1);return h?.type==="run"&&h.state==="start"&&f.seq-1>p?f.seq-2:f.seq-1}entriesAround(e,o,a,u){let m=this.lastSeq(e);if(m===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let p=Math.min(Math.max(1,o),m),f=this.alignToUser(e,Math.max(1,p-a)),h=this.alignToTurnEnd(e,Math.min(m,p+u));return this.window(e,f,h,m)}entriesFrom(e,o,a){let u=this.lastSeq(e),m=Math.max(1,o);if(m>u)return{entries:[],from:m,to:u,hasBefore:u>0,hasAfter:!1};let p=this.alignToTurnEnd(e,Math.min(u,m+a-1));return this.window(e,m,p,u)}window(e,o,a,u){let m=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,a+1),from:o,to:a,hasBefore:m!==null,hasAfter:a<u}}replayStart(e,o,a,u=Number.POSITIVE_INFINITY){let m=this.lastSeq(e),p=this.lastEntry(e,"compaction"),f=p?.type==="compaction"?p.through+1:1,h=Math.max(1,m-o+1),I=Math.max(1,m-a+1,Math.min(f,h));return this.alignToUser(e,I<h?Math.min(h,this.budgetStart(e,I,u)):I)}budgetStart(e,o,a){let u=this.db.query("SELECT seq, length(body) AS size FROM entries WHERE session_id = ? AND seq >= ? ORDER BY seq DESC").all(e,o),m=0;for(let p of u)if(m+=p.size,m>a)return p.seq+1;return o}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((a)=>{let u=Ys(JSON.parse(a.body),this.blobs);return{entry:{...u,seq:a.seq,time:a.time},...a.raw===null?{}:{raw:Cg(u,JSON.parse(a.raw))}}})}lastEntry(e,o){if(Vl.has(o)){let u=this.cachedEntries(e);if(u){let m=u.findLast((p)=>p.type===o);return m?{...Ys(m,this.blobs)}:void 0}}let a=this.db.query("SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return a?{...Ys(JSON.parse(a.body),this.blobs),seq:a.seq,time:a.time}:void 0}async enqueueNotice(e,o){let a=this.truncationEpoch(e),u=o;if(this.plugins){let m=this.plugins.pin();try{let p=await m.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(p===null)return!1;o={...p,dedupeKey:u.dedupeKey,wake:u.wake&&p.wake,recovery:u.recovery}}finally{await m.release()}}return this.db.transaction(()=>{let m=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!m||m.truncation_epoch!==a)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((h)=>h.type==="notice_pending"&&h.notice.dedupeKey===o.dedupeKey||h.type==="user"&&h.notices?.some((I)=>I.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,a=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let p of a)if(p.type==="user"&&p.notices)for(let f of p.notices)u.add(f.dedupeKey);else if(p.type==="extension"&&p.namespace==="basalt.notice"&&p.kind==="discarded"&&p.payload&&typeof p.payload==="object"&&"dedupeKey"in p.payload&&typeof p.payload.dedupeKey==="string")u.add(p.payload.dedupeKey);let m=[];for(let p of a)if(p.type==="notice_pending"&&!u.has(p.notice.dedupeKey))m.push(p.notice);return m}}function re(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as HK,readdirSync as vv,statSync as Mv}from"fs";import{join as Ov}from"path";function Zc(e){try{return Mv(e).size}catch{return 0}}function _v(e){try{return Math.round(Mv(e).mtimeMs)}catch{return}}function Lv(e){let o=0,a=0;try{let u=vv(e,{withFileTypes:!0});for(let m of u){let p=Ov(e,m.name);if(m.isDirectory()){let f=Lv(p);o+=f.bytes,a+=f.files}else if(m.isFile())o+=Zc(p),a+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:a}}function WK(e){if(!HK(e))return[];try{return vv(e,{withFileTypes:!0}).flatMap((o)=>{let a=Ov(zK(e),o.name),u=_v(a);if(o.isDirectory()){let m=Lv(a);return[{name:o.name,kind:"directory",bytes:m.bytes,files:m.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Zc(a),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,a)=>a.bytes-o.bytes||o.name.localeCompare(a.name))}catch{return[]}}function zK(e){return e}function Zs(e,o){let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return 0;let u=Object.values(a)[0];return typeof u==="number"?u:0}function Cv(e,o){try{let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return;let u=Object.values(a)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var VK={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},JK={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function QK(e){let o=new Map;try{let a=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let p of u)a.set(p.name,p.tbl_name);let m=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let p of m){let f=a.get(p.name)??p.name;if(f.startsWith("sqlite_autoindex_")){let I=f.slice(17),E=I.lastIndexOf("_");if(E>0)f=I.slice(0,E)}let h=o.get(f)??{bytes:0,pages:0};o.set(f,{bytes:h.bytes+(Number(p.bytes)||0),pages:h.pages+(Number(p.pages)||0)})}}catch{}return o}function XK(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,a=e.db.query(`SELECT
378
378
  count(*) AS total,
379
379
  sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
380
380
  sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
@@ -399,15 +399,15 @@ ${p.data}
399
399
  coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
400
400
  FROM plugin_kv
401
401
  GROUP BY namespace
402
- ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let k of S){R.add(k.namespace);let P=I.get(k.namespace);h.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[k,P]of I.entries())if(!R.has(k))h.push({namespace:k,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:o,mainSessionCount:Number(a?.main_count)||0,subSessionCount:Number(a?.sub_count)||0,forkedSessionCount:Number(a?.forked_count)||0,automationSessionCount:Number(a?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:f,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:p,pluginNamespaces:h}}function Ql(e,o){let a=Zs(e,"page_size"),u=Zs(e,"page_count"),m=Zs(e,"freelist_count"),p=e.db.query("PRAGMA journal_mode").get(),f=e.db.query("SELECT sqlite_version() AS v").get(),h=Zs(e,"synchronous"),I=Zs(e,"auto_vacuum"),E=Zs(e,"cache_size"),S=E<0?Math.abs(E)*1024:E*a,R=Zs(e,"foreign_keys")===1,k=Zs(e,"busy_timeout"),P=kv(e,"encoding")??"UTF-8",v=kv(e,"quick_check(1)")??"ok",_=e.path!==":memory:"?vv(e.path):void 0,Q=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),L=zK(e),V=GK(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((J,Z)=>J+Z.bytes,0),database:{size:Zc(e.path),walSize:Zc(`${e.path}-wal`),shmSize:Zc(`${e.path}-shm`),sqliteVersion:f?.v??"unknown",journalMode:p?.journal_mode??"unknown",synchronous:HK[h]??String(h),foreignKeys:R,busyTimeout:k,encoding:P,autoVacuum:WK[I]??String(I),cacheSizeBytes:S,pageSize:a,pageCount:u,freelistCount:m,reclaimableBytes:m*a,schemaVersion:Zs(e,"user_version"),..._!==void 0?{lastModified:_}:{},integrity:v},analytics:VK(e),entries:V,tables:Q.map(({name:J,sql:Z})=>{let ne=J.replaceAll('"','""'),z=e.db.query(`SELECT count(*) AS count FROM "${ne}"`).get().count,oe=e.db.query(`PRAGMA table_info("${ne}")`).all().map((ee)=>ee.name),fe=e.db.query(`PRAGMA index_list("${ne}")`).all().length,ke=Boolean(Z&&/WITHOUT\s+ROWID/i.test(Z)),Ee=L.get(J);return{name:J,rows:z,...Ee?{bytes:Ee.bytes,pages:Ee.pages}:{},indexes:fe,columns:oe,withoutRowid:ke}})}}function Av(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let a=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let p of a)for(let f of p.body.matchAll(/@blob:([0-9a-f]{64})/g)){let h=f[1];if(h)u.add(h)}let m=[];for(let p of o)if(!u.has(p.hash))m.push(p.hash);if(m.length===0)return 0;try{e.db.transaction(()=>{let p=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let f of m)p.run(f)})()}catch{return 0}return m.length}function Ov(e,o,a){let u=Ql(e,o);if(a.vacuum)wv(e.db),e.invalidateEntryCache(),Av(e),e.db.run("VACUUM");else if(a.checkpoint)Av(e);if(a.checkpoint||a.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Ql(e,o)}}var JK=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Xl{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(JK.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function _v(e,o){let a=sn(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:a.length>0?a:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function Lv(e,o){let a=e.options.visibleModelProviders?.(),m=(await e.options.models.getAvailable().catch(()=>[])).filter((f)=>!a||a.includes(f.provider)).map((f)=>({..._v(ot(f),f),available:!0})),p=new Set(m.map((f)=>f.id));for(let f of[o,...e.list(!0,{archive:"all"}).map((h)=>h.model)]){if(p.has(f))continue;let h=Tn(e.options.models,f);if(!h||a&&!a.includes(h.provider))continue;p.add(f),m.push({..._v(f,h),available:!1})}return{models:m}}function Nv(e,o){if(typeof o!=="string"||!Tn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as QK,statSync as XK}from"fs";import{basename as YK,resolve as ZK}from"path";class vg{runtime;sessions;emit;arm;constructor(e,o,a,u){this.runtime=e;this.sessions=o;this.emit=a;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new y("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=ZK(e.directory.trim());if(!QK(o)||!XK(o).isDirectory())throw new t(`${o} is not a directory on the server`);let a=this.runtime.store.projectByDirectory(o);if(a){if(a.closedAt!==null)return this.updateProject(a.id,{closed:!1});return a}let u=Date.now(),m={id:re("p"),name:e.name?.trim()||YK(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(m),this.emit({type:"project",project:m}),m}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let m of this.sessions.values())if(m.projectID===e)m.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((m)=>typeof m==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((m)=>m.id)),a=new Set(e);if(!(a.size===e.length&&a.size===o.size&&e.every((m)=>o.has(m))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),a=[...this.sessions.values()].filter((m)=>m.projectID===e);if(a.some((m)=>m.status==="busy"))throw new ce("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let m of a)m.close(),this.runtime.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as bH,readFileSync as EH}from"fs";import{homedir as SH}from"os";import{join as Eu}from"path";var Gv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),eH={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"]},tH=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),_g={'"':['"'],"\u201C":["\u201D",'"']},Mg=(e)=>e!==void 0&&/\s/.test(e),Kv=(e)=>[...new Set(e)],em=(e)=>[...e].length;var rH={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function nH(e,o){let a=e.trim().toLowerCase(),u=new Date(o),m=u.getFullYear(),p=u.getMonth(),f=u.getDate();if(a==="today")return{start:new Date(m,p,f).getTime(),end:new Date(m,p,f+1).getTime()};if(a==="yesterday")return{start:new Date(m,p,f-1).getTime(),end:new Date(m,p,f).getTime()};let h=/^(\d+)(h|d|w|mo|y)$/.exec(a);if(h)return{start:o-Number(h[1])*rH[h[2]]};if(/^\d{4}$/.test(a))return{start:new Date(Number(a),0,1).getTime(),end:new Date(Number(a)+1,0,1).getTime()};let I=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(a);if(!I)return null;let E=Number(I[1]),S=Number(I[3]);if(S<1||S>12)return null;if(I[4]===void 0){if(I[5]!==void 0)return null;return{start:new Date(E,S-1,1).getTime(),end:new Date(E,S,1).getTime()}}let R=Number(I[4]),k=Number(I[5]??0),P=Number(I[6]??0),v=Number(I[7]??0);if(k>23||P>59||v>59)return null;let _=new Date(E,S-1,R,k,P,v);if(_.getMonth()!==S-1||_.getDate()!==R)return null;if(I[5]!==void 0)return{start:_.getTime()};return{start:_.getTime(),end:new Date(E,S-1,R+1).getTime()}}var oH=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Lg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),Ng=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function Og(e,o,a,u,m,p){let f=a.trim(),h=(E,S)=>e.diagnostics.push({code:E,message:S,filter:o});if(!f)return h("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return h("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let I=m?[f]:f.split(",").map((E)=>E.trim()).filter(Boolean);switch(o){case"in":case"project":for(let E of I){let S=E.toLowerCase();if(o==="in"&&S==="this")e.currentSession=!0;else if(o==="in"&&S==="title")e.fields.push("title");else e.projectID.push(E)}return;case"session":for(let E of I)if(E.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(E);return;case"from":case"role":for(let E of I){let S=eH[E.toLowerCase()];if(S)e.fields.push(...S);else h("bad_filter_value",`${o}:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...I);return;case"model":e.model.push(...I);return;case"is":for(let E of I){let S=E.toLowerCase();if(S==="error")e.isError=!u;else if(S==="archived")e.archived=!u;else if(S==="compacted")e.compacted=!u;else h("bad_filter_value",`is:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let E=nH(f,p);if(!E)return h("bad_filter_value",`${o}:${f} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=Lg(e.after,E.start);else if(o==="before")e.before=Ng(e.before,E.start);else if(e.after=Lg(e.after,E.start),E.end!==void 0)e.before=Ng(e.before,E.end)}}}function sH(e,o){let a={},u=(v,_)=>{let Q=Kv([...v??[],..._]);return Q.length?Q:void 0},m=u(e?.projectID,o.projectID),p=u(e?.sessionID,o.sessionID),f=u(e?.fields,o.fields),h=u(e?.tools,o.tools),I=u(e?.model,o.model);if(m)a.projectID=m;if(p)a.sessionID=p;if(f)a.fields=f;if(h)a.tools=h;if(I)a.model=I;let E=o.isError??e?.isError,S=o.archived??e?.archived,R=o.compacted??e?.compacted;if(E!==void 0)a.isError=E;if(S!==void 0)a.archived=S;if(R!==void 0)a.compacted=R;let k=Lg(e?.after,o.after),P=Ng(e?.before,o.before);if(k!==void 0)a.after=k;if(P!==void 0)a.before=P;if(k!==void 0&&P!==void 0&&k>=P)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return a}function Dv(e,o){let a=_g[e[o]]??['"'],u="",m=o+1;while(m<e.length){let p=e[m],f=e[m+1];if(p==="\\"&&f!==void 0&&(f==="\\"||f==='"'||f==="\u201C"||f==="\u201D")){u+=f,m+=2;continue}if(a.includes(p))return{text:u,next:m+1,closed:!0};u+=p,m++}return{text:u,next:m,closed:!1}}function qv(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let a=e.slice(0,-1).map((m)=>m.esc||!/[A-Za-z]/.test(m.c)?"":m.c).join("");if(a.length!==e.length-1)return;let u=a.toLowerCase();return Gv.has(u)?u:void 0}function Fv(e,o,a){let u=e==="word"&&!a&&em(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:a,fuzzy:u}}function iH(e,o){let a=[],u=e.length,m=0;while(m<u){if(Mg(e[m])){m++;continue}let p=!1;if(e[m]==="-"){if(m+1>=u||Mg(e[m+1])){m++;continue}p=!0,m++}if(_g[e[m]]){let P=Dv(e,m);if(m=P.next,!P.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let v=P.text.trim();if(v)a.push({kind:"term",negated:p,term:Fv("phrase",v,!1)});continue}let f=[],h;while(m<u&&!Mg(e[m])){let P=e[m],v=e[m+1];if(P==="\\"&&v!==void 0&&tH.has(v)){f.push({c:v,esc:!0}),m+=2;continue}let _=_g[P]?qv(f):void 0;if(_){let Q=Dv(e,m);if(m=Q.next,!Q.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});h={key:_,value:Q.text,quoted:!0};break}f.push({c:P,esc:!1}),m++}if(h){a.push({kind:"filter",negated:p,...h});continue}let I=f.findIndex((P,v)=>v>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),E=I>0?qv(f.slice(0,I+1)):void 0;if(E){a.push({kind:"filter",negated:p,key:E,value:f.slice(I+1).map((P)=>P.c).join(""),quoted:!1});continue}if(!p&&f.length===2&&f.every((P)=>!P.esc)&&f[0]?.c==="O"&&f[1]?.c==="R"){a.push({kind:"or"});continue}let S=f[f.length-1],R=f.length>1&&S!==void 0&&!S.esc&&S.c==="*",k=(R?f.slice(0,-1):f).map((P)=>P.c).join("");if(k)a.push({kind:"term",negated:p,term:Fv("word",k,R)})}return a}var aH=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function jv(e){let o=[];return{rest:e.replace(aH,(u,m,p,f,h)=>{let I=f.toLowerCase();if(!Gv.has(I))return u;let E=h.startsWith('"')&&h.length>=2;return o.push({key:I,value:E?h.slice(1,-1).replace(/\\(["\\])/g,"$1"):h,negated:p==="-",quoted:E}),m}).trim(),filters:o}}var Uv={n:`
403
- `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function uH(e){let o=[...e],a=0,u=(S)=>{let R=o.slice(a,a+S).join("");if(R.length!==S||!/^[0-9a-fA-F]+$/.test(R))return;return a+=S,String.fromCodePoint(Number.parseInt(R,16))},m=()=>{let S=o[a++];if(S===void 0)return{kind:"lit",ch:"\\"};if(S in Uv)return{kind:"lit",ch:Uv[S]};if("dDwWsS".includes(S))return{kind:"any"};if(S==="b"||S==="B")return{kind:"zero"};if(S>="1"&&S<="9"){while(o[a]!==void 0&&/\d/.test(o[a]))a++;return{kind:"any"}}if(S==="k"||S==="p"||S==="P"){let R=o[a];if(R==="<"||R==="{"){let k=R==="<"?">":"}",P=o.indexOf(k,a);a=P<0?o.length:P+1}return{kind:"any"}}if(S==="c")return a++,{kind:"any"};if(S==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(S==="u"){if(o[a]==="{"){let k=o.indexOf("}",a),P=k<0?"":o.slice(a+1,k).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return a=k+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:S}},p=()=>{if(o[a]==="^")a++;while(a<o.length&&o[a]!=="]")a+=o[a]==="\\"?2:1;return a++,{kind:"any"}},f=()=>{let S="capture";if(o[a]==="?"){let k=o[a+1],P=o[a+2];if(k===":")S="plain",a+=2;else if(k==="="||k==="!")S="look",a+=2;else if(k==="<"&&(P==="="||P==="!"))S="look",a+=3;else if(k==="<"){let v=o.indexOf(">",a);a=v<0?o.length:v+1}else{S="opaque";while(a<o.length&&o[a]!==":"&&o[a]!==")")a++;if(o[a]===":")a++}}let R=E();if(o[a]===")")a++;if(S==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:S==="opaque"}},h=()=>{let S=o[a],R=1,k=!0;if(S==="*"||S==="?")R=0,a++;else if(S==="+")a++;else if(S==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(a,a+24).join(""));if(!P)return{quantified:!1,min:1};R=Number(P[1]),a+=P[0].length}else return{quantified:!1,min:1};if(o[a]==="?")a++;return{quantified:k,min:R}},I=()=>{let S=[];while(a<o.length){let R=o[a];if(R==="|"||R===")")break;a++;let k;if(R==="(")k=f();else if(R==="[")k=p();else if(R==="\\")k=m();else if(R===".")k={kind:"any"};else if(R==="^"||R==="$")k={kind:"zero"};else if(R==="*"||R==="+"||R==="?")k={kind:"zero"};else k={kind:"lit",ch:R};S.push({atom:k,...h()})}return S};function E(){let S=[I()];while(o[a]==="|")a++,S.push(I());return S}return E()}function Bv(e){let o=[],a="",u=()=>{if(a)o.push([a]);a=""},m=(p)=>{for(let f of p){let h=f.atom;if(h.kind==="lit")if(f.min>=1){if(a+=h.ch,f.quantified)u()}else u();else if(h.kind==="group"&&!h.opaque&&f.min>=1)if(h.alts.length===1&&!f.quantified)m(h.alts[0]);else u(),o.push(...Hv(h.alts));else u()}};return m(e),u(),o}function Hv(e){if(e.length===1)return Bv(e[0]);let o=[];for(let a of e){let u=Bv(a).filter((m)=>m.length===1).map((m)=>m[0]);if(!u.length)return[];o.push(u.reduce((m,p)=>em(p)>em(m)?p:m))}return[Kv(o)]}var cH=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function mH(e){return!/^\s*$/.test(e)&&(em(e)>=2||cH.test(e))}function pH(e){let o;try{o=Hv(uH(e))}catch{return[]}let a=o.filter((I)=>I.every(mH)),u=a.filter((I)=>I.length===1).map((I)=>I[0]),m=a.filter((I)=>{if(I.length!==1)return!0;let E=I[0];return!u.some((S)=>S!==E&&S.includes(E))}),p=new Set,f=m.filter((I)=>{let E=JSON.stringify(I);if(p.has(E))return!1;return p.add(E),!0}),h=(I)=>Math.min(...I.map(em));return f.sort((I,E)=>h(E)-h(I))}function lH(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 dH(e,o){let a=`m${o?"":"i"}`;try{return new RegExp(e,`${a}u`),{flags:`${a}u`}}catch{}try{return new RegExp(e,a),{flags:a}}catch(u){let m=u instanceof Error?u.message:String(u),p="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(m))p="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(m))p="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(m))p="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(m))p="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${p}`}}}function Yl(e,o={}){let a=o.now??Date.now(),u=e.q??"",m=oH(),p=m.diagnostics,f,h=[];if(e.mode==="regex"){let _=jv(u);for(let Q of _.filters)Og(m,Q.key,Q.value,Q.negated,Q.quoted,a);f=_.rest}else{let _=jv(u),Q=/^\/([\s\S]+)\/$/.exec(_.rest);if(Q){for(let L of _.filters)Og(m,L.key,L.value,L.negated,L.quoted,a);f=Q[1]}else{h=[{include:[],exclude:[]}];for(let L of iH(u,p)){let V=h[h.length-1];if(L.kind==="or")h.push({include:[],exclude:[]});else if(L.kind==="filter")Og(m,L.key,L.value,L.negated,L.quoted,a);else(L.negated?V.exclude:V.include).push(L.term)}h=h.filter((L)=>L.include.length||L.exclude.length)}}let I=h.flatMap((_)=>[..._.include,..._.exclude]),E=f!==void 0?lH(f):I.some((_)=>/\p{Lu}/u.test(_.text)),S=e.caseSensitive??E,R=e.caseSensitive===void 0&&E,k,P;if(f){let _=dH(f,S);if("message"in _)P={code:"bad_regex",message:_.message};else{let Q=pH(f);k={source:f,flags:_.flags,literals:Q,deepScan:Q.length===0}}}let v=sH(e.filters,m);return{mode:f!==void 0?"regex":"text",branches:h,...k?{regex:k}:{},filters:v,currentSession:m.currentSession,caseSensitive:S,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:h.some((_)=>_.include.some((Q)=>Q.fuzzy)),hasPositive:k!==void 0||h.some((_)=>_.include.length>0),hasFilters:Object.keys(v).length>0||m.currentSession,...P?{error:P}:{},diagnostics:p}}var qg={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},Wv=new WeakMap;function zv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,a=Wv.get(e);if(a?.version===o)return a.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return Wv.set(e,{version:o,terms:u}),u}var Dg=32,fH=1024,tm=(e)=>`"${e.replaceAll('"','""')}"`;function hH(e,o){let a=Array.from({length:o.length+1},(u,m)=>m);for(let u=0;u<e.length;u++){let m=[u+1];for(let p=0;p<o.length;p++)m.push(Math.min((m[p]??0)+1,(a[p+1]??0)+1,(a[p]??0)+Number(e[u]!==o[p])));a=m}return a[o.length]??e.length}function Fg(e,o){let a=Ct(o.trim());if(!a||a.length>64)return[];let u=zv(e),m=u.filter((h)=>h.t.startsWith(a)).slice(0,8).map((h)=>h.t);if(m.length>=8||a.length<4)return m;let p=a.length>=8?2:1,f=[];for(let h of u){if(Math.abs(h.t.length-a.length)>p)continue;if(hH(a,h.t)<=p)f.push(h.t);if(f.length>=8)break}return[...new Set([...m,...f])].slice(0,8)}function Vv(e,o){let a=!1,u=[],m=[],p=o.filters,f=(Q,L)=>{if(!L?.length)return;m.push(`${Q} IN (${L.map(()=>"?").join(",")})`),u.push(...L)};if(f("s.project_id",p.projectID),p.sessionID?.length){m.push(`(${p.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let Q of p.sessionID)u.push(Q,Q)}if(p.archived!==void 0)m.push(`s.archived_at IS ${p.archived?"NOT ":""}NULL`);let h=m.length?m.join(" AND "):"1",I=[...u];if(f("r.kind",p.fields?.map((Q)=>Be[Q])),f("r.tool",p.tools),p.model?.length){m.push(`(${p.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let Q of p.model)u.push(Q,Q)}if(p.isError!==void 0)m.push("r.err = ?"),u.push(Number(p.isError));if(p.compacted!==void 0)m.push(`(r.seq>0 AND r.seq<=COALESCE((
402
+ ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let k of S){R.add(k.namespace);let P=I.get(k.namespace);h.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[k,P]of I.entries())if(!R.has(k))h.push({namespace:k,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:o,mainSessionCount:Number(a?.main_count)||0,subSessionCount:Number(a?.sub_count)||0,forkedSessionCount:Number(a?.forked_count)||0,automationSessionCount:Number(a?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:f,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:p,pluginNamespaces:h}}function Ql(e,o){let a=Zs(e,"page_size"),u=Zs(e,"page_count"),m=Zs(e,"freelist_count"),p=e.db.query("PRAGMA journal_mode").get(),f=e.db.query("SELECT sqlite_version() AS v").get(),h=Zs(e,"synchronous"),I=Zs(e,"auto_vacuum"),E=Zs(e,"cache_size"),S=E<0?Math.abs(E)*1024:E*a,R=Zs(e,"foreign_keys")===1,k=Zs(e,"busy_timeout"),P=Cv(e,"encoding")??"UTF-8",v=Cv(e,"quick_check(1)")??"ok",_=e.path!==":memory:"?_v(e.path):void 0,Q=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),L=QK(e),V=WK(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((J,Z)=>J+Z.bytes,0),database:{size:Zc(e.path),walSize:Zc(`${e.path}-wal`),shmSize:Zc(`${e.path}-shm`),sqliteVersion:f?.v??"unknown",journalMode:p?.journal_mode??"unknown",synchronous:VK[h]??String(h),foreignKeys:R,busyTimeout:k,encoding:P,autoVacuum:JK[I]??String(I),cacheSizeBytes:S,pageSize:a,pageCount:u,freelistCount:m,reclaimableBytes:m*a,schemaVersion:Zs(e,"user_version"),..._!==void 0?{lastModified:_}:{},integrity:v},analytics:XK(e),entries:V,tables:Q.map(({name:J,sql:Z})=>{let ne=J.replaceAll('"','""'),z=e.db.query(`SELECT count(*) AS count FROM "${ne}"`).get().count,oe=e.db.query(`PRAGMA table_info("${ne}")`).all().map((ee)=>ee.name),fe=e.db.query(`PRAGMA index_list("${ne}")`).all().length,Ae=Boolean(Z&&/WITHOUT\s+ROWID/i.test(Z)),Ge=L.get(J);return{name:J,rows:z,...Ge?{bytes:Ge.bytes,pages:Ge.pages}:{},indexes:fe,columns:oe,withoutRowid:Ae}})}}function $v(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let a=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let p of a)for(let f of p.body.matchAll(/@blob:([0-9a-f]{64})/g)){let h=f[1];if(h)u.add(h)}let m=[];for(let p of o)if(!u.has(p.hash))m.push(p.hash);if(m.length===0)return 0;try{e.db.transaction(()=>{let p=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let f of m)p.run(f)})()}catch{return 0}return m.length}function Nv(e,o,a){let u=Ql(e,o);if(a.vacuum)kv(e.db),e.invalidateEntryCache(),$v(e),e.db.run("VACUUM");else if(a.checkpoint)$v(e);if(a.checkpoint||a.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Ql(e,o)}}var YK=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Xl{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(YK.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function Dv(e,o){let a=sn(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:a.length>0?a:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function qv(e,o){let a=e.options.visibleModelProviders?.(),m=(await e.options.models.getAvailable().catch(()=>[])).filter((f)=>!a||a.includes(f.provider)).map((f)=>({...Dv(ot(f),f),available:!0})),p=new Set(m.map((f)=>f.id));for(let f of[o,...e.list(!0,{archive:"all"}).map((h)=>h.model)]){if(p.has(f))continue;let h=Tn(e.options.models,f);if(!h||a&&!a.includes(h.provider))continue;p.add(f),m.push({...Dv(f,h),available:!1})}return{models:m}}function Fv(e,o){if(typeof o!=="string"||!Tn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as ZK,statSync as eH}from"fs";import{basename as tH,resolve as rH}from"path";class Mg{runtime;sessions;emit;arm;constructor(e,o,a,u){this.runtime=e;this.sessions=o;this.emit=a;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new y("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=rH(e.directory.trim());if(!ZK(o)||!eH(o).isDirectory())throw new t(`${o} is not a directory on the server`);let a=this.runtime.store.projectByDirectory(o);if(a){if(a.closedAt!==null)return this.updateProject(a.id,{closed:!1});return a}let u=Date.now(),m={id:re("p"),name:e.name?.trim()||tH(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(m),this.emit({type:"project",project:m}),m}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let m of this.sessions.values())if(m.projectID===e)m.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((m)=>typeof m==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((m)=>m.id)),a=new Set(e);if(!(a.size===e.length&&a.size===o.size&&e.every((m)=>o.has(m))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),a=[...this.sessions.values()].filter((m)=>m.projectID===e);if(a.some((m)=>m.status==="busy"))throw new ce("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let m of a)m.close(),this.runtime.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as wH,readFileSync as TH}from"fs";import{homedir as RH}from"os";import{join as Eu}from"path";var Wv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),nH={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"]},oH=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),Lg={'"':['"'],"\u201C":["\u201D",'"']},Og=(e)=>e!==void 0&&/\s/.test(e),zv=(e)=>[...new Set(e)],em=(e)=>[...e].length;var sH={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function iH(e,o){let a=e.trim().toLowerCase(),u=new Date(o),m=u.getFullYear(),p=u.getMonth(),f=u.getDate();if(a==="today")return{start:new Date(m,p,f).getTime(),end:new Date(m,p,f+1).getTime()};if(a==="yesterday")return{start:new Date(m,p,f-1).getTime(),end:new Date(m,p,f).getTime()};let h=/^(\d+)(h|d|w|mo|y)$/.exec(a);if(h)return{start:o-Number(h[1])*sH[h[2]]};if(/^\d{4}$/.test(a))return{start:new Date(Number(a),0,1).getTime(),end:new Date(Number(a)+1,0,1).getTime()};let I=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(a);if(!I)return null;let E=Number(I[1]),S=Number(I[3]);if(S<1||S>12)return null;if(I[4]===void 0){if(I[5]!==void 0)return null;return{start:new Date(E,S-1,1).getTime(),end:new Date(E,S,1).getTime()}}let R=Number(I[4]),k=Number(I[5]??0),P=Number(I[6]??0),v=Number(I[7]??0);if(k>23||P>59||v>59)return null;let _=new Date(E,S-1,R,k,P,v);if(_.getMonth()!==S-1||_.getDate()!==R)return null;if(I[5]!==void 0)return{start:_.getTime()};return{start:_.getTime(),end:new Date(E,S-1,R+1).getTime()}}var aH=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Ng=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),Dg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function _g(e,o,a,u,m,p){let f=a.trim(),h=(E,S)=>e.diagnostics.push({code:E,message:S,filter:o});if(!f)return h("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return h("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let I=m?[f]:f.split(",").map((E)=>E.trim()).filter(Boolean);switch(o){case"in":case"project":for(let E of I){let S=E.toLowerCase();if(o==="in"&&S==="this")e.currentSession=!0;else if(o==="in"&&S==="title")e.fields.push("title");else e.projectID.push(E)}return;case"session":for(let E of I)if(E.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(E);return;case"from":case"role":for(let E of I){let S=nH[E.toLowerCase()];if(S)e.fields.push(...S);else h("bad_filter_value",`${o}:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...I);return;case"model":e.model.push(...I);return;case"is":for(let E of I){let S=E.toLowerCase();if(S==="error")e.isError=!u;else if(S==="archived")e.archived=!u;else if(S==="compacted")e.compacted=!u;else h("bad_filter_value",`is:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let E=iH(f,p);if(!E)return h("bad_filter_value",`${o}:${f} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=Ng(e.after,E.start);else if(o==="before")e.before=Dg(e.before,E.start);else if(e.after=Ng(e.after,E.start),E.end!==void 0)e.before=Dg(e.before,E.end)}}}function uH(e,o){let a={},u=(v,_)=>{let Q=zv([...v??[],..._]);return Q.length?Q:void 0},m=u(e?.projectID,o.projectID),p=u(e?.sessionID,o.sessionID),f=u(e?.fields,o.fields),h=u(e?.tools,o.tools),I=u(e?.model,o.model);if(m)a.projectID=m;if(p)a.sessionID=p;if(f)a.fields=f;if(h)a.tools=h;if(I)a.model=I;let E=o.isError??e?.isError,S=o.archived??e?.archived,R=o.compacted??e?.compacted;if(E!==void 0)a.isError=E;if(S!==void 0)a.archived=S;if(R!==void 0)a.compacted=R;let k=Ng(e?.after,o.after),P=Dg(e?.before,o.before);if(k!==void 0)a.after=k;if(P!==void 0)a.before=P;if(k!==void 0&&P!==void 0&&k>=P)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return a}function jv(e,o){let a=Lg[e[o]]??['"'],u="",m=o+1;while(m<e.length){let p=e[m],f=e[m+1];if(p==="\\"&&f!==void 0&&(f==="\\"||f==='"'||f==="\u201C"||f==="\u201D")){u+=f,m+=2;continue}if(a.includes(p))return{text:u,next:m+1,closed:!0};u+=p,m++}return{text:u,next:m,closed:!1}}function Uv(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let a=e.slice(0,-1).map((m)=>m.esc||!/[A-Za-z]/.test(m.c)?"":m.c).join("");if(a.length!==e.length-1)return;let u=a.toLowerCase();return Wv.has(u)?u:void 0}function Bv(e,o,a){let u=e==="word"&&!a&&em(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:a,fuzzy:u}}function cH(e,o){let a=[],u=e.length,m=0;while(m<u){if(Og(e[m])){m++;continue}let p=!1;if(e[m]==="-"){if(m+1>=u||Og(e[m+1])){m++;continue}p=!0,m++}if(Lg[e[m]]){let P=jv(e,m);if(m=P.next,!P.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let v=P.text.trim();if(v)a.push({kind:"term",negated:p,term:Bv("phrase",v,!1)});continue}let f=[],h;while(m<u&&!Og(e[m])){let P=e[m],v=e[m+1];if(P==="\\"&&v!==void 0&&oH.has(v)){f.push({c:v,esc:!0}),m+=2;continue}let _=Lg[P]?Uv(f):void 0;if(_){let Q=jv(e,m);if(m=Q.next,!Q.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});h={key:_,value:Q.text,quoted:!0};break}f.push({c:P,esc:!1}),m++}if(h){a.push({kind:"filter",negated:p,...h});continue}let I=f.findIndex((P,v)=>v>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),E=I>0?Uv(f.slice(0,I+1)):void 0;if(E){a.push({kind:"filter",negated:p,key:E,value:f.slice(I+1).map((P)=>P.c).join(""),quoted:!1});continue}if(!p&&f.length===2&&f.every((P)=>!P.esc)&&f[0]?.c==="O"&&f[1]?.c==="R"){a.push({kind:"or"});continue}let S=f[f.length-1],R=f.length>1&&S!==void 0&&!S.esc&&S.c==="*",k=(R?f.slice(0,-1):f).map((P)=>P.c).join("");if(k)a.push({kind:"term",negated:p,term:Bv("word",k,R)})}return a}var mH=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function Gv(e){let o=[];return{rest:e.replace(mH,(u,m,p,f,h)=>{let I=f.toLowerCase();if(!Wv.has(I))return u;let E=h.startsWith('"')&&h.length>=2;return o.push({key:I,value:E?h.slice(1,-1).replace(/\\(["\\])/g,"$1"):h,negated:p==="-",quoted:E}),m}).trim(),filters:o}}var Kv={n:`
403
+ `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function pH(e){let o=[...e],a=0,u=(S)=>{let R=o.slice(a,a+S).join("");if(R.length!==S||!/^[0-9a-fA-F]+$/.test(R))return;return a+=S,String.fromCodePoint(Number.parseInt(R,16))},m=()=>{let S=o[a++];if(S===void 0)return{kind:"lit",ch:"\\"};if(S in Kv)return{kind:"lit",ch:Kv[S]};if("dDwWsS".includes(S))return{kind:"any"};if(S==="b"||S==="B")return{kind:"zero"};if(S>="1"&&S<="9"){while(o[a]!==void 0&&/\d/.test(o[a]))a++;return{kind:"any"}}if(S==="k"||S==="p"||S==="P"){let R=o[a];if(R==="<"||R==="{"){let k=R==="<"?">":"}",P=o.indexOf(k,a);a=P<0?o.length:P+1}return{kind:"any"}}if(S==="c")return a++,{kind:"any"};if(S==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(S==="u"){if(o[a]==="{"){let k=o.indexOf("}",a),P=k<0?"":o.slice(a+1,k).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return a=k+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:S}},p=()=>{if(o[a]==="^")a++;while(a<o.length&&o[a]!=="]")a+=o[a]==="\\"?2:1;return a++,{kind:"any"}},f=()=>{let S="capture";if(o[a]==="?"){let k=o[a+1],P=o[a+2];if(k===":")S="plain",a+=2;else if(k==="="||k==="!")S="look",a+=2;else if(k==="<"&&(P==="="||P==="!"))S="look",a+=3;else if(k==="<"){let v=o.indexOf(">",a);a=v<0?o.length:v+1}else{S="opaque";while(a<o.length&&o[a]!==":"&&o[a]!==")")a++;if(o[a]===":")a++}}let R=E();if(o[a]===")")a++;if(S==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:S==="opaque"}},h=()=>{let S=o[a],R=1,k=!0;if(S==="*"||S==="?")R=0,a++;else if(S==="+")a++;else if(S==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(a,a+24).join(""));if(!P)return{quantified:!1,min:1};R=Number(P[1]),a+=P[0].length}else return{quantified:!1,min:1};if(o[a]==="?")a++;return{quantified:k,min:R}},I=()=>{let S=[];while(a<o.length){let R=o[a];if(R==="|"||R===")")break;a++;let k;if(R==="(")k=f();else if(R==="[")k=p();else if(R==="\\")k=m();else if(R===".")k={kind:"any"};else if(R==="^"||R==="$")k={kind:"zero"};else if(R==="*"||R==="+"||R==="?")k={kind:"zero"};else k={kind:"lit",ch:R};S.push({atom:k,...h()})}return S};function E(){let S=[I()];while(o[a]==="|")a++,S.push(I());return S}return E()}function Hv(e){let o=[],a="",u=()=>{if(a)o.push([a]);a=""},m=(p)=>{for(let f of p){let h=f.atom;if(h.kind==="lit")if(f.min>=1){if(a+=h.ch,f.quantified)u()}else u();else if(h.kind==="group"&&!h.opaque&&f.min>=1)if(h.alts.length===1&&!f.quantified)m(h.alts[0]);else u(),o.push(...Vv(h.alts));else u()}};return m(e),u(),o}function Vv(e){if(e.length===1)return Hv(e[0]);let o=[];for(let a of e){let u=Hv(a).filter((m)=>m.length===1).map((m)=>m[0]);if(!u.length)return[];o.push(u.reduce((m,p)=>em(p)>em(m)?p:m))}return[zv(o)]}var lH=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function dH(e){return!/^\s*$/.test(e)&&(em(e)>=2||lH.test(e))}function fH(e){let o;try{o=Vv(pH(e))}catch{return[]}let a=o.filter((I)=>I.every(dH)),u=a.filter((I)=>I.length===1).map((I)=>I[0]),m=a.filter((I)=>{if(I.length!==1)return!0;let E=I[0];return!u.some((S)=>S!==E&&S.includes(E))}),p=new Set,f=m.filter((I)=>{let E=JSON.stringify(I);if(p.has(E))return!1;return p.add(E),!0}),h=(I)=>Math.min(...I.map(em));return f.sort((I,E)=>h(E)-h(I))}function hH(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 gH(e,o){let a=`m${o?"":"i"}`;try{return new RegExp(e,`${a}u`),{flags:`${a}u`}}catch{}try{return new RegExp(e,a),{flags:a}}catch(u){let m=u instanceof Error?u.message:String(u),p="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(m))p="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(m))p="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(m))p="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(m))p="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${p}`}}}function Yl(e,o={}){let a=o.now??Date.now(),u=e.q??"",m=aH(),p=m.diagnostics,f,h=[];if(e.mode==="regex"){let _=Gv(u);for(let Q of _.filters)_g(m,Q.key,Q.value,Q.negated,Q.quoted,a);f=_.rest}else{let _=Gv(u),Q=/^\/([\s\S]+)\/$/.exec(_.rest);if(Q){for(let L of _.filters)_g(m,L.key,L.value,L.negated,L.quoted,a);f=Q[1]}else{h=[{include:[],exclude:[]}];for(let L of cH(u,p)){let V=h[h.length-1];if(L.kind==="or")h.push({include:[],exclude:[]});else if(L.kind==="filter")_g(m,L.key,L.value,L.negated,L.quoted,a);else(L.negated?V.exclude:V.include).push(L.term)}h=h.filter((L)=>L.include.length||L.exclude.length)}}let I=h.flatMap((_)=>[..._.include,..._.exclude]),E=f!==void 0?hH(f):I.some((_)=>/\p{Lu}/u.test(_.text)),S=e.caseSensitive??E,R=e.caseSensitive===void 0&&E,k,P;if(f){let _=gH(f,S);if("message"in _)P={code:"bad_regex",message:_.message};else{let Q=fH(f);k={source:f,flags:_.flags,literals:Q,deepScan:Q.length===0}}}let v=uH(e.filters,m);return{mode:f!==void 0?"regex":"text",branches:h,...k?{regex:k}:{},filters:v,currentSession:m.currentSession,caseSensitive:S,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:h.some((_)=>_.include.some((Q)=>Q.fuzzy)),hasPositive:k!==void 0||h.some((_)=>_.include.length>0),hasFilters:Object.keys(v).length>0||m.currentSession,...P?{error:P}:{},diagnostics:p}}var Fg={title:8,user:5,assistant:3,error:3,tool_input:2,notice:2,extension:1,thinking:0.5,tool_output:0.5,attachment:0.5},Jv=new WeakMap;function Qv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,a=Jv.get(e);if(a?.version===o)return a.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return Jv.set(e,{version:o,terms:u}),u}var qg=32,yH=1024,tm=(e)=>`"${e.replaceAll('"','""')}"`;function xH(e,o){let a=Array.from({length:o.length+1},(u,m)=>m);for(let u=0;u<e.length;u++){let m=[u+1];for(let p=0;p<o.length;p++)m.push(Math.min((m[p]??0)+1,(a[p+1]??0)+1,(a[p]??0)+Number(e[u]!==o[p])));a=m}return a[o.length]??e.length}function jg(e,o){let a=Ct(o.trim());if(!a||a.length>64)return[];let u=Qv(e),m=u.filter((h)=>h.t.startsWith(a)).slice(0,8).map((h)=>h.t);if(m.length>=8||a.length<4)return m;let p=a.length>=8?2:1,f=[];for(let h of u){if(Math.abs(h.t.length-a.length)>p)continue;if(xH(a,h.t)<=p)f.push(h.t);if(f.length>=8)break}return[...new Set([...m,...f])].slice(0,8)}function Xv(e,o){let a=!1,u=[],m=[],p=o.filters,f=(Q,L)=>{if(!L?.length)return;m.push(`${Q} IN (${L.map(()=>"?").join(",")})`),u.push(...L)};if(f("s.project_id",p.projectID),p.sessionID?.length){m.push(`(${p.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let Q of p.sessionID)u.push(Q,Q)}if(p.archived!==void 0)m.push(`s.archived_at IS ${p.archived?"NOT ":""}NULL`);let h=m.length?m.join(" AND "):"1",I=[...u];if(f("r.kind",p.fields?.map((Q)=>Be[Q])),f("r.tool",p.tools),p.model?.length){m.push(`(${p.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let Q of p.model)u.push(Q,Q)}if(p.isError!==void 0)m.push("r.err = ?"),u.push(Number(p.isError));if(p.compacted!==void 0)m.push(`(r.seq>0 AND r.seq<=COALESCE((
404
404
  SELECT max(json_extract(body,'$.through')) FROM store.entries
405
405
  WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
406
- ),0)) = ?`),u.push(Number(p.compacted));if(p.after!==void 0)m.push("r.time >= ?"),u.push(p.after);if(p.before!==void 0)m.push("r.time < ?"),u.push(p.before);let E=e.query("SELECT v FROM meta WHERE k='layout'").get(),S=E&&JSON.parse(E.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),k=(Q)=>{let L=(Z)=>{let ne=Ct(Z);if(!Q&&S){if([...ne].length<3){let ee=[...ne].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ne,`${ne}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ne);if([...ne].length===1&&ee.length>Dg)ee.length=Dg,a=!0;if(!ee.length)return tm("__basalt_no_short_match__");return`(${ee.map((ue)=>tm(ue.term)).join(" OR ")})`}return tm(ne)}let z=/^[\p{Script=Latin}\p{N}]+$/u.test(Z)?[ne]:Yi(Z),oe=z.filter((ee)=>!/^[a-z0-9]{1,2}$/.test(ee)),fe=oe.length?oe:z;if(!fe.length){R=!0;return}let ke=fe.map((ee,ue)=>{let $e=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(ee),gt=fe.length>2&&ue>0&&ue<fe.length-1;if($e||gt){let _e=e.query("SELECT n FROM term WHERE t=?").get(ee)?.n??0;return{expression:tm(ee),frequency:_e}}let Ke=[ee],Zt=0;for(let _e of zv(e)){if(!_e.t.includes(ee))continue;if(Zt+=_e.n,_e.t!==ee)Ke.push(_e.t);if(Ke.length>=Dg){a=!0;break}}return{expression:`(${Ke.map(tm).join(" OR ")})`,frequency:Zt}});return ke.sort((ee,ue)=>ee.frequency-ue.frequency),`(${ke.slice(0,(ke[0]?.frequency??1/0)<=fH?1:2).map((ee)=>ee.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((Z)=>Z.include.map((ne)=>ne.text));if(o.regex){let Z=V.map((ne)=>ne.map(L));if(Z.some((ne)=>ne.some((z)=>!z)))return;return Z.map((ne)=>`(${ne.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((Z)=>{let ne=Z.filter((z)=>!/^[a-z0-9]{1,2}$/i.test(z));return(ne.length?ne:Z).map(L)});if(J.some((Z)=>!Z.length||Z.some((ne)=>!ne)))return;return J.map((Z)=>`(${Z.join(" AND ")})`).join(" OR ")||void 0},P=k(!1),v=k(!0),_=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:v,scan:R,where:m.length?m.join(" AND "):"1",bindings:u,forks:_,sessionWhere:h,sessionBindings:I,partial:a,candidateLimit:o.branches.some((Q)=>Q.include.length>0&&Q.include.every((L)=>[...L.text].length<2))?512:void 0}}function Jv(e){let o=1/0,a=-1/0;for(let u of e)o=Math.min(o,u.relevance),a=Math.max(a,u.relevance);return e.map((u)=>({...u,relevance:o===a?-1:-(0.5+0.5*(a-u.relevance)/(a-o))}))}function Zl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(qg).map(([a,u])=>`WHEN ${Be[a]} THEN ${u}`).join(" ")} ELSE 1 END) *
407
- (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function Qv(e,o,a,u){let m=Math.max(0,u-a)/86400000;return Math.max(0.000000001,-e)*qg[o]*(0.3+0.7/(1+m/30))}function jg(e,o){return e.sort((a,u)=>(o==="best"?u.score-a.score:0)||(o==="recent"?u.time-a.time:0)||(a.sessionID<u.sessionID?-1:Number(a.sessionID>u.sessionID))||u.seq-a.seq||a.field.localeCompare(u.field))}var Bg=512;function Xv(e,o,a){let u=performance.now(),m=o.partial;Gg(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[p,f]of[["fts",o.msg],["fts_out",o.out]]){if(!f)continue;let h=o.candidateLimit??2000,I=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
406
+ ),0)) = ?`),u.push(Number(p.compacted));if(p.after!==void 0)m.push("r.time >= ?"),u.push(p.after);if(p.before!==void 0)m.push("r.time < ?"),u.push(p.before);let E=e.query("SELECT v FROM meta WHERE k='layout'").get(),S=E&&JSON.parse(E.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),k=(Q)=>{let L=(Z)=>{let ne=Ct(Z);if(!Q&&S){if([...ne].length<3){let ee=[...ne].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ne,`${ne}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ne);if([...ne].length===1&&ee.length>qg)ee.length=qg,a=!0;if(!ee.length)return tm("__basalt_no_short_match__");return`(${ee.map((ue)=>tm(ue.term)).join(" OR ")})`}return tm(ne)}let z=/^[\p{Script=Latin}\p{N}]+$/u.test(Z)?[ne]:Yi(Z),oe=z.filter((ee)=>!/^[a-z0-9]{1,2}$/.test(ee)),fe=oe.length?oe:z;if(!fe.length){R=!0;return}let Ae=fe.map((ee,ue)=>{let we=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(ee),Ve=fe.length>2&&ue>0&&ue<fe.length-1;if(we||Ve){let $e=e.query("SELECT n FROM term WHERE t=?").get(ee)?.n??0;return{expression:tm(ee),frequency:$e}}let je=[ee],Qt=0;for(let $e of Qv(e)){if(!$e.t.includes(ee))continue;if(Qt+=$e.n,$e.t!==ee)je.push($e.t);if(je.length>=qg){a=!0;break}}return{expression:`(${je.map(tm).join(" OR ")})`,frequency:Qt}});return Ae.sort((ee,ue)=>ee.frequency-ue.frequency),`(${Ae.slice(0,(Ae[0]?.frequency??1/0)<=yH?1:2).map((ee)=>ee.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((Z)=>Z.include.map((ne)=>ne.text));if(o.regex){let Z=V.map((ne)=>ne.map(L));if(Z.some((ne)=>ne.some((z)=>!z)))return;return Z.map((ne)=>`(${ne.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((Z)=>{let ne=Z.filter((z)=>!/^[a-z0-9]{1,2}$/i.test(z));return(ne.length?ne:Z).map(L)});if(J.some((Z)=>!Z.length||Z.some((ne)=>!ne)))return;return J.map((Z)=>`(${Z.join(" AND ")})`).join(" OR ")||void 0},P=k(!1),v=k(!0),_=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:v,scan:R,where:m.length?m.join(" AND "):"1",bindings:u,forks:_,sessionWhere:h,sessionBindings:I,partial:a,candidateLimit:o.branches.some((Q)=>Q.include.length>0&&Q.include.every((L)=>[...L.text].length<2))?512:void 0}}function Yv(e){let o=1/0,a=-1/0;for(let u of e)o=Math.min(o,u.relevance),a=Math.max(a,u.relevance);return e.map((u)=>({...u,relevance:o===a?-1:-(0.5+0.5*(a-u.relevance)/(a-o))}))}function Zl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(Fg).map(([a,u])=>`WHEN ${Be[a]} THEN ${u}`).join(" ")} ELSE 1 END) *
407
+ (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function Zv(e,o,a,u){let m=Math.max(0,u-a)/86400000;return Math.max(0.000000001,-e)*Fg[o]*(0.3+0.7/(1+m/30))}function Ug(e,o){return e.sort((a,u)=>(o==="best"?u.score-a.score:0)||(o==="recent"?u.time-a.time:0)||(a.sessionID<u.sessionID?-1:Number(a.sessionID>u.sessionID))||u.seq-a.seq||a.field.localeCompare(u.field))}var Gg=512;function eM(e,o,a){let u=performance.now(),m=o.partial;Kg(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[p,f]of[["fts",o.msg],["fts_out",o.out]]){if(!f)continue;let h=o.candidateLimit??2000,I=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
408
408
  ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(f,o.candidateLimit?h+1:h);if(o.candidateLimit&&I.length>h)I.length=h,m=!0;else if(!o.candidateLimit&&I.length===h){let S=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
409
- AND rowid NOT IN (SELECT value FROM json_each(?))`).all(f,JSON.stringify(I.map((R)=>R.doc)));for(let R of S)I.push(R)}let E=Jv(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
410
- FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(E))}return a?.("match",performance.now()-u),m}function Yv(e,o,a,u,m){let p=performance.now();if(o.candidateLimit){let h=e.query(`
409
+ AND rowid NOT IN (SELECT value FROM json_each(?))`).all(f,JSON.stringify(I.map((R)=>R.doc)));for(let R of S)I.push(R)}let E=Yv(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
410
+ FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(E))}return a?.("match",performance.now()-u),m}function tM(e,o,a,u,m){let p=performance.now();if(o.candidateLimit){let h=e.query(`
411
411
  SELECT r.session_id,r.seq,${Zl(u)} AS score
412
412
  FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
413
413
  ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
@@ -419,14 +419,14 @@ ${p.data}
419
419
  WHERE ${o.where}
420
420
  GROUP BY r.session_id${a?",r.seq":""}
421
421
  ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
422
- `).all(...o.bindings);return m?.("filter",performance.now()-p),f}var Zv=new WeakMap,gH=`WITH RECURSIVE lineage(child,ancestor,through) AS (
422
+ `).all(...o.bindings);return m?.("filter",performance.now()-p),f}var rM=new WeakMap,IH=`WITH RECURSIVE lineage(child,ancestor,through) AS (
423
423
  SELECT id,forked_from_id,forked_from_seq FROM store.sessions
424
424
  WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
425
425
  UNION
426
426
  SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
427
427
  FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
428
428
  WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
429
- )`;function Gg(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(`${gH} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let a=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();Zv.set(e,new Map(a.map((u)=>[u.ancestor,u.through])))}function Ug(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
429
+ )`;function Kg(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(`${IH} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let a=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();rM.set(e,new Map(a.map((u)=>[u.ancestor,u.through])))}function Bg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
430
430
  SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
431
431
  JOIN store.sessions ps ON ps.id=pr.session_id
432
432
  WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
@@ -436,47 +436,47 @@ ${p.data}
436
436
  ON copied.session_id=r.session_id AND copied.seq=r.seq
437
437
  WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
438
438
  ))
439
- ))`}function eM(e,o,a,u,m){let p=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 f=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,h=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
439
+ ))`}function nM(e,o,a,u,m){let p=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 f=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,h=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
440
440
  INSERT INTO temp.search_window SELECT r.* FROM ref r ${f>4000?"INDEXED BY ref_time":""}
441
- ${h} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${Ug(o)}
441
+ ${h} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${Bg(o)}
442
442
  ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${u} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],a);let I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(I===u){let E=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(E)e.query(`
443
443
  INSERT INTO temp.search_window SELECT r.* FROM ref r ${h}
444
444
  WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
445
- AND ${o.where} AND ${Ug(o)} AND NOT EXISTS (
445
+ AND ${o.where} AND ${Bg(o)} AND NOT EXISTS (
446
446
  SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
447
- )`).run(E.session_id,E.seq,...o.bindings,...o.forks?o.bindings:[]),I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return m?.("filter",performance.now()-p),I}function tM(e,o,a,u,m,p,f){let h=performance.now(),I=o.group==="none",E=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",S=e.query(`
447
+ )`).run(E.session_id,E.seq,...o.bindings,...o.forks?o.bindings:[]),I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return m?.("filter",performance.now()-p),I}function oM(e,o,a,u,m,p,f){let h=performance.now(),I=o.group==="none",E=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",S=e.query(`
448
448
  SELECT r.session_id,${I?"r.seq":"0"} AS seq,
449
449
  max(${Zl(m)}) AS relevance,max(r.time) AS time
450
450
  FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
451
451
  WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
452
452
  GROUP BY r.session_id${I?",r.seq":""}
453
- ORDER BY ${E},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(p),u,a);return f?.("group",performance.now()-h),S}function rM(e,o,a,u,m,p){let f=performance.now(),h=m?o:{...o,forks:!1},I=e.query(`
453
+ ORDER BY ${E},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(p),u,a);return f?.("group",performance.now()-h),S}function sM(e,o,a,u,m,p){let f=performance.now(),h=m?o:{...o,forks:!1},I=e.query(`
454
454
  SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
455
455
  ${h.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
456
456
  WHERE r.session_id=? ${u?"AND r.seq=?":""}
457
- AND ${o.where} AND ${Ug(h)}
458
- ${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(a.session_id,...u?[a.seq]:[],...o.bindings,...h.forks?o.bindings:[]);return p?.("filter",performance.now()-f),I}function Kg(e,o,a,u){if(!o.forks)return[];let m=Zv.get(e)?.get(a.session_id);if(m===void 0||a.seq>m)return[];return e.query(`
457
+ AND ${o.where} AND ${Bg(h)}
458
+ ${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(a.session_id,...u?[a.seq]:[],...o.bindings,...h.forks?o.bindings:[]);return p?.("filter",performance.now()-f),I}function Hg(e,o,a,u){if(!o.forks)return[];let m=rM.get(e)?.get(a.session_id);if(m===void 0||a.seq>m)return[];return e.query(`
459
459
  SELECT DISTINCT r.session_id,s.title,e.body
460
460
  FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
461
461
  CROSS JOIN ref r ON r.session_id=l.child
462
462
  JOIN store.sessions s ON s.id=r.session_id
463
463
  LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
464
- WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(a.session_id,a.doc,a.seq,a.part,...o.bindings).filter((p)=>{if(a.seq===0)return p.title===u;if(!p.body)return!1;let f=JSON.parse(p.body);return Je(f,!0).some((h)=>h.part===a.part&&h.kind===uo[a.kind]&&h.text===u)}).map((p)=>p.session_id)}function yH(e,o){let a=o?e:Ct(e);if(a.length===e.length)return{normalized:a,starts:void 0,ends:void 0};let u="",m=[],p=[],f=0;for(let h of e){let I=o?h:Ct(h);u+=I;for(let E=0;E<I.length;E++)m.push(f),p.push(f+h.length);f+=h.length}return{normalized:u,starts:m,ends:p}}function ed(e,o){if(o.regex){let I=new RegExp(o.regex.source,`${o.regex.flags}g`),E=[];for(let S of e.matchAll(I)){if(o.wholeWord&&!nM(e,S.index,S.index+S[0].length))continue;E.push([S.index,S.index+S[0].length])}return E.length?E:void 0}let{normalized:a,starts:u,ends:m}=yH(e,o.caseSensitive),p=(I)=>{let E=o.caseSensitive?I.text:Ct(I.text),S=[],R=a.indexOf(E);while(R>=0&&E){let k=u?u[R]:R,P=m?m[R+E.length-1]:R+E.length,v=k===0||k!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(k-1,k))||/[a-z0-9][A-Z]/.test(e.slice(k-1,k+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(I.text));if(k!==void 0&&P!==void 0&&(!I.prefix||v)&&(!o.wholeWord||nM(e,k,P)))S.push([k,P]);R=a.indexOf(E,R+Math.max(1,E.length))}return S};if(!o.branches.length)return[];let f=[],h=!1;for(let I of o.branches){if(I.exclude.some((S)=>p(S).length))continue;let E=I.include.map(p);if(E.some((S)=>!S.length))continue;h=!0,f.push(...E.flat())}return h?f:void 0}function nM(e,o,a){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(a===e.length||!u.test(e.slice(a,a+1)))}function td(e,o){let a=e.split(`
465
- `),u=new Set,m=0,p=a.map((f,h)=>{let I=m;if(o.some(([E,S])=>E<=I+f.length&&S>=I))for(let E=Math.max(0,h-1);E<=Math.min(a.length-1,h+1);E++)u.add(E);return m+=f.length+1,I});if(!u.size)u.add(0);return[...u].sort((f,h)=>f-h).slice(0,5).map((f)=>{let h=a[f]??"",I=p[f]??0,E=o.filter(([P,v])=>v>I&&P<I+h.length),S=Math.max(0,(E[0]?.[0]??I)-I-100),R=h.slice(S,S+300),k=E.map(([P,v])=>[Math.max(0,P-I-S),Math.min(R.length,v-I-S)]);return{text:R,line:f+1,ranges:k.filter(([P,v])=>P<v)}})}var oM=3;function xH(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 sM(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function IH(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let a=JSON.parse(Buffer.from(e,"base64url").toString());if(a&&typeof a==="object"&&"offset"in a&&"key"in a&&"now"in a&&a.key===o&&typeof a.offset==="number"&&Number.isSafeInteger(a.offset)&&a.offset>=0&&typeof a.now==="number"&&Number.isFinite(a.now)){let u="window"in a?a.window:0,m="seen"in a?a.seen:[],p="emitted"in a?a.emitted:[],f="after"in a?a.after:void 0;if(f!==void 0&&!xH(f))throw Error("invalid best cursor");let h=(I)=>Array.isArray(I)&&I.every((E)=>typeof E==="string"&&E.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&h(m)&&h(p))return{offset:a.offset,key:o,now:a.now,window:u,seen:m,emitted:p,after:f}}}catch{}throw Error("invalid search cursor")}function zn(e,o){let a=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return IH(e.cursor,a)}async function Yr(e,o,a){let u="search"in e?e.search:e,m=performance.now(),p=(_e)=>{if(!a.signal?.aborted)a.onEvent(_e)};if(a.signal?.aborted)return;let f=zn(o,a.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let h=Yl(o,{now:f.now});if(h.error){p({type:"error",...h.error});return}if(h.currentSession){if(!a.sessionID){p({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}h.filters.sessionID=[a.sessionID]}if(!o.deep&&h.regex?.deepScan){p({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),a.signal?.aborted)return;let I=performance.now(),E=u.withIndex((_e)=>Vv(_e,h));if(!E){p({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}a.onTiming?.("plan",performance.now()-I);let S=E.partial,R=f.after,k=new Map,P=new Map,v=[],_=!1,Q=new Map,L=new WeakMap,V=new Map,J=new Map,{offset:Z,window:ne}=f,z=[...f.seen],oe=[...f.emitted],fe=!1,ke=Math.max(1,Math.min(200,o.limit??30)),Ee=Math.min(E.candidateLimit??2000,o.group==="none"?Bg:Math.min(2000,Math.max(Bg,ke*32))),ee=(_e,qe)=>{let Dt=k.get(qe);if(Dt)return Dt;let pt=_e.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(qe);if(pt)k.set(qe,pt);return pt??void 0},ue=(_e,qe,Dt)=>{if(a.allowedSessionIDs&&!a.allowedSessionIDs.has(qe.session_id))return;if(a.excludeEntry?.sessionID===qe.session_id&&a.excludeEntry.seq===qe.seq)return;let pt=ee(_e,qe.session_id);if(!pt)return;let Mt=uo[qe.kind];if(!Mt)return;let Ir=pt.title;if(qe.seq!==0){let tt=`${qe.session_id}:${qe.seq}`,Qt=J.get(tt);if(!Qt){let dn=Dt?void 0:_e.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(qe.session_id,qe.seq);if(!Dt&&!dn)return;let Wt=Dt??JSON.parse(dn?.body??"null");Qt=Je(Wt,!0),J.set(tt,Qt)}let er=Qt.find((dn)=>dn.part===qe.part&&dn.kind===Mt);if(!er)return;Ir=er.text}let nr=ed(Ir,h);if(!nr)return;let Ut=P.get(pt.id);if(Ut===void 0)Ut=_e.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(pt.id)?.through??0,P.set(pt.id,Ut);let et=qe.seq>0&&qe.seq<=Ut;if(h.filters.compacted!==void 0&&et!==h.filters.compacted)return;let Pt={sessionID:pt.id,seq:qe.seq,time:qe.time,field:Mt,tool:qe.tool??void 0,isError:Boolean(qe.err),model:qe.model??void 0,snippet:[],score:Qv(qe.relevance,Mt,qe.time,f.now),flags:{archived:pt.archived_at!==null,compacted:et,partial:Ir.length>Ki+Qi}};return Q.set(Pt,{text:Ir,ranges:nr}),v.push(Pt),_=!0,V.set(Pt,{doc:qe.doc,part:qe.part}),Pt},$e=(_e)=>{let qe=performance.now(),Dt=[..._e].sort((et,Pt)=>et.time-Pt.time||et.sessionID.localeCompare(Pt.sessionID)),pt=[],Mt=new Map;for(let et of Dt){let Pt=V.get(et),Qt=k.get(et.sessionID),er=new Set;while(Qt?.forked_from_id&&Qt.forked_from_seq!==null&&et.seq<=Qt.forked_from_seq&&!er.has(Qt.id))er.add(Qt.id),Qt=k.get(Qt.forked_from_id)??u.withIndex(($o)=>ee($o,Qt?.forked_from_id??""));let dn=`${Qt?.id??et.sessionID}:${et.seq}:${Pt?.part}:${Pt?.doc}`,Wt=Mt.get(dn);if(Wt){if(Wt.sessionID!==et.sessionID)Wt.forks=[...new Set([...Wt.forks??[],et.sessionID])]}else Mt.set(dn,et),pt.push(et)}let Ir=[],nr=new Map,Ut=new Map;for(let et of pt){let Pt=`${et.sessionID}:${et.seq}`,tt=Ut.get(Pt);if(!tt){Ut.set(Pt,et),L.set(et,[et]);continue}let Qt=[...L.get(tt)??[tt],et],er=et.score>tt.score?et:tt;if(er.forks=[...new Set([...tt.forks??[],...et.forks??[]])],!er.forks.length)er.forks=void 0;er.flags={archived:tt.flags.archived||et.flags.archived,compacted:tt.flags.compacted||et.flags.compacted,partial:tt.flags.partial||et.flags.partial},Ut.set(Pt,er),L.set(er,Qt)}for(let et of jg([...Ut.values()],o.sort??"best")){let Pt=k.get(et.sessionID);if(!Pt)continue;let tt=o.group==="none"?void 0:nr.get(Pt.id);if(!tt)tt={session:{id:Pt.id,title:Pt.title,projectID:Pt.project_id,updated:Pt.updated},hits:[],more:0,...S&&o.group!=="none"?{moreIsLowerBound:!0}:{}},Ir.push(tt),nr.set(Pt.id,tt);if(tt.hits.length<oM||o.group==="none")tt.hits.push(et);else tt.more++}return a.onTiming?.("group",performance.now()-qe),Ir},gt=(_e)=>{for(let qe of _e)for(let Dt of qe.hits){if(a.allowedSessionIDs&&Dt.forks)Dt.forks=Dt.forks.filter((Ir)=>a.allowedSessionIDs?.has(Ir));let pt=performance.now(),Mt=new Map;for(let Ir of L.get(Dt)??[Dt]){let nr=Q.get(Ir);if(!nr)continue;for(let Ut of td(nr.text,nr.ranges)){let et=`${Ut.line}:${Ut.text}`,Pt=Mt.get(et);if(!Pt)Mt.set(et,Ut);else Pt.ranges=[...new Map([...Pt.ranges,...Ut.ranges].map((tt)=>[tt.join(":"),tt])).values()]}}Dt.snippet=[...Mt.values()],a.onTiming?.("snippet",performance.now()-pt)}},Ke=o.deep||E.scan,Zt=(_e,qe)=>{let Dt=ee(_e,qe.session_id);if(!Dt)return[];let pt=rM(_e,E,qe,o.group==="none",Dt.forked_from_id!==null,a.onTiming);if(E.candidateLimit&&pt.length>E.candidateLimit)pt.length=E.candidateLimit,S=!0;let Mt=v.length,Ir=performance.now();for(let nr of pt){if(a.signal?.aborted)break;let Ut=ue(_e,nr);if(!Ut)continue;let et=Kg(_e,E,nr,Q.get(Ut)?.text??"");if(et.length)Ut.forks=et}return a.onTiming?.("body",performance.now()-Ir),v.slice(Mt)};if(Ke){S=!1;let _e=[],qe=new Set,Dt=u.withIndex((tt)=>{Gg(tt,E);for(let Wt of tt.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())k.set(Wt.id,Wt);let Qt=new Set(tt.query(`SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}`).all(...E.sessionBindings).map((Wt)=>Wt.id)),er=(Wt)=>{if(qe.has(Wt.id))return;qe.add(Wt.id);let $o=Wt.forked_from_id?k.get(Wt.forked_from_id):void 0;if($o)er($o);if(Qt.has(Wt.id))_e.push(Wt)};for(let Wt of k.values())er(Wt);return(tt.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
464
+ WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(a.session_id,a.doc,a.seq,a.part,...o.bindings).filter((p)=>{if(a.seq===0)return p.title===u;if(!p.body)return!1;let f=JSON.parse(p.body);return Je(f,!0).some((h)=>h.part===a.part&&h.kind===uo[a.kind]&&h.text===u)}).map((p)=>p.session_id)}function bH(e,o){let a=o?e:Ct(e);if(a.length===e.length)return{normalized:a,starts:void 0,ends:void 0};let u="",m=[],p=[],f=0;for(let h of e){let I=o?h:Ct(h);u+=I;for(let E=0;E<I.length;E++)m.push(f),p.push(f+h.length);f+=h.length}return{normalized:u,starts:m,ends:p}}function ed(e,o){if(o.regex){let I=new RegExp(o.regex.source,`${o.regex.flags}g`),E=[];for(let S of e.matchAll(I)){if(o.wholeWord&&!iM(e,S.index,S.index+S[0].length))continue;E.push([S.index,S.index+S[0].length])}return E.length?E:void 0}let{normalized:a,starts:u,ends:m}=bH(e,o.caseSensitive),p=(I)=>{let E=o.caseSensitive?I.text:Ct(I.text),S=[],R=a.indexOf(E);while(R>=0&&E){let k=u?u[R]:R,P=m?m[R+E.length-1]:R+E.length,v=k===0||k!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(k-1,k))||/[a-z0-9][A-Z]/.test(e.slice(k-1,k+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(I.text));if(k!==void 0&&P!==void 0&&(!I.prefix||v)&&(!o.wholeWord||iM(e,k,P)))S.push([k,P]);R=a.indexOf(E,R+Math.max(1,E.length))}return S};if(!o.branches.length)return[];let f=[],h=!1;for(let I of o.branches){if(I.exclude.some((S)=>p(S).length))continue;let E=I.include.map(p);if(E.some((S)=>!S.length))continue;h=!0,f.push(...E.flat())}return h?f:void 0}function iM(e,o,a){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(a===e.length||!u.test(e.slice(a,a+1)))}function td(e,o){let a=e.split(`
465
+ `),u=new Set,m=0,p=a.map((f,h)=>{let I=m;if(o.some(([E,S])=>E<=I+f.length&&S>=I))for(let E=Math.max(0,h-1);E<=Math.min(a.length-1,h+1);E++)u.add(E);return m+=f.length+1,I});if(!u.size)u.add(0);return[...u].sort((f,h)=>f-h).slice(0,5).map((f)=>{let h=a[f]??"",I=p[f]??0,E=o.filter(([P,v])=>v>I&&P<I+h.length),S=Math.max(0,(E[0]?.[0]??I)-I-100),R=h.slice(S,S+300),k=E.map(([P,v])=>[Math.max(0,P-I-S),Math.min(R.length,v-I-S)]);return{text:R,line:f+1,ranges:k.filter(([P,v])=>P<v)}})}var aM=3;function EH(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 uM(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function SH(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let a=JSON.parse(Buffer.from(e,"base64url").toString());if(a&&typeof a==="object"&&"offset"in a&&"key"in a&&"now"in a&&a.key===o&&typeof a.offset==="number"&&Number.isSafeInteger(a.offset)&&a.offset>=0&&typeof a.now==="number"&&Number.isFinite(a.now)){let u="window"in a?a.window:0,m="seen"in a?a.seen:[],p="emitted"in a?a.emitted:[],f="after"in a?a.after:void 0;if(f!==void 0&&!EH(f))throw Error("invalid best cursor");let h=(I)=>Array.isArray(I)&&I.every((E)=>typeof E==="string"&&E.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&h(m)&&h(p))return{offset:a.offset,key:o,now:a.now,window:u,seen:m,emitted:p,after:f}}}catch{}throw Error("invalid search cursor")}function zn(e,o){let a=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return SH(e.cursor,a)}async function Yr(e,o,a){let u="search"in e?e.search:e,m=performance.now(),p=($e)=>{if(!a.signal?.aborted)a.onEvent($e)};if(a.signal?.aborted)return;let f=zn(o,a.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let h=Yl(o,{now:f.now});if(h.error){p({type:"error",...h.error});return}if(h.currentSession){if(!a.sessionID){p({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}h.filters.sessionID=[a.sessionID]}if(!o.deep&&h.regex?.deepScan){p({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),a.signal?.aborted)return;let I=performance.now(),E=u.withIndex(($e)=>Xv($e,h));if(!E){p({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}a.onTiming?.("plan",performance.now()-I);let S=E.partial,R=f.after,k=new Map,P=new Map,v=[],_=!1,Q=new Map,L=new WeakMap,V=new Map,J=new Map,{offset:Z,window:ne}=f,z=[...f.seen],oe=[...f.emitted],fe=!1,Ae=Math.max(1,Math.min(200,o.limit??30)),Ge=Math.min(E.candidateLimit??2000,o.group==="none"?Gg:Math.min(2000,Math.max(Gg,Ae*32))),ee=($e,_e)=>{let Dt=k.get(_e);if(Dt)return Dt;let lt=$e.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(_e);if(lt)k.set(_e,lt);return lt??void 0},ue=($e,_e,Dt)=>{if(a.allowedSessionIDs&&!a.allowedSessionIDs.has(_e.session_id))return;if(a.excludeEntry?.sessionID===_e.session_id&&a.excludeEntry.seq===_e.seq)return;let lt=ee($e,_e.session_id);if(!lt)return;let Mt=uo[_e.kind];if(!Mt)return;let Ir=lt.title;if(_e.seq!==0){let rt=`${_e.session_id}:${_e.seq}`,Xt=J.get(rt);if(!Xt){let dn=Dt?void 0:$e.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(_e.session_id,_e.seq);if(!Dt&&!dn)return;let Wt=Dt??JSON.parse(dn?.body??"null");Xt=Je(Wt,!0),J.set(rt,Xt)}let er=Xt.find((dn)=>dn.part===_e.part&&dn.kind===Mt);if(!er)return;Ir=er.text}let nr=ed(Ir,h);if(!nr)return;let Ut=P.get(lt.id);if(Ut===void 0)Ut=$e.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,P.set(lt.id,Ut);let tt=_e.seq>0&&_e.seq<=Ut;if(h.filters.compacted!==void 0&&tt!==h.filters.compacted)return;let Pt={sessionID:lt.id,seq:_e.seq,time:_e.time,field:Mt,tool:_e.tool??void 0,isError:Boolean(_e.err),model:_e.model??void 0,snippet:[],score:Zv(_e.relevance,Mt,_e.time,f.now),flags:{archived:lt.archived_at!==null,compacted:tt,partial:Ir.length>Ki+Qi}};return Q.set(Pt,{text:Ir,ranges:nr}),v.push(Pt),_=!0,V.set(Pt,{doc:_e.doc,part:_e.part}),Pt},we=($e)=>{let _e=performance.now(),Dt=[...$e].sort((tt,Pt)=>tt.time-Pt.time||tt.sessionID.localeCompare(Pt.sessionID)),lt=[],Mt=new Map;for(let tt of Dt){let Pt=V.get(tt),Xt=k.get(tt.sessionID),er=new Set;while(Xt?.forked_from_id&&Xt.forked_from_seq!==null&&tt.seq<=Xt.forked_from_seq&&!er.has(Xt.id))er.add(Xt.id),Xt=k.get(Xt.forked_from_id)??u.withIndex(($o)=>ee($o,Xt?.forked_from_id??""));let dn=`${Xt?.id??tt.sessionID}:${tt.seq}:${Pt?.part}:${Pt?.doc}`,Wt=Mt.get(dn);if(Wt){if(Wt.sessionID!==tt.sessionID)Wt.forks=[...new Set([...Wt.forks??[],tt.sessionID])]}else Mt.set(dn,tt),lt.push(tt)}let Ir=[],nr=new Map,Ut=new Map;for(let tt of lt){let Pt=`${tt.sessionID}:${tt.seq}`,rt=Ut.get(Pt);if(!rt){Ut.set(Pt,tt),L.set(tt,[tt]);continue}let Xt=[...L.get(rt)??[rt],tt],er=tt.score>rt.score?tt:rt;if(er.forks=[...new Set([...rt.forks??[],...tt.forks??[]])],!er.forks.length)er.forks=void 0;er.flags={archived:rt.flags.archived||tt.flags.archived,compacted:rt.flags.compacted||tt.flags.compacted,partial:rt.flags.partial||tt.flags.partial},Ut.set(Pt,er),L.set(er,Xt)}for(let tt of Ug([...Ut.values()],o.sort??"best")){let Pt=k.get(tt.sessionID);if(!Pt)continue;let rt=o.group==="none"?void 0:nr.get(Pt.id);if(!rt)rt={session:{id:Pt.id,title:Pt.title,projectID:Pt.project_id,updated:Pt.updated},hits:[],more:0,...S&&o.group!=="none"?{moreIsLowerBound:!0}:{}},Ir.push(rt),nr.set(Pt.id,rt);if(rt.hits.length<aM||o.group==="none")rt.hits.push(tt);else rt.more++}return a.onTiming?.("group",performance.now()-_e),Ir},Ve=($e)=>{for(let _e of $e)for(let Dt of _e.hits){if(a.allowedSessionIDs&&Dt.forks)Dt.forks=Dt.forks.filter((Ir)=>a.allowedSessionIDs?.has(Ir));let lt=performance.now(),Mt=new Map;for(let Ir of L.get(Dt)??[Dt]){let nr=Q.get(Ir);if(!nr)continue;for(let Ut of td(nr.text,nr.ranges)){let tt=`${Ut.line}:${Ut.text}`,Pt=Mt.get(tt);if(!Pt)Mt.set(tt,Ut);else Pt.ranges=[...new Map([...Pt.ranges,...Ut.ranges].map((rt)=>[rt.join(":"),rt])).values()]}}Dt.snippet=[...Mt.values()],a.onTiming?.("snippet",performance.now()-lt)}},je=o.deep||E.scan,Qt=($e,_e)=>{let Dt=ee($e,_e.session_id);if(!Dt)return[];let lt=sM($e,E,_e,o.group==="none",Dt.forked_from_id!==null,a.onTiming);if(E.candidateLimit&&lt.length>E.candidateLimit)lt.length=E.candidateLimit,S=!0;let Mt=v.length,Ir=performance.now();for(let nr of lt){if(a.signal?.aborted)break;let Ut=ue($e,nr);if(!Ut)continue;let tt=Hg($e,E,nr,Q.get(Ut)?.text??"");if(tt.length)Ut.forks=tt}return a.onTiming?.("body",performance.now()-Ir),v.slice(Mt)};if(je){S=!1;let $e=[],_e=new Set,Dt=u.withIndex((rt)=>{Kg(rt,E);for(let Wt of rt.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())k.set(Wt.id,Wt);let Xt=new Set(rt.query(`SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}`).all(...E.sessionBindings).map((Wt)=>Wt.id)),er=(Wt)=>{if(_e.has(Wt.id))return;_e.add(Wt.id);let $o=Wt.forked_from_id?k.get(Wt.forked_from_id):void 0;if($o)er($o);if(Xt.has(Wt.id))$e.push(Wt)};for(let Wt of k.values())er(Wt);return(rt.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
466
466
  SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}
467
- )`).get(...E.sessionBindings)?.n??0)+Qt.size})??0,pt=0,Mt=0,Ir=0;if(h.regex?.deepScan)p({type:"groups",groups:[]});let nr=new Set,Ut=new Set,et=new Map,Pt=()=>{let tt=$e(v),Qt=[];for(let er of tt){let dn=er.session.id,Wt=o.group==="none"?void 0:et.get(dn);if(o.group!=="none"&&Ut.has(dn)&&!Wt)continue;if(!Wt){if(Ut.add(dn),Mt<f.offset){Mt++;continue}if(Ir>=ke){fe=!0;break}Ir++,Z++}if(o.group!=="none"){let $o=(Wt?.count??0)+er.hits.length+er.more;er.hits=er.hits.slice(0,oM-(Wt?.shown??0));let Su=(Wt?.shown??0)+er.hits.length;er.more=$o-Su,et.set(dn,{shown:Su,count:$o})}Qt.push(er)}if(Qt.length)gt(Qt),p({type:"groups",groups:Qt});v.length=0,Q.clear(),V.clear(),J.clear()};for(let tt of _e){if(a.signal?.aborted||fe)break;let Qt=-1,er;for(;;){if(a.signal?.aborted||fe)break;let dn=u.withIndex((Wt)=>{let $o=Wt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(tt.id,Math.max(0,Qt));if(Qt<0)$o.unshift({seq:0,time:tt.updated,body:null});for(let Ci of $o){if(a.signal?.aborted)break;let wu=Ci.body?JSON.parse(Ci.body):void 0;if(wu?.type==="assistant")er=wu.model;let pM=wu?Je(wu,!0):[{part:0,kind:"title",text:tt.title}];for(let Do of pM){if(a.signal?.aborted)break;let Ns={session_id:tt.id,seq:Ci.seq,part:Do.part,doc:Number(BigInt(Bun.hash(Do.text))&0x1fffffffffffffn),kind:Be[Do.kind],tool:Do.tool??null,err:Number(Do.err??!1),model:Do.model??(Do.tool?er:void 0)??null,time:Ci.time,relevance:-1};if(!Wt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
468
- JOIN store.sessions s ON s.id=r.session_id WHERE ${E.where}`).get(Ns.session_id,Ns.seq,Ns.kind,Ns.tool,Ns.err,Ns.model,Ns.time,...E.bindings))continue;let oi=tt,zg=new Set;while(oi.forked_from_id&&oi.forked_from_seq!==null&&Ci.seq<=oi.forked_from_seq&&!zg.has(oi.id)){zg.add(oi.id);let Tu=k.get(oi.forked_from_id);if(!Tu)break;oi=Tu}let Vg=`${oi.id}:${Ci.seq}:${Do.part}:${Bun.hash(Do.text)}`;if(nr.has(Vg))continue;let Jg=ue(Wt,Ns,wu);if(Jg){if(nr.add(Vg),E.forks){let Tu=Wt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(tt.id,Ci.seq,Do.part);if(Tu){let Qg=Kg(Wt,E,{...Ns,doc:Tu.doc},Do.text);if(Qg.length)Jg.forks=Qg}}}}}let Su=$o.at(-1);if(Su)Qt=Su.seq;return $o.length});if(dn===void 0){p({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(pt+=dn,p({type:"progress",scanned:pt,total:Dt}),a.signal?.aborted)return;if(Pt(),!dn||fe)break;await Bun.sleep(0)}}}else u.withIndex((_e)=>{if(S=Xv(_e,E,a.onTiming)||S,h.regex?h.regex.literals.every((pt)=>pt.some((Mt)=>[...Mt].length<3)):h.branches.some((pt)=>pt.include.length>0&&pt.include.every((Mt)=>[...Mt.text].length<3)))_e.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let pt=Yv(_e,E,o.group==="none",f.now,a.onTiming);if(S||=E.partial,E.candidateLimit&&pt.length>E.candidateLimit)pt.length=E.candidateLimit,S=!0;let Mt=[];for(let nr of pt){if(a.signal?.aborted)return;let Ut=Mt[ke]?.key.score;if(Ut!==void 0&&nr.score+0.000000000001<Ut)break;let et=v.length,Pt=Zt(_e,nr);v.splice(et);let tt=jg([...Pt],"best")[0];if(!tt)continue;let Qt={score:tt.score,sessionID:tt.sessionID,seq:o.group==="none"?tt.seq:0};if(f.after&&sM(Qt,f.after)<=0)continue;if(Mt.push({key:Qt,hits:Pt}),Mt.sort((er,dn)=>sM(er.key,dn.key)),Mt.length>ke+1)Mt.length=ke+1}fe=Mt.length>ke;let Ir=Mt.slice(0,ke);for(let nr of Ir)v.push(...nr.hits);R=Ir.at(-1)?.key;return}let Dt=0;for(;;){if(a.signal?.aborted)return;let pt=eM(_e,E,ne,Ee,a.onTiming),Mt=E.candidateLimit!==void 0&&ne+pt>=E.candidateLimit;S||=Mt;let Ir=tM(_e,o,Z,ke-Dt+1,f.now,z,a.onTiming);fe=Ir.length>ke-Dt;let nr=Ir.slice(0,ke-Dt);if(!nr.length){if(pt<Ee||Mt){fe=!1;break}ne+=pt,Z=0,z=[...new Set([...z,...oe])],oe=[];continue}for(let Ut of nr)if(Z++,Zt(_e,Ut).length){if(Dt++,o.group!=="none")oe.push(Ut.session_id)}if(Dt>=ke){fe||=!Mt&&pt>=Ee;break}if(!fe){if(pt<Ee||Mt)break;ne+=pt,Z=0,z=[...new Set([...z,...oe])],oe=[]}}});if(a.signal?.aborted)return;if(!Ke){let _e=$e(v);gt(_e),p({type:"groups",groups:_e})}if(!_){let _e=h.branches.flatMap((qe)=>qe.include).find((qe)=>qe.fuzzy)?.text;if(_e)p({type:"suggest",terms:u.withIndex((qe)=>Fg(qe,_e))??[]})}p({type:"done",cursor:fe?Buffer.from(JSON.stringify(!Ke&&o.sort!=="recent"?{...f,offset:0,window:0,seen:[],emitted:[],after:R}:{...f,offset:Z,window:ne,seen:z,emitted:oe})).toString("base64url"):void 0,tookMs:performance.now()-m,partial:S,index:u.status()})}function Yo(e,o){return e.withIndex((a)=>Fg(a,o))??[]}function iM(e,o,a){let u=T({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(g([s({maxLength:2000}),On()])),scope:n(g([i("session"),i("project"),i("all"),i(""),On()])),fields:n(g([H(sr({type:"string",enum:[...Wn]})),On()])),tool:n(g([s(),On()])),isError:n(g([N(),On()])),after:n(g([s(),te(),On()])),before:n(g([s(),te(),On()])),limit:n(g([x(),On()])),session:n(g([s(),On()])),seq:n(g([x(),On()])),around:n(g([x(),On()]))}),async execute(m,p,f){let h={query:p.query?.trim(),scope:p.scope||void 0,fields:p.fields?.length?p.fields:void 0,tool:p.tool?.trim(),isError:p.isError??void 0,after:p.after??void 0,before:p.before??void 0,limit:p.limit||void 0,session:p.session?.trim(),seq:p.seq??void 0,around:p.around??void 0},I=h.query?.trim(),E=!I&&Boolean(h.session?.trim())&&Number.isSafeInteger(h.seq)&&(h.seq??0)>=1;if(E&&h.around!==void 0&&(!Number.isInteger(h.around)||h.around<0||h.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(h.scope&&!["session","project","all"].includes(h.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(f?.aborted)throw Error("History search cancelled");let S=e.sessions().find((ee)=>ee.id===a);if(!S)throw Error("History session is unavailable");let R=(ee)=>{if(ee===void 0||ee===0||typeof ee==="string"&&!ee.trim())return;if(typeof ee==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(ee))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let ue=typeof ee==="number"?ee:Date.parse(ee);if(!Number.isFinite(ue)||Math.abs(ue)>8640000000000000){if(typeof ee==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return ue},k=E?void 0:R(h.after),P=E?void 0:R(h.before);if(k!==void 0&&P!==void 0&&k>=P)throw Error("after must precede before");let v=[];if(E&&h.session&&h.seq!==void 0){if(!e.sessions().find((Ke)=>Ke.id===h.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let ue=h.around??3,$e=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(h.session,Math.max(1,h.seq-ue),h.seq+ue);if(!$e.some((Ke)=>Ke.seq===h.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:$e.map((Ke)=>{let Zt={...JSON.parse(Ke.body),seq:Ke.seq,time:Ke.time};return`[seq=${Ke.seq}]
469
- ${Je(Zt,!0).map((_e)=>`${_e.kind}: ${_e.kind==="error"?_e.text.replace(/^(?:error:\s*)+/i,""):_e.text}`).join(`
467
+ )`).get(...E.sessionBindings)?.n??0)+Xt.size})??0,lt=0,Mt=0,Ir=0;if(h.regex?.deepScan)p({type:"groups",groups:[]});let nr=new Set,Ut=new Set,tt=new Map,Pt=()=>{let rt=we(v),Xt=[];for(let er of rt){let dn=er.session.id,Wt=o.group==="none"?void 0:tt.get(dn);if(o.group!=="none"&&Ut.has(dn)&&!Wt)continue;if(!Wt){if(Ut.add(dn),Mt<f.offset){Mt++;continue}if(Ir>=Ae){fe=!0;break}Ir++,Z++}if(o.group!=="none"){let $o=(Wt?.count??0)+er.hits.length+er.more;er.hits=er.hits.slice(0,aM-(Wt?.shown??0));let Su=(Wt?.shown??0)+er.hits.length;er.more=$o-Su,tt.set(dn,{shown:Su,count:$o})}Xt.push(er)}if(Xt.length)Ve(Xt),p({type:"groups",groups:Xt});v.length=0,Q.clear(),V.clear(),J.clear()};for(let rt of $e){if(a.signal?.aborted||fe)break;let Xt=-1,er;for(;;){if(a.signal?.aborted||fe)break;let dn=u.withIndex((Wt)=>{let $o=Wt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(rt.id,Math.max(0,Xt));if(Xt<0)$o.unshift({seq:0,time:rt.updated,body:null});for(let Ci of $o){if(a.signal?.aborted)break;let wu=Ci.body?JSON.parse(Ci.body):void 0;if(wu?.type==="assistant")er=wu.model;let fM=wu?Je(wu,!0):[{part:0,kind:"title",text:rt.title}];for(let Do of fM){if(a.signal?.aborted)break;let Ns={session_id:rt.id,seq:Ci.seq,part:Do.part,doc:Number(BigInt(Bun.hash(Do.text))&0x1fffffffffffffn),kind:Be[Do.kind],tool:Do.tool??null,err:Number(Do.err??!1),model:Do.model??(Do.tool?er:void 0)??null,time:Ci.time,relevance:-1};if(!Wt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
468
+ JOIN store.sessions s ON s.id=r.session_id WHERE ${E.where}`).get(Ns.session_id,Ns.seq,Ns.kind,Ns.tool,Ns.err,Ns.model,Ns.time,...E.bindings))continue;let oi=rt,Vg=new Set;while(oi.forked_from_id&&oi.forked_from_seq!==null&&Ci.seq<=oi.forked_from_seq&&!Vg.has(oi.id)){Vg.add(oi.id);let Tu=k.get(oi.forked_from_id);if(!Tu)break;oi=Tu}let Jg=`${oi.id}:${Ci.seq}:${Do.part}:${Bun.hash(Do.text)}`;if(nr.has(Jg))continue;let Qg=ue(Wt,Ns,wu);if(Qg){if(nr.add(Jg),E.forks){let Tu=Wt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(rt.id,Ci.seq,Do.part);if(Tu){let Xg=Hg(Wt,E,{...Ns,doc:Tu.doc},Do.text);if(Xg.length)Qg.forks=Xg}}}}}let Su=$o.at(-1);if(Su)Xt=Su.seq;return $o.length});if(dn===void 0){p({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=dn,p({type:"progress",scanned:lt,total:Dt}),a.signal?.aborted)return;if(Pt(),!dn||fe)break;await Bun.sleep(0)}}}else u.withIndex(($e)=>{if(S=eM($e,E,a.onTiming)||S,h.regex?h.regex.literals.every((lt)=>lt.some((Mt)=>[...Mt].length<3)):h.branches.some((lt)=>lt.include.length>0&&lt.include.every((Mt)=>[...Mt.text].length<3)))$e.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let lt=tM($e,E,o.group==="none",f.now,a.onTiming);if(S||=E.partial,E.candidateLimit&&lt.length>E.candidateLimit)lt.length=E.candidateLimit,S=!0;let Mt=[];for(let nr of lt){if(a.signal?.aborted)return;let Ut=Mt[Ae]?.key.score;if(Ut!==void 0&&nr.score+0.000000000001<Ut)break;let tt=v.length,Pt=Qt($e,nr);v.splice(tt);let rt=Ug([...Pt],"best")[0];if(!rt)continue;let Xt={score:rt.score,sessionID:rt.sessionID,seq:o.group==="none"?rt.seq:0};if(f.after&&uM(Xt,f.after)<=0)continue;if(Mt.push({key:Xt,hits:Pt}),Mt.sort((er,dn)=>uM(er.key,dn.key)),Mt.length>Ae+1)Mt.length=Ae+1}fe=Mt.length>Ae;let Ir=Mt.slice(0,Ae);for(let nr of Ir)v.push(...nr.hits);R=Ir.at(-1)?.key;return}let Dt=0;for(;;){if(a.signal?.aborted)return;let lt=nM($e,E,ne,Ge,a.onTiming),Mt=E.candidateLimit!==void 0&&ne+lt>=E.candidateLimit;S||=Mt;let Ir=oM($e,o,Z,Ae-Dt+1,f.now,z,a.onTiming);fe=Ir.length>Ae-Dt;let nr=Ir.slice(0,Ae-Dt);if(!nr.length){if(lt<Ge||Mt){fe=!1;break}ne+=lt,Z=0,z=[...new Set([...z,...oe])],oe=[];continue}for(let Ut of nr)if(Z++,Qt($e,Ut).length){if(Dt++,o.group!=="none")oe.push(Ut.session_id)}if(Dt>=Ae){fe||=!Mt&&lt>=Ge;break}if(!fe){if(lt<Ge||Mt)break;ne+=lt,Z=0,z=[...new Set([...z,...oe])],oe=[]}}});if(a.signal?.aborted)return;if(!je){let $e=we(v);Ve($e),p({type:"groups",groups:$e})}if(!_){let $e=h.branches.flatMap((_e)=>_e.include).find((_e)=>_e.fuzzy)?.text;if($e)p({type:"suggest",terms:u.withIndex((_e)=>jg(_e,$e))??[]})}p({type:"done",cursor:fe?Buffer.from(JSON.stringify(!je&&o.sort!=="recent"?{...f,offset:0,window:0,seen:[],emitted:[],after:R}:{...f,offset:Z,window:ne,seen:z,emitted:oe})).toString("base64url"):void 0,tookMs:performance.now()-m,partial:S,index:u.status()})}function Yo(e,o){return e.withIndex((a)=>jg(a,o))??[]}function cM(e,o,a){let u=T({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(g([s({maxLength:2000}),On()])),scope:n(g([i("session"),i("project"),i("all"),i(""),On()])),fields:n(g([F(sr({type:"string",enum:[...Wn]})),On()])),tool:n(g([s(),On()])),isError:n(g([N(),On()])),after:n(g([s(),te(),On()])),before:n(g([s(),te(),On()])),limit:n(g([x(),On()])),session:n(g([s(),On()])),seq:n(g([x(),On()])),around:n(g([x(),On()]))}),async execute(m,p,f){let h={query:p.query?.trim(),scope:p.scope||void 0,fields:p.fields?.length?p.fields:void 0,tool:p.tool?.trim(),isError:p.isError??void 0,after:p.after??void 0,before:p.before??void 0,limit:p.limit||void 0,session:p.session?.trim(),seq:p.seq??void 0,around:p.around??void 0},I=h.query?.trim(),E=!I&&Boolean(h.session?.trim())&&Number.isSafeInteger(h.seq)&&(h.seq??0)>=1;if(E&&h.around!==void 0&&(!Number.isInteger(h.around)||h.around<0||h.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(h.scope&&!["session","project","all"].includes(h.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(f?.aborted)throw Error("History search cancelled");let S=e.sessions().find((ee)=>ee.id===a);if(!S)throw Error("History session is unavailable");let R=(ee)=>{if(ee===void 0||ee===0||typeof ee==="string"&&!ee.trim())return;if(typeof ee==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(ee))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let ue=typeof ee==="number"?ee:Date.parse(ee);if(!Number.isFinite(ue)||Math.abs(ue)>8640000000000000){if(typeof ee==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return ue},k=E?void 0:R(h.after),P=E?void 0:R(h.before);if(k!==void 0&&P!==void 0&&k>=P)throw Error("after must precede before");let v=[];if(E&&h.session&&h.seq!==void 0){if(!e.sessions().find((je)=>je.id===h.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let ue=h.around??3,we=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(h.session,Math.max(1,h.seq-ue),h.seq+ue);if(!we.some((je)=>je.seq===h.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:we.map((je)=>{let Qt={...JSON.parse(je.body),seq:je.seq,time:je.time};return`[seq=${je.seq}]
469
+ ${Je(Qt,!0).map(($e)=>`${$e.kind}: ${$e.kind==="error"?$e.text.replace(/^(?:error:\s*)+/i,""):$e.text}`).join(`
470
470
  `).slice(0,4000)}`}).join(`
471
471
 
472
- `)||"No history content"}],details:{groups:v,count:$e.length}}}if(!I)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let _=Number.isFinite(h.limit)?Math.max(1,Math.min(30,Math.trunc(h.limit??10))):10,Q=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(a)?.seq,L=new Set(e.sessions().filter((ee)=>{if(h.scope==="session")return ee.id===a;if((h.scope??"project")==="project"&&S.projectID)return ee.projectID===S.projectID;return!0}).map((ee)=>ee.id)),V={q:I,filters:{tools:h.tool?.trim()?[h.tool.trim()]:void 0,isError:h.isError,after:k,before:P},group:"none",limit:_},J=Yl(V);if(J.error)throw Error(J.error.message);if(h.fields?.length){if(J.filters.fields=h.fields.filter((ee)=>(ee in Be)),J.filters.fields.length!==h.fields.length)throw Error("Unknown search field")}if((h.scope??"project")==="session")J.filters.sessionID=[a];else if((h.scope??"project")==="project"&&S.projectID)J.filters.projectID=[S.projectID];let Z=o.status().state!=="ready",ne=!1;if(!Z){let ee=J.filters.fields??Object.keys(Be).filter((gt)=>(gt in Be)),ue=ee.filter((gt)=>gt!=="title"),$e=ue.length?[ue]:[];if(ee.includes("title"))$e.push(["title"]);for(let gt of $e){if(v.length>=_&&ne)break;if(await Yr(o,{...V,limit:Math.max(1,_-v.length),filters:{...J.filters,fields:gt}},{signal:f,excludeEntry:Q===void 0?void 0:{sessionID:a,seq:Q},sessionID:a,allowedSessionIDs:L,onEvent(Ke){if(Ke.type==="groups")v.push(...Ke.groups);if(Ke.type==="done")ne||=Boolean(Ke.cursor)||Ke.partial;if(Ke.type==="error")if(Ke.code==="unavailable")Z=!0;else throw Error(Ke.message)}}),Z)break}}let z=[],oe=0;if(Z){v.length=0;let ee=performance.now()+2000;e:for(let ue of e.sessions()){if(!L.has(ue.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(ue.id))continue;if(J.filters.projectID&&(!ue.projectID||!J.filters.projectID.includes(ue.projectID)))continue;let $e=Number.MAX_SAFE_INTEGER,gt=!0;for(;;){let Ke=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(ue.id,$e);if(gt)Ke.push({body:"null",seq:0,time:ue.updated}),gt=!1;if(!Ke.length)break;for(let Zt of Ke){if(Zt.seq>0)$e=Zt.seq;if(f?.aborted)throw Error("History search cancelled");if(oe>=1e4||performance.now()>ee){ne=!0;break e}if(oe++,ue.id===a&&Zt.seq===Q)continue;if(J.filters.after!==void 0&&Zt.time<J.filters.after||J.filters.before!==void 0&&Zt.time>=J.filters.before)continue;let _e=Zt.seq===0?[{part:0,kind:"title",text:ue.title,tool:void 0,err:!1}]:Je(JSON.parse(Zt.body),!0);for(let qe of _e){if(J.filters.fields&&!J.filters.fields.includes(qe.kind))continue;if(J.filters.tools&&(!qe.tool||!J.filters.tools.includes(qe.tool)))continue;if(J.filters.isError!==void 0&&Boolean(qe.err)!==J.filters.isError)continue;let Dt=ed(qe.text,J);if(!Dt)continue;if(v.length>=_&&qe.kind!=="title"){ne=!0;break e}(qe.kind==="title"?z:v).push({session:{id:ue.id,title:ue.title,projectID:ue.projectID,updated:ue.updated},more:0,hits:[{sessionID:ue.id,seq:Zt.seq,time:Zt.time,field:qe.kind,tool:qe.tool,isError:Boolean(qe.err),snippet:td(qe.text,Dt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(f?.aborted)throw Error("History search cancelled");if(z.length>Math.max(0,_-v.length))ne=!0;if(v.push(...z.slice(0,_)),v.sort((ee,ue)=>Number(ee.hits[0]?.field==="title")-Number(ue.hits[0]?.field==="title")),v.length>_)ne=!0;v.length=Math.min(v.length,_);let fe=new Map;for(let ee of v)for(let ue of ee.hits){let $e=fe.get(ee.session.id)??[];$e.push(`[${ee.session.title.replace(/[\r\n]/g," ")} \xB7 ${ue.sessionID} \xB7 ${ue.seq} \xB7 ${new Date(ue.time).toISOString()} \xB7 ${ue.field}${ue.tool?`/${ue.tool}`:""}]
473
- ${ue.snippet.slice(0,3).map((gt)=>{let Ke=gt.text;for(let[Zt,_e]of[...gt.ranges].sort((qe,Dt)=>Dt[0]-qe[0]))Ke=`${Ke.slice(0,Zt)}\u3010${Ke.slice(Zt,_e)}\u3011${Ke.slice(_e)}`;return Ke}).join(`
474
- `)}`),fe.set(ee.session.id,$e)}let ke="";if(Z){if(ke="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")ke="\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=v.reduce((ee,ue)=>ee+ue.hits.length,0);return{content:[{type:"text",text:[ke,Z&&ne?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${oe} \u6761`:"",[...fe.values()].map((ee)=>ee.join(`
472
+ `)||"No history content"}],details:{groups:v,count:we.length}}}if(!I)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let _=Number.isFinite(h.limit)?Math.max(1,Math.min(30,Math.trunc(h.limit??10))):10,Q=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(a)?.seq,L=new Set(e.sessions().filter((ee)=>{if(h.scope==="session")return ee.id===a;if((h.scope??"project")==="project"&&S.projectID)return ee.projectID===S.projectID;return!0}).map((ee)=>ee.id)),V={q:I,filters:{tools:h.tool?.trim()?[h.tool.trim()]:void 0,isError:h.isError,after:k,before:P},group:"none",limit:_},J=Yl(V);if(J.error)throw Error(J.error.message);if(h.fields?.length){if(J.filters.fields=h.fields.filter((ee)=>(ee in Be)),J.filters.fields.length!==h.fields.length)throw Error("Unknown search field")}if((h.scope??"project")==="session")J.filters.sessionID=[a];else if((h.scope??"project")==="project"&&S.projectID)J.filters.projectID=[S.projectID];let Z=o.status().state!=="ready",ne=!1;if(!Z){let ee=J.filters.fields??Object.keys(Be).filter((Ve)=>(Ve in Be)),ue=ee.filter((Ve)=>Ve!=="title"),we=ue.length?[ue]:[];if(ee.includes("title"))we.push(["title"]);for(let Ve of we){if(v.length>=_&&ne)break;if(await Yr(o,{...V,limit:Math.max(1,_-v.length),filters:{...J.filters,fields:Ve}},{signal:f,excludeEntry:Q===void 0?void 0:{sessionID:a,seq:Q},sessionID:a,allowedSessionIDs:L,onEvent(je){if(je.type==="groups")v.push(...je.groups);if(je.type==="done")ne||=Boolean(je.cursor)||je.partial;if(je.type==="error")if(je.code==="unavailable")Z=!0;else throw Error(je.message)}}),Z)break}}let z=[],oe=0;if(Z){v.length=0;let ee=performance.now()+2000;e:for(let ue of e.sessions()){if(!L.has(ue.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(ue.id))continue;if(J.filters.projectID&&(!ue.projectID||!J.filters.projectID.includes(ue.projectID)))continue;let we=Number.MAX_SAFE_INTEGER,Ve=!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(ue.id,we);if(Ve)je.push({body:"null",seq:0,time:ue.updated}),Ve=!1;if(!je.length)break;for(let Qt of je){if(Qt.seq>0)we=Qt.seq;if(f?.aborted)throw Error("History search cancelled");if(oe>=1e4||performance.now()>ee){ne=!0;break e}if(oe++,ue.id===a&&Qt.seq===Q)continue;if(J.filters.after!==void 0&&Qt.time<J.filters.after||J.filters.before!==void 0&&Qt.time>=J.filters.before)continue;let $e=Qt.seq===0?[{part:0,kind:"title",text:ue.title,tool:void 0,err:!1}]:Je(JSON.parse(Qt.body),!0);for(let _e of $e){if(J.filters.fields&&!J.filters.fields.includes(_e.kind))continue;if(J.filters.tools&&(!_e.tool||!J.filters.tools.includes(_e.tool)))continue;if(J.filters.isError!==void 0&&Boolean(_e.err)!==J.filters.isError)continue;let Dt=ed(_e.text,J);if(!Dt)continue;if(v.length>=_&&_e.kind!=="title"){ne=!0;break e}(_e.kind==="title"?z:v).push({session:{id:ue.id,title:ue.title,projectID:ue.projectID,updated:ue.updated},more:0,hits:[{sessionID:ue.id,seq:Qt.seq,time:Qt.time,field:_e.kind,tool:_e.tool,isError:Boolean(_e.err),snippet:td(_e.text,Dt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(f?.aborted)throw Error("History search cancelled");if(z.length>Math.max(0,_-v.length))ne=!0;if(v.push(...z.slice(0,_)),v.sort((ee,ue)=>Number(ee.hits[0]?.field==="title")-Number(ue.hits[0]?.field==="title")),v.length>_)ne=!0;v.length=Math.min(v.length,_);let fe=new Map;for(let ee of v)for(let ue of ee.hits){let we=fe.get(ee.session.id)??[];we.push(`[${ee.session.title.replace(/[\r\n]/g," ")} \xB7 ${ue.sessionID} \xB7 ${ue.seq} \xB7 ${new Date(ue.time).toISOString()} \xB7 ${ue.field}${ue.tool?`/${ue.tool}`:""}]
473
+ ${ue.snippet.slice(0,3).map((Ve)=>{let je=Ve.text;for(let[Qt,$e]of[...Ve.ranges].sort((_e,Dt)=>Dt[0]-_e[0]))je=`${je.slice(0,Qt)}\u3010${je.slice(Qt,$e)}\u3011${je.slice($e)}`;return je}).join(`
474
+ `)}`),fe.set(ee.session.id,we)}let Ae="";if(Z){if(Ae="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")Ae="\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 Ge=v.reduce((ee,ue)=>ee+ue.hits.length,0);return{content:[{type:"text",text:[Ae,Z&&ne?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${oe} \u6761`:"",[...fe.values()].map((ee)=>ee.join(`
475
475
 
476
476
  `)).join(`
477
477
 
478
- `),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${ne?"\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(`
479
- `)}],details:{groups:v,count:Ee}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var Hg="basalt.git-snapshot";async function aM(e,o,a){let u=o.projectID?e.store.project(o.projectID):void 0,m=u?.directory??process.cwd(),f=o.info().kind==="sub",h=()=>f||o.entries(0,["compaction"],!1).length>0,I=e.options.tools??ur({directory:u?.directory,records:()=>o.records,history:(R)=>e.resolveHistory(o.id,R),onTodos:(R)=>o.setTodos(R),shell:()=>e.serverShell(),hasCompacted:h});if(e.options.tools===void 0)I.push(iM(e.store,e.search,o.id));let E;if(u&&e.options.systemPrompt===void 0){let R=o.entries(0,["compaction"],!1).length,k=e.store.db,P=k.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(Hg,o.id),v;try{v=P?JSON.parse(P.value):void 0}catch{v=void 0}if(v?.compactions===R&&(v.summary===void 0||typeof v.summary==="string"))E=v.summary;else if(E=await iv(u.directory,a),!e.isClosed&&!a?.aborted)k.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(Hg,o.id,JSON.stringify({compactions:R,summary:E})),k.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(Hg)}let S=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:sv({project:u,globalInstructions:TH(e),git:E,shell:e.serverShell()});return{systemPrompt:S.map((R)=>R.detail).join(""),systemParts:S,tools:[...I,...e.tools.snapshot()],cwd:m}}var wH=[Eu(".basalt","AGENTS.md"),Eu(".agents","AGENTS.md"),Eu(".opencode","AGENTS.md"),Eu(".claude","CLAUDE.md"),Eu(".codex","AGENTS.md")];function TH(e){let o=e.options.homeDir??SH();for(let a of wH){let u=Eu(o,a);try{if(bH(u))return EH(u,"utf8")}catch{return}}return}class Zr{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new vg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Jl(Wg(e.dataDir,"basalt.db")),this.plugins=new mg(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Xl(this.plugins,()=>this.builtinToolNames()),this.search=new pg({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let a=this.open(o,"restore");this.sessions.set(o.id,a),this.restored.add(a)}}static async create(e){let o=new Zr(e);try{return await o.initialize(),o}catch(a){throw await o.close(),a}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Wg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Wg(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 Lv(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Ql(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>Ov(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((a)=>e||a.info().parentID===null).map((a)=>a.info()).filter((a)=>{let u=o.archive??"active";return u==="all"||a.archivedAt!==null===(u==="archived")}).sort((a,u)=>u.updated-a.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let a=this.get(e);if(!a)throw new t("History session is unavailable");return a.resolveHistory(o)}openStoredSession(e,o="restore"){let a=this.open(e,o);return this.sessions.set(e.id,a),this.emit({type:"session",session:a.info()}),a}create(e={}){let o=e.model??this.defaultModel;if(!Tn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let a=Date.now(),u={id:re("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:a,updated:a,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let m=this.open(u);return this.sessions.set(u.id,m),this.emit({type:"session",session:m.info()}),m}copyHistory(e,o,a){o={...o,archivedAt:null},this.store.copySession(e,o,a);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new y("no such session");let a=o.info(),u=a.projectID?this.store.project(a.projectID):void 0;return gv(a,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let a=[o.model,e.model,this.defaultModel].find((f)=>f!==void 0&&Tn(this.options.models,f)!==void 0),u=a?Tn(this.options.models,a):void 0;if(!a||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let m={id:re("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:a,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(m,e.needsRaw?Iv(e.records,u):e.records);let p=this.open(m);return this.sessions.set(m.id,p),this.emit({type:"session",session:p.info()}),p}truncateHistory(e,o){let a=this.sessions.get(e.id);if(!a)throw new y("no such session");if(a.assertWritable(),a.status==="busy")throw new ce;if(!Tn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);a.close();for(let f of this.sessions.values()){if(f.info().parentID!==e.id)continue;if(f.status==="busy")f.abort();f.close()}this.store.truncateSession(e,o);let u=[],m=this.store.lastEntry(e.id,"run");if(m?.type==="run"&&m.state==="start"){let f=this.store.records(e.id,m.seq).filter((h)=>h.raw);for(let h of Po(f)){if(h.result)continue;let{body:I,raw:E}=yl(h.call,"\u4E4B\u540E\u7684\u6D88\u606F\u88AB\u7528\u6237\u4FEE\u6539\uFF0C\u8FD9\u6B21\u8C03\u7528\u7684\u7ED3\u679C\u5DF2\u968F\u622A\u65AD\u4E22\u5F03\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\u3002");u.push(this.store.appendEntry(e.id,void 0,I,E))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let p=this.open(e,"replay");this.sessions.set(e.id,p),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let f of u)this.emit({type:"entry",sessionID:e.id,entry:f});return p}setArchived(e,o){let a=this.sessions.get(e);if(!a)throw new y("no such session");let u=a.info().parentID;if(!o&&u&&this.sessions.get(u)?.isArchived)throw new t("\u8BF7\u5148\u6062\u590D\u6240\u5C5E\u7236\u4F1A\u8BDD");let m=this.sessionTree(a);if(m.some((p)=>p.status==="busy"))throw new ce;if(a.isArchived===o)return a.info();this.store.setArchived(m.map((p)=>p.id),o?Date.now():null);for(let p of m)p.refreshArchive();for(let p of m)p.archiveChanged();return a.info()}sessionTree(e){let o=[e];for(let a=0;a<o.length;a++){let u=o[a];if(!u)continue;for(let m of this.sessions.values())if(m.info().parentID===u.id)o.push(m)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new y("no such session");if(o.status==="busy")throw new ce;let a=this.sessionTree(o).slice(1),u=()=>{for(let m of a)m.close(),this.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!a.length)return u();o.close();for(let m of a)m.close(),m.abort();return Promise.all(a.map((m)=>m.idle())).then(u)}open(e,o="create"){let a=e.id,u=new Bl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(m,p)=>aM(this,m,p)},{entry:(m)=>{this.emit({type:"entry",sessionID:a,entry:m})},entryRemoved:(m)=>{this.emit({type:"entry_removed",sessionID:a,seq:m})},aborted:()=>{this.emit({type:"aborted",sessionID:a})},draft:(m)=>this.emit({type:"draft",sessionID:a,parts:m}),changed:()=>{let m=this.sessions.get(a);if(m)this.emit({type:"session",session:m.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new Pi(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(!id.includes(e))throw new t(`Invalid shell type; must be ${id.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return Nv(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(a){console.error("runtime listener failed",a)}}}var Le={now:()=>Date.now(),after(e,o){let a=setTimeout(o,e);return()=>clearTimeout(a)}};var uM=1048576,cM=8;class Gt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,a,u){this.cwd=e;this.outputLimit=o;this.terminal=a;this.shellPreference=u}setTerminalObserver(e){this.terminal=e}start(e,o,a){let u=a?.observer,m=a?.clock??Le;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!a?.shellGuardApproved){let Q=gd(e);if(Q.length>0)throw Error(yd(Q))}if(this.list().filter((Q)=>Q.state==="running").length>=cM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${cM}\uFF09`);let f=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:h,isWindows:I}=Aa(e,f),E=Bun.spawn(h,{cwd:this.cwd,stdin:a?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!I,windowsHide:!0,env:{...process.env,...am(this.cwd)}}),S={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:E,started:m.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(S.id,S);let R=()=>{for(let Q of S.waiters.splice(0))Q()},k=async(Q,L)=>{let V=new Ol;for await(let Z of Q){let ne=V.decode(Z);S.output+=ne,u?.output(ne,L);let z=Buffer.from(S.output);if(z.length>uM){let oe=z.length-uM;while(oe<z.length&&(z[oe]??0)>>6===2)oe++;let fe=z.subarray(oe).toString(),ke=S.output.length-fe.length;S.unreadDroppedBytes+=Buffer.byteLength(S.output.slice(Math.max(0,S.readAt-S.dropped),ke)),S.output=fe,S.dropped+=ke}R()}let J=V.flush();if(S.output+=J,J)u?.output(J,L)},P,v=Promise.all([k(E.stdout,"stdout"),k(E.stderr,"stderr")]).catch((Q)=>{P=Q,this.kill(S)}),_=!1;if(S.done=(async()=>{if(S.code=await E.exited,S.timer?.(),this.kill(S),await v,P)throw P;if(S.state==="running")S.state="exited";if(_=!0,u?.end(S.state,S.code),!u&&S.state!=="killed")this.terminal?.(S);R()})().catch((Q)=>{if(S.state="exited",S.output+=`
480
- [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(Q)}]`,!_)u?.end(S.state,S.code);if(u)throw Q;if(!u)this.terminal?.(S,Q);R()}),o!==void 0)S.timer=m.after(o,()=>{if(S.state==="running")S.state="timeout",this.kill(S)});return S}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128)try{e.proc.kill()}catch{}}else process.kill(-e.proc.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,o,a=0,u=!1,m){let p=this.find(e),f=o?new RegExp(o):void 0,h=Date.now()+a;m?.throwIfAborted();while(p.state==="running"){m?.throwIfAborted();let k=p.output.slice(Math.max(0,p.readAt-p.dropped));if((f?f.test(k):!u)||Date.now()>=h)break;await new Promise((P,v)=>{let _=()=>{clearTimeout(L);let V=p.waiters.indexOf(Q);if(V>=0)p.waiters.splice(V,1);v(m?.reason)},Q=()=>{clearTimeout(L),m?.removeEventListener("abort",_);let V=p.waiters.indexOf(Q);if(V>=0)p.waiters.splice(V,1);P()},L=setTimeout(Q,Math.max(0,h-Date.now()));p.waiters.push(Q),m?.addEventListener("abort",_,{once:!0})})}m?.throwIfAborted();let I=p.unreadDroppedBytes;p.unreadDroppedBytes=0;let E=p.output.slice(Math.max(0,p.readAt-p.dropped));p.readAt=p.dropped+p.output.length;let S=E.slice(-this.outputLimit),R=I+Buffer.byteLength(E.slice(0,E.length-S.length));return{job:p,output:`${R?`[truncated ${R} bytes]
481
- `:""}${S}`}}async write(e,o,a=!1,u){let m=this.find(e);if(m.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let p=m.proc.stdin;if(!p||typeof p==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let f=await Qe(o,u);if(f)throw Error(f);p.write(o)}if(a)await p.end();else await p.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 rd=new WeakMap,nd=new WeakMap;function mr(e,o){let a=rd.get(e);if(!a)a=o(),rd.set(e,a);return a}function hr(e){nd.set(e,(nd.get(e)??0)+1)}function fr(e,o){let a=(nd.get(o)??1)-1;if(nd.set(o,a),a>0)return!1;if(o.close(),rd.get(e)===o)rd.delete(e);return!0}async function O(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function A(e,o){let a=e[o];if(!a)throw new t(`${o} is required`);return a}var jn=100,gr=1e4,RH=60000,kH=200,Cn=()=>s(),mM=()=>n(x({minimum:1,maximum:gr})),rm=()=>n(s({minLength:1,maxLength:128})),AH=g([l({click:g([Cn(),l({selector:Cn()})])}),l({type:l({label:Cn(),text:Cn()})}),l({waitText:Cn(),timeoutMs:mM()}),l({expectText:Cn(),within:n(Cn())}),l({waitSelector:Cn(),timeoutMs:mM()}),l({expectCount:l({selector:Cn(),n:x({minimum:0})})}),l({snapshot:l({selector:Cn(),depth:n(x({minimum:0,maximum:kH}))})}),l({expectCalls:l({onOpen:n(H(Cn())),onClose:n(x({minimum:0}))})}),l({expectValue:l({label:Cn(),value:Cn()})})]),PH=l({status:x({minimum:100,maximum:599}),body:Pr(),delayMs:n(x({minimum:0,maximum:gr}))}),CH=g([i("paths"),i("request"),i("verify"),i("ui_test"),i("list"),i("docs"),i("check"),i("load"),i("reload"),i("enable"),i("disable")]),$H=g([i("page"),i("tab"),i("card"),i("sidebar")]),Wi=l({action:CH,path:n(s({minLength:1,maxLength:4096})),method:n(Cn()),body:n(ks(Cn(),Pr())),importTimeoutMs:n(x({minimum:1,maximum:gr})),timeoutMs:n(x({minimum:1,maximum:RH})),sessionID:rm(),scope:n(g([i("user"),i("all")])),id:rm(),slot:rm(),view:rm(),codeBlock:rm(),kind:n($H),props:n(ks(Cn(),Pr())),context:n(ks(Cn(),Pr())),steps:n(H(AH,{maxItems:jn})),mockRoutes:n(ks(Cn(),PH)),topic:n(s({maxLength:100})),grep:n(s({minLength:1,maxLength:200}))});
482
- export{t,y,kt,Vr,Kr,Li,Qr,ir,qo,Xr,Wn,Oi,Ni,Di,Ht,Ui,Bi,Jr,Go,Fi,We,$i,mt,qt,Hn,j,zo,Qe,nt,H,n,l,sr,N,x,i,te,s,g,b,de,qn,jo,Vo,Ko,Qo,Te,T,ot,ht,C,F,q,Me,me,Gn,ar,Xo,Ce,c,le,it,lr,cr,ur,ft,ce,Jo,pr,dr,re,zn,Yr,Yo,Zr,Le,Gt,mr,hr,fr,O,A,Zo,jn,gr,Wi};
478
+ `),Ge===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 ${Ge} \u6761\uFF1B${ne?"\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(`
479
+ `)}],details:{groups:v,count:Ge}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var Wg="basalt.git-snapshot";async function mM(e,o,a){let u=o.projectID?e.store.project(o.projectID):void 0,m=u?.directory??process.cwd(),f=o.info().kind==="sub",h=()=>f||o.entries(0,["compaction"],!1).length>0,I=e.options.tools??ur({directory:u?.directory,records:()=>o.records,history:(R)=>e.resolveHistory(o.id,R),onTodos:(R)=>o.setTodos(R),shell:()=>e.serverShell(),hasCompacted:h});if(e.options.tools===void 0)I.push(cM(e.store,e.search,o.id));let E;if(u&&e.options.systemPrompt===void 0){let R=o.entries(0,["compaction"],!1).length,k=e.store.db,P=k.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(Wg,o.id),v;try{v=P?JSON.parse(P.value):void 0}catch{v=void 0}if(v?.compactions===R&&(v.summary===void 0||typeof v.summary==="string"))E=v.summary;else if(E=await av(u.directory,a),!e.isClosed&&!a?.aborted)k.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(Wg,o.id,JSON.stringify({compactions:R,summary:E})),k.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(Wg)}let S=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:iv({project:u,globalInstructions:AH(e),git:E,shell:e.serverShell()});return{systemPrompt:S.map((R)=>R.detail).join(""),systemParts:S,tools:[...I,...e.tools.snapshot()],cwd:m}}var kH=[Eu(".basalt","AGENTS.md"),Eu(".agents","AGENTS.md"),Eu(".opencode","AGENTS.md"),Eu(".claude","CLAUDE.md"),Eu(".codex","AGENTS.md")];function AH(e){let o=e.options.homeDir??RH();for(let a of kH){let u=Eu(o,a);try{if(wH(u))return TH(u,"utf8")}catch{return}}return}class Zr{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new Mg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Jl(zg(e.dataDir,"basalt.db")),this.plugins=new pg(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Xl(this.plugins,()=>this.builtinToolNames()),this.search=new lg({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let a=this.open(o,"restore");this.sessions.set(o.id,a),this.restored.add(a)}}static async create(e){let o=new Zr(e);try{return await o.initialize(),o}catch(a){throw await o.close(),a}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[zg(this.options.dataDir,"plugins"),...this.projects().map((e)=>zg(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 qv(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Ql(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>Nv(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((a)=>e||a.info().parentID===null).map((a)=>a.info()).filter((a)=>{let u=o.archive??"active";return u==="all"||a.archivedAt!==null===(u==="archived")}).sort((a,u)=>u.updated-a.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let a=this.get(e);if(!a)throw new t("History session is unavailable");return a.resolveHistory(o)}openStoredSession(e,o="restore"){let a=this.open(e,o);return this.sessions.set(e.id,a),this.emit({type:"session",session:a.info()}),a}create(e={}){let o=e.model??this.defaultModel;if(!Tn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let a=Date.now(),u={id:re("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:a,updated:a,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let m=this.open(u);return this.sessions.set(u.id,m),this.emit({type:"session",session:m.info()}),m}copyHistory(e,o,a){o={...o,archivedAt:null},this.store.copySession(e,o,a);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new y("no such session");let a=o.info(),u=a.projectID?this.store.project(a.projectID):void 0;return Iv(a,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let a=[o.model,e.model,this.defaultModel].find((f)=>f!==void 0&&Tn(this.options.models,f)!==void 0),u=a?Tn(this.options.models,a):void 0;if(!a||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let m={id:re("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:a,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(m,e.needsRaw?Sv(e.records,u):e.records);let p=this.open(m);return this.sessions.set(m.id,p),this.emit({type:"session",session:p.info()}),p}truncateHistory(e,o){let a=this.sessions.get(e.id);if(!a)throw new y("no such session");if(a.assertWritable(),a.status==="busy")throw new ce;if(!Tn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);a.close();for(let f of this.sessions.values()){if(f.info().parentID!==e.id)continue;if(f.status==="busy")f.abort();f.close()}this.store.truncateSession(e,o);let u=[],m=this.store.lastEntry(e.id,"run");if(m?.type==="run"&&m.state==="start"){let f=this.store.records(e.id,m.seq).filter((h)=>h.raw);for(let h of Po(f)){if(h.result)continue;let{body:I,raw:E}=yl(h.call,"\u4E4B\u540E\u7684\u6D88\u606F\u88AB\u7528\u6237\u4FEE\u6539\uFF0C\u8FD9\u6B21\u8C03\u7528\u7684\u7ED3\u679C\u5DF2\u968F\u622A\u65AD\u4E22\u5F03\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\u3002");u.push(this.store.appendEntry(e.id,void 0,I,E))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let p=this.open(e,"replay");this.sessions.set(e.id,p),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let f of u)this.emit({type:"entry",sessionID:e.id,entry:f});return p}setArchived(e,o){let a=this.sessions.get(e);if(!a)throw new y("no such session");let u=a.info().parentID;if(!o&&u&&this.sessions.get(u)?.isArchived)throw new t("\u8BF7\u5148\u6062\u590D\u6240\u5C5E\u7236\u4F1A\u8BDD");let m=this.sessionTree(a);if(m.some((p)=>p.status==="busy"))throw new ce;if(a.isArchived===o)return a.info();this.store.setArchived(m.map((p)=>p.id),o?Date.now():null);for(let p of m)p.refreshArchive();for(let p of m)p.archiveChanged();return a.info()}sessionTree(e){let o=[e];for(let a=0;a<o.length;a++){let u=o[a];if(!u)continue;for(let m of this.sessions.values())if(m.info().parentID===u.id)o.push(m)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new y("no such session");if(o.status==="busy")throw new ce;let a=this.sessionTree(o).slice(1),u=()=>{for(let m of a)m.close(),this.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!a.length)return u();o.close();for(let m of a)m.close(),m.abort();return Promise.all(a.map((m)=>m.idle())).then(u)}open(e,o="create"){let a=e.id,u=new Bl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(m,p)=>mM(this,m,p)},{entry:(m)=>{this.emit({type:"entry",sessionID:a,entry:m})},entryRemoved:(m)=>{this.emit({type:"entry_removed",sessionID:a,seq:m})},aborted:()=>{this.emit({type:"aborted",sessionID:a})},draft:(m)=>this.emit({type:"draft",sessionID:a,parts:m}),changed:()=>{let m=this.sessions.get(a);if(m)this.emit({type:"session",session:m.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new Pi(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(!id.includes(e))throw new t(`Invalid shell type; must be ${id.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 Fv(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(a){console.error("runtime listener failed",a)}}}var Le={now:()=>Date.now(),after(e,o){let a=setTimeout(o,e);return()=>clearTimeout(a)}};var pM=1048576,lM=8;class Gt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,a,u){this.cwd=e;this.outputLimit=o;this.terminal=a;this.shellPreference=u}setTerminalObserver(e){this.terminal=e}start(e,o,a){let u=a?.observer,m=a?.clock??Le;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!a?.shellGuardApproved){let Q=gd(e);if(Q.length>0)throw Error(yd(Q))}if(this.list().filter((Q)=>Q.state==="running").length>=lM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${lM}\uFF09`);let f=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:h,isWindows:I}=Aa(e,f),E=Bun.spawn(h,{cwd:this.cwd,stdin:a?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!I,windowsHide:!0,env:{...process.env,...am(this.cwd)}}),S={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:E,started:m.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(S.id,S);let R=()=>{for(let Q of S.waiters.splice(0))Q()},k=async(Q,L)=>{let V=new Ol;for await(let Z of Q){let ne=V.decode(Z);S.output+=ne,u?.output(ne,L);let z=Buffer.from(S.output);if(z.length>pM){let oe=z.length-pM;while(oe<z.length&&(z[oe]??0)>>6===2)oe++;let fe=z.subarray(oe).toString(),Ae=S.output.length-fe.length;S.unreadDroppedBytes+=Buffer.byteLength(S.output.slice(Math.max(0,S.readAt-S.dropped),Ae)),S.output=fe,S.dropped+=Ae}R()}let J=V.flush();if(S.output+=J,J)u?.output(J,L)},P,v=Promise.all([k(E.stdout,"stdout"),k(E.stderr,"stderr")]).catch((Q)=>{P=Q,this.kill(S)}),_=!1;if(S.done=(async()=>{if(S.code=await E.exited,S.timer?.(),this.kill(S),await v,P)throw P;if(S.state==="running")S.state="exited";if(_=!0,u?.end(S.state,S.code),!u&&S.state!=="killed")this.terminal?.(S);R()})().catch((Q)=>{if(S.state="exited",S.output+=`
480
+ [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(Q)}]`,!_)u?.end(S.state,S.code);if(u)throw Q;if(!u)this.terminal?.(S,Q);R()}),o!==void 0)S.timer=m.after(o,()=>{if(S.state==="running")S.state="timeout",this.kill(S)});return S}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128)try{e.proc.kill()}catch{}}else process.kill(-e.proc.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}peek(e,o=0,a=64000){let u=this.find(e),m=u.output.slice(Math.max(0,o-u.dropped));return{id:u.id,command:u.command,state:u.state,code:u.code,output:m.slice(-a),next:u.dropped+u.output.length,truncated:o<u.dropped||m.length>a}}async read(e,o,a=0,u=!1,m,p){let f=this.find(e),h=o?new RegExp(o):void 0,I=Date.now()+a;m?.throwIfAborted();while(f.state==="running"){m?.throwIfAborted();let P=f.output.slice(Math.max(0,f.readAt-f.dropped));if((h?h.test(P):!u)||Date.now()>=I||p?.aborted)break;await new Promise((v,_)=>{let Q=()=>{clearTimeout(V),p?.removeEventListener("abort",L);let J=f.waiters.indexOf(L);if(J>=0)f.waiters.splice(J,1);_(m?.reason)},L=()=>{clearTimeout(V),m?.removeEventListener("abort",Q),p?.removeEventListener("abort",L);let J=f.waiters.indexOf(L);if(J>=0)f.waiters.splice(J,1);v()},V=setTimeout(L,Math.max(0,I-Date.now()));f.waiters.push(L),m?.addEventListener("abort",Q,{once:!0}),p?.addEventListener("abort",L,{once:!0})})}m?.throwIfAborted();let E=f.unreadDroppedBytes;f.unreadDroppedBytes=0;let S=f.output.slice(Math.max(0,f.readAt-f.dropped));f.readAt=f.dropped+f.output.length;let R=S.slice(-this.outputLimit),k=E+Buffer.byteLength(S.slice(0,S.length-R.length));return{job:f,output:`${k?`[truncated ${k} bytes]
481
+ `:""}${R}`,stopped:f.state==="running"&&p?.aborted===!0}}async write(e,o,a=!1,u){let m=this.find(e);if(m.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let p=m.proc.stdin;if(!p||typeof p==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let f=await Qe(o,u);if(f)throw Error(f);p.write(o)}if(a)await p.end();else await p.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 rd=new WeakMap,nd=new WeakMap;function mr(e,o){let a=rd.get(e);if(!a)a=o(),rd.set(e,a);return a}function hr(e){nd.set(e,(nd.get(e)??0)+1)}function fr(e,o){let a=(nd.get(o)??1)-1;if(nd.set(o,a),a>0)return!1;if(o.close(),rd.get(e)===o)rd.delete(e);return!0}async function O(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function A(e,o){let a=e[o];if(!a)throw new t(`${o} is required`);return a}var jn=100,gr=1e4,PH=60000,CH=200,Cn=()=>s(),dM=()=>n(x({minimum:1,maximum:gr})),rm=()=>n(s({minLength:1,maxLength:128})),$H=g([l({click:g([Cn(),l({selector:Cn()})])}),l({type:l({label:Cn(),text:Cn()})}),l({waitText:Cn(),timeoutMs:dM()}),l({expectText:Cn(),within:n(Cn())}),l({waitSelector:Cn(),timeoutMs:dM()}),l({expectCount:l({selector:Cn(),n:x({minimum:0})})}),l({snapshot:l({selector:Cn(),depth:n(x({minimum:0,maximum:CH}))})}),l({expectCalls:l({onOpen:n(F(Cn())),onClose:n(x({minimum:0}))})}),l({expectValue:l({label:Cn(),value:Cn()})})]),vH=l({status:x({minimum:100,maximum:599}),body:Pr(),delayMs:n(x({minimum:0,maximum:gr}))}),MH=g([i("paths"),i("request"),i("verify"),i("ui_test"),i("list"),i("docs"),i("check"),i("load"),i("reload"),i("enable"),i("disable")]),OH=g([i("page"),i("tab"),i("card"),i("sidebar")]),Wi=l({action:MH,path:n(s({minLength:1,maxLength:4096})),method:n(Cn()),body:n(ks(Cn(),Pr())),importTimeoutMs:n(x({minimum:1,maximum:gr})),timeoutMs:n(x({minimum:1,maximum:PH})),sessionID:rm(),scope:n(g([i("user"),i("all")])),id:rm(),slot:rm(),view:rm(),codeBlock:rm(),kind:n(OH),props:n(ks(Cn(),Pr())),context:n(ks(Cn(),Pr())),steps:n(F($H,{maxItems:jn})),mockRoutes:n(ks(Cn(),vH)),topic:n(s({maxLength:100})),grep:n(s({minLength:1,maxLength:200}))});
482
+ export{t,y,kt,Vr,Kr,Li,Qr,ir,qo,Xr,Wn,Oi,Ni,Di,Ht,Ui,Bi,Jr,Go,Fi,We,$i,mt,qt,Hn,q,zo,Qe,nt,F,n,l,sr,N,x,i,te,s,g,b,de,qn,jo,Vo,Ko,Qo,Te,T,ot,ht,C,W,j,Me,me,Gn,ar,Xo,Ce,c,le,it,lr,cr,ur,ft,ce,Jo,pr,dr,re,zn,Yr,Yo,Zr,Le,Gt,mr,hr,fr,O,A,Zo,jn,gr,Wi};