@bkm016/basalt 0.0.0-stage → 0.1.0

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 (252) hide show
  1. package/README.md +275 -2
  2. package/chunk-0hbjv3y6.js +11 -0
  3. package/chunk-0rya8cxe.js +3 -0
  4. package/chunk-0szjy61m.js +2 -0
  5. package/chunk-0tdv0t5q.js +3 -0
  6. package/chunk-1egbcp85.js +59 -0
  7. package/chunk-1fv27j4b.js +3 -0
  8. package/chunk-1yzt0qm0.js +2 -0
  9. package/chunk-2zqny2sy.js +2 -0
  10. package/chunk-32at88hc.js +3 -0
  11. package/chunk-356q8e0y.js +10 -0
  12. package/chunk-3jz9g8ab.js +10 -0
  13. package/chunk-3p7q2pyp.js +3 -0
  14. package/chunk-501zkf9b.js +3 -0
  15. package/chunk-58vz2qsq.js +2 -0
  16. package/chunk-5fdgy0q2.js +16 -0
  17. package/chunk-5wp4egky.js +7 -0
  18. package/chunk-665jzf2w.js +25 -0
  19. package/chunk-6gyhajhx.js +3 -0
  20. package/chunk-7yw8aa5j.js +31 -0
  21. package/chunk-8wjgbd9k.js +3 -0
  22. package/chunk-913tfr9c.js +2 -0
  23. package/chunk-97kjn55j.js +2 -0
  24. package/chunk-9y69ywyg.js +3 -0
  25. package/chunk-a6r4z44b.js +2 -0
  26. package/chunk-agntrqs9.js +2 -0
  27. package/chunk-b9bg5fhd.js +2 -0
  28. package/chunk-bj14jshr.js +3 -0
  29. package/chunk-c25s4w6a.js +5 -0
  30. package/chunk-d48bfd2e.js +3 -0
  31. package/chunk-d913kpyw.js +3 -0
  32. package/chunk-dakrpbe6.js +3 -0
  33. package/chunk-g2k3yhgh.js +12 -0
  34. package/chunk-hat3s3pr.js +3 -0
  35. package/chunk-hcn9cf6v.js +2 -0
  36. package/chunk-j2x0g1vg.js +2 -0
  37. package/chunk-k0t23cmx.js +2 -0
  38. package/chunk-k7w7ac9q.js +18 -0
  39. package/chunk-kgdrjqsy.js +3 -0
  40. package/chunk-kjr81mrd.js +9 -0
  41. package/chunk-m38ber71.js +2 -0
  42. package/chunk-n6e43rvk.js +3 -0
  43. package/chunk-qbf8x2ft.js +5 -0
  44. package/chunk-qcwnkr5y.js +2 -0
  45. package/chunk-qffb7een.js +3 -0
  46. package/chunk-qnr1f5pj.js +3 -0
  47. package/chunk-r9aatvwm.js +3 -0
  48. package/chunk-rad3dm0q.js +2 -0
  49. package/chunk-rjdhaasf.js +3 -0
  50. package/chunk-rm3kcxq9.js +20 -0
  51. package/chunk-rv06x0kn.js +7 -0
  52. package/chunk-sf13azm4.js +12 -0
  53. package/chunk-sytpmbfp.js +471 -0
  54. package/chunk-t057xfrt.js +5 -0
  55. package/chunk-tjpvayr1.js +2 -0
  56. package/chunk-tnrqkc7b.js +8 -0
  57. package/chunk-v9fea96h.js +3 -0
  58. package/chunk-ve7qx8wm.js +3 -0
  59. package/chunk-vkkj4awb.js +2 -0
  60. package/chunk-wc5j0hfw.js +39 -0
  61. package/chunk-wd9zxhza.js +2 -0
  62. package/chunk-wx7kdf0b.js +2 -0
  63. package/chunk-x9982ek7.js +25 -0
  64. package/chunk-xhk54h2q.js +7 -0
  65. package/chunk-xsbxykr4.js +2 -0
  66. package/chunk-y69ewdn2.js +3 -0
  67. package/chunk-y8ced1jm.js +5 -0
  68. package/chunk-y9xe9ct2.js +2 -0
  69. package/chunk-yb1jxgnk.js +2 -0
  70. package/chunk-zt1wvkyf.js +3 -0
  71. package/compiled.js +3773 -0
  72. package/icon-dp9pmcvp.png +0 -0
  73. package/package.json +20 -4
  74. package/ui-test-worker.js +226 -0
  75. package/web/KaTeX_AMS-Regular-n7eqehx2.woff2 +0 -0
  76. package/web/KaTeX_Caligraphic-Bold-20r3b6fv.woff2 +0 -0
  77. package/web/KaTeX_Caligraphic-Regular-kkjm8f18.woff2 +0 -0
  78. package/web/KaTeX_Fraktur-Bold-pz5vg4t0.woff2 +0 -0
  79. package/web/KaTeX_Fraktur-Regular-a1e9wkwk.woff2 +0 -0
  80. package/web/KaTeX_Main-Bold-mcp098h8.woff2 +0 -0
  81. package/web/KaTeX_Main-BoldItalic-fy74z249.woff2 +0 -0
  82. package/web/KaTeX_Main-Italic-hw2gxy7f.woff2 +0 -0
  83. package/web/KaTeX_Main-Regular-xvp1b75c.woff2 +0 -0
  84. package/web/KaTeX_Math-BoldItalic-mf5nf33d.woff2 +0 -0
  85. package/web/KaTeX_Math-Italic-ap60jrna.woff2 +0 -0
  86. package/web/KaTeX_SansSerif-Bold-we3bymb6.woff2 +0 -0
  87. package/web/KaTeX_SansSerif-Italic-ent92bjx.woff2 +0 -0
  88. package/web/KaTeX_SansSerif-Regular-0573pbz9.woff2 +0 -0
  89. package/web/KaTeX_Script-Regular-z2rtj6vq.woff2 +0 -0
  90. package/web/KaTeX_Size1-Regular-dfr3w1hv.woff2 +0 -0
  91. package/web/KaTeX_Size2-Regular-kted78zb.woff2 +0 -0
  92. package/web/KaTeX_Size3-Regular-e6k1k5jk.woff2 +0 -0
  93. package/web/KaTeX_Size4-Regular-abedc1pd.woff2 +0 -0
  94. package/web/KaTeX_Typewriter-Regular-scw9zx1z.woff2 +0 -0
  95. package/web/apple-touch-icon-7dkm33qp.png +0 -0
  96. package/web/apple-touch-icon.png +0 -0
  97. package/web/chunk-00mq7bhx.js +1 -0
  98. package/web/chunk-0atfn8jf.js +1 -0
  99. package/web/chunk-0k0hvh59.js +40 -0
  100. package/web/chunk-0mrkjnte.js +1 -0
  101. package/web/chunk-0pbjgdgp.js +2 -0
  102. package/web/chunk-0s80zw00.js +1 -0
  103. package/web/chunk-0xck277j.js +140 -0
  104. package/web/chunk-1t760bg0.js +1 -0
  105. package/web/chunk-1v3d60pp.js +217 -0
  106. package/web/chunk-1x8fn8w9.js +1 -0
  107. package/web/chunk-20q90epj.js +2 -0
  108. package/web/chunk-24mfx6w1.js +2 -0
  109. package/web/chunk-29e1trsq.js +78 -0
  110. package/web/chunk-2j4m0bh1.js +2 -0
  111. package/web/chunk-310yey4q.js +1 -0
  112. package/web/chunk-32ezm0ry.js +1136 -0
  113. package/web/chunk-3ahpr030.js +2 -0
  114. package/web/chunk-3bqh2dkw.js +7 -0
  115. package/web/chunk-3cfabjey.js +370 -0
  116. package/web/chunk-3hvgs5aw.js +1 -0
  117. package/web/chunk-3kh6zefg.js +1 -0
  118. package/web/chunk-3pf33xsm.js +98 -0
  119. package/web/chunk-3pm4645m.js +2 -0
  120. package/web/chunk-401v5ht6.js +8 -0
  121. package/web/chunk-4b5mt5pd.js +70 -0
  122. package/web/chunk-4gavbw65.js +1 -0
  123. package/web/chunk-4rm1vy7w.js +1 -0
  124. package/web/chunk-4wd9r73y.js +1 -0
  125. package/web/chunk-4y2td14d.js +24 -0
  126. package/web/chunk-54thej0t.js +2 -0
  127. package/web/chunk-55kw67nv.js +1 -0
  128. package/web/chunk-59kqahb3.js +1 -0
  129. package/web/chunk-5hex8g0y.js +24 -0
  130. package/web/chunk-5r5kv4gh.js +1 -0
  131. package/web/chunk-6atq9qtt.js +7 -0
  132. package/web/chunk-6beqrmtq.js +1 -0
  133. package/web/chunk-6m69hczt.js +2 -0
  134. package/web/chunk-6r912gfj.js +34 -0
  135. package/web/chunk-74j07k8k.js +2 -0
  136. package/web/chunk-7f0m2yrd.js +169 -0
  137. package/web/chunk-8g239029.js +1 -0
  138. package/web/chunk-942prjb6.js +332 -0
  139. package/web/chunk-95q1bwxn.js +1 -0
  140. package/web/chunk-9s7c178f.js +1 -0
  141. package/web/chunk-9v1f6yc8.js +1 -0
  142. package/web/chunk-a3xt6840.js +38 -0
  143. package/web/chunk-ad6x47yy.js +1 -0
  144. package/web/chunk-b5brnfv9.js +2 -0
  145. package/web/chunk-benmmqt2.js +1 -0
  146. package/web/chunk-bgqdcnke.js +1 -0
  147. package/web/chunk-bhe4jzha.js +1 -0
  148. package/web/chunk-bwyw10wx.js +39 -0
  149. package/web/chunk-c85wxnpw.js +292 -0
  150. package/web/chunk-canbct9d.js +55 -0
  151. package/web/chunk-cg3jterp.js +2 -0
  152. package/web/chunk-d18r4m14.js +141 -0
  153. package/web/chunk-d4d3mnak.js +84 -0
  154. package/web/chunk-dmqtdeb4.js +1 -0
  155. package/web/chunk-dy2gm1fs.js +1 -0
  156. package/web/chunk-e5rmr47n.js +2 -0
  157. package/web/chunk-ea9swkkt.js +1 -0
  158. package/web/chunk-ejd43q75.js +19 -0
  159. package/web/chunk-eqegxtdt.js +1 -0
  160. package/web/chunk-ev1g5cqw.js +2 -0
  161. package/web/chunk-ezyvv4ab.js +3 -0
  162. package/web/chunk-f91wzwtk.js +1 -0
  163. package/web/chunk-fdkp6tzq.js +36 -0
  164. package/web/chunk-g1ev11wx.js +1 -0
  165. package/web/chunk-g9qv15hq.js +41 -0
  166. package/web/chunk-ghxe4gam.js +2 -0
  167. package/web/chunk-gmfp7fg4.js +1 -0
  168. package/web/chunk-gxay64d5.js +1 -0
  169. package/web/chunk-gxn0bey7.js +142 -0
  170. package/web/chunk-haphmhz8.js +200 -0
  171. package/web/chunk-hejz98gw.js +1 -0
  172. package/web/chunk-hfaffkrh.js +1 -0
  173. package/web/chunk-hp167dbv.js +1 -0
  174. package/web/chunk-hryhthxr.js +16 -0
  175. package/web/chunk-j2vt8c8v.js +1 -0
  176. package/web/chunk-jg6nzn6q.js +1 -0
  177. package/web/chunk-jtwhjp20.js +303 -0
  178. package/web/chunk-jvhmna7z.js +89 -0
  179. package/web/chunk-ka3q31t1.js +1 -0
  180. package/web/chunk-kbtbbarw.js +2 -0
  181. package/web/chunk-ktqt87qw.js +1 -0
  182. package/web/chunk-kx2xk3bb.js +1 -0
  183. package/web/chunk-m2d1sp30.js +1 -0
  184. package/web/chunk-mdsgekpk.js +1 -0
  185. package/web/chunk-mq92vqb1.js +2 -0
  186. package/web/chunk-n1dmrz44.js +2 -0
  187. package/web/chunk-n5fn9khr.js +1 -0
  188. package/web/chunk-n90cqdvg.js +2 -0
  189. package/web/chunk-nerx2q12.js +139 -0
  190. package/web/chunk-ngpq43vn.js +1 -0
  191. package/web/chunk-nj0cv1cq.js +257 -0
  192. package/web/chunk-nzey7cpv.js +1 -0
  193. package/web/chunk-p8y0hjx9.js +2 -0
  194. package/web/chunk-pxe3vna4.js +1 -0
  195. package/web/chunk-pz934t6t.js +30 -0
  196. package/web/chunk-r1dnh0s8.js +1 -0
  197. package/web/chunk-r5eakmw6.js +1 -0
  198. package/web/chunk-rkesqprv.js +1 -0
  199. package/web/chunk-rsn8j7xv.js +120 -0
  200. package/web/chunk-rtf2zzzv.js +1 -0
  201. package/web/chunk-ry9256r7.js +1 -0
  202. package/web/chunk-rykfak98.js +2 -0
  203. package/web/chunk-rz6wwdd5.js +106 -0
  204. package/web/chunk-s8vapqgr.js +12 -0
  205. package/web/chunk-sc63gh9d.js +2 -0
  206. package/web/chunk-srrfphes.js +1 -0
  207. package/web/chunk-svdzmaxb.js +2 -0
  208. package/web/chunk-svmhj9hd.js +1 -0
  209. package/web/chunk-t6agpn2z.js +1 -0
  210. package/web/chunk-tfyxp2qs.js +89 -0
  211. package/web/chunk-ts7zrf5b.js +2 -0
  212. package/web/chunk-ttg6tbwx.js +2 -0
  213. package/web/chunk-v47rhg7b.js +1 -0
  214. package/web/chunk-v5cnt7c8.js +1 -0
  215. package/web/chunk-v6v831tc.js +214 -0
  216. package/web/chunk-vadqkz3x.js +99 -0
  217. package/web/chunk-vfqdy860.js +1 -0
  218. package/web/chunk-vfqe8298.js +1 -0
  219. package/web/chunk-vqjs551t.js +7 -0
  220. package/web/chunk-wtawdeej.css +1 -0
  221. package/web/chunk-x3zwjkwg.js +62 -0
  222. package/web/chunk-x59p8sg2.js +1 -0
  223. package/web/chunk-x9q4kh67.js +4 -0
  224. package/web/chunk-xet1jjy9.js +1 -0
  225. package/web/chunk-xzp7jf7e.js +2 -0
  226. package/web/chunk-y7z144e3.js +1 -0
  227. package/web/chunk-ydgqrfvw.js +2 -0
  228. package/web/chunk-ydtrc1ay.js +2 -0
  229. package/web/chunk-yj1a2d37.js +1 -0
  230. package/web/chunk-ykxpb3wv.js +2 -0
  231. package/web/chunk-ytpwz01r.js +291 -0
  232. package/web/chunk-z09emmrb.js +1 -0
  233. package/web/chunk-z1jtv4c0.js +2 -0
  234. package/web/chunk-zakv2xdf.js +1 -0
  235. package/web/chunk-zbj1trar.js +2 -0
  236. package/web/chunk-zk2f7x5e.js +4 -0
  237. package/web/icon-192.png +0 -0
  238. package/web/icon-512.png +0 -0
  239. package/web/icon-maskable-512.png +0 -0
  240. package/web/icon-yx2p2pye.svg +13 -0
  241. package/web/icon.svg +13 -0
  242. package/web/index.html +23 -0
  243. package/web/install.ps1 +91 -0
  244. package/web/install.sh +177 -0
  245. package/web/inter-latin-wght-normal-an0py913.woff2 +0 -0
  246. package/web/jetbrains-mono-latin-wght-normal-hj2e42wt.woff2 +0 -0
  247. package/web/manifest-txf6vfbq.webmanifest +35 -0
  248. package/web/manifest.webmanifest +35 -0
  249. package/web/source-serif-4-latin-wght-italic-ta5tqqvz.woff2 +0 -0
  250. package/web/source-serif-4-latin-wght-normal-1yyvbhsz.woff2 +0 -0
  251. package/web/sw.js +90 -0
  252. package/worker.js +2 -0
@@ -0,0 +1,471 @@
1
+ // @bun
2
+ import{No,zr,F}from"./chunk-c25s4w6a.js";import{Bo,$e,Tt,Wo,Qn,$o,xi,wi,ft,qo,Oe,Qr,Ke}from"./chunk-x9982ek7.js";import{$n,vi,Gr}from"./chunk-9y69ywyg.js";import{Ie,re,Do,qn,C,Hn,mt,Ce,ur,N,Me,Gn,ht,ue,$t,ne,jr,Uo,Le,te,nt,zn,Fo,ge,Ai,yi,ye,jn,d,Ei,Q,Vr,H,_i}from"./chunk-sf13azm4.js";import{Vn,M,Kn,Ve,bi,qt,Te}from"./chunk-0rya8cxe.js";import{t,Ye}from"./chunk-qnr1f5pj.js";var vg=t(function(gK,Mg){var mM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Wl=/[\n\r\u2028\u2029]/,pM=/[\s#!"$&'():;<=>@\\^`|~]/g;Mg.exports=function(n){var i=!1;return n.map(function(c){if(i&&typeof c==="string"&&Wl.test(c))throw TypeError("a token after a `comment` must not contain line terminators");if(c==="")return"''";if(c&&typeof c==="object"){if("op"in c&&c.op==="glob"){if(typeof c.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Wl.test(c.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(c.pattern==="")return"''";return c.pattern.replace(pM,"\\$&")}if("op"in c&&typeof c.op==="string"){if(mM.indexOf(c.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(c.op));return c.op.replace(/[\s\S]/g,"\\$&")}if("comment"in c&&typeof c.comment==="string"){if(Wl.test(c.comment))throw TypeError("`comment` must not contain line terminators");return i=!0,"#"+c.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(c)&&/!/.test(c))return"'"+c.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(c)&&!/'/.test(c))return"'"+c+"'";if(/["'\s]/.test(c))return'"'+c.replace(/(["\\$`])/g,"\\$1")+'"';return String(c).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var jg=t(function(yK,Fg){var Dg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Og=new RegExp("^"+Dg+"$"),_g="|&;()<> \\t",lM="'([^']*?)'",qg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Lg="\\$'"+qg+"'",Jc=new RegExp("\\$'"+qg+"(?:(')|\\\\?$)","g"),dM="abeEfnrtv",fM=`\x07\b\x1B\x1B\f
3
+ \r \v`,hM=/^#$/,zl="'",Ng='"',fu="$",Ni="",gM=4294967296;for(Qc=0;Qc<4;Qc++)Ni+=(gM*Math.random()).toString(16);var Qc,yM=new RegExp("^"+Ni);function xM(e,n){var i=n.lastIndex,c=[],p;while(p=n.exec(e))if(c[c.length]=p,n.lastIndex===p.index)n.lastIndex+=1;return n.lastIndex=i,c}function IM(e,n,i){var c=typeof e==="function"?e(i):e[i];if(typeof c>"u"&&i!="")c="";else if(typeof c>"u")c="$";if(typeof c==="object")return n+Ni+JSON.stringify(c)+Ni;return n+c}var bM=/\\([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 EM(e,n){var i=n.charAt(0);if(i==="c"){var c=n.charAt(1);return c==="?"?"\x7F":String.fromCharCode(c.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var p=parseInt(n.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(i>="0"&&i<="7")return String.fromCharCode(parseInt(n,8)&255);var f=dM.indexOf(n);return f<0?n:fM.charAt(f)}function SM(e){return e.replace(bM,EM).split("\x00")[0]}function wM(e,n){return Jc.lastIndex=n,!!Jc.exec(e)[1]}function TM(e,n,i){if(!i)i={};var c=i.escape||"\\",p=i.splitUnquoted===!0?`
4
+ `:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",f="(\\"+c+`['"$\\`+c+_g+"]|\\$\\$|\\$(?!"+Lg.slice(2)+`)|[^\\s'"$`+_g+"])+",g='"(?:\\'+c+'[\\s\\S]|[^"\\'+c+'])*"',x=new RegExp(["("+Dg+")","("+Lg+"|"+f+"|"+g+"|"+lM+")+"].join("|"),"g"),I=xM(e,x);if(I.length===0)return[];if(!n)n={};var b=!1;return I.map(function(E){var T=E[0];if(!T||b)return;if(Og.test(T))return{op:T};var k=!1,A=!1,L="",q=[],Z=!1,B=null,V=!1,X;function ie(){X+=1;var me,qe,xt=T.charAt(X);if(xt==="{"){if(X+=1,T.charAt(X)==="}")throw Error("Bad substitution: "+T.slice(X-2,X+1));var Qe=1;me=X;while(Qe>0&&me<T.length){if(T.charAt(me)==="{"&&T.charAt(me-1)==="$")Qe+=1;else if(T.charAt(me)==="}")Qe-=1;me+=1}if(Qe!==0)throw Error("Bad substitution: "+T.slice(X));me-=1,qe=T.slice(X,me),X=me}else if(/[*@#?$!-]/.test(xt))qe=xt;else{var Yt=T.slice(X);if(me=Yt.match(/[^\w\d_]/),!me)qe=Yt,X=T.length;else qe=Yt.slice(0,me.index),X+=me.index-1}return IM(n,"",qe)}function Y(){if(B===null)return;if(B===0){if(L!=="")q[q.length]=L,L=""}else{q[q.length]=L,L="";for(var me=1;me<B;me+=1)q[q.length]=""}B=null}for(X=0;X<T.length;X++){var z=T.charAt(X);if(p&&z!==fu)Y();if(V=V||!k&&(z==="*"||z==="?"),A)L+=z,A=!1;else if(k)if(z===k)k=!1;else if(k==zl)L+=z;else if(z===c)if(X+=1,z=T.charAt(X),z===Ng||z===c||z===fu)L+=z;else L+=c+z;else if(z===fu)L+=ie();else L+=z;else if(z===Ng||z===zl)k=z,Z=!0;else if(Og.test(z))return{op:T};else if(hM.test(z)){b=!0;var ce={comment:e.slice(E.index+X+1)};if(L.length)return[L,ce];return[ce]}else if(z===c)A=!0;else if(z===fu&&T.charAt(X+1)===zl&&wM(T,X))Y(),Z=!0,L+=SM(T.slice(X+2,Jc.lastIndex-1)),X=Jc.lastIndex-1;else if(z===fu){var he=ie();if(!p)L+=he;else for(var ve=0;ve<he.length;ve+=1){var de=he.charAt(ve);if(p.indexOf(de)<0)Y(),L+=de;else if(B===null)B=de===" "||de==="\t"||de===`
5
+ `?0:1;else if(de!==" "&&de!=="\t"&&de!==`
6
+ `)B+=1}}else L+=z}if(V)return{op:"glob",pattern:L};if(p){if(B!==null&&B>0){q[q.length]=L,L="";for(var se=1;se<B;se+=1)q[q.length]=""}if(L!==""||Z&&q.length===0)q[q.length]=L;return q}return L}).reduce(function(E,T){if(typeof T>"u")return E;return[].concat(T).forEach(function(k){E[E.length]=k}),E},[])}Fg.exports=function(n,i,c){var p=TM(n,i,c);if(typeof i!=="function")return p;return p.reduce(function(f,g){if(typeof g==="object")return f[f.length]=g,f;var x=g.split(RegExp("("+Ni+".*?"+Ni+")","g"));if(x.length===1)return f[f.length]=x[0],f;return x.filter(Boolean).forEach(function(I){f[f.length]=yM.test(I)?JSON.parse(I.split(Ni)[1]):I}),f},[])}});var Oo={};Ye(Oo,{ArchivedError:()=>dt,BadRequestError:()=>r,BusyError:()=>oe,DEFAULT_TIMEOUT:()=>zP,FoldingPolicy:()=>Nc,MAX_ATTACHMENTS:()=>et,MAX_TIMEOUT:()=>VP,MAX_TOOL_OUTPUT:()=>Pe,NotFoundError:()=>y,PluginCheckError:()=>pt,ProcessRegistry:()=>Wt,Type:()=>eo,aliased:()=>we,budget:()=>Lc,calls:()=>ss,clip:()=>je,clipSaved:()=>rt,dataDir:()=>Pt,definePlugin:()=>R,estimateMessage:()=>U,estimateTokens:()=>O,estimateTools:()=>Pi,extensionTranscript:()=>qc,findWindowsBash:()=>Il,foldPoint:()=>Oc,foldedThrough:()=>pa,formatLines:()=>Fc,gateShellCommand:()=>ze,groupRuns:()=>ks,historyTodos:()=>ir,newID:()=>fe,normalizeRunRecords:()=>Ph,processRegistry:()=>sr,project:()=>ke,projectUserText:()=>$i,releaseProcesses:()=>lr,requestBody:()=>G,resolveShellCommand:()=>fa,retainProcesses:()=>ar,routeParam:()=>P,runShell:()=>rr,sealPoint:()=>eu,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>fl,text:()=>u,timerClock:()=>Re,tool:()=>v,toolSession:()=>K,transcript:()=>ou,usable:()=>We,userTranscript:()=>Dc,validAttachment:()=>_t,workState:()=>gl});var Mo={};Ye(Mo,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>cR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>lR,EventStream:()=>Vn,InMemoryCredentialStore:()=>qn,InMemoryModelsStore:()=>Hn,ModelsError:()=>C,StringEnum:()=>fq,Type:()=>eo,appendAssistantMessageDiagnostic:()=>Te,calculateCost:()=>Q,clampThinkingLevel:()=>H,cleanupSessionResources:()=>vi,collapseSystemMessages:()=>Le,contentText:()=>ur,createAssistantMessageDiagnostic:()=>qt,createAssistantMessageEventStream:()=>Kn,createFauxCore:()=>uR,createInitialSystemMessage:()=>Gn,createModels:()=>jn,createProvider:()=>d,declarationsEqual:()=>zn,defaultProviderAuthContext:()=>Do,envApiKeyAuth:()=>h,extractDiagnosticError:()=>bi,fauxAssistantMessage:()=>Io,fauxProvider:()=>Co,fauxText:()=>Fn,fauxThinking:()=>Ro,fauxToolCall:()=>zD,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>jr,getCurrentSystemPrompt:()=>Uo,getCurrentTools:()=>ne,getDeclaredTools:()=>ge,getInitialSystemMessage:()=>ue,getModelType:()=>mt,getOverflowPatterns:()=>cq,getSupportedThinkingLevels:()=>Vr,getSystemMessageText:()=>N,getToolStateChanges:()=>Fo,hasApi:()=>Ei,hasNonAdditiveToolChanges:()=>yi,hasToolRedefinitions:()=>Ai,isContextOverflow:()=>oi,isModelType:()=>Ce,isRecoverableLength:()=>uq,isRetryableAssistantError:()=>fR,lazyApi:()=>re,lazyOAuth:()=>ae,lazyStream:()=>Ie,modelsAreEqual:()=>_i,normalizeContext:()=>ht,parseJsonWithRepair:()=>zr,parseStreamingJson:()=>F,reduceAssistantMessageFrames:()=>sq,registerSessionResourceCleanup:()=>$n,renderSystemMessageUpdate:()=>Me,repairJson:()=>No,resolveTranscript:()=>te,resolveTranscriptTools:()=>ye,retryAssistantCall:()=>dq,retryDelayMs:()=>dR,toToolDeclaration:()=>nt,uuidv7:()=>Gr,validateToolArguments:()=>Xa,validateToolCall:()=>Zj,withoutInitialSystemMessage:()=>$t});var j={};Ye(j,{Counted:()=>rd,Entries:()=>an,EntriesRegExp:()=>nd,Every:()=>tn,EveryAll:()=>En,GraphemeCount:()=>JM,HasPropertyKey:()=>pe,IsArray:()=>Be,IsBigInt:()=>vr,IsBoolean:()=>sn,IsClassInstance:()=>ry,IsConstructor:()=>ed,IsDeepEqual:()=>xa,IsEqual:()=>_,IsFunction:()=>as,IsGreaterEqualThan:()=>ga,IsGreaterThan:()=>qi,IsInteger:()=>Zc,IsLessEqualThan:()=>us,IsLessThan:()=>yu,IsMaxLength:()=>ny,IsMinLength:()=>oy,IsMultipleOf:()=>ty,IsNull:()=>uo,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>Go,IsString:()=>gt,IsSymbol:()=>td,IsUndefined:()=>Gt,IsUnsafePropertyKey:()=>xu,IsValueLike:()=>Fi,Keys:()=>Ee,ShiftLeft:()=>It,Some:()=>ya,SomeAll:()=>sy,Symbols:()=>iy,Values:()=>od});var Wi={};Ye(Wi,{Hash:()=>pd,HashCode:()=>jy});var Lt={};Ye(Lt,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Se,ExtendsUnion:()=>Od,IsExtendsFalse:()=>Nd,IsExtendsTrue:()=>Ld,IsExtendsTrueLike:()=>Zn,IsExtendsUnion:()=>_d,Match:()=>yr});var eo={};Ye(eo,{Any:()=>Sa,Array:()=>W,BigInt:()=>Tu,Boolean:()=>D,Call:()=>ZS,Capitalize:()=>iw,Codec:()=>cm,Conditional:()=>fw,Constructor:()=>ms,ConstructorParameters:()=>gw,Cyclic:()=>ds,Decode:()=>Ky,DecodeBuilder:()=>um,Dependent:()=>Hi,Encode:()=>Hy,EncodeBuilder:()=>am,Enum:()=>$y,Evaluate:()=>In,Exclude:()=>xw,Extends:()=>xn,ExtendsResult:()=>Lt,Extract:()=>bw,Function:()=>ps,Generic:()=>zs,Identifier:()=>Ru,Immutable:()=>Wy,Index:()=>Tw,Infer:()=>wu,InstanceType:()=>Qw,Instantiate:()=>Eo,Integer:()=>w,Interface:()=>_S,Intersect:()=>wn,IsAny:()=>Ar,IsArray:()=>St,IsBigInt:()=>oo,IsBoolean:()=>_n,IsCall:()=>_a,IsCodec:()=>On,IsConstructor:()=>Kr,IsCyclic:()=>Jt,IsDependent:()=>Or,IsEnum:()=>Zr,IsEnumValue:()=>Py,IsFunction:()=>Jr,IsGeneric:()=>Ea,IsIdentifier:()=>Jy,IsImmutable:()=>zi,IsInfer:()=>Yr,IsInteger:()=>cn,IsIntersect:()=>He,IsKind:()=>Ae,IsLiteral:()=>yt,IsNever:()=>no,IsNull:()=>hs,IsNumber:()=>wr,IsObject:()=>Je,IsOptional:()=>nn,IsParameter:()=>ex,IsReadonly:()=>Qi,IsRecord:()=>Kt,IsRef:()=>jt,IsRefine:()=>mm,IsRest:()=>Zs,IsSchema:()=>kr,IsString:()=>en,IsSymbol:()=>gs,IsTemplateLiteral:()=>er,IsThis:()=>Tm,IsTuple:()=>ct,IsUndefined:()=>Qo,IsUnion:()=>be,IsUnknown:()=>Xr,IsUnsafe:()=>im,IsVoid:()=>so,KeyOf:()=>Xw,Literal:()=>a,Lowercase:()=>aw,Mapped:()=>sT,Module:()=>zT,Never:()=>zt,NonNullable:()=>cT,Null:()=>Tn,Number:()=>J,Object:()=>s,Omit:()=>pT,Optional:()=>o,Parameter:()=>Ji,Parameters:()=>fT,Partial:()=>gT,Pick:()=>wT,Readonly:()=>zy,ReadonlyObject:()=>lf,ReadonlyType:()=>kT,Record:()=>ys,RecordKey:()=>Ys,RecordPattern:()=>mn,RecordValue:()=>pr,Ref:()=>rn,Refine:()=>Vy,Required:()=>UT,Rest:()=>Yi,ReturnType:()=>GT,Script:()=>XT,String:()=>l,Symbol:()=>Ra,TemplateLiteral:()=>tS,This:()=>wm,Tuple:()=>Lr,Uncapitalize:()=>uw,Undefined:()=>Ca,Union:()=>m,Unknown:()=>Sr,Unsafe:()=>$r,Uppercase:()=>cw,Void:()=>Rm,With:()=>cp});var Va={};Ye(Va,{Clear:()=>$k,Entries:()=>EF,Get:()=>TF,Has:()=>wF,IsDate:()=>Ha,IsDateTime:()=>xp,IsDuration:()=>Ip,IsEmail:()=>bp,IsHostname:()=>Cp,IsIPv4:()=>Mp,IsIPv6:()=>vp,IsIdnEmail:()=>Pp,IsIdnHostname:()=>$p,IsIri:()=>_p,IsIriReference:()=>Op,IsJsonPointer:()=>Np,IsJsonPointerUriFragment:()=>Lp,IsRegex:()=>Dp,IsRelativeJsonPointer:()=>qp,IsTime:()=>Wa,IsUri:()=>Up,IsUriReference:()=>Fp,IsUriTemplate:()=>jp,IsUrl:()=>Bp,IsUuid:()=>Gp,Reset:()=>vk,Set:()=>SF,Test:()=>Mk});var zc="shell-guard";class r extends Error{constructor(e){super(e);this.name="BadRequestError"}}class y extends Error{constructor(e){super(e);this.name="NotFoundError"}}function Tg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Rg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function iM(e,n){if(e===n)return 0;let i=Array.from({length:n.length+1},(c,p)=>p);for(let c=1;c<=e.length;c++){let p=i[0]??0;i[0]=c;for(let f=1;f<=n.length;f++){let g=i[f]??0;i[f]=Math.min((i[f]??0)+1,(i[f-1]??0)+1,p+(e[c-1]===n[f-1]?0:1)),p=g}}return i[n.length]??0}function kg(e,n){let i=Tg(e);if(!i)return[];let c=Rg(e),p=[];for(let f of n){let g=f.id.indexOf("/"),x=g>=0?f.id.slice(g+1):"",b=[f.id,f.name,x].filter(Boolean).map((T)=>({compact:Tg(T),tokens:Rg(T)})).filter((T)=>T.compact.length>0),E=Number.POSITIVE_INFINITY;for(let T of b)if(T.compact===i)E=Math.min(E,0);else if(T.compact.includes(i)||i.includes(T.compact)){let k=Math.abs(T.compact.length-i.length);E=Math.min(E,1+k/Math.max(T.compact.length,i.length))}else{let k=0;for(let A of c)if(T.tokens.has(A))k++;if(k>0){let A=k/Math.max(c.size,T.tokens.size);E=Math.min(E,10+(1-A)*10)}}if(!Number.isFinite(E)&&i.length>=4){let T=Math.max(2,Math.floor(i.length*0.34));for(let k of b){if(Math.abs(k.compact.length-i.length)>T)continue;let A=iM(i,k.compact);if(A<=T)E=Math.min(E,100+A)}}if(Number.isFinite(E))p.push({model:f,score:E})}return p.sort((f,g)=>f.score-g.score||f.model.id.localeCompare(g.model.id))}function aM(e,n,i=5){return kg(e,n).slice(0,Math.max(1,i)).map((c)=>c.model)}function si(e,n){let i=kg(e,n);if(i.length===0)return;let c=i.filter((f)=>f.score===0);if(c.length===1&&c[0])return c[0].model;if(c.length>1)return;let p=i.filter((f)=>f.score<10);if(p.length===1&&p[0])return p[0].model;return}function ai(e,n){let i=[...n].sort((g,x)=>g.id.localeCompare(x.id)),c=(g)=>g.name===g.id?g.id:`${g.id} (${g.name})`,p=aM(e,i).map(c),f=i.map(c);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${f.length}): ${f.length>0?f.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
+ `)}var li=["openai-completions","openai-responses","anthropic-messages"];function Br(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let n=e.trim().toLowerCase();if(!n)return;let i=n.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let c=Number.parseFloat(i[1]??"");if(!Number.isFinite(c)||c<=0)return;let p=i[2];if(p==="k")return Math.round(c*1000);if(p==="m")return Math.round(c*1e6);return Math.round(c)}function Kl(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 uM(e){let n=e.trim();if(!n)return;let i,c,p=n,f=p.match(/\s*\[(.*?)\]\s*$/);if(f&&f.index!==void 0){p=p.slice(0,f.index).trim();let E=f[1]?.split(",").map((k)=>k.trim()).filter(Boolean)??[],T=0;for(let k of E){let A=k.indexOf("=");if(A>=0){let L=k.slice(0,A).trim().toLowerCase(),q=Br(k.slice(A+1).trim());if(L==="context"||L==="ctx"||L==="window"||L==="contextwindow")i=q;else if(L==="max"||L==="output"||L==="maxtokens")c=q}else{let L=Br(k);if(T===0)i=L;else if(T===1)c=L;T++}}}else{let E=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(E?.[1]&&E[2])p=E[1].trim(),i=Br(E[2])}let g=p.indexOf("="),x,I;if(g<0)x=p.trim(),I=x;else x=p.slice(0,g).trim(),I=p.slice(g+1).trim()||x;if(!x)return;let b={id:x,name:I};if(i!==void 0)b.contextWindow=i;if(c!==void 0)b.maxTokens=c;return b}function Wr(e){return e.split(/\r?\n/).map(uM).filter((n)=>n!==void 0)}function Po(e){return e.map((n)=>{let i=n.name===n.id?n.id:`${n.id}=${n.name}`,c=[];if(n.contextWindow!==void 0)c.push(Kl(n.contextWindow));if(n.maxTokens!==void 0)if(n.contextWindow!==void 0)c.push(Kl(n.maxTokens));else c.push(`max=${Kl(n.maxTokens)}`);return c.length>0?`${i} [${c.join(", ")}]`:i}).join(`
8
+ `)}var Ag=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var Un=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],ci=["text","regex"],ui=["best","recent"],pi=["session","none"];var Bt=4,di="https://basalt.work",mi=["https://basalt.work","https://www.basalt.work"],hi=7420;var Hl=["auto","bash","powershell","cmd"],fi="Bkm016/Basalt";var To=["active","archived","all"];var Cg=["pending","in_progress","completed"],Vc=["image","text","path"];var Pg=["defer","always"],$g=["global","tool","source"];function _e(e,n){if(e.toLowerCase()!=="tool_call"||!n||typeof n!=="object")return{name:e,input:n};let i=n;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:n};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:n}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:n};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:n}}}var et=10,cM=15000000;function _t(e){if(!e||typeof e!=="object")return!1;let n=e;return typeof n.name==="string"&&n.name.length>0&&n.name.length<=255&&typeof n.mimeType==="string"&&n.mimeType.length>0&&typeof n.kind==="string"&&Vc.includes(n.kind)&&typeof n.data==="string"&&n.data.length>0&&n.data.length<=cM}var RM=vg(),Vl=jg();import{AsyncLocalStorage as kM}from"async_hooks";var K=new kM;var AM=3,Ug=160,CM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),PM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),Kg=/^[A-Za-z_][A-Za-z0-9_]*=/,$M=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),MM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),vM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,OM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),_M=new Set(["command","builtin","nohup","time","exec"]),LM=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 Xc(e){return{out:e.out,depth:e.depth+1}}function Bg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function Ql(e,n,i,c){let p=e.length,f=0,g=n;while(g<p){let x=e.charAt(g);if(x==="\\"){g+=2;continue}if(x==="'"||x==='"'||x==="`"){let I=g+1;while(I<p){let b=e.charAt(I);if(b==="\\"){I+=2;continue}if(b===x)break;I++}g=I+1;continue}if(x===i)f++;else if(x===c){if(f--,f===0)return g+1}g++}return p}function NM(e){let n={text:"",subs:[],heredocs:[]},i=[],c=[],p=e.length,f=0,g=0,x=null,I=(b)=>{if(e.charAt(b)==="`"){let A=b+1;while(A<p){let L=e.charAt(A);if(L==="\\"){A+=2;continue}if(L==="`")break;A++}return n.subs.push(e.slice(b+1,A)),A<p?A+1:p}if(e.charAt(b+1)==="("){let A=Ql(e,b+1,"(",")");if(e.charAt(b+2)==="(")return i.push(e.slice(b,A)),A;return n.subs.push(e.slice(b+2,A-1)),A}let T=Ql(e,b+1,"{","}"),k=e.slice(b+2,T-1);for(let A=0;A<k.length;A++){let L=k.charAt(A);if(L==="\\"){A++;continue}if(L==="`"){let q=k.indexOf("`",A+1);n.subs.push(q<0?k.slice(A+1):k.slice(A+1,q)),A=q<0?k.length:q;continue}if(L==="$"&&k.charAt(A+1)==="("){let q=Ql(k,A+1,"(",")");n.subs.push(k.slice(A+2,q-1)),A=q-1}}return T};while(f<p){let b=e.charAt(f);if(x==="'"){if(b==="'")x=null;i.push(b),f++;continue}if(x==='"'){if(b==="\\"){if(!'$`"\\\n'.includes(e.charAt(f+1)))i.push("\\");i.push(b,e.charAt(f+1)),f+=2;continue}if(b==='"'){x=null,i.push(b),f++;continue}if(b==="`"||b==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=I(f);continue}i.push(b),f++;continue}if(b==="'"||b==='"'){x=b,i.push(b),f++;continue}if(b==="\\"){i.push(b,e.charAt(f+1)),f+=2;continue}if(b==="`"||b==="$"&&(e.charAt(f+1)==="("||e.charAt(f+1)==="{")){f=I(f);continue}if(b==="#"){let E=i.at(-1);if(E===void 0||`
9
+ ;&|()`.includes(E)){while(f<p&&e.charAt(f)!==`
10
+ `)f++;continue}i.push(b),f++;continue}if(b==="<"&&e.charAt(f+1)==="<"&&e.charAt(f+2)!=="<"){let E=f+2;if(e.charAt(E)==="-")E++;i.push(e.slice(f,E));let T=E;while(T<p&&(e.charAt(T)===" "||e.charAt(T)==="\t"))T++;let k="";while(T<p){let A=e.charAt(T);if(A==="'"||A==='"'){let L=e.indexOf(A,T+1);if(L<0)break;k+=e.slice(T+1,L),T=L+1;continue}if(A==="\\"){k+=e.charAt(T+1),T+=2;continue}if(` \r
11
+ ;&|()<>`.includes(A))break;k+=A,T++}if(k)c.push(k);f=E;continue}if(b===`
12
+ `){if(c.length>0){let E=vM.test(i.slice(g).join(""));f++;for(let T of c.splice(0)){let k=f,A=p;while(f<p){let L=e.indexOf(`
13
+ `,f),q=L<0?p:L;if(e.slice(f,q).trim()===T){A=f,f=L<0?p:L+1;break}f=L<0?p:L+1}if(E&&A>k)n.heredocs.push(e.slice(k,A))}}else f++;i.push(";",`
14
+ `),g=i.length;continue}i.push(b),f++}return n.text=i.join(""),n}function hu(e,n){if(n.depth>AM)return;let i=NM(e),c;try{c=Vl(i.text)}catch{return}let p=[];for(let f of c){if(typeof f==="string"){p.push({kind:"word",text:f});continue}if("pattern"in f){p.push({kind:"word",text:f.pattern});continue}if("op"in f)p.push({kind:"op",text:f.op})}DM(p,n);for(let f of i.subs)hu(f,Xc(n));for(let f of i.heredocs)hu(f,Xc(n))}function DM(e,n){let i=[],c=()=>{if(i.length>0)qM(i,n);i=[]};for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;if(f.kind==="op"){if($M.has(f.text)){c();continue}if(MM.has(f.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(f.text)}c()}function qM(e,n){let i=0;for(;;){let g=e[i];if(g===void 0)return;if(PM.has(g)||Kg.test(g)){i++;continue}let x=jM(Bg(g),e,i);if(x===i)break;i=x}let c=e[i];if(c===void 0)return;let p=Bg(c),f=e.slice(i+1);if(p==="git"){BM(c,f,n);return}if(CM.has(p)){FM(f,n);return}if(p==="powershell"||p==="pwsh")Gg(f,/^-(command|c)$/i,n);if(p==="cmd")Gg(f,/^\/[ck]$/i,n)}function Gg(e,n,i){for(let c=0;c<e.length;c++)if(n.test(e[c]??"")){let p=e.slice(c+1).join(" ");if(p.trim())hu(p,Xc(i));return}}function FM(e,n){for(let i=0;i<e.length;i++){let c=e[i]??"";if(c==="-o"||c==="-O"||c==="--init-file"||c==="--rcfile"){i++;continue}if(c.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(c);if(p){let f=p[1]||e[i+1];if(f)hu(f,Xc(n));return}if(c.startsWith("-")||c==="")continue;return}}function jM(e,n,i){if(_M.has(e)){let f=i+1;while(n[f]?.startsWith("-"))f++;return f}let c=LM.get(e);if(!c)return i;let p=i+1;for(;;){let f=n[p];if(f===void 0)return p;if(c.includes(f)){p+=2;continue}if(Kg.test(f)||f.startsWith("-")){p++;continue}return p}}function jo(e,n){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(n))}function Jn(e,n){return e.some((i)=>i===`--${n}`||i.startsWith(`--${n}=`))}var UM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(jo(e,"f")||jo(e,"i")||Jn(e,"force")||Jn(e,"interactive"))&&!(jo(e,"n")||Jn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>jo(e,"f")||Jn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>jo(e,"f")||Jn(e,"force")||jo(e,"C")||Jn(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)=>jo(e,"f")||Jn(e,"force")||Jn(e,"force-with-lease")||Jn(e,"force-if-includes")||Jn(e,"delete")||Jn(e,"mirror")||e.some((n)=>n.startsWith("+")||n.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>Jn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>jo(e,"D")||jo(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)=>Jn(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)=>jo(e,"f")||Jn(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"&&(jo(e,"f")||Jn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function BM(e,n,i){let c=0;for(;;){let I=n[c];if(I===void 0)break;if(OM.has(I)){c+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(I)||/^-[Cc].+/.test(I)||I.startsWith("-")){c++;continue}break}let p=n[c]?.toLowerCase();if(!p)return;let f=UM[p];if(!f)return;let g=f(n.slice(c+1));if(!g)return;let x=[e,...n.slice(c)].join(" ");i.out.push({rule:p,fragment:x.length>Ug?`${x.slice(0,Ug)}\u2026`:x,reason:g})}function Xl(e){let n={out:[],depth:0};return hu(e,n),n.out}function Hg(e){let n=e.slice(0,5).map((c)=>`${c.fragment}\uFF08${c.reason}\uFF09`),i=e.length>n.length?` \u7B49 ${e.length} \u5904`:"";return`${n.join("\uFF1B")}${i}`}var Jl=new Map;function GM(e,n,i,c,p){let f=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((g)=>{let x=(b)=>{if(!Jl.delete(f))return;p?.removeEventListener("abort",I),g(b)},I=()=>{KM(e,f),x("aborted")};if(Jl.set(f,{session:e,finish:x}),e.appendExtension({namespace:zc,kind:"requested",schemaVersion:1,payload:{id:f,sessionID:e.id,command:n.slice(0,4000),summary:c.slice(0,5).map(({fragment:b,reason:E})=>({fragment:b,reason:E})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)I();else p?.addEventListener("abort",I,{once:!0})})}function KM(e,n){try{e.appendExtension({namespace:zc,kind:"cancelled",schemaVersion:1,payload:{id:n,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function ko(e,n,i){let c=Jl.get(n);if(!c||c.session!==e)return!1;return e.appendExtension({namespace:zc,kind:"answered",schemaVersion:1,payload:{id:n,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),c.finish(i?"approved":"denied"),!0}function Yl(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${Hg(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function ze(e,n){let i=Xl(e);if(!i.at(0))return;let p=Hg(i),f=K.getStore();if(f?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(n?.aborted)return`${Yl(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let g=await GM(f,e,p,i,n);if(g==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${g==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{homedir as HM}from"os";import{join as gu}from"path";function Pt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let n=HM();if(process.platform==="win32")return gu(e.LOCALAPPDATA??gu(n,"AppData","Local"),"basalt");if(process.platform==="darwin")return gu(n,"Library","Application Support","basalt");return gu(e.XDG_DATA_HOME??gu(n,".local","share"),"basalt")}var is={assign:0,create:0,clone:0,discard:0,update:0};function Di(e,n,i){return e>=n&&e<=i}function Vg(e){return e===8205}function WM(e){return Di(e,55296,56319)}function Wg(e){return Di(e,127462,127487)}function Qg(e){return Di(e,65024,65039)}function Jg(e){return Di(e,768,879)||Di(e,6832,6911)||Di(e,7616,7679)||Di(e,65056,65071)}function Yc(e){return e>65535?2:1}function zg(e,n){while(n<e.length){let i=e.codePointAt(n);if(Jg(i)||Qg(i))n+=Yc(i);else break}return n}function Zl(e,n){let i=e.codePointAt(n),c=n+Yc(i);c=zg(e,c);while(c<e.length-1&&Vg(e.codePointAt(c))){let p=e.codePointAt(c+1);c+=1+Yc(p),c=zg(e,c)}if(Wg(i)&&c<e.length&&Wg(e.codePointAt(c)))c+=Yc(e.codePointAt(c));return c}function Xg(e){return e>=768&&(WM(e)||Jg(e)||Qg(e)||Vg(e))}function Yg(e){let n=0,i=0;while(i<e.length)i=Zl(e,i),n++;return n}function zM(e,n){let i=0,c=0;while(c<e.length)if(c=Zl(e,c),++i>=n)return!0;return!1}function VM(e,n){let i=0,c=0;while(c<e.length)if(c=Zl(e,c),++i>n)return!1;return!0}function Zg(e,n){if(n===0)return!0;if(e.length<n)return!1;let i=0;while(!0){if(Xg(e.charCodeAt(i)))return zM(e,n);if(++i>=n)return!0}}function ey(e,n){if(e.length<=n)return!0;let i=0;while(!0){if(Xg(e.charCodeAt(i)))return VM(e,n);if(++i>n)return!1}}function Be(e){return Array.isArray(e)}function vr(e){return _(typeof e,"bigint")}function sn(e){return _(typeof e,"boolean")}function ed(e){if(Gt(e)||!as(e))return!1;let n=Function.prototype.toString.call(e);if(/^class\s/.test(n))return!0;if(/\[native code\]/.test(n))return!0;return!1}function as(e){return _(typeof e,"function")}function Zc(e){return Number.isInteger(e)}function uo(e){return _(e,null)}function Ot(e){return Number.isFinite(e)}function Go(e){return at(e)&&!Be(e)}function at(e){return _(typeof e,"object")&&!uo(e)}function gt(e){return _(typeof e,"string")}function td(e){return _(typeof e,"symbol")}function Gt(e){return _(e,void 0)}function _(e,n){return e===n}function qi(e,n){return e>n}function yu(e,n){return e<n}function us(e,n){return e<=n}function ga(e,n){return e>=n}function ty(e,n){if(vr(e)||vr(n))return BigInt(e)%BigInt(n)===0n;let i=0.0000000001;if(!Ot(e))return!0;if(Zc(e)&&1/n%1===0)return!0;let c=e%n;return Math.min(Math.abs(c),Math.abs(c-n),Math.abs(c+n))<i}function ry(e){if(!at(e))return!1;let n=globalThis.Object.getPrototypeOf(e);if(uo(n))return!1;return _(typeof n.constructor,"function")&&!(_(n.constructor,globalThis.Object)||_(n.constructor.name,"Object"))}function Fi(e){return vr(e)||sn(e)||uo(e)||Ot(e)||gt(e)||Gt(e)}function JM(e){return Yg(e)}function ny(e,n){return ey(e,n)}function oy(e,n){return Zg(e,n)}function tn(e,n,i){return e.every((c,p)=>p<n||i(c,p))}function En(e,n,i){let c=!0;return e.forEach((p,f)=>{if(f>=n&&!i(p,f))c=!1}),c}function ya(e,n){return e.some((i,c)=>n(i,c))}function sy(e,n){let i=!1;return e.forEach((c,p)=>{if(n(c,p))i=!0}),i}function rd(e,n){return e.reduce((i,c,p)=>n(c,p)?++i:i,0)}function It(e,n,i){return _(e.length,0)?i():n(e[0],e.slice(1))}function xu(e){return _(e,"__proto__")||_(e,"constructor")||_(e,"prototype")}function pe(e,n){return xu(n)?Object.prototype.hasOwnProperty.call(e,n):(n in e)}function nd(e){return Ee(e).map((n)=>[new RegExp(`^${n}$`),e[n]])}function an(e){return Object.entries(e)}function Ee(e){return Object.getOwnPropertyNames(e)}function iy(e){return Object.getOwnPropertySymbols(e)}function od(e){return Object.values(e)}function XM(e,n){if(!at(n))return!1;let i=Ee(e);return _(i.length,Ee(n).length)&&i.every((c)=>xa(e[c],n[c]))}function YM(e,n){return Be(n)&&_(e.length,n.length)&&e.every((i,c)=>xa(e[c],n[c]))}function xa(e,n){return Be(e)?YM(e,n):at(e)?XM(e,n):_(e,n)}var ZM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function ev(e){return ZM.test(e)}function gn(e,n){return`(${e} && ${n})`}function hr(e,n){return`(${e} || ${n})`}function Mn(e){return`!(${e})`}function em(e){return`Array.isArray(${e})`}function ay(e){return`typeof ${e} === "bigint"`}function tv(e){return`typeof ${e} === "boolean"`}function rv(e){return`Number.isInteger(${e})`}function nv(e){return`${e} === null`}function uy(e){return`Number.isFinite(${e})`}function cy(e){return gn(my(e),Mn(em(e)))}function my(e){return`typeof ${e} === "object" && ${e} !== null`}function py(e){return`typeof ${e} === "string"`}function ov(e){return`typeof ${e} === "symbol"`}function sd(e){return`${e} === undefined`}function sv(e){return`typeof ${e} === "function"`}function iv(e){return`Guard.IsConstructor(${e})`}function ro(e,n){return`${e} === ${n}`}function ly(e,n){return`${e} > ${n}`}function id(e,n){return`${e} < ${n}`}function ji(e,n){return`${e} <= ${n}`}function Iu(e,n){return`${e} >= ${n}`}function av(e,n){return`Guard.IsMinLength(${e}, ${n})`}function uv(e,n){return`Guard.IsMaxLength(${e}, ${n})`}function cs(e,n,i,c){return _(n,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${c}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${n}) || (${c}))`}function cv(e,n,i){return`${e}.some((${n[0]}, ${n[1]}) => ${i})`}function mv(e,n,i){return`((value) => { let result = false; value.forEach((${n[0]}, ${n[1]}) => { if (${i}) result = true }); return result })(${e})`}function tm(e,n,i){return`${e}.reduce((result, ${n[0]}, ${n[1]}) => (${i}) ? ++result : result, 0)`}function dy(e){return`Object.entries(${e})`}function Ui(e){return`Object.getOwnPropertyNames(${e})`}function Bi(e,n){return _(n,'"__proto__"')||_(n,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${n})`:`${n} in ${e}`}function fy(e,n){return`Guard.IsDeepEqual(${e}, ${n})`}function pv(e){return`[${e.join(", ")}]`}function Ks(e,n){return`((${e.join(", ")}) => ${n})`}function gr(e,n){return`${e}(${n.join(", ")})`}function ad(e,n){return`new ${e}(${n.join(", ")})`}function bt(e,n){return`${e}${ev(n)?`.${n}`:`[${De(n)}]`}`}function De(e){if(!Fi(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function lv(e,n,i){return`(${e} ? ${n} : ${i})`}function rm(e){return`{ ${e.join("; ")}; }`}function Ps(e,n){return`const ${e} = ${n}`}function hy(e,n){return`if(${e}) { ${n} }`}function nm(e){return`return ${e}`}function Sn(e){return _(e.length,0)?"true":e.reduce((n,i)=>gn(n,i))}function ud(e){return _(e.length,0)?"false":e.reduce((n,i)=>hr(n,i))}function dv(e,n){return`Guard.IsMultipleOf(${e}, ${n})`}function fv(e){return e instanceof Boolean}function hv(e){return e instanceof Number}function gv(e){return e instanceof String}function gy(e){return globalThis.ArrayBuffer.isView(e)}function yy(e){return e instanceof globalThis.RegExp}function yv(e){return e instanceof globalThis.Date}function xv(e){return e instanceof globalThis.Set}function Iv(e){return e instanceof globalThis.Map}var Ev={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Ko(){return Ev}function Hs(e){return Ko().immutableTypes?Object.freeze(e):e}function un(e,n){return is.assign+=1,Hs({...e,...n})}function Sv(e){return e}function wv(e){return pe(e,"~kind")||pe(e,"~unsafe")}function Tv(e){let n={};for(let i of Ee(e)){if(xu(i))continue;let c=Object.getOwnPropertyDescriptor(e,i);if(c.value=Gi(c.value),_(c.enumerable,!0))n[i]=c.value;else Object.defineProperty(n,i,c)}return n}function Rv(e){let n={};for(let i of Ee(e)){if(xu(i))continue;n[i]=Gi(e[i])}for(let i of iy(e))n[i]=Gi(e[i]);return n}function kv(e){return ry(e)?Sv(e):wv(e)?Tv(e):Rv(e)}function Av(e){return e.map((n)=>Gi(n))}function Cv(e){return e.slice()}function Pv(e){return new RegExp(e.source,e.flags)}function $v(e){return new Map(Gi([...e.entries()]))}function Mv(e){return new Set(Gi([...e.values()]))}function Gi(e){return gy(e)?Cv(e):yy(e)?Pv(e):Iv(e)?$v(e):xv(e)?Mv(e):Be(e)?Av(e):at(e)?kv(e):e}function Ia(e){return is.clone+=1,Gi(e)}function vv(e,n){for(let i of Object.keys(n))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:n[i]});return e}function xy(e,n){return{...e,...n}}function Ct(e,n,i={}){is.create+=1;let c=xy(n,i),p=Ko().enumerableKind?xy(c,e):vv(c,e);return Hs(p)}function Ho(e,n){is.discard+=1;let i={};for(let c of Ee(e)){if(n.includes(c))continue;let p=Object.getOwnPropertyDescriptor(e,c);p.value=Ia(p.value),Object.defineProperty(i,c,p)}return Hs(i)}function Et(e,n,i){is.update+=1;let c=Ko(),p=Ia(e);for(let f of Object.keys(n))Object.defineProperty(p,f,{configurable:!0,writable:!0,enumerable:c.enumerableKind,value:n[f]});for(let f of Object.keys(i))Object.defineProperty(p,f,{configurable:!0,enumerable:!0,writable:!0,value:i[f]});return Hs(p)}function Ae(e,n){return at(e)&&pe(e,"~kind")&&_(e["~kind"],n)}function kr(e){return at(e)}function Ne(e,n,i){return Ct({"~kind":"Deferred"},{type:"deferred",action:e,parameters:n,options:i},{})}function Ws(e){return Ae(e,"Deferred")}function Ov(e){return Et(e,{"~readonly":!0},{})}function Eu(e,n){return Et(Ov(e),{},n)}function Iy(e,n,i,c){let p=le(e,n,i);return Eu(p,c)}function _v(e){return Et(e,{"~optional":!0},{})}function Su(e,n){return Et(_v(e),{},n)}function by(e,n,i,c){let p=le(e,n,i);return Su(p,c)}function W(e,n){return Ct({"~kind":"Array"},{type:"array",items:e},n)}function St(e){return Ae(e,"Array")}function ba(e){return Ho(e,["~kind","type","items"])}function ms(e,n,i={}){return Ct({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:n},i)}function Kr(e){return Ae(e,"Constructor")}function Ey(e){return Ho(e,["~kind","type","parameters","instanceType"])}function ps(e,n,i={}){return Ct({["~kind"]:"Function"},{type:"function",parameters:e,returnType:n},i)}function Jr(e){return Ae(e,"Function")}function Sy(e){return Ho(e,["~kind","type","parameters","returnType"])}function rn(e,n){return Ct({["~kind"]:"Ref"},{$ref:e},n)}function jt(e){return Ae(e,"Ref")}function zs(e,n){return Ct({"~kind":"Generic"},{type:"generic",parameters:e,expression:n})}function Ea(e){return Ae(e,"Generic")}function Sa(e){return Ct({["~kind"]:"Any"},{},e)}function Ar(e){return Ae(e,"Any")}var wy="(?!)";function zt(e){return Ct({"~kind":"Never"},{not:{}},e)}function no(e){return Ae(e,"Never")}function ls(e,n={}){return Ne("AddOptional",[e],n)}function Ki(e,n={}){return Su(e,n)}function o(e){return Ki(e)}function nn(e){return kr(e)&&pe(e,"~optional")}function Ty(e){return Ee(e).filter((n)=>!nn(e[n]))}function om(e){return Ee(e)}function sm(e){return od(e)}function s(e,n={}){let i=Ty(e),c=i.length>0?{required:i}:{};return Ct({"~kind":"Object"},{type:"object",...c,properties:e},n)}function Je(e){return Ae(e,"Object")}function Ry(e){return Ho(e,["~kind","type","properties","required"])}function Sr(e){return Ct({["~kind"]:"Unknown"},{},e)}function Xr(e){return Ae(e,"Unknown")}function ds(e,n,i){let c=Ee(e).reduce((p,f)=>({...p,[f]:Et(e[f],{},{$id:f})}),{});return Ct({["~kind"]:"Cyclic"},{$defs:c,$ref:n},i)}function Jt(e){return Ae(e,"Cyclic")}function $r(e){return Et(e,{["~unsafe"]:null},{})}function im(e){return Go(e)&&pe(e,"~unsafe")&&uo(e["~unsafe"])}function yn(e,n){return n[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function wu(...e){let[n,i]=yn(e,{2:(c,p)=>[c,p,p],1:(c)=>[c,Sr(),Sr()]});return Ct({["~kind"]:"Infer"},{type:"infer",name:n,extends:i},{})}function Yr(e){return Ae(e,"Infer")}function Hi(e,n,i,c={}){return Ct({"~kind":"Dependent"},{if:e,then:n,else:i},c)}function Or(e){return Ae(e,"Dependent")}function ky(e){return Ho(e,["~kind","if","then","else"])}function Ay(e){return Go(e)}function Cy(e){return Ee(e).filter((i)=>isNaN(i)).reduce((i,c)=>[...i,e[c]],[])}function Py(e){return gt(e)||Ot(e)}function $y(e,n){let i=Ay(e)?Cy(e):e;return Ct({"~kind":"Enum"},{enum:i},n)}function Zr(e){return Ae(e,"Enum")}function wn(e,n={}){return Ct({"~kind":"Intersect"},{allOf:e},n)}function He(e){return Ae(e,"Intersect")}function My(e){return Ho(e,["~kind","allOf"])}var cd=void 0;function Lv(){try{return Oy("null")(),!0}catch{return!1}}function vy(){if(Gt(cd))cd=Lv();return cd&&Ko().useAcceleration}function Oy(...e){return new globalThis.Function(...e)}function _r(){throw Error("Unreachable")}function Nv(e){let n=new Set,i=e;while(i&&i!==Object.prototype){for(let c of Reflect.ownKeys(i))if(c!=="constructor"&&typeof c!=="symbol")n.add(c);i=Object.getPrototypeOf(i)}return[...n]}function Dv(e){return typeof e==="number"}var vn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(vn||(vn={}));var wa=BigInt("14695981039346656037"),[qv,Fv]=[BigInt("1099511628211"),BigInt("18446744073709551616")],jv=Array.from({length:256}).map((e,n)=>BigInt(n)),Dy=new Float64Array(1),qy=new DataView(Dy.buffer),Fy=new Uint8Array(Dy.buffer);function fn(e){wa=wa^jv[e],wa=wa*qv%Fv}function Uv(e){fn(vn.Array);for(let n of e)Vs(n)}function Bv(e){fn(vn.BigInt),qy.setBigInt64(0,e);for(let n of Fy)fn(n)}function Ly(e){fn(vn.Boolean),fn(e?1:0)}function Gv(e){fn(vn.Constructor),Vs(e.toString())}function Kv(e){fn(vn.Date),Vs(e.getTime())}function Hv(e){fn(vn.Function),Vs(e.toString())}function Wv(e){fn(vn.Null)}function Ny(e){fn(vn.Number),qy.setFloat64(0,e,!0);for(let n of Fy)fn(n)}function zv(e){fn(vn.Object);for(let n of Nv(e).sort())Vs(n),Vs(e[n])}function Vv(e){fn(vn.RegExp),md(e.toString())}var Qv=new TextEncoder;function md(e){fn(vn.String);for(let n of Qv.encode(e))fn(n)}function Jv(e){fn(vn.Symbol),Vs(e.toString())}function Xv(e){fn(vn.TypeArray);let n=new Uint8Array(e.buffer);for(let i=0;i<n.length;i++)fn(n[i])}function Yv(e){return fn(vn.Undefined)}function Vs(e){return gy(e)?Xv(e):yv(e)?Kv(e):yy(e)?Vv(e):fv(e)?Ly(e.valueOf()):gv(e)?md(e.valueOf()):hv(e)?Ny(e.valueOf()):Dv(e)?Ny(e):Be(e)?Uv(e):sn(e)?Ly(e):vr(e)?Bv(e):ed(e)?Gv(e):uo(e)?Wv(e):at(e)?zv(e):gt(e)?md(e):td(e)?Jv(e):Gt(e)?Yv(e):as(e)?Hv(e):_r()}function jy(e){return wa=BigInt("14695981039346656037"),Vs(e),wa}function pd(e){return jy(e).toString(16).padStart(16,"0")}function Uy(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 Zv=Uy;function By(){return Zv}class am{constructor(e,n){this.type=e,this.decode=n}Encode(e){let n=this.type,i=On(n)?(f)=>this.decode(n["~codec"].decode(f)):this.decode,c=On(n)?(f)=>n["~codec"].encode(e(f)):e,p={decode:i,encode:c};return Et(this.type,{"~codec":p},{})}}class um{constructor(e){this.type=e}Decode(e){return new am(this.type,e)}}function cm(e){return new um(e)}function Ky(e,n){return cm(e).Decode(n).Encode(()=>{throw Error("Encode not implemented")})}function Hy(e,n){return cm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(n)}function On(e){return kr(e)&&pe(e,"~codec")&&at(e["~codec"])&&pe(e["~codec"],"encode")&&pe(e["~codec"],"decode")}function Wy(e){return Ta(e)}function zi(e){return kr(e)&&pe(e,"~immutable")}function fs(e,n={}){return Ne("AddReadonly",[e],n)}function Vi(e,n={}){return Eu(e,n)}function zy(e){return Vi(e)}function Qi(e){return kr(e)&&pe(e,"~readonly")}function tO(e,n){let i=mm(e)?[...e["~refine"],n]:[n];return Et(e,{"~refine":i},{})}function Vy(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[p,f,()=>"Refine Error"]});return tO(n,{check:i,error:c})}function rO(e){return Go(e)&&pe(e,"check")&&pe(e,"error")&&as(e.check)&&as(e.error)}function mm(e){return kr(e)&&pe(e,"~refine")&&Be(e["~refine"])&&tn(e["~refine"],0,(n)=>rO(n))}var Qy="-?(?:0|[1-9][0-9]*)n";function Tu(e){return Ct({"~kind":"BigInt"},{type:"bigint"},e)}function oo(e){return Ae(e,"BigInt")}function D(e){return Ct({"~kind":"Boolean"},{type:"boolean"},e)}function _n(e){return Ae(e,"Boolean")}function Ru(e){return Ct({"~kind":"Identifier"},{name:e})}function Jy(e){return Ae(e,"Identifier")}var pm="-?(?:0|[1-9][0-9]*)";function w(e){return Ct({"~kind":"Integer"},{type:"integer"},e)}function cn(e){return Ae(e,"Integer")}class Xy extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function nO(e){return vr(e)?"bigint":sn(e)?"boolean":Ot(e)?"number":gt(e)?"string":(()=>{throw new Xy(e)})()}function a(e,n){return Ct({"~kind":"Literal"},{type:nO(e),const:e},n)}function lm(e){return vr(e)||sn(e)||Ot(e)||gt(e)}function Yy(e){return yt(e)&&vr(e.const)}function Zy(e){return yt(e)&&sn(e.const)}function dm(e){return yt(e)&&Ot(e.const)}function fm(e){return yt(e)&&gt(e.const)}function yt(e){return Ae(e,"Literal")}function Tn(e){return Ct({"~kind":"Null"},{type:"null"},e)}function hs(e){return Ae(e,"Null")}var hm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function J(e){return Ct({"~kind":"Number"},{type:"number"},e)}function wr(e){return Ae(e,"Number")}function Ra(e){return Ct({"~kind":"Symbol"},{type:"symbol"},e)}function gs(e){return Ae(e,"Symbol")}function Ji(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[p,f,f],1:(p)=>[p,Sr(),Sr()]});return Ct({"~kind":"Parameter"},{name:n,extends:i,equals:c},{})}function ex(e){return Ae(e,"Parameter")}var gm=".*";function l(e){return Ct({"~kind":"String"},{type:"string"},e)}function en(e){return Ae(e,"String")}function m(e,n={}){return Ct({"~kind":"Union"},{anyOf:e},n)}function be(e){return Ae(e,"Union")}function tx(e){return Ho(e,["~kind","anyOf"])}function ku(e){let n=rx(e);return _(n.length,2)?n[0]:[]}function oO(e){return!0}function nx(e){return It(e,(n,i)=>sO(n)?nx(i):!1,()=>!0)}function ox(e){return _(e.length,0)?!1:nx(e)}function sO(e){return be(e)?ox(e.anyOf):yt(e)?oO(e.const):!1}function ym(e){return ox(e)}function xm(e){return Ct({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function sx(e,n,i=[]){return It(e,(c,p)=>sx(p,n,[...i,`${c}${n}`]),()=>i)}function iO(e,n){return _(e.length,0)?[`${n}`]:sx(e,n)}function ix(e,n,i=[]){return It(n,(c,p)=>ix(e,p,[...i,...ax(e,c)]),()=>i)}function ax(e,n){return be(n)?ix(e,n.anyOf):yt(n)?iO(e,n.const):_r()}function ux(e,n){return It(n,(i,c)=>ux(ax(e,i),c),()=>e)}function aO(e){return e.map((n)=>a(n))}function uO(e){let n=ux([],e),i=aO(n);return m(i)}function cO(e){return _(e.length,0)?_r():_(e.length,1)&&yt(e[0])?e[0]:uO(e)}function ld(e){let n=ku(e);return _(n.length,0)?l():ym(n)?cO(n):xm(e)}function Au(e){let n=ld(e);return er(n)?l():n}function Xn(e,n){let c={[e]:n};return Ct({["~kind"]:"Record"},{type:"object",patternProperties:c})}function cx(e){return Xn(zo,e)}function mx(e){return s({true:e,false:e})}function Lr(e,n={}){let[i,c,p]=[e,e.length,!1];return Ct({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:c},n)}function ct(e){return Ae(e,"Tuple")}function px(e){return Ho(e,["~kind","type","items","minItems","additionalItems"])}function mO(e){return Ho(e,["~readonly"])}function dd(e,n){return Et(mO(e),{},n)}function lx(e,n,i,c){let p=le(e,n,i);return dd(p,c)}function dx(e,n={}){return Ne("RemoveReadonly",[e],n)}function fx(e,n={}){return dd(e,n)}function pO(e){return Ho(e,["~optional"])}function fd(e,n){return Et(pO(e),{},n)}function hx(e,n,i,c){let p=le(e,n,i);return fd(p,c)}function gx(e,n={}){return Ne("RemoveOptional",[e],n)}function Im(e,n={}){return fd(e,n)}function hd(e){return e.reduceRight((i,c,p)=>({[p]:c,...i}),{})}function yx(e){let n=hd(e.items);return s(n)}function gd(e){return Je(e)||ct(e)}function lO(e,n){return Qi(e)?Qi(n)?!0:!1:!1}function dO(e,n){return nn(e)?nn(n)?!0:!1:!1}function fO(e,n){let i=lO(e,n),c=dO(e,n),p=Tr([e,n]),f=fx(Im(p));return i&&c?Vi(Ki(f)):i&&!c?Vi(f):!i&&c?Ki(f):f}function hO(e,n,i){return i in e?i in n?fO(e[i],n[i]):e[i]:(i in n)?n[i]:zt()}function gO(e,n){return[...new Set([...Ee(e),...Ee(n)])].reduce((p,f)=>({...p,[f]:hO(e,n,f)}),{})}function xx(e){return Je(e)?e.properties:ct(e)?hd(e.items):{}}function Ix(e,n){let i=xx(e),c=xx(n),p=gO(i,c);return s(p)}function yO(e,n){let i=ka(e,n);return _(i,Pu)?e:_(i,$u)?n:_(i,Cu)?n:zt()}function xO(e,n){let i=gd(e),c=gd(n);return i&&c?Ix(e,n):i&&!c?e:!i&&c?n:yO(e,n)}function bx(e,n){return no(e)?e:Ar(e)?e:Xr(e)?n:no(n)?n:Ar(n)?n:Xr(n)?e:xO(e,n)}function IO(e,n){return be(e)||be(n)}function bO(e,n){let i=bo(e),c=bo(n);return IO(i,c)?Tr([i,c]):bx(i,c)}function Ex(e,n,i=[]){return It(n,(c,p)=>Ex(e,p,[...i,bO(c,e)]),()=>_(i.length,0)?[e]:i)}function Sx(e,n,i=[]){return It(e,(c,p)=>Sx(p,n,[...i,...Mu([c],n)]),()=>i)}function Mu(e,n=[]){return It(e,(i,c)=>be(i)?Mu(c,Sx(i.anyOf,n)):Mu(c,Ex(i,n)),()=>n)}function EO(e,n){let i=xn({},e,n);return Zn(i)?[]:[e]}function wx(e,n,i=[]){return It(e,(c,p)=>wx(p,n,[...i,...EO(c,n)]),()=>i)}function bm(e,n){let i=bo(e),c=be(i)?i.anyOf:[i],p=wx(c,n);return Yn(p)}function Vo(e,n,i){let c=Tr([e,n]),p=bm(i,e);return Yn([c,p])}function Ln(e,n=[]){return It(e,(i,c)=>Ln(c,[...n,a(i)]),()=>Yn(n))}function Tr(e){let n=Mu(e),i=yd(n);return Yn(i)}function Rn(e){let n=Au(e);return bo(n)}function Yn(e){let n=yd(e);return Qs(n)}function bo(e){return Or(e)?Vo(e.if,e.then,e.else):Zr(e)?Ln(e.enum):He(e)?Tr(e.allOf):er(e)?Rn(e.pattern):be(e)?Yn(e.anyOf):e}function Qs(e){return _(e.length,1)?e[0]:_(e.length,0)?zt():m(e)}function Tx(e,n){let i=Ln(e);return Js(i,n)}function Rx(e,n){return Xn(Xs,n)}function kx(e,n){let i=Tr(e);return Js(i,n)}function Ax(e,n){return gt(e)||Ot(e)?s({[e]:n}):_(e,!1)?s({false:n}):_(e,!0)?s({true:n}):s({})}function Cx(e,n){return Xn(Aa,n)}function Px(e,n){return pe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?Xn(e.pattern.toString(),n):Xn(zo,n)}function $x(e,n){let i=ku(e);return ym(i)?Js(Rn(e),n):Xn(e,n)}function SO(e){return be(e)?Xi(e.anyOf):[e]}function Xi(e,n=[]){return It(e,(i,c)=>Xi(c,[...n,...SO(i)]),()=>n)}function wO(e){return e.some((n)=>en(n)||wr(n)||cn(n))}function TO(e,n){return _(wO(e),!0)?Xn(zo,n):void 0}function RO(e,n){return e.reduce((i,c)=>yt(c)&&(gt(c.const)||Ot(c.const))?{...i,[c.const]:n}:i,{})}function kO(e,n){let i=RO(e,n);return s(i)}function Mx(e,n){let i=Xi(e),c=TO(i,n);return kr(c)?c:kO(i,n)}function Js(e,n){return Ar(e)?cx(n):_n(e)?mx(n):Zr(e)?Tx(e.enum,n):cn(e)?Rx(e,n):He(e)?kx(e.allOf,n):yt(e)?Ax(e.const,n):wr(e)?Cx(e,n):be(e)?Mx(e.anyOf,n):en(e)?Px(e,n):er(e)?$x(e.pattern,n):s({})}function xd(e,n,i){return ut([e])?Et(Js(e,n),{},i):Em(e,n,i)}function vx(e,n,i,c,p){let f=le(e,n,i),g=le(e,n,c);return xd(f,g,p)}var Xs=`^${pm}$`,Aa=`^${hm}$`,zo=`^${gm}$`;function Em(e,n,i={}){return Ne("Record",[e,n],i)}function ys(e,n,i={}){return xd(e,n,i)}function Ox(e,n){return Xn(e,n)}function Sm(e){return _(e,zo)?l():_(e,Xs)?w():_(e,Aa)?J():ld(e)}function mn(e){return Ee(e.patternProperties)[0]}function Ys(e){let n=mn(e);return Sm(n)}function pr(e){return e.patternProperties[mn(e)]}function Kt(e){return Ae(e,"Record")}function Yi(e){return Ct({"~kind":"Rest"},{type:"rest",items:e},{})}function Zs(e){return Ae(e,"Rest")}function wm(e){return Ct({["~kind"]:"This"},{$ref:"#"},e)}function Tm(e){return Ae(e,"This")}function Ca(e){return Ct({"~kind":"Undefined"},{type:"undefined"},e)}function Qo(e){return Ae(e,"Undefined")}function Rm(e){return Ct({"~kind":"Void"},{type:"void"},e)}function so(e){return Ae(e,"Void")}function CO(e,n){return _(e,"Array")?W(n[0]):_(e,"Capitalize")?Am(n[0]):_(e,"ConstructorParameters")?vm(n[0]):_(e,"Evaluate")?Jb(n[0]):_(e,"Exclude")?Om(n[0],n[1]):_(e,"Extract")?_m(n[0],n[1]):_(e,"Index")?Lu(n[0],n[1]):_(e,"InstanceType")?Lm(n[0]):_(e,"Lowercase")?Cm(n[0]):_(e,"NonNullable")?Nm(n[0]):_(e,"Omit")?Dm(n[0],n[1]):_(e,"Parameters")?qm(n[0]):_(e,"Partial")?Fm(n[0]):_(e,"Pick")?jm(n[0],n[1]):_(e,"Readonly")?Um(n[0]):_(e,"KeyOf")?Nu(n[0]):_(e,"Record")?Em(n[0],n[1]):_(e,"Required")?Bm(n[0]):_(e,"ReturnType")?Gm(n[0]):_(e,"Uncapitalize")?Pm(n[0]):_(e,"Uppercase")?$m(n[0]):_u(rn(e),n)}function Zi(){throw Error("Unreachable")}function qx(e,n=[]){return It(e,(i,c)=>qx(c,[...n,i[1]]),()=>n)}function $s(e){return _(e.length,3)?[e[0],...qx(e[1])]:[]}function Fx(e){return Ji(e[0],e[2],e[4])}function jx(e){return Ji(e[0],e[2],e[2])}function Ux(e){return Ji(e[0],Sr(),e[2])}function Bx(e){return Ji(e,Sr(),Sr())}function Gx(e){return e}function Kx(e){return $s(e)}function Hx(e){return e[1]}function Wx(e){return $s(e)}function zx(e){return e[1]}function Vx(e){return CO(e[0],e[1])}function Qx(e){return null}function Jx(e){return l()}function Xx(e){return J()}function Yx(e){return D()}function Zx(e){return Ca()}function eI(e){return Tn()}function tI(e){return w()}function rI(e){return Tu()}function nI(e){return Sr()}function oI(e){return Sa()}function sI(e){return s({})}function iI(e){return zt()}function aI(e){return Ra()}function uI(e){return Rm()}function cI(e){return wm()}function mI(e){return a(BigInt(e))}function pI(e){return a(_(e,"true"))}function lI(e){return a(parseFloat(e))}function dI(e){return a(e)}function fI(e){return e[1]}function hI(e){return a(e)}function gI(e){return _(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function yI(e){return e[1]}function xI(e){return km(e)}function II(e){return _(e.length,6)?Hi(e[1],e[3],e[5]):Hi(e[1],e[3],Sr())}function bI(e){return e.length>0}function EI(e){return e.reduce((n,i)=>_(i.length,3)?[...n,[i[1]]]:[...n,[]],[])}function SI(e){return _(e.length,6)?[e[1],e[3],e[5]]:[]}function wI(e){return Be(e)&&_(e.length,3)?e[1]:e}function TI(e){return _(e.length,2)?e[1]:[]}function _x(e,n){return n.reduce((i,c)=>{let p=c;return _(p.length,1)?Lu(i,p[0]):_(p.length,0)?W(i):Zi()},e)}function Lx(e,n){return _(n.length,3)?Mm(e,n[0],n[1],n[2]):e}function PO(e,n){return Be(n)&&_(n.length,0)?e:Km(e,n)}function RI(e){let[n,i,c,p,f]=e;return PO(n?Lx(Nu(_x(i,c)),p):Lx(_x(i,c),p),f)}function Id(e,n){return _(n.length,3)?(()=>{let[i,c,p]=n,f=Id(c,p);if(_(i,"&"))return He(f)?wn([e,...f.allOf]):wn([e,f]);if(_(i,"|"))return be(f)?m([e,...f.anyOf]):m([e,f]);Zi()})():e}function kI(e){return e}function AI(e){let[n,i]=e;return Id(n,i)}function CI(e){return e}function PI(e){let[n,i]=e;return Id(n,i)}function $I(e){return Qb(e[1])}function MI(e){return e[1]}function vI(e){return zs(e[0],e[2])}function OI(e){return _(e.length,4)?wu(e[1],e[3]):_(e.length,2)?wu(e[1],Sr()):Zi()}function _I(e){return e}function LI(e){return`${e}`}function NI(e){return e}function DI(e){return e}function qI(e){return cn(e[3])?Xs:wr(e[3])?Aa:gs(e[3])?zo:en(e[3])?zo:Zi()}function FI(e){return e}function jI(e){return e.length>0}function UI(e){return e.length>0}function BI(e){let[n,i,c,p,f]=e;return{[i]:n&&c?fs(ls(f)):n&&!c?fs(f):!n&&c?ls(f):f}}function GI(e){return e}function KI(e){return $s(e)}function HI(e){return e.reduce((n,i)=>pe(i,Xs)||pe(i,Aa)||pe(i,zo)?[n[0],un(n[1],i)]:[un(n[0],i),n[1]],[{},{}])}function WI(e){return HI(e[1])}function zI(e){let[n,i]=e,c=_(Ee(i).length,0)?{}:{patternProperties:i};return s(n,c)}function VI(e){return _(e.length,5)?fs(ls(e[4])):_(e.length,3)?e[2]:_(e.length,4)?_(e[2],"readonly")?fs(e[3]):ls(e[3]):Zi()}function QI(e){if(!Be(e)||!_(e.length,3))return e;let[n,i,c]=e;return n&&c?fs(ls(i)):n&&!c?fs(i):!n&&c?ls(i):i}function JI(e){return _(e.length,2)?Yi(e[1]):_(e.length,1)?e[0]:Zi()}function XI(e){return $s(e)}function YI(e){return Lr(e[1])}function ZI(e){return fs(ls(e[4]))}function eb(e){return fs(e[3])}function tb(e){return ls(e[3])}function rb(e){return e[2]}function nb(e){return e}function ob(e){return _(e.length,2)?Yi(e[1]):_(e.length,1)?e[0]:Zi()}function sb(e){return $s(e)}function ib(e){return ps(e[1],e[4])}function ab(e){return ms(e[2],e[5])}function Nx(e,n){return _(e,"remove")?dx(n):_(e,"add")?fs(n):n}function ub(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function Dx(e,n){return _(e,"remove")?gx(n):_(e,"add")?ls(n):n}function cb(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function mb(e){return _(e.length,2)?[e[1]]:[]}function pb(e){return Be(e[6])&&_(e[6].length,1)?vu(Ru(e[3]),e[5],e[6][0],Nx(e[1],Dx(e[8],e[10]))):vu(Ru(e[3]),e[5],rn(e[3]),Nx(e[1],Dx(e[8],e[10])))}function lb(e){return rn(e)}function db(e){return BigInt(e)}function fb(e){return parseFloat(e)}function hb(e){return _(e,"true")}function gb(e){return e}function yb(e){return null}function xb(e){return}function Ib(e){return{[e[0]]:e[2]}}function bb(e){return $s(e)}function $O(e){return e.reduce((n,i)=>un(n,i),{})}function Eb(e){return $O(e[1])}function Sb(e){return $s(e)}function wb(e){return e[1]}function Tb(e){return e}function Rb(e){return Tu()}function kb(e){return l()}function Ab(e){return J()}function Cb(e){return w()}function Pb(e){return zt()}function $b(e){return a(e)}function Mb(e){return e}function vb(e){return m(e[1])}function Ob(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function _b(e){return[e[0],...e[1]]}function Lb(e){return e}function Nb(e){return e[1]}function Db(e){return $s(e)}function qb(e){return _(e.length,2)?e[1]:[]}function Fb(e){let n=e[2],i=e[3],[c,p]=e[4],f=_(Ee(p).length,0)?{}:{patternProperties:p};return{[e[1]]:zs(n,Ou(i,c,f))}}function jb(e){let n=e[2],[i,c]=e[3],p=_(Ee(c).length,0)?{}:{patternProperties:c};return{[e[1]]:Ou(n,i,p)}}function Ub(e){return{[e[1]]:zs(e[2],e[4])}}function Bb(e){return{[e[1]]:e[3]}}function Gb(e){return null}function Kb(e){return e}function Hb(e){return $s(e)}function Wb(e){return e[1]}function zb(e){let[n,i]=[e[0],e[1]];return Xb(un(n,HI(i)[0]))}function Vb(e){return e}function Du(e){return _(e.length,2)}function wt(e,n,i){return Du(e)?n(e[0],e[1]):i()}function OO(e,n){return _(n.indexOf(e),0)?[e,n.slice(e.length)]:[]}function Pr(e,n){for(let i=0;i<e.length;i++){let c=OO(e[i],n);if(Du(c))return c}return[]}function bd(e,n){return Array.from({length:n-e+1},(i,c)=>String.fromCharCode(e+c))}var Yb=[...bd(97,122),...bd(65,90)],Ed="0",Sd=bd(49,57),Pa=[Ed,...Sd],Zb=" ",$a=`
15
+ `;var ei="_",Hm=".",eE="$",Wm="-";var tE="//",rE="/*",LO="*/";function nE(e){let n=e.indexOf(LO);return _(n,-1)?"":e.slice(n+2)}function oE(e){let n=e.indexOf($a);return _(n,-1)?"":e.slice(n)}function NO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function zm(e){let n=NO(e);return n.startsWith(rE)?zm(nE(n.slice(2))):n.startsWith(tE)?zm(oE(n.slice(2))):n}function hn(e){let n=e.trimStart();return n.startsWith(rE)?hn(nE(n.slice(2))):n.startsWith(tE)?hn(oE(n.slice(2))):n}function Vm(e,n){return wt(Pr([e],n),(i,c)=>[i,c],()=>["",n])}function DO(e,n){return e.includes(n)}function Ma(e,n,i,c=""){return wt(Pr(e,i),(p,f)=>DO(n,p)?Ma(e,n,f,c):Ma(e,n,f,`${c}${p}`),()=>[c,i])}function qO(e){return Pr(Sd,e)}var FO=[...Pa,ei];function jO(e){return Ma(FO,[ei],e)}function UO(e){return wt(Pr([Ed],e),(n,i)=>[n,i],()=>wt(qO(e),(n,i)=>wt(jO(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[]))}function Qm(e){return UO(hn(e))}function BO(e){return Vm(Wm,e)}function GO(e){return wt(BO(e),(n,i)=>wt(Qm(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function sE(e){return GO(hn(e))}function KO(e){return wt(sE(e),(n,i)=>wt(Pr(["n"],i),(c,p)=>[`${n}`,p],()=>[]),()=>[])}function wd(e){return KO(e)}function Td(e,n){return Pr([e],n)}function ee(e,n){return _(e,"")?["",n]:e.startsWith($a)?Td(e,zm(n)):e.startsWith(Zb)?Td(e,n):Td(e,hn(n))}var iE=[...Yb,ei,eE];function HO(e){return Pr(iE,e)}var WO=[...iE,...Pa];function aE(e,n=""){return wt(Pr(WO,e),(i,c)=>aE(c,`${n}${i}`),()=>[n,e])}function zO(e){return wt(HO(e),(n,i)=>wt(aE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function Nr(e){return zO(hn(e))}var VO=[...Pa,ei];function QO(e){return Du(Pr([Hm],e))}function uE(e){return wt(Ma(VO,[ei],e),(n,i)=>_(n,"")?[]:[n,i],()=>[])}function JO(e){return wt(Pr([Hm],e),(n,i)=>wt(uE(i),(c,p)=>[`0${n}${c}`,p],()=>[]),()=>[])}function XO(e){return wt(Qm(e),(n,i)=>wt(Pr([Hm],i),(c,p)=>wt(uE(p),(f,g)=>[`${n}${c}${f}`,g],()=>[`${n}`,p]),()=>[`${n}`,i]),()=>[])}function YO(e){return QO(e)?JO(e):XO(e)}function cE(e){return YO(hn(e))}function ZO(e){return Vm(Wm,e)}function e_(e){return wt(ZO(e),(n,i)=>wt(cE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function Jm(e){return e_(hn(e))}function t_(e){return _(e,"")?[]:[e.slice(0,1),e.slice(1)]}function mE(e,n){return It(e,(i,c)=>n.startsWith(i)?!0:mE(c,n),()=>!1)}function ti(e,n,i=""){return wt(t_(n),(c,p)=>mE(e,n)?[i,n]:ti(e,p,`${i}${c}`),()=>[])}function r_(e,n,i){return wt(Pr([e],i),(c,p)=>wt(ti([n],p),(f,g)=>wt(Pr([n],g),(x,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function n_(e,n,i){return wt(Pr([e],i),(c,p)=>wt(ti([$a,n],p),(f,g)=>wt(Pr([n],g),(x,I)=>[`${f}`,I],()=>[]),()=>[]),()=>[])}function pE(e,n,i,c){return i?r_(e,n,hn(c)):n_(e,n,hn(c))}function o_(e,n){return Pr(e,n)}function s_(e,n){return pE(e,e,!1,n)}function i_(e,n){return wt(o_(e,n),(i,c)=>s_(i,`${i}${c}`),()=>[])}function Xm(e,n){return i_(e,hn(n))}function lE(e,n){return wt(ti(e,n),(i,c)=>_(i,"")?[]:[i,c],()=>[])}var S=(e,n,i=()=>[])=>e.length===2?n(e):i(),u_=(e)=>S(S(Nr(e),([n,i])=>S(ee("extends",i),([c,p])=>S(Mt(p),([f,g])=>S(ee("=",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[Fx(n),i]),c_=(e)=>S(S(Nr(e),([n,i])=>S(ee("extends",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[jx(n),i]),m_=(e)=>S(S(Nr(e),([n,i])=>S(ee("=",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Ux(n),i]),p_=(e)=>S(Nr(e),([n,i])=>[Bx(n),i]),hE=(e)=>S(S(u_(e),([n,i])=>[n,i],()=>S(c_(e),([n,i])=>[n,i],()=>S(m_(e),([n,i])=>[n,i],()=>S(p_(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[Gx(n),i]),gE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(hE(c),([p,f])=>[[i,p],f])),([i,c])=>gE(c,[...n,i]),()=>[n,e]),l_=(e)=>S(S(S(hE(e),([n,i])=>S(gE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Kx(n),i]),Ad=(e)=>S(S(ee("<",e),([n,i])=>S(l_(i),([c,p])=>S(ee(">",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Hx(n),i]),yE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(Mt(c),([p,f])=>[[i,p],f])),([i,c])=>yE(c,[...n,i]),()=>[n,e]),d_=(e)=>S(S(S(Mt(e),([n,i])=>S(yE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Wx(n),i]),f_=(e)=>S(S(ee("<",e),([n,i])=>S(d_(i),([c,p])=>S(ee(">",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[zx(n),i]),h_=(e)=>S(S(Nr(e),([n,i])=>S(f_(i),([c,p])=>[[n,c],p])),([n,i])=>[Vx(n),i]),xE=(e)=>S(S(S(ee(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Qx(n),i]),IE=(e)=>S(ee("string",e),([n,i])=>[Jx(n),i]),bE=(e)=>S(ee("number",e),([n,i])=>[Xx(n),i]),g_=(e)=>S(ee("boolean",e),([n,i])=>[Yx(n),i]),y_=(e)=>S(ee("undefined",e),([n,i])=>[Zx(n),i]),x_=(e)=>S(ee("null",e),([n,i])=>[eI(n),i]),EE=(e)=>S(ee("integer",e),([n,i])=>[tI(n),i]),I_=(e)=>S(ee("bigint",e),([n,i])=>[rI(n),i]),b_=(e)=>S(ee("unknown",e),([n,i])=>[nI(n),i]),E_=(e)=>S(ee("any",e),([n,i])=>[oI(n),i]),S_=(e)=>S(ee("object",e),([n,i])=>[sI(n),i]),w_=(e)=>S(ee("never",e),([n,i])=>[iI(n),i]),SE=(e)=>S(ee("symbol",e),([n,i])=>[aI(n),i]),T_=(e)=>S(ee("void",e),([n,i])=>[uI(n),i]),R_=(e)=>S(ee("this",e),([n,i])=>[cI(n),i]),k_=(e)=>S(S(ee("${",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("}",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[fI(n),i]),Rd=(e)=>S(ti(["${","`"],e),([n,i])=>[hI(n),i]),wE=(e)=>S(S(S(Rd(e),([n,i])=>S(k_(i),([c,p])=>S(wE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S(S(Rd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(Rd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[gI(n),i]),Cd=(e)=>S(S(ee("`",e),([n,i])=>S(wE(i),([c,p])=>S(ee("`",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[yI(n),i]),A_=(e)=>S(Cd(e),([n,i])=>[xI(n),i]),C_=(e)=>S(S(S(ee("if",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("then",p),([f,g])=>S(Mt(g),([x,I])=>S(ee("else",I),([b,E])=>S(Mt(E),([T,k])=>[[n,c,f,x,b,T],k])))))),([n,i])=>[n,i],()=>S(S(ee("if",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("then",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>[])),([n,i])=>[II(n),i]),P_=(e)=>S(wd(e),([n,i])=>[mI(n),i]),$_=(e)=>S(S(ee("true",e),([n,i])=>[n,i],()=>S(ee("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[pI(n),i]),M_=(e)=>S(Jm(e),([n,i])=>[lI(n),i]),v_=(e)=>S(Xm(["'",'"'],e),([n,i])=>[dI(n),i]),O_=(e)=>S(S(S(ee("keyof",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[bI(n),i]),TE=(e,n=[])=>S(S(S(ee("[",e),([i,c])=>S(Mt(c),([p,f])=>S(ee("]",f),([g,x])=>[[i,p,g],x]))),([i,c])=>[i,c],()=>S(S(ee("[",e),([i,c])=>S(ee("]",c),([p,f])=>[[i,p],f])),([i,c])=>[i,c],()=>[])),([i,c])=>TE(c,[...n,i]),()=>[n,e]),__=(e)=>S(TE(e),([n,i])=>[EI(n),i]),L_=(e)=>S(S(S(ee("extends",e),([n,i])=>S(Mt(i),([c,p])=>S(ee("?",p),([f,g])=>S(Mt(g),([x,I])=>S(ee(":",I),([b,E])=>S(Mt(E),([T,k])=>[[n,c,f,x,b,T],k])))))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[SI(n),i]),N_=(e)=>S(S(S(ee("(",e),([n,i])=>S(Mt(i),([c,p])=>S(ee(")",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S(IE(e),([n,i])=>[n,i],()=>S(bE(e),([n,i])=>[n,i],()=>S(g_(e),([n,i])=>[n,i],()=>S(y_(e),([n,i])=>[n,i],()=>S(x_(e),([n,i])=>[n,i],()=>S(EE(e),([n,i])=>[n,i],()=>S(I_(e),([n,i])=>[n,i],()=>S(b_(e),([n,i])=>[n,i],()=>S(E_(e),([n,i])=>[n,i],()=>S(S_(e),([n,i])=>[n,i],()=>S(w_(e),([n,i])=>[n,i],()=>S(SE(e),([n,i])=>[n,i],()=>S(T_(e),([n,i])=>[n,i],()=>S(R_(e),([n,i])=>[n,i],()=>S(P_(e),([n,i])=>[n,i],()=>S($_(e),([n,i])=>[n,i],()=>S(M_(e),([n,i])=>[n,i],()=>S(v_(e),([n,i])=>[n,i],()=>S(A_(e),([n,i])=>[n,i],()=>S(C_(e),([n,i])=>[n,i],()=>S(z_(e),([n,i])=>[n,i],()=>S(J_(e),([n,i])=>[n,i],()=>S(rL(e),([n,i])=>[n,i],()=>S(tL(e),([n,i])=>[n,i],()=>S(iL(e),([n,i])=>[n,i],()=>S(h_(e),([n,i])=>[n,i],()=>S(aL(e),([n,i])=>[n,i],()=>[])))))))))))))))))))))))))))),([n,i])=>[wI(n),i]),D_=(e)=>S(S(S(ee("with",e),([n,i])=>S(UE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[TI(n),i]),RE=(e)=>S(S(O_(e),([n,i])=>S(N_(i),([c,p])=>S(__(p),([f,g])=>S(L_(g),([x,I])=>S(D_(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[RI(n),i]),kE=(e)=>S(S(S(ee("&",e),([n,i])=>S(RE(i),([c,p])=>S(kE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[kI(n),i]),AE=(e)=>S(S(RE(e),([n,i])=>S(kE(i),([c,p])=>[[n,c],p])),([n,i])=>[AI(n),i]),CE=(e)=>S(S(S(ee("|",e),([n,i])=>S(AE(i),([c,p])=>S(CE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[CI(n),i]),Ym=(e)=>S(S(AE(e),([n,i])=>S(CE(i),([c,p])=>[[n,c],p])),([n,i])=>[PI(n),i]),q_=(e)=>S(S(ee("readonly",e),([n,i])=>S(Ym(i),([c,p])=>[[n,c],p])),([n,i])=>[$I(n),i]),F_=(e)=>S(S(ee("|",e),([n,i])=>S(Ym(i),([c,p])=>[[n,c],p])),([n,i])=>[MI(n),i]),j_=(e)=>S(S(Ad(e),([n,i])=>S(ee("=",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[vI(n),i]),U_=(e)=>S(S(S(ee("infer",e),([n,i])=>S(Nr(i),([c,p])=>S(ee("extends",p),([f,g])=>S(Ym(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>S(S(ee("infer",e),([n,i])=>S(Nr(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>[])),([n,i])=>[OI(n),i]),Mt=(e)=>S(S(U_(e),([n,i])=>[n,i],()=>S(F_(e),([n,i])=>[n,i],()=>S(q_(e),([n,i])=>[n,i],()=>S(Ym(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[_I(n),i]),B_=(e)=>S(Jm(e),([n,i])=>[LI(n),i]),G_=(e)=>S(Nr(e),([n,i])=>[NI(n),i]),K_=(e)=>S(Xm(["'",'"'],e),([n,i])=>[DI(n),i]),H_=(e)=>S(S(ee("[",e),([n,i])=>S(Nr(i),([c,p])=>S(ee(":",p),([f,g])=>S(S(EE(g),([x,I])=>[x,I],()=>S(bE(g),([x,I])=>[x,I],()=>S(IE(g),([x,I])=>[x,I],()=>S(SE(g),([x,I])=>[x,I],()=>[])))),([x,I])=>S(ee("]",I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[qI(n),i]),PE=(e)=>S(S(B_(e),([n,i])=>[n,i],()=>S(G_(e),([n,i])=>[n,i],()=>S(K_(e),([n,i])=>[n,i],()=>S(H_(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[FI(n),i]),$E=(e)=>S(S(S(ee("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[jI(n),i]),ME=(e)=>S(S(S(ee("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[UI(n),i]),vE=(e)=>S(S($E(e),([n,i])=>S(PE(i),([c,p])=>S(ME(p),([f,g])=>S(ee(":",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[BI(n),i]),Zm=(e)=>S(S(S(ee(",",e),([n,i])=>S(ee(`
16
+ `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee(";",e),([n,i])=>S(ee(`
17
+ `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee(",",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(ee(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(ee(`
18
+ `,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))))),([n,i])=>[GI(n),i]),OE=(e,n=[])=>S(S(Zm(e),([i,c])=>S(vE(c),([p,f])=>[[i,p],f])),([i,c])=>OE(c,[...n,i]),()=>[n,e]),W_=(e)=>S(S(S(vE(e),([n,i])=>S(OE(i),([c,p])=>S(S(Zm(p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[KI(n),i]),Pd=(e)=>S(S(ee("{",e),([n,i])=>S(W_(i),([c,p])=>S(ee("}",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[WI(n),i]),z_=(e)=>S(Pd(e),([n,i])=>[zI(n),i]),V_=(e)=>S(S(S(Nr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(ee("readonly",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[n,i],()=>S(S(Nr(e),([n,i])=>S(ee(":",i),([c,p])=>S(ee("readonly",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>S(S(Nr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[n,i],()=>S(S(Nr(e),([n,i])=>S(ee(":",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>[])))),([n,i])=>[VI(n),i]),dE=(e)=>S(S(V_(e),([n,i])=>[n,i],()=>S(S($E(e),([n,i])=>S(Mt(i),([c,p])=>S(ME(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>[])),([n,i])=>[QI(n),i]),_E=(e)=>S(S(S(ee("...",e),([n,i])=>S(dE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(dE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[JI(n),i]),LE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(_E(c),([p,f])=>[[i,p],f])),([i,c])=>LE(c,[...n,i]),()=>[n,e]),Q_=(e)=>S(S(S(_E(e),([n,i])=>S(LE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[XI(n),i]),J_=(e)=>S(S(ee("[",e),([n,i])=>S(Q_(i),([c,p])=>S(ee("]",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[YI(n),i]),X_=(e)=>S(S(Nr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(ee("readonly",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[ZI(n),i]),Y_=(e)=>S(S(Nr(e),([n,i])=>S(ee(":",i),([c,p])=>S(ee("readonly",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[eb(n),i]),Z_=(e)=>S(S(Nr(e),([n,i])=>S(ee("?",i),([c,p])=>S(ee(":",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[tb(n),i]),eL=(e)=>S(S(Nr(e),([n,i])=>S(ee(":",i),([c,p])=>S(Mt(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[rb(n),i]),fE=(e)=>S(S(X_(e),([n,i])=>[n,i],()=>S(Y_(e),([n,i])=>[n,i],()=>S(Z_(e),([n,i])=>[n,i],()=>S(eL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[nb(n),i]),NE=(e)=>S(S(S(ee("...",e),([n,i])=>S(fE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(fE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[ob(n),i]),DE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(NE(c),([p,f])=>[[i,p],f])),([i,c])=>DE(c,[...n,i]),()=>[n,e]),qE=(e)=>S(S(S(NE(e),([n,i])=>S(DE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[sb(n),i]),tL=(e)=>S(S(ee("(",e),([n,i])=>S(qE(i),([c,p])=>S(ee(")",p),([f,g])=>S(ee("=>",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[ib(n),i]),rL=(e)=>S(S(ee("new",e),([n,i])=>S(ee("(",i),([c,p])=>S(qE(p),([f,g])=>S(ee(")",g),([x,I])=>S(ee("=>",I),([b,E])=>S(Mt(E),([T,k])=>[[n,c,f,x,b,T],k])))))),([n,i])=>[ab(n),i]),nL=(e)=>S(S(S(ee("+",e),([n,i])=>S(ee("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("-",e),([n,i])=>S(ee("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[ub(n),i]),oL=(e)=>S(S(S(ee("+",e),([n,i])=>S(ee("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("-",e),([n,i])=>S(ee("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[cb(n),i]),sL=(e)=>S(S(S(ee("as",e),([n,i])=>S(Mt(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[mb(n),i]),iL=(e)=>S(S(ee("{",e),([n,i])=>S(nL(i),([c,p])=>S(ee("[",p),([f,g])=>S(Nr(g),([x,I])=>S(ee("in",I),([b,E])=>S(Mt(E),([T,k])=>S(sL(k),([A,L])=>S(ee("]",L),([q,Z])=>S(oL(Z),([B,V])=>S(ee(":",V),([X,ie])=>S(Mt(ie),([Y,z])=>S(xE(z),([ce,he])=>S(ee("}",he),([ve,de])=>[[n,c,f,x,b,T,A,q,B,X,Y,ce,ve],de]))))))))))))),([n,i])=>[pb(n),i]),aL=(e)=>S(Nr(e),([n,i])=>[lb(n),i]),uL=(e)=>S(wd(e),([n,i])=>[db(n),i]),cL=(e)=>S(Jm(e),([n,i])=>[fb(n),i]),mL=(e)=>S(S(ee("true",e),([n,i])=>[n,i],()=>S(ee("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[hb(n),i]),pL=(e)=>S(Xm(['"',"'"],e),([n,i])=>[gb(n),i]),lL=(e)=>S(ee("null",e),([n,i])=>[yb(n),i]),dL=(e)=>S(ee("undefined",e),([n,i])=>[xb(n),i]),FE=(e)=>S(S(PE(e),([n,i])=>S(ee(":",i),([c,p])=>S($d(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Ib(n),i]),jE=(e,n=[])=>S(S(Zm(e),([i,c])=>S(FE(c),([p,f])=>[[i,p],f])),([i,c])=>jE(c,[...n,i]),()=>[n,e]),fL=(e)=>S(S(S(FE(e),([n,i])=>S(jE(i),([c,p])=>S(S(Zm(p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[bb(n),i]),UE=(e)=>S(S(ee("{",e),([n,i])=>S(fL(i),([c,p])=>S(ee("}",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Eb(n),i]),BE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S($d(c),([p,f])=>[[i,p],f])),([i,c])=>BE(c,[...n,i]),()=>[n,e]),hL=(e)=>S(S(S($d(e),([n,i])=>S(BE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Sb(n),i]),gL=(e)=>S(S(ee("[",e),([n,i])=>S(hL(i),([c,p])=>S(ee("]",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[wb(n),i]),$d=(e)=>S(S(uL(e),([n,i])=>[n,i],()=>S(cL(e),([n,i])=>[n,i],()=>S(mL(e),([n,i])=>[n,i],()=>S(pL(e),([n,i])=>[n,i],()=>S(lL(e),([n,i])=>[n,i],()=>S(dL(e),([n,i])=>[n,i],()=>S(UE(e),([n,i])=>[n,i],()=>S(gL(e),([n,i])=>[n,i],()=>[])))))))),([n,i])=>[Tb(n),i]),yL=(e)=>S(ee("-?(?:0|[1-9][0-9]*)n",e),([n,i])=>[Rb(n),i]),xL=(e)=>S(ee(".*",e),([n,i])=>[kb(n),i]),IL=(e)=>S(ee("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([n,i])=>[Ab(n),i]),bL=(e)=>S(ee("-?(?:0|[1-9][0-9]*)",e),([n,i])=>[Cb(n),i]),EL=(e)=>S(ee("(?!)",e),([n,i])=>[Pb(n),i]),SL=(e)=>S(lE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([n,i])=>[$b(n),i]),wL=(e)=>S(S(yL(e),([n,i])=>[n,i],()=>S(xL(e),([n,i])=>[n,i],()=>S(IL(e),([n,i])=>[n,i],()=>S(bL(e),([n,i])=>[n,i],()=>S(EL(e),([n,i])=>[n,i],()=>S(TL(e),([n,i])=>[n,i],()=>S(SL(e),([n,i])=>[n,i],()=>[]))))))),([n,i])=>[Mb(n),i]),TL=(e)=>S(S(ee("(",e),([n,i])=>S(Md(i),([c,p])=>S(ee(")",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[vb(n),i]),GE=(e)=>S(S(S(kd(e),([n,i])=>S(ee("|",i),([c,p])=>S(GE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S(S(kd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[]))),([n,i])=>[Ob(n),i]),kd=(e)=>S(S(wL(e),([n,i])=>S(Md(i),([c,p])=>[[n,c],p])),([n,i])=>[_b(n),i]),Md=(e)=>S(S(GE(e),([n,i])=>[n,i],()=>S(kd(e),([n,i])=>[n,i],()=>[])),([n,i])=>[Lb(n),i]),rx=(e)=>S(S(ee("^",e),([n,i])=>S(Md(i),([c,p])=>S(ee("$",p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Nb(n),i]),KE=(e,n=[])=>S(S(ee(",",e),([i,c])=>S(Mt(c),([p,f])=>[[i,p],f])),([i,c])=>KE(c,[...n,i]),()=>[n,e]),RL=(e)=>S(S(S(Mt(e),([n,i])=>S(KE(i),([c,p])=>S(S(ee(",",p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Db(n),i]),HE=(e)=>S(S(S(ee("extends",e),([n,i])=>S(RL(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[qb(n),i]),kL=(e)=>S(S(ee("interface",e),([n,i])=>S(Nr(i),([c,p])=>S(Ad(p),([f,g])=>S(HE(g),([x,I])=>S(Pd(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[Fb(n),i]),AL=(e)=>S(S(ee("interface",e),([n,i])=>S(Nr(i),([c,p])=>S(HE(p),([f,g])=>S(Pd(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[jb(n),i]),CL=(e)=>S(S(ee("type",e),([n,i])=>S(Nr(i),([c,p])=>S(Ad(p),([f,g])=>S(ee("=",g),([x,I])=>S(Mt(I),([b,E])=>[[n,c,f,x,b],E]))))),([n,i])=>[Ub(n),i]),PL=(e)=>S(S(ee("type",e),([n,i])=>S(Nr(i),([c,p])=>S(ee("=",p),([f,g])=>S(Mt(g),([x,I])=>[[n,c,f,x],I])))),([n,i])=>[Bb(n),i]),$L=(e)=>S(S(S(ee("export",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Gb(n),i]),WE=(e)=>S(S(S(ee(";",e),([n,i])=>S(ee(`
19
+ `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>S(S(ee(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>S(S(ee(`
20
+ `,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[Kb(n),i]),zE=(e,n=[])=>S(S(WE(e),([i,c])=>S(vd(c),([p,f])=>[[i,p],f])),([i,c])=>zE(c,[...n,i]),()=>[n,e]),ML=(e)=>S(S(S(vd(e),([n,i])=>S(zE(i),([c,p])=>S(S(WE(p),([f,g])=>[[f],g],()=>[[],p]),([f,g])=>[[n,c,f],g]))),([n,i])=>[n,i],()=>S([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Hb(n),i]),vd=(e)=>S(S($L(e),([n,i])=>S(S(kL(i),([c,p])=>[c,p],()=>S(AL(i),([c,p])=>[c,p],()=>S(CL(i),([c,p])=>[c,p],()=>S(PL(i),([c,p])=>[c,p],()=>[])))),([c,p])=>S(xE(p),([f,g])=>[[n,c,f],g]))),([n,i])=>[Wb(n),i]),vL=(e)=>S(S(vd(e),([n,i])=>S(ML(i),([c,p])=>[[n,c],p])),([n,i])=>[zb(n),i]),VE=(e)=>S(S(vL(e),([n,i])=>[n,i],()=>S(j_(e),([n,i])=>[n,i],()=>S(Mt(e),([n,i])=>[n,i],()=>[]))),([n,i])=>[Vb(n),i]);function QE(e){let n=Cd(`\`${e}\``);return _(n.length,2)?n[0]:_r()}function _L(e){return e.join("|")}function LL(e){return e.slice(1,e.length-1)}function NL(e,n,i){return ri(n,`${i}${e}`)}function DL(e,n){return ri(e,`${n}${Qy}`)}function qL(e,n){return ri(e,`${n}${pm}`)}function FL(e,n){return ri(e,`${n}${hm}`)}function jL(e,n){return qu(m([a("false"),a("true")]),e,n)}function UL(e,n){return ri(e,`${n}${gm}`)}function BL(e,n,i){return ri(n,`${i}${LL(e)}`)}function GL(e,n,i){let c=Fu(e,{});return qu(c,n,i)}function KL(e,n,i){let c=Ln(e);return qu(c,n,i)}function JE(e,n,i,c=[]){return It(e,(p,f)=>JE(f,n,i,[...c,qu(p,[],"")]),()=>ri(n,`${i}(${_L(c)})`))}function qu(e,n,i){return Zr(e)?KL(e.enum,n,i):cn(e)?qL(n,i):yt(e)?NL(e.const,n,i):oo(e)?DL(n,i):_n(e)?jL(n,i):wr(e)?FL(n,i):en(e)?UL(n,i):er(e)?BL(e.pattern,n,i):YE(e)?GL(e.parameters[0],n,i):be(e)?JE(e.anyOf,n,i):wy}function ri(e,n){return It(e,(i,c)=>qu(i,c,n),()=>n)}function HL(e){return`^${ri(e,"")}$`}function XE(e){let n=HL(e);return xm(n)}function Fu(e,n){return ut(e)?Et(XE(e),{},n):km(e,n)}function ZE(e,n,i,c){let p=mo(e,n,i);return Fu(p,c)}function km(e,n={}){return Ne("TemplateLiteral",[e],n)}function YE(e){return kr(e)&&pe(e,"action")&&_(e.action,"TemplateLiteral")}function eS(e){return Fu(e,{})}function WL(e){let n=QE(e);return eS(n)}function tS(e,n={}){let i=gt(e)?WL(e):eS(e);return Et(i,{},n)}function er(e){return Ae(e,"TemplateLiteral")}function Od(e){return Ct({["~kind"]:"ExtendsUnion"},{inferred:e})}function _d(e){return at(e)&&pe(e,"~kind")&&pe(e,"inferred")&&_(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function Se(e){return Ct({["~kind"]:"ExtendsTrue"},{inferred:e})}function Ld(e){return at(e)&&pe(e,"~kind")&&pe(e,"inferred")&&_(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ze(){return Ct({["~kind"]:"ExtendsFalse"},{})}function Nd(e){return at(e)&&pe(e,"~kind")&&_(e["~kind"],"ExtendsFalse")}function Zn(e){return _d(e)||Ld(e)}function yr(e,n,i){return Zn(e)?n(e.inferred):i()}function zL(e,n,i,c){return yr(Rt(e,i,c),(p)=>Se(un(un(e,p),{[n]:i})),()=>Ze())}function VL(e,n){return Se(e)}function QL(e,n,i,c,p){return yr(Rt(e,n,i),(f)=>yr(Rt(f,n,c),(g)=>Se(g),()=>Ze()),()=>yr(Rt(e,n,p),(f)=>Se(f),()=>Ze()))}function JL(e,n,i){let c=Ln(i);return Rt(e,n,c)}function rS(e,n,i){return It(i,(c,p)=>yr(Rt(e,n,c),(f)=>rS(f,n,p),()=>Ze()),()=>Se(e))}function XL(e,n,i){let c=Rn(i);return Rt(e,n,c)}function nS(e,n,i){return It(i,(c,p)=>yr(Rt(e,n,c),(f)=>Se(f),()=>nS(e,n,p)),()=>Ze())}function Dt(e,n,i){return Ar(i)?VL(e,n):Or(i)?QL(e,n,i.if,i.then,i.else):Zr(i)?JL(e,n,i.enum):Yr(i)?zL(e,i.name,n,i.extends):He(i)?rS(e,n,i.allOf):er(i)?XL(e,n,i.pattern):be(i)?nS(e,n,i.anyOf):Xr(i)?Se(e):Ze()}function oS(e,n,i){return Yr(i)?Dt(e,n,i):Ar(i)?Se(e):Xr(i)?Se(e):Od(e)}function YL(e,n){let i=zi(e),c=zi(n);return i&&c?!0:!i&&c?!0:i&&!c?!1:!0}function sS(e,n,i,c){return St(c)?YL(n,c)?Rt(e,i,c.items):Ze():Dt(e,n,c)}function iS(e,n,i){return oo(i)?Se(e):Dt(e,n,i)}function aS(e,n,i){return _n(i)?Se(e):Dt(e,n,i)}function ZL(e,n,i,c,p){let f=Yr(c)?n:c,g=Yr(c)?c:n,x=nn(n),I=nn(c);return!x&&I?Ze():yr(Rt(e,f,g),(b)=>ju(b,i,p),()=>Ze())}function eN(e,n,i,c){return It(c,(p,f)=>ZL(e,n,i,p,f),()=>nn(n)?Se(e):Ze())}function tN(e,n,i){return It(n,(c,p)=>eN(e,c,p,i),()=>Se(e))}function ju(e,n,i){return tN(e,n,i)}function ep(e,n,i){return so(i)?Se(e):Rt(e,n,i)}function uS(e,n,i,c){return Ar(c)?Se(e):Xr(c)?Se(e):Kr(c)?yr(ju(e,n,c.parameters),(p)=>ep(p,i,c.instanceType),()=>Ze()):Ze()}function cS(e,n,i,c,p){return yr(Rt(e,n,p),()=>Rt(e,i,p),()=>Rt(e,c,p))}function mS(e,n,i){let c=Ln(n);return Rt(e,c,i)}function pS(e,n,i,c){return Ar(c)?Se(e):Xr(c)?Se(e):Jr(c)?yr(ju(e,n,c.parameters),(p)=>ep(p,i,c.returnType),()=>Ze()):Ze()}function lS(e,n,i){return cn(i)?Se(e):wr(i)?Se(e):Dt(e,n,i)}function dS(e,n,i){let c=Tr(n);return Rt(e,c,i)}function tp(e,n,i){return n===i?Se(e):Ze()}function rN(e,n,i){return yt(i)?tp(e,n,i.const):oo(i)?Se(e):Dt(e,a(n),i)}function nN(e,n,i){return yt(i)?tp(e,n,i.const):_n(i)?Se(e):Dt(e,a(n),i)}function oN(e,n,i){return yt(i)?tp(e,n,i.const):wr(i)?Se(e):Dt(e,a(n),i)}function sN(e,n,i){return yt(i)?tp(e,n,i.const):en(i)?Se(e):Dt(e,a(n),i)}function fS(e,n,i){return vr(n.const)?rN(e,n.const,i):sn(n.const)?nN(e,n.const,i):Ot(n.const)?oN(e,n.const,i):gt(n.const)?sN(e,n.const,i):_r()}function hS(e,n,i){return Yr(i)?Dt(e,n,i):Se(e)}function gS(e,n,i){return hs(i)?Se(e):Dt(e,n,i)}function yS(e,n,i){return wr(i)?Se(e):Dt(e,n,i)}function iN(e,n,i){return nn(n)?nn(i)?Se(e):Ze():Se(e)}function aN(e,n,i){return Yr(i)&&no(i.extends)?Ze():yr(Rt(e,n,i),(c)=>iN(c,n,i),()=>Ze())}function uN(e,n){return e.reduce((i,c)=>(c in n)?Zn(n[c])?{...i,...n[c].inferred}:_r():_r(),{})}function cN(e,n,i){let c={};for(let g of Ee(i))c[g]=g in n?aN({},n[g],i[g]):nn(i[g])?Yr(i[g])?Se(un(e,{[i[g].name]:i[g].extends})):Se(e):Ze();let p=od(c).every((g)=>Zn(g)),f=p?uN(Ee(c),c):{};return p?Se(f):Ze()}function mN(e,n,i){let c=cN(e,n,i);return Zn(c)?Se(un(e,c.inferred)):Ze()}function pN(e,n,i){return mN(e,n,i)}function lN(e,n){return Ee(n).reduce((i,c)=>({...i,[c]:pe(e,c)?be(i[c])?m([...i[c].anyOf,n[c]]):m([e[c],n[c]]):n[c]}),e)}function xS(e,n,i,c){return It(n,(p,f)=>yr(Rt({},e[p],i),(g)=>xS(e,f,i,lN(c,g)),()=>Ze()),()=>Se(c))}function dN(e,n,i,c){let p=Ee(n);return xS(n,p,c,e)}function IS(e,n,i){return Kt(i)?dN(e,n,mn(i),pr(i)):Je(i)?pN(e,n,i.properties):Dt(e,s(n),i)}function fN(e,n){return _(Ee(n).length,0)?Se(e):Ze()}function hN(e,n,i,c,p){return Rt(e,i,p)}function bS(e,n,i,c){return Kt(c)?hN(e,Sm(n),i,Sm(mn(c)),pr(c)):Je(c)?fN(e,c.properties):Ar(c)?Se(e):Xr(c)?Se(e):Ze()}function ES(e,n,i){return en(i)?Se(e):Dt(e,n,i)}function SS(e,n,i){return gs(i)?Se(e):Dt(e,n,i)}function wS(e,n,i){let c=Rn(n);return Rt(e,c,i)}function Dd(e,n){return Ct({"~kind":"Inferrable"},{name:e,type:n},{})}function Uu(e){return at(e)&&pe(e,"~kind")&&pe(e,"name")&&pe(e,"type")&&_(e["~kind"],"Inferrable")&&gt(e.name)&&at(e.type)}function qd(e){return Zs(e)?Yr(e.items)?St(e.items.extends)?Dd(e.items.name,e.items.extends.items):Xr(e.items.extends)?Dd(e.items.name,e.items.extends):void 0:_r():void 0}function rp(e){return Yr(e)?Dd(e.name,e.extends):void 0}function Fd(e,n,i=[]){return It(e,(c,p)=>yr(Rt({},c,n),()=>Fd(p,n,[...i,c]),()=>{return}),()=>i)}function TS(e,n,i,c){let p=Fd(i,c);return Be(p)?Se(un(e,{[n]:Lr(p)})):Ze()}function np(e,n,i,c){let p=Fd(i,c);return Be(p)?Se(un(e,{[n]:m(p)})):Ze()}function gN(e){return[...e].reverse()}function jd(e,n){return n?gN(e):e}function yN(e){let n=e.length>0?e[0]:void 0,i=kr(n)?qd(n):void 0;return kr(i)}function xN(e,n,i,c,p,f){return yr(Rt(e,i,p),(g)=>RS(g,n,c,f),()=>Ze())}function IN(e,n,i,c,p){let f=qd(c);return Uu(f)?TS(e,f.name,jd(i,n),f.type):It(i,(g,x)=>xN(e,n,g,x,c,p),()=>Ze())}function bN(e,n,i,c){return It(c,(p,f)=>IN(e,n,i,p,f),()=>_(i.length,0)?Se(e):Ze())}function RS(e,n,i,c){return bN(e,n,i,c)}function EN(e,n,i){let c=ni(e,dr([],[]),i),p=yN(c);return RS(e,p,jd(n,p),jd(c,p))}function kS(e,n,i){let c=rp(i);return Uu(c)?np(e,c.name,n,c.type):It(n,(p,f)=>yr(Rt(e,p,i),(g)=>kS(g,f,i),()=>Ze()),()=>Se(e))}function AS(e,n,i){let c=ni(e,dr([],[]),n);return ct(i)?EN(e,c,i.items):St(i)?kS(e,c,i.items):Dt(e,Lr(c),i)}function CS(e,n,i){return so(i)?Se(e):Qo(i)?Se(e):Dt(e,n,i)}function PS(e,n,i){return It(i,(c,p)=>yr(Rt(e,n,c),(f)=>Se(f),()=>PS(e,n,p)),()=>Ze())}function Ud(e,n,i){return It(n,(c,p)=>yr(PS(e,c,i),(f)=>Ud(f,p,i),()=>Ze()),()=>Se(e))}function $S(e,n,i){let c=rp(i);return Uu(c)?np(e,c.name,n,c.type):be(i)?Ud(e,n,i.anyOf):Ud(e,n,[i])}function MS(e,n,i){return Yr(i)?Dt(e,n,i):Ar(i)?Se(e):Xr(i)?Se(e):Ze()}function vS(e,n,i){return so(i)?Se(e):Dt(e,n,i)}function Rt(e,n,i){return Ar(n)?oS(e,n,i):St(n)?sS(e,n,n.items,i):oo(n)?iS(e,n,i):_n(n)?aS(e,n,i):Kr(n)?uS(e,n.parameters,n.instanceType,i):Or(n)?cS(e,n.if,n.then,n.else,i):Zr(n)?mS(e,n.enum,i):Jr(n)?pS(e,n.parameters,n.returnType,i):cn(n)?lS(e,n,i):He(n)?dS(e,n.allOf,i):yt(n)?fS(e,n,i):no(n)?hS(e,n,i):hs(n)?gS(e,n,i):wr(n)?yS(e,n,i):Je(n)?IS(e,n.properties,i):Kt(n)?bS(e,mn(n),pr(n),i):en(n)?ES(e,n,i):gs(n)?SS(e,n,i):er(n)?wS(e,n.pattern,i):ct(n)?AS(e,n.items,i):Qo(n)?CS(e,n,i):be(n)?$S(e,n.anyOf,i):Xr(n)?MS(e,n,i):so(n)?vS(e,n,i):Ze()}function SN(e,n){return Tr([...e,s(n)])}function Bd(e,n,i){return ut(e)?Et(SN(e,n),{},i):Ou(e,n,i)}function OS(e,n,i,c,p){let f=mo(e,n,i),g=Bu(e,n,c);return Bd(f,g,p)}function Ou(e,n,i={}){return Ne("Interface",[e,n],i)}function va(e){return kr(e)&&pe(e,"action")&&_(e.action,"Interface")}function _S(e,n,i={}){return Bd(e,n,i)}function wN(e,n,i){return e.includes(i)?!0:Gu([...e,i],n,n[i])}function LS(e,n,i){let c=sm(i);return ea(e,n,c)}function ea(e,n,i){return It(i,(c,p)=>Gu(e,n,c)?!0:ea(e,n,p),()=>!1)}function Gu(e,n,i){return jt(i)?wN(e,n,i.$ref):St(i)?Gu(e,n,i.items):Kr(i)?ea(e,n,[...i.parameters,i.instanceType]):Jr(i)?ea(e,n,[...i.parameters,i.returnType]):va(i)?LS(e,n,i.parameters[1]):He(i)?ea(e,n,i.allOf):Je(i)?LS(e,n,i.properties):be(i)?ea(e,n,i.anyOf):ct(i)?ea(e,n,i.items):Kt(i)?Gu(e,n,pr(i)):!1}function NS(e,n,i){return Gu(e,n,i)}function TN(e,n){return n.reduce((i,c)=>NS([c],e,e[c])?[...i,c]:i,[])}function DS(e){let n=om(e);return TN(e,n)}function RN(e,n,i){return i.includes(n)?i:(n in e)?Ku(e,e[n],[...i,n]):_r()}function qS(e,n,i){let c=sm(n);return Oa(e,c,i)}function Oa(e,n,i){return n.reduce((c,p)=>Ku(e,p,c),i)}function Ku(e,n,i){return jt(n)?RN(e,n.$ref,i):St(n)?Ku(e,n.items,i):Kr(n)?Oa(e,[...n.parameters,n.instanceType],i):Jr(n)?Oa(e,[...n.parameters,n.returnType],i):va(n)?qS(e,n.parameters[1],i):He(n)?Oa(e,n.allOf,i):Je(n)?qS(e,n.properties,i):be(n)?Oa(e,n.anyOf,i):ct(n)?Oa(e,n.items,i):Kt(n)?Ku(e,pr(n),i):i}function FS(e,n,i){return Ku(e,i,[n])}function kN(e){return Sa()}function AN(e){return Ee(e).reduce((n,i)=>({...n,[i]:ta(e[i])}),{})}function Hu(e){return e.reduce((n,i)=>[...n,ta(i)],[])}function ta(e){return jt(e)?kN(e.$ref):St(e)?W(ta(e.items),ba(e)):Kr(e)?ms(Hu(e.parameters),ta(e.instanceType)):Jr(e)?ps(Hu(e.parameters),ta(e.returnType)):He(e)?wn(Hu(e.allOf)):Je(e)?s(AN(e.properties)):Kt(e)?ys(Ys(e),ta(pr(e))):be(e)?m(Hu(e.anyOf)):ct(e)?Lr(Hu(e.items)):e}function CN(e,n){return n in e?ta(e[n]):Sr()}function jS(e){return CN(e.$defs,e.$ref)}function PN(e,n,i){let c=mo(e,dr([],[]),n),p=Bu({},dr([],[]),i);return Tr([...c,s(p)])}function $N(e,n){return Ee(e).filter((c)=>n.includes(c)).reduce((c,p)=>{let f=e[p],g=va(f)?PN(e,f.parameters[0],f.parameters[1]):f;return{...c,[p]:g}},{})}function US(e,n,i){let c=FS(e,n,i),p=$N(e,c);return ds(p,n)}function BS(e,n){return n in e?jt(e[n])?BS(e,e[n].$ref):e[n]:zt()}function xs(e,n){return BS(e,n)}function GS(e){return Jt(e)?jS(e):im(e)?Sr():e}function xn(e,n,i){let c=GS(n),p=GS(i);return Rt(e,c,p)}var Cu=0,Wu=1,Pu=2,$u=3;function ka(e,n){let i=[xn({},e,n),xn({},n,e)];return Zn(i[0])&&Zn(i[1])?Cu:Zn(i[0])&&Nd(i[1])?Pu:Nd(i[0])&&Zn(i[1])?$u:Wu}function Gd(e,n,i=[],c=n){return It(n,(p,f)=>{let g=ka(e,p);return _(g,Pu)||_(g,Cu)?c:_(g,Wu)?Gd(e,f,[...i,p],c):Gd(e,f,i,c)},()=>[...i,e])}function MN(e,n,i){let c=bo(e);return Ar(c)?[c]:Xr(c)?[c]:no(c)?op(n,i):Je(c)?op(n,[...i,c]):op(n,Gd(c,i))}function op(e,n=[]){return It(e,(i,c)=>MN(i,c,n),()=>n)}function yd(e){let n=op(e);return Xi(n)}function Kd(e,n){return Et(bo(e),{},n)}function KS(e,n,i,c){let p=le(e,n,i);return Kd(p,c)}function zu(e,n=[]){return Ws(e)&&_(e.action,"Conditional")?jt(e.parameters[0])?zu(e.parameters[2],zu(e.parameters[3],[...n,e.parameters[0].$ref])):zu(e.parameters[2],zu(e.parameters[3],n)):Ws(e)&&_(e.action,"Mapped")?Ws(e.parameters[1])&&_(e.parameters[1].action,"KeyOf")&&jt(e.parameters[1].parameters[0])?[...n,e.parameters[1].parameters[0].$ref]:n:n}function vN(e,n){return e.reduce((i,c)=>[...i,n.includes(c.name)],[])}function zS(e,n,i=[]){return It(e,(c,p)=>It(n,(f,g)=>zS(p,g,[...i,[f,c]]),()=>i),()=>i)}function ON(e){return er(e)?Rn(e.pattern):Zr(e)?Ln(e.enum):e}function _N(e){let n=ON(e);return be(n)?[...n.anyOf]:[n]}function LN(e,n){return e.reduce((i,c)=>[...i,[...c,n]],[])}function HS(e,n){return n.reduce((i,c)=>[...i,...LN(e,c)],[])}function WS(e){return e.reduce((n,i)=>_(i[0],!0)?HS(n,_N(i[1])):HS(n,[i[1]]),[[]])}function VS(e,n,i){let c=zu(i),p=vN(e,c),f=zS(n,p);return Ws(i)&&_(i.action,"Conditional")?WS(f):Ws(i)&&_(i.action,"Mapped")?WS(f):[n]}function NN(){return["(not-resolvable)",zt()]}function DN(){return["(not-generic)",zt()]}function qN(e,n,i){return[e,zs(n,i)]}function FN(e,n,i){return n in e?QS(e,n,e[n],i):NN()}function QS(e,n,i,c){return Ea(i)?qN(n,i.parameters,i.expression):jt(i)?FN(e,i.$ref,c):DN()}function JS(e,n,i){return QS(e,"(anonymous)",n,i)}function jN(e,n,i){if(Yr(n)||_a(n)||Zn(xn({},n,i)))return;let c={parameter:e,expect:i,actual:n};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:c})}function XS(e,n,i,c,p){let f=le(e,n,p);return jN(i,f,c),un(e,{[i]:f})}function UN(e,n,i,c,p){let f=le(e,n,i.extends),g=le(e,n,i.equals);return It(p,(x,I)=>Hd(XS(e,n,i.name,f,x),n,c,I),()=>Hd(XS(e,n,i.name,f,g),n,c,[]))}function Hd(e,n,i,c){return It(i,(p,f)=>UN(e,n,p,f,c),()=>e)}function YS(e,n,i,c){return Hd(e,n,i,c)}var Wd=0,zd=0;function BN(){if(yu(zd,Ko().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function GN(){BN(),zd++,Wd++}function KN(){if(Wd--,_(Wd,0))zd=0}function HN(e){return qi(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function WN(e,n){return _(HN(e),n)}function zN(e,n,i,c,p,f){GN();try{let g=YS(e,n,c,f),x=le(g,dr([...n.callstack,i.$ref],n.visited),p);return le(g,dr([],[]),x)}finally{KN()}}function VN(e,n,i,c,p,f){return f.reduce((g,x)=>{let I=zN(e,n,i,c,p,x);return[...g,I]},[])}function QN(e,n,i,c,p,f){let g=VS(c,f,p),x=VN(e,n,i,c,p,g);return _(x.length,1)?x[0]:Yn(x)}function sp(e,n,i,c){let p=mo(e,n,c),f=JS(e,i,c),g=f[0],x=f[1];return Ea(x)?WN(n,g)?_u(rn(g),p):QN(e,n,rn(g),x.parameters,x.expression,p):_u(i,p)}function _u(e,n){return Ct({["~kind"]:"Call"},{type:"call",target:e,arguments:n},{})}function ZS(e,n){return sp({},dr([],[]),e,n)}function _a(e){return Ae(e,"Call")}function JN(e){return Ho(e,["~immutable"])}function ew(e,n){return Et(JN(e),{},n)}function tw(e,n,i,c){let p=le(e,n,i);return ew(p,c)}function rw(e,n){return e(n)}function nw(e,n){return gt(n)?a(rw(e,n)):a(n)}function ow(e,n){let i=Rn(n);return Ms(e,i)}function sw(e,n){let i=n.map((c)=>Ms(e,c));return m(i)}function Ms(e,n){return yt(n)?nw(e,n.const):er(n)?ow(e,n.pattern):be(n)?sw(e,n.anyOf):n}function Am(e,n={}){return Ne("Capitalize",[e],n)}function iw(e,n={}){return Vd(e,n)}function Cm(e,n={}){return Ne("Lowercase",[e],n)}function aw(e,n={}){return Qd(e,n)}function Pm(e,n={}){return Ne("Uncapitalize",[e],n)}function uw(e,n={}){return Jd(e,n)}function $m(e,n={}){return Ne("Uppercase",[e],n)}function cw(e,n={}){return Xd(e,n)}var XN=(e)=>e[0].toUpperCase()+e.slice(1),YN=(e)=>e.toLowerCase(),ZN=(e)=>e[0].toLowerCase()+e.slice(1),eD=(e)=>e.toUpperCase();function Vd(e,n){return ut([e])?Et(Ms(XN,e),{},n):Am(e,n)}function Qd(e,n){return ut([e])?Et(Ms(YN,e),{},n):Cm(e,n)}function Jd(e,n){return ut([e])?Et(Ms(ZN,e),{},n):Pm(e,n)}function Xd(e,n){return ut([e])?Et(Ms(eD,e),{},n):$m(e,n)}function mw(e,n,i,c){let p=le(e,n,i);return Vd(p,c)}function pw(e,n,i,c){let p=le(e,n,i);return Qd(p,c)}function lw(e,n,i,c){let p=le(e,n,i);return Jd(p,c)}function dw(e,n,i,c){let p=le(e,n,i);return Xd(p,c)}function Mm(e,n,i,c,p={}){return Ne("Conditional",[e,n,i,c],p)}function fw(e,n,i,c,p={}){return Yd({},dr([],[]),e,n,i,c,p)}function tD(e,n,i,c,p,f){let g=xn(e,i,c);return _d(g)?m([le(g.inferred,n,p),le(e,n,f)]):Ld(g)?le(g.inferred,n,p):le(e,n,f)}function Yd(e,n,i,c,p,f,g){return ut([i,c])?Et(tD(e,n,i,c,p,f),{},g):Mm(i,c,p,f,g)}function hw(e,n,i,c,p,f,g){let x=le(e,n,i),I=le(e,n,c);return Yd(e,n,x,I,p,f,g)}function vm(e,n={}){return Ne("ConstructorParameters",[e],n)}function gw(e,n={}){return Zd(e,n)}function rD(e){let n=Kr(e)?e.parameters:[],i=ni({},dr([],[]),n);return Lr(i)}function Zd(e,n){return ut([e])?Et(rD(e),{},n):vm(e,n)}function yw(e,n,i,c){let p=le(e,n,i);return Zd(p,c)}function Om(e,n,i={}){return Ne("Exclude",[e,n],i)}function xw(e,n,i={}){return Vu(e,n,i)}function Vu(e,n,i){return ut([e,n])?Et(bm(e,n),{},i):Om(e,n,i)}function Iw(e,n,i,c,p){let f=le(e,n,i),g=le(e,n,c);return Vu(f,g,p)}function _m(e,n,i={}){return Ne("Extract",[e,n],i)}function bw(e,n,i={}){return ef(e,n,i)}function nD(e,n){let i=xn({},e,n);return Zn(i)?[e]:[]}function Ew(e,n,i=[]){return It(e,(c,p)=>Ew(p,n,[...i,...nD(c,n)]),()=>i)}function Sw(e,n){let i=bo(e),c=be(i)?i.anyOf:[i],p=Ew(c,n);return Yn(p)}function ef(e,n,i){return ut([e,n])?Et(Sw(e,n),{},i):_m(e,n,i)}function ww(e,n,i,c,p){let f=le(e,n,i),g=le(e,n,c);return ef(f,g,p)}function oD(e){return e.reduce((n,i)=>lm(i)?[...n,a(i)]:n,[])}function La(e){let n=oD(e);return m(n)}function Lu(e,n,i={}){return Ne("Index",[e,n],i)}function Tw(e,n,i={}){let c=Be(n)?La(n):n;return tf(e,c,i)}function Rw(e,n){let i=xs(e,n);return po(i)}function kw(e,n,i){let c=Vo(e,n,i);return po(c)}function sD(e,n){let i=Ee(e).filter((E)=>!pe(n,E)),c=Ee(n).filter((E)=>!pe(e,E)),p=Ee(e).filter((E)=>pe(n,E)),f=i.reduce((E,T)=>({...E,[T]:e[T]}),{}),g=c.reduce((E,T)=>({...E,[T]:n[T]}),{}),x=p.reduce((E,T)=>({...E,[T]:Tr([e[T],n[T]])}),{}),I=un(f,g);return un(I,x)}function Aw(e){return e.reduce((n,i)=>sD(n,po(i)),{})}function Cw(e){return e}function Pw(e){let n=yx(Lr(e));return po(n)}function iD(e,n){return Ee(e).filter((p)=>(p in n)).reduce((p,f)=>({...p,[f]:Yn([e[f],n[f]])}),{})}function $w(e,n){return It(e,(i,c)=>$w(c,iD(n,po(i))),()=>n)}function Mw(e){return It(e,(n,i)=>$w(i,po(n)),()=>_r())}function po(e){return Jt(e)?Rw(e.$defs,e.$ref):Or(e)?kw(e.if,e.then,e.else):He(e)?Aw(e.allOf):be(e)?Mw(e.anyOf):ct(e)?Pw(e.items):Je(e)?Cw(e.properties):{}}function Na(e){let n=po(e);return s(n)}var aD=new RegExp("^(?:0|[1-9][0-9]*)$");function Da(e){let n=`${e}`;return aD.test(n)?parseInt(n):e}function uD(e){return a(Da(e))}function vw(e){return e.map((n)=>Ow(n))}function Ow(e){return He(e)?wn(vw(e.allOf)):be(e)?m(vw(e.anyOf)):yt(e)?uD(e.const):e}function _w(e,n){let i=Ow(n),c=xn({},i,J());return Zn(c)?e:yt(n)&&_(n.const,"length")?J():zt()}function Lw(e,n){let i=xs(e,n);return io(i)}function Nw(e,n,i){let c=Vo(e,n,i);return io(c)}function Dw(e){let n=Ln(e);return io(n)}function qw(e){let n=Tr(e);return io(n)}function Fw(e){return[`${e}`]}function jw(e){let n=Rn(e);return io(n)}function Uw(e){return e.reduce((n,i)=>[...n,...io(i)],[])}function io(e){return Jt(e)?Lw(e.$defs,e.$ref):Or(e)?Nw(e.if,e.then,e.else):Zr(e)?Dw(e.enum):He(e)?qw(e.allOf):yt(e)?Fw(e.const):er(e)?jw(e.pattern):be(e)?Uw(e.anyOf):[]}function qa(e){return io(e)}function Qu(e,n){return n.map((i)=>Ju(e,i))}function Ju(e,n){return St(n)?W(Ju(e,n.items)):Kr(n)?ms(Qu(e,n.parameters),Ju(e,n.instanceType)):Jr(n)?ps(Qu(e,n.parameters),Ju(e,n.returnType)):ct(n)?Lr(Qu(e,n.items)):be(n)?m(Qu(e,n.anyOf)):He(n)?wn(Qu(e,n.allOf)):Tm(n)?s(e):n}function Bw(e,n){return Ju(e,n)}function cD(e,n){let i=n in e?e[n]:zt();return Bw(e,i)}function Gw(e,n){return n.reduce((i,c)=>[...i,cD(e,c)],[])}function mD(e,n){let i=qa(n),c=Gw(e,i);return Yn(c)}var pD=new RegExp(Xs);function lD(e){return e.filter((i)=>pD.test(i))}function dD(e){let n=om(e),i=lD(n),c=Gw(e,i);return Yn(c)}function Kw(e,n){return wr(n)?dD(e):mD(e,n)}function fD(e){return a(Da(e))}function Hw(e){return e.map((n)=>rf(n))}function rf(e){return He(e)?wn(Hw(e.allOf)):be(e)?m(Hw(e.anyOf)):yt(e)?fD(e.const):e}function hD(e,n){return e.reduceRight((i,c,p)=>{let f=xn({},a(p),n);return Zn(f)?[c,...i]:i},[])}function gD(e,n){let i=rf(n),c=hD(e,i);return Qs(c)}function yD(e){return Qs(e)}function Ww(e,n){return yt(n)&&_(n.const,"length")?a(e.length):wr(n)||cn(n)?yD(e):gD(e,n)}function zw(e,n){return St(e)?_w(e.items,n):Je(e)?Kw(e.properties,n):ct(e)?Ww(e.items,n):zt()}function xD(e){return Jt(e)||Or(e)||He(e)||be(e)?Na(e):e}function tf(e,n,i){return ut([e,n])?Et(zw(xD(e),n),{},i):Lu(e,n,i)}function Vw(e,n,i,c,p){let f=le(e,n,i),g=le(e,n,c);return tf(f,g,p)}function Lm(e,n={}){return Ne("InstanceType",[e],n)}function Qw(e,n={}){return nf(e,n)}function ID(e){return Kr(e)?e.instanceType:zt()}function nf(e,n){return ut([e])?Et(ID(e),{},n):Lm(e,n)}function Jw(e,n,i,c={}){let p=le(e,n,i);return nf(p,c)}function Nu(e,n={}){return Ne("KeyOf",[e],n)}function Xw(e,n={}){return of(e,n)}function Yw(){return m([J(),l(),Ra()])}function Zw(e){return J()}function bD(e){return e.reduce((i,c)=>lm(c)?[...i,a(Da(c))]:_r(),[])}function eT(e){let n=Ee(e),i=bD(n);return Qs(i)}function tT(e){return Ys(e)}function rT(e){let n=e.map((i,c)=>a(c));return Qs(n)}function nT(e){return Ar(e)?Yw():St(e)?Zw(e.items):Je(e)?eT(e.properties):Kt(e)?tT(e):ct(e)?rT(e.items):zt()}function ED(e){return Jt(e)||Or(e)||He(e)||be(e)?Na(e):e}function of(e,n){return ut([e])?Et(nT(ED(e)),{},n):Nu(e,n)}function oT(e,n,i,c){let p=le(e,n,i);return of(p,c)}function vu(e,n,i,c,p={}){return Ne("Mapped",[e,n,i,c],p)}function sT(e,n,i,c,p={}){return sf({},dr([],[]),e,n,i,c,p)}function SD(e){let n=Rn(e);return ip(n)}function wD(e){return e.reduce((n,i)=>[...n,...ip(i)],[])}function TD(e){let n=Ln(e);return ip(n)}function RD(e){return Ot(e)?[a(`${e}`)]:[a(e)]}function ip(e){return Zr(e)?TD(e.enum):yt(e)?RD(e.const):er(e)?SD(e.pattern):be(e)?wD(e.anyOf):[e]}function iT(e){return ip(e)}function kD(e){return er(e)?Rn(e.pattern):e}function AD(e,n,i,c,p,f){let g=un(e,{[i.name]:c}),x=le(g,n,p),I=kD(x),b=le(g,n,f);return dm(I)||fm(I)?{[I.const]:b}:{}}function CD(e,n,i,c,p,f){return c.reduce((g,x)=>[...g,AD(e,n,i,x,p,f)],[])}function PD(e){return e.reduce((n,i)=>[...n,s(i)],[])}function aT(e,n,i,c,p,f){let g=iT(c),x=CD(e,n,i,g,p,f),I=PD(x);return Tr(I)}function sf(e,n,i,c,p,f,g){return ut([c])?Et(aT(e,n,i,c,p,f),{},g):vu(i,c,p,f,g)}function uT(e,n,i,c,p,f,g){let x=le(e,n,c);return sf(e,n,i,x,p,f,g)}function $D(e,n,i){let c=un(e,n);return Ee(n).filter((f)=>i.includes(f)).reduce((f,g)=>({...f,[g]:US(c,g,n[g])}),{})}function MD(e,n,i){let c=un(e,n);return Ee(n).filter((f)=>!i.includes(f)).reduce((f,g)=>({...f,[g]:le(c,dr([],[]),n[g])}),{})}function vD(e,n,i){let c=DS(n),p=$D(e,n,c),f=MD(e,n,c),g={...p,...f};return Et(g,{},i)}function ap(e,n,i,c){return vD(e,i,c)}function Nm(e,n={}){return Ne("NonNullable",[e],n)}function cT(e,n={}){return af(e,n)}function OD(e){let n=m([Tn(),Ca()]);return Vu(e,n,{})}function af(e,n){return ut([e])?Et(OD(e),{},n):Nm(e,n)}function mT(e,n,i,c){let p=le(e,n,i);return af(p,c)}function Dm(e,n,i={}){return Ne("Omit",[e,n],i)}function pT(e,n,i={}){let c=Be(n)?La(n):n;return uf(e,c,i)}function up(e){let n=Na(e);return Je(n)?n.properties:_r()}function _D(e,n){return Ee(e).reduce((c,p)=>n.includes(p)?c:{...c,[p]:e[p]},{})}function lT(e,n){let i=up(e),c=qa(n),p=_D(i,c);return s(p)}function uf(e,n,i){return ut([e,n])?Et(lT(e,n),{},i):Dm(e,n,i)}function dT(e,n,i,c,p){let f=le(e,n,i),g=le(e,n,c);return uf(f,g,p)}function qm(e,n={}){return Ne("Parameters",[e],n)}function fT(e,n={}){return cf(e,n)}function LD(e){let n=Jr(e)?e.parameters:[],i=ni({},dr([],[]),n);return Lr(i)}function cf(e,n){return ut([e])?Et(LD(e),{},n):qm(e,n)}function hT(e,n,i,c){let p=le(e,n,i);return cf(p,c)}function Fm(e,n={}){return Ne("Partial",[e],n)}function gT(e,n={}){return mf(e,n)}function yT(e,n){let i=xs(e,n),c=Is(i);return ds(un(e,{[n]:c}),n)}function xT(e,n,i){let c=Vo(e,n,i);return Is(c)}function IT(e){let n=Tr(e);return Is(n)}function bT(e){let n=e.map((i)=>Is(i));return m(n)}function ET(e){let n=Ee(e).reduce((c,p)=>({...c,[p]:Ki(e[p])}),{});return s(n)}function Is(e){return Jt(e)?yT(e.$defs,e.$ref):Or(e)?xT(e.if,e.then,e.else):He(e)?IT(e.allOf):be(e)?bT(e.anyOf):Je(e)?ET(e.properties):s({})}function mf(e,n){return ut([e])?Et(Is(e),{},n):Fm(e,n)}function ST(e,n,i,c){let p=le(e,n,i);return mf(p,c)}function jm(e,n,i={}){return Ne("Pick",[e,n],i)}function wT(e,n,i={}){let c=Be(n)?La(n):n;return pf(e,c,i)}function ND(e,n){return Ee(e).reduce((c,p)=>n.includes(p)?un(c,{[p]:e[p]}):c,{})}function TT(e,n){let i=up(e),c=qa(n),p=ND(i,c);return s(p)}function pf(e,n,i){return ut([e,n])?Et(TT(e,n),{},i):jm(e,n,i)}function RT(e,n,i,c,p){let f=le(e,n,i),g=le(e,n,c);return pf(f,g,p)}function Um(e,n={}){return Ne("ReadonlyObject",[e],n)}function lf(e,n={}){return df(e,n)}var kT=lf;function AT(e){return Ta(W(e))}function CT(e,n){let i=xs(e,n),c=bs(i);return ds(un(e,{[n]:c}),n)}function PT(e,n,i){let c=Vo(e,n,i);return bs(c)}function $T(e){let n=Tr(e);return bs(n)}function MT(e){let n=Ee(e).reduce((c,p)=>({...c,[p]:Vi(e[p])}),{});return s(n)}function vT(e){return Ta(Lr(e))}function OT(e){let n=e.map((i)=>bs(i));return m(n)}function bs(e){return St(e)?AT(e.items):Jt(e)?CT(e.$defs,e.$ref):Or(e)?PT(e.if,e.then,e.else):He(e)?$T(e.allOf):Je(e)?MT(e.properties):ct(e)?vT(e.items):be(e)?OT(e.anyOf):e}function df(e,n){return ut([e])?Et(bs(e),{},n):Um(e)}function _T(e,n,i,c){let p=le(e,n,i);return df(p,c)}function LT(e,n,i,c){return n.visited.includes(c)?i:(c in e)?le(e,dr(n.callstack,[...n.visited,c]),e[c]):i}function NT(e,n){let i=xs(e,n),c=Es(i);return ds(un(e,{[n]:c}),n)}function DT(e,n,i){let c=Vo(e,n,i);return Es(c)}function qT(e){let n=Tr(e);return Es(n)}function FT(e){let n=e.map((i)=>Es(i));return m(n)}function jT(e){let n=Ee(e).reduce((c,p)=>({...c,[p]:Im(e[p])}),{});return s(n)}function Es(e){return Jt(e)?NT(e.$defs,e.$ref):Or(e)?DT(e.if,e.then,e.else):He(e)?qT(e.allOf):be(e)?FT(e.anyOf):Je(e)?jT(e.properties):s({})}function Bm(e,n={}){return Ne("Required",[e],n)}function UT(e,n={}){return ff(e,n)}function ff(e,n){return ut([e])?Et(Es(e),{},n):Bm(e,n)}function BT(e,n,i,c){let p=le(e,n,i);return ff(p,c)}function Gm(e,n={}){return Ne("ReturnType",[e],n)}function GT(e,n={}){return hf(e,n)}function DD(e){return Jr(e)?e.returnType:zt()}function hf(e,n){return ut([e])?Et(DD(e),{},n):Gm(e,n)}function KT(e,n,i,c={}){let p=le(e,n,i);return hf(p,c)}function Km(e,n){return Ne("With",[e,n],{})}function cp(e,n){return gf(e,n)}function gf(e,n){return ut([e])?Et(e,{},n):Km(e,n)}function HT(e,n,i,c){let p=le(e,n,i);return gf(p,c)}function qD(e){return Zs(e)?ct(e.items)?yf(e.items.items):Yr(e.items)?[e]:jt(e.items)?[e]:[zt()]:[e]}function yf(e){return e.reduce((i,c)=>[...i,...qD(c)],[])}function dr(e,n){return{callstack:e,visited:n}}function ut(e){return It(e,(n,i)=>jt(n)?!1:ut(i),()=>!0)}function Bu(e,n,i){return Ee(i).reduce((c,p)=>({...c,[p]:le(e,n,i[p])}),{})}function ni(e,n,i){let c=mo(e,n,i);return yf(c)}function mo(e,n,i){return i.map((c)=>le(e,n,c))}function FD(e,n){let i=nn(e)?Su(n,{}):n,c=Qi(e)?Eu(i,{}):i;return zi(e)?Xu(c,{}):c}function jD(e,n,i,c,p){return _(i,"AddImmutable")?WT(e,n,c[0],p):_(i,"RemoveImmutable")?tw(e,n,c[0],p):_(i,"AddReadonly")?Iy(e,n,c[0],p):_(i,"RemoveReadonly")?lx(e,n,c[0],p):_(i,"AddOptional")?by(e,n,c[0],p):_(i,"RemoveOptional")?hx(e,n,c[0],p):_(i,"Capitalize")?mw(e,n,c[0],p):_(i,"Conditional")?hw(e,n,c[0],c[1],c[2],c[3],p):_(i,"ConstructorParameters")?yw(e,n,c[0],p):_(i,"Evaluate")?KS(e,n,c[0],p):_(i,"Exclude")?Iw(e,n,c[0],c[1],p):_(i,"Extract")?ww(e,n,c[0],c[1],p):_(i,"Index")?Vw(e,n,c[0],c[1],p):_(i,"InstanceType")?Jw(e,n,c[0],p):_(i,"Interface")?OS(e,n,c[0],c[1],p):_(i,"KeyOf")?oT(e,n,c[0],p):_(i,"Lowercase")?pw(e,n,c[0],p):_(i,"Mapped")?uT(e,n,c[0],c[1],c[2],c[3],p):_(i,"Module")?ap(e,n,c[0],p):_(i,"NonNullable")?mT(e,n,c[0],p):_(i,"Pick")?RT(e,n,c[0],c[1],p):_(i,"Parameters")?hT(e,n,c[0],p):_(i,"Partial")?ST(e,n,c[0],p):_(i,"Omit")?dT(e,n,c[0],c[1],p):_(i,"ReadonlyObject")?_T(e,n,c[0],p):_(i,"Record")?vx(e,n,c[0],c[1],p):_(i,"Required")?BT(e,n,c[0],p):_(i,"ReturnType")?KT(e,n,c[0],p):_(i,"TemplateLiteral")?ZE(e,n,c[0],p):_(i,"Uncapitalize")?lw(e,n,c[0],p):_(i,"Uppercase")?dw(e,n,c[0],p):_(i,"With")?HT(e,n,c[0],c[1]):Ne(i,c,p)}function UD(e,n,i){let c=jt(i)?LT(e,n,i,i.$ref):St(i)?W(le(e,n,i.items),ba(i)):_a(i)?sp(e,n,i.target,i.arguments):Kr(i)?ms(mo(e,n,i.parameters),le(e,n,i.instanceType),Ey(i)):Jr(i)?ps(mo(e,n,i.parameters),le(e,n,i.returnType),Sy(i)):Or(i)?Hi(le(e,n,i.if),le(e,n,i.then),le(e,n,i.else),ky(i)):He(i)?wn(mo(e,n,i.allOf),My(i)):Je(i)?s(Bu(e,n,i.properties),Ry(i)):Kt(i)?Ox(mn(i),le(e,n,pr(i))):Zs(i)?Yi(le(e,n,i.items)):ct(i)?Lr(ni(e,n,i.items),px(i)):be(i)?m(mo(e,n,i.anyOf),tx(i)):i;return FD(i,c)}function le(e,n,i){return Ws(i)?jD(e,n,i.action,i.parameters,i.options):UD(e,n,i)}function Eo(e,n){return le(e,dr([],[]),n)}function BD(e){return Et(e,{"~immutable":!0},{})}function Xu(e,n){return Et(BD(e),{},n)}function WT(e,n,i,c){let p=le(e,n,i);return Xu(p,c)}function Qb(e,n={}){return Ne("AddImmutable",[e],n)}function Ta(e,n={}){return Xu(e,n)}function Jb(e,n={}){return Ne("Evaluate",[e],n)}function In(e,n={}){return Kd(e,n)}function Xb(e,n={}){return Ne("Module",[e],n)}function zT(e,n={}){return ap({},dr([],[]),e,n)}function GD(e,n){let i=ka(e,n);return _(i,$u)?1:_(i,Wu)?1:0}function VT(e,n,i=[]){return It(n,(c,p)=>_(GD(e,c),1)?VT(e,p,[...i,c]):[...i,e,...n],()=>[...i,e])}function QT(e,n=[]){return It(e,(i,c)=>QT(c,VT(i,n)),()=>n)}function JT(e){return QT(e)}function XT(...e){let[n,i,c]=yn(e,{2:(g,x)=>gt(g)?[{},g,x]:[g,x,{}],3:(g,x,I)=>[g,x,I],1:(g)=>[{},g,{}]}),p=VE(i),f=Be(p)&&_(p.length,2)?le(n,dr([],[]),p[0]):zt();return Et(f,{},c)}function h(e,n){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let c=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:c}},resolve:async({ctx:i,credential:c,signal:p})=>{if(p.throwIfAborted(),c?.key)return{auth:{apiKey:c.key},env:c.env,source:"stored credential"};for(let f of n){let g=await i.env(f);if(p.throwIfAborted(),g)return{auth:{apiKey:g},source:f}}return}}}function ae(e){let n,i=()=>(n??=e.load(),n);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(c,p)=>(await i()).login(c,p),refresh:async(c,p)=>(await i()).refresh(c,p),toAuth:async(c)=>(await i()).toAuth(c)}}var tR="faux",rR="faux",nR="faux-1",KD="Faux Model",HD="http://localhost:0",WD=3,YT=5,lp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Fn(e){return{type:"text",text:e}}function Ro(e){return{type:"thinking",thinking:e}}function zD(e,n,i={}){return{type:"toolCall",id:i.id??bf("tool"),name:e,arguments:n}}function VD(e){if(typeof e==="string")return[Fn(e)];return Array.isArray(e)?e:[e]}function Io(e,n={}){return{role:"assistant",content:VD(e),api:tR,provider:rR,model:nR,usage:lp,stopReason:n.stopReason??"stop",...n.deferred===void 0?{}:{deferred:n.deferred},...n.errorMessage===void 0?{}:{errorMessage:n.errorMessage},...n.responseId===void 0?{}:{responseId:n.responseId},timestamp:n.timestamp??Date.now()}}function oR(e){return Math.ceil(e.length/4)}function bf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function sR(e){if(typeof e==="string")return e;return e.map((n)=>{if(n.type==="text")return n.text;return`[image:${n.mimeType}:${n.data.length}]`}).join(`
21
+ `)}function iR(e){return e.map((n)=>{if(n.type==="text")return n.text;if(n.type==="thinking")return n.thinking;return`${n.name}:${JSON.stringify(n.arguments)}`}).join(`
22
+ `)}function QD(e){return[e.toolName,...e.content.map((n)=>sR([n]))].join(`
23
+ `)}function JD(e){if(e.role==="system")return[N(e),...e.toolsRemoved?.map((n)=>`tool-:${JSON.stringify(n)}`)??[],...e.toolsAdded?.map((n)=>`tool+:${JSON.stringify(n)}`)??[]].filter((n)=>n.length>0).join(`
24
+ `);if(e.role==="user")return sR(e.content);if(e.role==="assistant")return iR(e.content);return QD(e)}function aR(e,n=e.length){let i=n>0?(n-1)*2:0;for(let c=0;c<n;c++)i+=e[c].length;return i}function XD(e,n){let i=0;while(i<e.length&&i<n.length&&e[i]===n[i])i++;let c=(p)=>i===p.length?"":(i>0?`
25
+
26
+ `:"")+p.slice(i).join(`
27
+
28
+ `);return aR(e,i)+YD(c(e),c(n))}function YD(e,n){let i=Math.min(e.length,n.length),c=0;while(c<i&&e[c]===n[c])c++;return c}function ZT(e,n,i,c){let p=n.messages.map((k)=>`${k.role}:${JD(k)}`),f=aR(p),g=Math.ceil(f/4),x=oR(iR(e.content)),I=g,b=0,E=0,T=i?.sessionId;if(T&&i?.cacheRetention!=="none"){let k=c.get(T);if(k){let A=XD(k,p);b=Math.ceil(A/4),E=Math.ceil((f-A)/4),I=Math.max(0,g-b)}else E=g;c.set(T,p)}return{...e,usage:{input:I,output:x,cacheRead:b,cacheWrite:E,totalTokens:I+x+b+E,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function xf(e,n,i){let c=[],p=0;while(p<e.length){let f=n+Math.floor(Math.random()*(i-n+1)),g=Math.max(1,f*4);c.push(e.slice(p,p+g)),p+=g}return c.length>0?c:[""]}function ZD(e,n,i,c){let p=structuredClone(e);return{...p,api:n,provider:i,model:c,timestamp:p.timestamp??Date.now(),usage:p.usage??lp}}function eR(e,n){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:lp,stopReason:"deferred",deferred:n,timestamp:Date.now()}}function mp(e,n,i,c){return{role:"assistant",content:[],api:n,provider:i,model:c,usage:lp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function Yu(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function If(e,n){if(!n||n<=0)return new Promise((c)=>queueMicrotask(c));let i=oR(e)/n*1000;return new Promise((c)=>setTimeout(c,i))}async function pp(e,n,i,c,p,f){let g={...n,content:[],stopReason:"pending"};if(f?.aborted){let x=Yu(g);e.push({type:"error",reason:"aborted",error:x}),e.end(x);return}e.push({type:"start",partial:{...g}});for(let x=0;x<n.content.length;x++){if(f?.aborted){let b=Yu(g);e.push({type:"error",reason:"aborted",error:b}),e.end(b);return}let I=n.content[x];if(I.type==="thinking"){g.content=[...g.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:x,partial:{...g}});for(let b of xf(I.thinking,i,c)){if(await If(b,p),f?.aborted){let E=Yu(g);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}g.content[x].thinking+=b,e.push({type:"thinking_delta",contentIndex:x,delta:b,partial:{...g}})}e.push({type:"thinking_end",contentIndex:x,content:I.thinking,partial:{...g}});continue}if(I.type==="text"){g.content=[...g.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:x,partial:{...g}});for(let b of xf(I.text,i,c)){if(await If(b,p),f?.aborted){let E=Yu(g);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}g.content[x].text+=b,e.push({type:"text_delta",contentIndex:x,delta:b,partial:{...g}})}e.push({type:"text_end",contentIndex:x,content:I.text,partial:{...g}});continue}g.content=[...g.content,{type:"toolCall",id:I.id,name:I.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:x,partial:{...g}});for(let b of xf(JSON.stringify(I.arguments),i,c)){if(await If(b,p),f?.aborted){let E=Yu(g);e.push({type:"error",reason:"aborted",error:E}),e.end(E);return}e.push({type:"toolcall_delta",contentIndex:x,delta:b,partial:{...g}})}g.content[x].arguments=I.arguments,e.push({type:"toolcall_end",contentIndex:x,toolCall:I,partial:{...g}})}if(n.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(n.stopReason==="error"||n.stopReason==="aborted"){e.push({type:"error",reason:n.stopReason,error:n}),e.end(n);return}e.push({type:"done",reason:n.stopReason,message:n}),e.end(n)}function uR(e){let n=e.api??bf(tR),i=e.provider??rR,c=Math.max(1,Math.min(e.tokenSize?.min??WD,e.tokenSize?.max??YT)),p=Math.max(c,e.tokenSize?.max??YT),f=[],g=e.tokensPerSecond,x={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},I=new Map,b=new Map,T=((e.models?.length)?e.models:[{id:nR,name:KD,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((V)=>({id:V.id,name:V.name??V.id,api:n,provider:i,baseUrl:HD,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),k=async(V,X,ie,Y)=>{let z=typeof V==="function"?await V(X,ie,x,Y):V;return ZT(ZD(z,n,i,Y.id),X,ie,I)},A=(V,X,ie)=>{let Y=Kn(),z=f.shift();return x.callCount++,queueMicrotask(async()=>{try{if(await ie?.onResponse?.({status:200,headers:{}},V),!z){let he=mp(Error("No more faux responses queued"),n,i,V.id);he=ZT(he,X,ie,I),Y.push({type:"error",reason:"error",error:he}),Y.end(he);return}if(ie?.deferred){let he={provider:V.provider,modelId:V.id,api:V.api,id:bf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};b.set(he.id,{handle:he,step:z,context:X,options:ie,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await pp(Y,eR(V,he),c,p,g,ie.signal);return}let ce=await k(z,X,ie,V);await pp(Y,ce,c,p,g,ie?.signal)}catch(ce){let he=mp(ce,n,i,V.id);Y.push({type:"error",reason:"error",error:he}),Y.end(he)}}),Y},L=(V,X,ie)=>A(V,X,ie),q=(V,X,ie)=>{let Y=Kn();return x.deferredFetchCount++,queueMicrotask(async()=>{try{await ie?.onResponse?.({status:200,headers:{}},V);let z=b.get(X.id);if(!z||z.handle.provider!==X.provider||z.handle.modelId!==X.modelId||z.handle.api!==X.api)throw Error(`Unknown faux deferred response: ${X.id}`);if(z.cancelled)throw Error(`Faux deferred response was cancelled: ${X.id}`);if(z.pendingFetches>0){z.pendingFetches--,await pp(Y,eR(V,z.handle),c,p,g,ie?.signal);return}if(!z.final){let{deferred:ce,signal:he,onResponse:ve,...de}=z.options??{};try{z.final=await k(z.step,z.context,de,z.model)}catch(se){z.final=mp(se,n,i,z.model.id)}}await pp(Y,z.final,c,p,g,ie?.signal)}catch(z){let ce=mp(z,n,i,V.id);Y.push({type:"error",reason:"error",error:ce}),Y.end(ce)}}),Y},Z=async(V,X,ie)=>{x.cancelledDeferred.push(structuredClone(X));let Y=b.get(X.id);if(Y)Y.cancelled=!0;await ie?.onResponse?.({status:200,headers:{}},V)};function B(V){if(!V)return T[0];return T.find((X)=>X.id===V)}return{api:n,provider:i,models:T,stream:A,streamSimple:L,fetchDeferred:q,cancelDeferred:Z,getModel:B,state:x,setResponses(V){f=[...V]},appendResponses(V){f.push(...V)},getPendingResponseCount(){return f.length}}}function Co(e={}){let n=uR(e);return{provider:d({id:n.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:n.models,api:{stream:n.stream,streamSimple:n.streamSimple,fetchDeferred:n.fetchDeferred,cancelDeferred:n.cancelDeferred}}),api:n.api,models:n.models,getModel:n.getModel,state:n.state,setResponses:n.setResponses,appendResponses:n.appendResponses,getPendingResponseCount:n.getPendingResponseCount}}function eq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function tq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function rq(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 nq(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 Zu(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Fa(e){Zu(e.contentIndex);let n=e.partial.content[e.contentIndex];if(!n)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return n}function Sf(e){let n=JSON.stringify(e);if(n===void 0)throw Error("Tool-call arguments are not JSON-serializable");return n}var oq=Sf(F(""));function wf(e,n){if(typeof e==="string")return typeof n==="string"&&n.startsWith(e);if(Array.isArray(e))return Array.isArray(n)&&e.length<=n.length&&e.every((c,p)=>wf(c,n[p]));if(typeof e!=="object"||e===null)return Object.is(e,n);if(typeof n!=="object"||n===null||Array.isArray(n))return!1;let i=n;return Object.entries(e).every(([c,p])=>Object.hasOwn(i,c)&&wf(p,i[c]))}class cR{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:nq(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let n=Fa(e);if(n.type!=="text")throw Error(`text_start event points to ${n.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:n.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:eq(n)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let n=Fa(e);if(n.type!=="text")throw Error(`text_end event points to ${n.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...n.textSignature===void 0?{}:{textSignature:n.textSignature}}}case"thinking_start":{let n=Fa(e);if(n.type!=="thinking")throw Error(`thinking_start event points to ${n.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:n.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:tq(n)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let n=Fa(e);if(n.type!=="thinking")throw Error(`thinking_end event points to ${n.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...n.thinkingSignature===void 0?{}:{thinkingSignature:n.thinkingSignature},...n.redacted===void 0?{}:{redacted:n.redacted}}}case"toolcall_start":{let n=Fa(e);if(n.type!=="toolCall")throw Error(`toolcall_start event points to ${n.type} block at index ${e.contentIndex}`);let i=Sf(n.arguments),c=i===oq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:c,catchupJson:"",snapshotArguments:c?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:rq(n)}}case"toolcall_delta":{let n=this.block(e.contentIndex,"toolCall");if(n.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(n.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};n.catchupJson+=e.delta;let i=F(n.catchupJson);if(Sf(i)!==n.snapshotArguments){let p=F(n.snapshotArguments);if(!wf(p,i))return}n.caughtUp=!0,n.snapshotArguments="";let c=n.catchupJson;return n.catchupJson="",c.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:c}}case"toolcall_end":{let n=Fa(e);if(n.type!=="toolCall")throw Error(`toolcall_end event points to ${n.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,n){if(Zu(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,n)}block(e,n){Zu(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${n} block ${e} has not started`);if(i.kind!==n)throw Error(`Assistant message block ${e} is ${i.kind}, not ${n}`);return i}endBlock(e,n){this.block(e,n),this.blocks.delete(e)}encodeTextDelta(e,n,i){let c=this.block(e,i);if(c.kind==="toolCall")throw Error("Unreachable text encoder state");let p=c.deltaChars;c.deltaChars+=n.length;let f=Math.max(0,c.coveredChars-p);if(f>=n.length)return;let g=f===0?n:n.slice(f);return i==="text"?{type:"text_delta",contentIndex:e,delta:g}:{type:"thinking_delta",contentIndex:e,delta:g}}}function Ef(e,n,i,c,p){if(Zu(i),i!==e.content.length){let f=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${f}`)}e.content.push(structuredClone(c)),n.set(i,p)}function ra(e,n,i,c,p){Zu(i);let f=n.get(i),g=e.content[i];if(!f||!g)throw Error(`${p} frame has no started block at index ${i}`);if(f.kind!==c||g.type!==c)throw Error(`${p} frame expected ${c} block at index ${i}, found ${g.type}`);if(f.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:g,state:f}}function sq(e){let n,i,c=new Map;for(let p of e){if(p.type==="start"){if(n)throw Error("Assistant message frame sequence contains more than one start frame");if(i!==void 0)throw Error(`${i} frame appears before the start frame`);n=structuredClone(p.partial);continue}if(!n){i??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);Ef(n,c,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:f}=ra(n,c,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");f.text+=p.delta;break}case"text_end":{let{block:f,state:g}=ra(n,c,p.contentIndex,"text",p.type);if(f.type!=="text")throw Error("Unreachable text frame state");if(f.text=p.content,delete f.textSignature,p.textSignature!==void 0)f.textSignature=p.textSignature;g.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);Ef(n,c,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:f}=ra(n,c,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");f.thinking+=p.delta;break}case"thinking_end":{let{block:f,state:g}=ra(n,c,p.contentIndex,"thinking",p.type);if(f.type!=="thinking")throw Error("Unreachable thinking frame state");if(f.thinking=p.content,delete f.thinkingSignature,delete f.redacted,p.thinkingSignature!==void 0)f.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)f.redacted=p.redacted;g.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);Ef(n,c,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:f,state:g}=ra(n,c,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||g.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");g.json=p.json,f.arguments=F(p.json);break}case"toolcall_delta":{let{block:f,state:g}=ra(n,c,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall"||g.kind!=="toolCall")throw Error("Unreachable tool-call frame state");g.json+=p.delta;break}case"toolcall_end":{let{block:f,state:g}=ra(n,c,p.contentIndex,"toolCall",p.type);if(f.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(f.id=p.id,f.name=p.name,f.arguments=structuredClone(p.arguments),delete f.thoughtSignature,delete f.namespace,p.thoughtSignature!==void 0)f.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)f.namespace=p.namespace;g.ended=!0;break}}}if(!n)return;for(let[p,f]of c){if(f.kind!=="toolCall"||f.ended||f.json.length===0)continue;let g=n.content[p];if(g?.type!=="toolCall")throw Error("Unreachable tool-call frame state");g.arguments=F(f.json)}return n}var mR=[/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],iq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,aq=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function oi(e,n){if(e.stopReason==="error"&&e.errorMessage){if(!aq.some((c)=>c.test(e.errorMessage))){if(mR.some((c)=>c.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&iq.test(e.errorMessage))return!0}}if(n&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>n)return!0}if(n&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=n*0.99)return!0}return!1}function uq(e,n){return e.stopReason==="length"&&n>0&&e.usage.output<n}function cq(){return[...mR]}function pR(e){return new RegExp(e.join("|"),"i")}var mq=pR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),pq=pR(["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"]),lR=60000;function dR(e,n){let i=e.baseDelayMs*2**Math.max(0,n-1),c=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(c,e.maxAgentDelayMs??lR)}class dp extends Error{constructor(){super("Aborted")}}function lq(e,n){return new Promise((i,c)=>{if(n?.aborted){c(new dp);return}let p=setTimeout(i,e);n?.addEventListener("abort",()=>{clearTimeout(p),c(new dp)},{once:!0})})}async function dq(e,n,i,c){let p=n?.enabled?n.maxRetries:0,f=0,g;for(;;){let x=await e();if(x.stopReason==="aborted"){if(g)await c?.onRetryFinished?.(!1,g.attempt);return x}if(x.stopReason!=="error"){if(g)await c?.onRetryFinished?.(!0,g.attempt);return x}if(f>=p||!fR(x)){if(g)await c?.onRetryFinished?.(!1,g.attempt,x.errorMessage);return x}f++,g={attempt:f,errorMessage:x.errorMessage||"Unknown error"};let I=dR(n,f);await c?.onRetryScheduled?.(f,p,I,g.errorMessage);try{await lq(I,i)}catch(b){if(await c?.onRetryFinished?.(!1,f,g.errorMessage),b instanceof dp){let{errorMessage:E,...T}=x;return{...T,stopReason:"aborted"}}throw b}await c?.onRetryAttemptStart?.()}}function fR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let n=e.errorMessage;if(mq.test(n))return!1;return pq.test(n)}function fq(e,n){return $r({type:"string",enum:e,...n?.description&&{description:n.description},...n?.default&&{default:n.default}})}function ec(e){return pe(e,"~refine")&&Be(e["~refine"])&&tn(e["~refine"],0,(n)=>at(n)&&pe(n,"check")&&pe(n,"error")&&as(n.check)&&as(n.error))}function pn(e){return at(e)&&!Be(e)}function vs(e){return sn(e)}function Xe(e){return pn(e)||vs(e)}function ja(e){return pe(e,"additionalItems")&&Xe(e.additionalItems)}function So(e){return pe(e,"additionalProperties")&&Xe(e.additionalProperties)}function tc(e){return pe(e,"allOf")&&Be(e.allOf)&&e.allOf.every((n)=>Xe(n))}function rc(e){return pe(e,"$anchor")&&gt(e.$anchor)}function nc(e){return pe(e,"anyOf")&&Be(e.anyOf)&&e.anyOf.every((n)=>Xe(n))}function fp(e){return pe(e,"const")}function Ss(e){return pe(e,"contains")&&Xe(e.contains)}function lo(e){return pe(e,"default")}function oc(e){return pe(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((n)=>Xe(n)||Be(n)&&n.every((i)=>gt(i)))}function sc(e){return pe(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((n)=>Be(n)&&n.every((i)=>gt(i)))}function Ua(e){return pe(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((n)=>Xe(n))}function Os(e){return pe(e,"$dynamicAnchor")&&gt(e.$dynamicAnchor)}function ic(e){return pe(e,"$dynamicRef")&&gt(e.$dynamicRef)}function ac(e){return pe(e,"else")&&Xe(e.else)}function hp(e){return pe(e,"enum")&&Be(e.enum)}function uc(e){return pe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||vr(e.exclusiveMaximum))}function Jo(e){return pe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||vr(e.exclusiveMinimum))}function na(e){return pe(e,"format")&&gt(e.format)}function fo(e){return pe(e,"$id")&&gt(e.$id)}function cc(e){return pe(e,"if")&&Xe(e.if)}function _s(e){return pe(e,"items")&&(Xe(e.items)||Be(e.items)&&e.items.every((n)=>Xe(n)))}function mc(e){return _s(e)&&Be(e.items)}function pc(e){return pe(e,"maximum")&&(Ot(e.maximum)||vr(e.maximum))}function lc(e){return pe(e,"maxContains")&&Ot(e.maxContains)}function Ba(e){return pe(e,"maxItems")&&Ot(e.maxItems)}function dc(e){return pe(e,"maxLength")&&Ot(e.maxLength)}function fc(e){return pe(e,"maxProperties")&&Ot(e.maxProperties)}function Xo(e){return pe(e,"minimum")&&(Ot(e.minimum)||vr(e.minimum))}function Ls(e){return pe(e,"minContains")&&Ot(e.minContains)}function ii(e){return pe(e,"minItems")&&Ot(e.minItems)}function oa(e){return pe(e,"minLength")&&Ot(e.minLength)}function sa(e){return pe(e,"minProperties")&&Ot(e.minProperties)}function hc(e){return pe(e,"multipleOf")&&(Ot(e.multipleOf)||vr(e.multipleOf))}function gc(e){return pe(e,"not")&&Xe(e.not)}function yc(e){return pe(e,"oneOf")&&Be(e.oneOf)&&e.oneOf.every((n)=>Xe(n))}function ia(e){return pe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function Ns(e){return pe(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((n)=>Xe(n))}function Yo(e){return pe(e,"prefixItems")&&Be(e.prefixItems)&&e.prefixItems.every((n)=>Xe(n))}function Ds(e){return pe(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((n)=>Xe(n))}function Ga(e){return pe(e,"propertyNames")&&(at(e.propertyNames)||Xe(e.propertyNames))}function hq(e){return pe(e,"$recursiveAnchor")&&sn(e.$recursiveAnchor)}function xc(e){return hq(e)&&_(e.$recursiveAnchor,!0)}function Ic(e){return pe(e,"$recursiveRef")&&gt(e.$recursiveRef)}function bc(e){return pe(e,"$ref")&&gt(e.$ref)}function Zo(e){return pe(e,"required")&&Be(e.required)&&e.required.every((n)=>gt(n))}function Ec(e){return pe(e,"then")&&Xe(e.then)}function Sc(e){return pe(e,"type")&&(gt(e.type)||Be(e.type)&&e.type.every((n)=>gt(n)))}function Ii(e){return pe(e,"uniqueItems")&&sn(e.uniqueItems)}function Si(e){return pe(e,"unevaluatedItems")&&Xe(e.unevaluatedItems)}function Ti(e){return pe(e,"unevaluatedProperties")&&Xe(e.unevaluatedProperties)}function gq(e){return Si(e)||Ti(e)||ya(Ee(e),(n)=>gp(e[n]))}function yq(e){return ya(e,(n)=>gp(n))}function gp(e){return Be(e)?yq(e):at(e)?gq(e):!1}function hR(e,n){return gp(n)||ya(Ee(e),(i)=>gp(e[i]))}class Tf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return gr(bt("context","Push"),[])}Pop(){return gr(bt("context","Pop"),[])}AddIndex(e){return gr(bt("context","AddIndex"),[e])}AddKey(e){return gr(bt("context","AddKey"),[e])}Merge(e){return gr(bt("context","Merge"),[e])}}class An{constructor(){let e=new Set,n=new Set;this.stack=[{indices:e,keys:n}]}Push(){let e=new Set,n=new Set;return this.stack.push({indices:e,keys:n}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let n of e)n.GetIndices().forEach((i)=>this.GetIndices().add(i)),n.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class Cn extends An{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Ko().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var yp={identifier:"External",variables:[]};function wo(e){let n=`External[${yp.variables.length}]`;return yp.variables.push(e),n}function gR(){yp.variables=[]}function yR(){return{...yp}}function xR(e,n,i,c){let p=wo(i["~refine"].map((f)=>f));return cs(p,De(0),["refinement","_"],gr(bt("refinement","check"),[c]))}function IR(e,n,i,c){return tn(i["~refine"],0,(p,f)=>p.check(c))}function bR(e,n,i,c,p,f){return En(p["~refine"],0,(g,x)=>g.check(f)||n.AddError({keyword:"~refine",schemaPath:i,instancePath:c,params:{index:x,message:g.error(f)}}))}var xq=0;function Vt(){return`var_${xq++}`}function Rf(e){return _s(e)&&Be(e.items)}function Iq(e,n,i,c){let[p,f]=[Vt(),Vt()],g=Nn(e,n,i.additionalItems,p),x=id(f,De(i.items.length)),I=n.AddIndex(f);return cs(c,De(0),[p,f],hr(x,gn(g,I)))}function bq(e,n,i,c){let[p,f]=[Vt(),Vt()],g=Nn(e,n,i.additionalItems,p),x=id(f,De(i.items.length));return cs(c,De(0),[p,f],hr(x,g))}function ER(e,n,i,c){if(!Rf(i))return De(!0);return n.UseUnevaluated()?Iq(e,n,i,c):bq(e,n,i,c)}function SR(e,n,i,c){if(!Rf(i))return!0;return tn(c,0,(f,g)=>yu(g,i.items.length)||ho(e,n,i.additionalItems,f)&&n.AddIndex(g))}function wR(e,n,i,c,p,f){if(!Rf(p))return!0;return tn(f,0,(x,I)=>{let b=`${i}/additionalItems`,E=`${c}/${I}`;return yu(I,p.items.length)||go(e,n,b,E,p.additionalItems,x)&&n.AddIndex(I)})}function es(e){return new RegExp(e,"u")}function Eq(e,n){return!e.UseUnevaluated()&&(_(n,!0)||at(n)&&_(Ee(n).length,0))}function Sq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function kf(e){let n=[];if(Ns(e))n.push(...Ee(e.patternProperties));if(Ds(e))n.push(...Ee(e.properties).map(Sq));return _(n.length,0)?"(?!)":`(${n.join("|")})`}function wq(e,n,i){return Zo(n)&&Ds(n)&&!Ns(n)&&_(n.additionalProperties,!1)&&_(Ee(n.properties).length,n.required.length)}function Tq(e,n,i){return ro(bt(gr(bt("Object","getOwnPropertyNames"),[i]),"length"),De(n.required.length))}function Rq(e,n,i,c){let[p,f]=[Vt(),Vt()],g=wo(es(kf(i))),x=Nn(e,n,i.additionalProperties,`${c}[${p}]`),I=gr(bt(g,"test"),[p]),b=n.AddKey(p),E=n.UseUnevaluated()?hr(I,gn(x,b)):hr(I,x);return cs(Ui(c),De(0),[p,f],E)}function TR(e,n,i,c){if(Eq(n,i.additionalProperties))return De(!0);return wq(n,i,c)?Tq(n,i,c):Rq(e,n,i,c)}function RR(e,n,i,c){let p=es(kf(i));return tn(Ee(c),0,(g,x)=>p.test(g)||ho(e,n,i.additionalProperties,c[g])&&n.AddKey(g))}function kR(e,n,i,c,p,f){let g=es(kf(p)),x=[];return En(Ee(f),0,(b,E)=>{let T=`${i}/additionalProperties`,k=`${c}/${b}`,A=g.test(b)||go(e,n,T,k,p.additionalProperties,f[b])&&n.AddKey(b);if(!A)x.push(b);return A})||n.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:c,params:{additionalProperties:x}})}function Ri(e,n,i,c,p){let f=Ps("results","[]"),g=i.map((E,T)=>Ps(`context_${T}`,ad("CheckContext",[]))),x=i.map((E,T)=>Ps(`condition_${T}`,gr(Ks(["context"],Nt(e,n,E,c)),[`context_${T}`]))),I=i.map((E,T)=>hy(`condition_${T}`,gr(bt("results","push"),[`context_${T}`]))),b=nm(gn(p,n.Merge("results")));return gr(Ks([],rm([f,...g,...x,...I,b])),[])}function kq(e,n,i,c){return Ri(e,n,i.allOf,c,ro(bt("results","length"),De(i.allOf.length)))}function Aq(e,n,i,c){return Sn(i.allOf.map((p)=>Nt(e,n,p,c)))}function AR(e,n,i,c){return n.UseUnevaluated()?kq(e,n,i,c):Aq(e,n,i,c)}function CR(e,n,i,c){let p=i.allOf.reduce((f,g)=>{let x=new An;return kt(e,x,g,c)?[...f,x]:f},[]);return _(p.length,i.allOf.length)&&n.Merge(p)}function PR(e,n,i,c,p,f){let g=[],x=p.allOf.reduce((b,E,T)=>{let k=`${i}/allOf/${T}`,A=new Cn,L=tr(e,A,k,c,E,f);if(!L)g.push(A);return L?[...b,A]:b},[]),I=_(x.length,p.allOf.length)&&n.Merge(x);if(!I)g.forEach((b)=>b.GetErrors().forEach((E)=>n.AddError(E)));return I}function Cq(e,n,i,c){return Ri(e,n,i.anyOf,c,ly(bt("results","length"),De(0)))}function Pq(e,n,i,c){return ud(i.anyOf.map((p)=>Nt(e,n,p,c)))}function $R(e,n,i,c){return n.UseUnevaluated()?Cq(e,n,i,c):Pq(e,n,i,c)}function MR(e,n,i,c){let p=i.anyOf.reduce((f,g)=>{let x=new An;return kt(e,x,g,c)?[...f,x]:f},[]);return qi(p.length,0)&&n.Merge(p)}function vR(e,n,i,c,p,f){let g=[],x=p.anyOf.reduce((b,E,T)=>{let k=new Cn,A=`${i}/anyOf/${T}`,L=tr(e,k,A,c,E,f);if(!L)g.push(k);return L?[...b,k]:b},[]),I=qi(x.length,0)&&n.Merge(x);if(!I)g.forEach((b)=>b.GetErrors().forEach((E)=>n.AddError(E)));return I||n.AddError({keyword:"anyOf",schemaPath:i,instancePath:c,params:{}})}function OR(e,n,i,c){return i?De(!0):De(!1)}function Af(e,n,i,c){return i}function _R(e,n,i,c,p,f){return Af(e,n,p,f)||n.AddError({keyword:"boolean",schemaPath:i,instancePath:c,params:{}})}function LR(e,n,i,c){return Fi(i.const)?ro(c,De(i.const)):fy(c,wo(i.const))}function Cf(e,n,i,c){return Fi(i.const)?_(c,i.const):xa(c,i.const)}function NR(e,n,i,c,p,f){return Cf(e,n,p,f)||n.AddError({keyword:"const",schemaPath:i,instancePath:c,params:{allowedValue:p.const}})}function DR(e){return!(Ls(e)&&_(e.minContains,0))}function $q(e,n,i,c){let[p,f]=[Vt(),Vt()],g=Mn(ro(bt(c,"length"),De(0))),x=mv(c,[p,f],gn(Nt(e,n,i.contains,p),n.AddIndex(f)));return gn(g,x)}function Mq(e,n,i,c){let[p]=[Vt()],f=Mn(ro(bt(c,"length"),De(0))),g=cv(c,[p,"_"],Nt(e,n,i.contains,p));return gn(f,g)}function qR(e,n,i,c){if(!DR(i))return De(!0);return n.UseUnevaluated()?$q(e,n,i,c):Mq(e,n,i,c)}function Pf(e,n,i,c){if(!DR(i))return!0;return!_(c.length,0)&&sy(c,(p,f)=>kt(e,n,i.contains,p)&&n.AddIndex(f))}function FR(e,n,i,c,p,f){return Pf(e,n,p,f)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:1}})}function jR(e,n,i,c){let p=ro(bt(Ui(c),"length"),De(0)),f=Sn(an(i.dependencies).map(([g,x])=>{let I=Mn(Bi(c,De(g))),b=Nt(e,n,x,c),E=(T)=>Sn(T.map((k)=>Bi(c,De(k))));return hr(I,Be(x)?E(x):b)}));return hr(p,f)}function UR(e,n,i,c){let p=_(Ee(c).length,0),f=tn(an(i.dependencies),0,([g,x])=>!pe(c,g)||(Be(x)?x.every((I)=>pe(c,I)):kt(e,n,x,c)));return p||f}function BR(e,n,i,c,p,f){let g=_(Ee(f).length,0),x=En(an(p.dependencies),0,([I,b])=>{let E=`${i}/dependencies/${I}`;return!pe(f,I)||(Be(b)?b.every((T)=>pe(f,T)||n.AddError({keyword:"dependencies",schemaPath:i,instancePath:c,params:{property:I,dependencies:b}})):tr(e,n,E,c,b,f))});return g||x}function GR(e,n,i,c){let p=ro(bt(Ui(c),"length"),De(0)),f=Sn(an(i.dependentRequired).map(([g,x])=>{let I=Mn(Bi(c,De(g))),b=Sn(x.map((E)=>Bi(c,De(E))));return hr(I,b)}));return hr(p,f)}function KR(e,n,i,c){let p=_(Ee(c).length,0),f=tn(an(i.dependentRequired),0,([g,x])=>!pe(c,g)||x.every((I)=>pe(c,I)));return p||f}function HR(e,n,i,c,p,f){let g=_(Ee(f).length,0),x=En(an(p.dependentRequired),0,([I,b])=>!pe(f,I)||En(b,0,(E)=>pe(f,E)||n.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:c,params:{property:I,dependencies:b}})));return g||x}function WR(e,n,i,c){let p=ro(bt(Ui(c),"length"),De(0)),f=Sn(an(i.dependentSchemas).map(([g,x])=>{let I=Mn(Bi(c,De(g))),b=Nt(e,n,x,c);return hr(I,b)}));return hr(p,f)}function zR(e,n,i,c){let p=_(Ee(c).length,0),f=tn(an(i.dependentSchemas),0,([g,x])=>!pe(c,g)||kt(e,n,x,c));return p||f}function VR(e,n,i,c,p,f){let g=_(Ee(f).length,0),x=En(an(p.dependentSchemas),0,([I,b])=>{let E=`${i}/dependentSchemas/${I}`;return!pe(f,I)||tr(e,n,E,c,b,f)});return g||x}function QR(e,n,i,c){let p=e.DynamicRef(i)??!1;return qs(e,n,p,c)}function JR(e,n,i,c){let p=e.DynamicRef(i)??!1;return Xe(p)&&kt(e,n,p,c)}function XR(e,n,i,c,p,f){let g=e.DynamicRef(p)??!1;return Xe(g)&&tr(e,n,"#",c,g,f)}function YR(e,n,i,c){return ud(i.enum.map((p)=>{if(Fi(p))return ro(c,De(p));let f=wo(p);return fy(c,f)}))}function Mf(e,n,i,c){return ya(i.enum,(p)=>Fi(p)?_(c,p):xa(c,p))}function ZR(e,n,i,c,p,f){return Mf(e,n,p,f)||n.AddError({keyword:"enum",schemaPath:i,instancePath:c,params:{allowedValues:p.enum}})}function ek(e,n,i,c){return id(c,De(i.exclusiveMaximum))}function vf(e,n,i,c){return yu(c,i.exclusiveMaximum)}function tk(e,n,i,c,p,f){return vf(e,n,p,f)||n.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:c,params:{comparison:"<",limit:p.exclusiveMaximum}})}function rk(e,n,i,c){return ly(c,De(i.exclusiveMinimum))}function Of(e,n,i,c){return qi(c,i.exclusiveMinimum)}function nk(e,n,i,c,p,f){return Of(e,n,p,f)||n.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:c,params:{comparison:">",limit:p.exclusiveMinimum}})}var vq=[0,31,28,31,30,31,30,31,31,30,31,30,31],Oq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function _q(e){return e%4===0&&(e%100!==0||e%400===0)}function Ha(e){let n=Oq.exec(e);if(!n)return!1;let i=+n[1],c=+n[2],p=+n[3];return c>=1&&c<=12&&p>=1&&p<=(c===2&&_q(i)?29:vq[c])}var Lq=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Wa(e,n=!0){let i=Lq.exec(e);if(!i)return!1;if(n&&!i[4]&&!i[5])return!1;let c=+i[1],p=+i[2],f=+i[3];if(c>23||p>59||f>60)return!1;if(i[5]){let E=+i[6],T=+i[7];if(E>23||T>59)return!1}if(f<60)return!0;let g=i[5]==="-"?-1:1,x=+(i[6]||0),I=+(i[7]||0);return((c*60+p-g*(x*60+I))%1440+1440)%1440===1439}function xp(e){let n=e.split(/T/i);return n.length===2&&Ha(n[0])&&Wa(n[1])}var Nq=/^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 Ip(e){return Nq.test(e)}var Dq=/^(?:[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 bp(e){return Dq.test(e)}var ok=/^(?!-).*(?<!-)$/,sk=/^(?!..--)/,ik=/^[a-zA-Z0-9-]*$/;var za=/[^\p{ASCII}]/u;var qq=/[0-9]/,ak=/[\u{0660}-\u{0669}]/u,Fq=/[\u{06f0}-\u{06f9}]/u,jq=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,Uq=/[\u{002d}\u{002b}]/u,_f=/\p{Mn}/u,Bq=/\p{Mc}/u;var uk=/[\p{Mn}\p{Mc}\p{Me}]/u,Lf=/\p{L}/u,Gq=/\p{Nd}/u,ck=/\p{Script=Greek}/u,Ep=/\p{Script=Hebrew}/u,mk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,pk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Nf=/[\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,lk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,Kq=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,Hq=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,dk=new RegExp([qq,Fq].map((e)=>e.source).join("|"),"u"),fk=new RegExp([Lf,Uq,jq,Gq,_f,Bq,Kq,Hq].map((e)=>e.source).join("|"),"u");function hk(e){return ok.test(e)&&sk.test(e)&&ik.test(e)}var ts=36,Tc=1,Rc=26,zq=38,Vq=700,yk=72,xk=128;function Df(){throw null}function Sp(e){return e.toLowerCase().startsWith("xn--")}function Ik(e,n,i){e=i?Math.floor(e/Vq):e>>1,e+=Math.floor(e/n);let c=0;while(e>(ts-Tc)*Rc>>1)e=Math.floor(e/(ts-Tc)),c+=ts;return c+Math.floor((ts-Tc+1)*e/(e+zq))}function wp(e){let n=[],i=xk,c=0,p=yk,f=e.lastIndexOf("-");if(f>0)for(let x=0;x<f;x++){let I=e.charCodeAt(x);if(I>=128)Df();n.push(I)}let g=f<0?0:f+1;while(g<e.length){let x=c,I=1,b=ts;while(!0){if(g>=e.length)Df();let T=e.charCodeAt(g++),k;if(T>=97&&T<=122)k=T-97;else if(T>=48&&T<=57)k=T-48+26;else Df();c+=k*I;let A=b<=p?Tc:b>=p+Rc?Rc:b-p;if(k<A)break;I*=ts-A,b+=ts}let E=n.length+1;p=Ik(c-x,E,x===0),i+=Math.floor(c/E),c%=E,n.splice(c,0,i),c++}return String.fromCodePoint(...n)}function gk(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var Qq=new RegExp(za.source,"gu");function bk(e){let n=e.replace(Qq,""),i=n.length,c=i>0?[n,"-"]:[],p=Array.from(e,(b)=>b.codePointAt(0)),f=xk,g=0,x=yk,I=i;while(I<p.length){let b=1/0;for(let E of p)if(E>=f&&E<b)b=E;g+=(b-f)*(I+1),f=b;for(let E of p){if(E<f)g++;if(E===f){let T=g;for(let k=ts;;k+=ts){let A=k<=x?Tc:k>=x+Rc?Rc:k-x;if(T<A)break;let L=A+(T-A)%(ts-A);c.push(gk(L)),T=Math.floor((T-A)/(ts-A))}c.push(gk(T)),x=Ik(g,I+1,I===i),g=0,I++}}g++,f++}return c.join("")}var Jq=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Ek=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,Xq=/^(?:R|AL|AN)$/;function Sk(e){if(Sp(e))try{return Tp(wp(e.slice(4).toLowerCase()))}catch{return!1}return Tp(e)}function wk(e){let n=String.fromCodePoint(e);return dk.test(n)?"EN":ak.test(n)?"AN":_f.test(n)?"NSM":Ep.test(n)?"R":pk.test(n)?"AL":Lf.test(n)?"L":"ON"}function Tp(e){for(let n of e)if(Xq.test(wk(n.codePointAt(0))))return!0;return!1}function Rp(e){let n=!1,i=Ek,c=!1,p=!1,f=!0;for(let g of e){let x=wk(g.codePointAt(0));if(f){if(x!=="L"&&x!=="R"&&x!=="AL")return!1;n=x==="R"||x==="AL",i=n?Jq:Ek,f=!1}if(!i.test(x))return!1;if(x==="EN")c=!0;else if(x==="AN")p=!0}if(n&&c&&p)return!1;return!0}function Yq(e){return za.test(e)&&bk(e).length+4>63}function Zq(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function kp(e){if(Yq(e))return!1;if(Tp(e)&&!Rp(e))return!1;let n=[...e],i=n.map((f)=>f.codePointAt(0)),c=i.length;if(Zq(n))return!1;if(uk.test(n[0]))return!1;let p=!1;for(let f=0;f<c;f++){let g=i[f],x=n[f];if(lk.test(x))return!1;if(!fk.test(x))return!1;if(mk.test(x))p=!0;let I=i[f-1],b=i[f+1];switch(g){case 183:if(I!==108||b!==108)return!1;break;case 885:if(!b||!ck.test(n[f+1]))return!1;break;case 1523:case 1524:if(!I||!Ep.test(n[f-1]))return!1;break;case 8204:if(!I||I<128&&!Nf.test(n[f-1]))return!1;break;case 8205:if(!I||!Nf.test(n[f-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function Ap(e){if(!Sp(e))return!1;try{let n=e.slice(4).toLowerCase();if(n.lastIndexOf("-")===0)return!1;let i=wp(n);if(!za.test(i))return!1;return kp(i)}catch{return!1}}function eF(e){return e.length>0&&e.length<=63}function tF(e){return eF(e)&&(Ap(e)||hk(e))}function Ak(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((n)=>tF(n))}function rF(e){return e.length>0&&e.length<=63}function nF(e){return rF(e)&&(Ap(e)||kp(e))}function oF(e){return e.replace(/[\uff01-\uff5e]/g,(n)=>String.fromCharCode(n.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function Ck(e){if(e.length===0||e.includes(" "))return!1;let n=oF(e);if(n.length>253)return!1;let i=n.split("."),c=i.some((p)=>Sk(p));return i.every((p)=>nF(p)&&(!c||Rp(p)))}function Cp(e){return Ak(e)}var sF=/^(?:[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 Pp(e){return sF.test(e.normalize("NFC"))}function $p(e){return Ck(e)}var iF=/^(?:(?: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 Mp(e){return iF.test(e)}var aF=/^(?:(?:(?:[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 vp(e){return aF.test(e)}var uF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,cF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Op(e){return!uF.test(e)&&!cF.test(e)&&URL.canParse(e,"http://example.com")}var mF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,pF=/[\x00-\x20<>\^`{|}\\]/,lF=/%(?![0-9a-fA-F]{2})/;function dF(e){return e.length<2048?e.replace(mF,"[::1]"):e}function _p(e){if(pF.test(e))return!1;if(lF.test(e))return!1;return URL.canParse(dF(e))}var fF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Lp(e){return fF.test(e)}var hF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Np(e){return hF.test(e)}function Dp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var gF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function qp(e){return gF.test(e)}var yF=/^(?:[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 Fp(e){return yF.test(e)}var xF=/^(?:(?:[^\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 jp(e){return xF.test(e)}var IF=/^[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 Up(e){return IF.test(e)}function Bp(e){return URL.canParse(e)}var bF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Gp(e){return bF.test(e)}var xr=new Map;function $k(){xr.clear()}function EF(){return[...xr.entries()]}function SF(e,n){xr.set(e,n)}function wF(e){return xr.has(e)}function TF(e){return xr.get(e)}function Mk(e,n){return xr.get(e)?.(n)??!0}function vk(){$k(),xr.set("date-time",xp),xr.set("date",Ha),xr.set("duration",Ip),xr.set("email",bp),xr.set("hostname",Cp),xr.set("idn-email",Pp),xr.set("idn-hostname",$p),xr.set("ipv4",Mp),xr.set("ipv6",vp),xr.set("iri-reference",Op),xr.set("iri",_p),xr.set("json-pointer-uri-fragment",Lp),xr.set("json-pointer",Np),xr.set("regex",Dp),xr.set("relative-json-pointer",qp),xr.set("time",Wa),xr.set("uri-reference",Fp),xr.set("uri-template",jp),xr.set("uri",Up),xr.set("url",Bp),xr.set("uuid",Gp)}vk();function Ok(e,n,i,c){return gr(bt("Format","Test"),[De(i.format),c])}function Ff(e,n,i,c){return Mk(i.format,c)}function _k(e,n,i,c,p,f){return Ff(e,n,p,f)||n.AddError({keyword:"format",schemaPath:i,instancePath:c,params:{format:p.format}})}function Lk(e,n,i,c){let p=Ec(i)?i.then:!0,f=ac(i)?i.else:!0;return lv(Nt(e,n,i.if,c),Nt(e,n,p,c),Nt(e,n,f,c))}function Nk(e,n,i,c){let p=Ec(i)?i.then:!0,f=ac(i)?i.else:!0;return kt(e,n,i.if,c)?kt(e,n,p,c):kt(e,n,f,c)}function Dk(e,n,i,c,p,f){let g=Ec(p)?p.then:!0,x=ac(p)?p.else:!0,I=new Cn,b=tr(e,I,`${i}/if`,c,p.if,f)?tr(e,I,`${i}/then`,c,g,f)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"then"}}):tr(e,n,`${i}/else`,c,x,f)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"else"}});if(b)n.Merge([I]);return b}function RF(e,n,i,c){return Sn(i.items.map((p,f)=>{let g=ji(bt(c,"length"),De(f)),x=Nn(e,n,p,`${c}[${f}]`),I=n.AddIndex(De(f));return hr(g,gn(x,I))}))}function kF(e,n,i,c){return Sn(i.items.map((p,f)=>{let g=ji(bt(c,"length"),De(f)),x=Nn(e,n,p,`${c}[${f}]`);return hr(g,x)}))}function AF(e,n,i,c){return n.UseUnevaluated()?RF(e,n,i,c):kF(e,n,i,c)}function CF(e,n,i,c){return tn(i.items,0,(p,f)=>us(c.length,f)||ho(e,n,p,c[f])&&n.AddIndex(f))}function PF(e,n,i,c,p,f){return En(p.items,0,(g,x)=>{let I=`${i}/items/${x}`,b=`${c}/${x}`;return us(f.length,x)||go(e,n,I,b,g,f[x])&&n.AddIndex(x)})}function $F(e,n,i,c){let p=Yo(i)?i.prefixItems.length:0,f=Nn(e,n,i.items,"element"),g=n.AddIndex("index");return cs(c,De(p),["element","index"],gn(f,g))}function MF(e,n,i,c){let p=Yo(i)?i.prefixItems.length:0,f=Nn(e,n,i.items,"element");return cs(c,De(p),["element","index"],f)}function vF(e,n,i,c){return n.UseUnevaluated()?$F(e,n,i,c):MF(e,n,i,c)}function OF(e,n,i,c){let p=Yo(i)?i.prefixItems.length:0;return tn(c,p,(f,g)=>ho(e,n,i.items,f)&&n.AddIndex(g))}function _F(e,n,i,c,p,f){let g=Yo(p)?p.prefixItems.length:0;return En(f,g,(x,I)=>{let b=`${i}/items`,E=`${c}/${I}`;return go(e,n,b,E,p.items,x)&&n.AddIndex(I)})}function qk(e,n,i,c){return mc(i)?AF(e,n,i,c):vF(e,n,i,c)}function Fk(e,n,i,c){return mc(i)?CF(e,n,i,c):OF(e,n,i,c)}function jk(e,n,i,c,p,f){return mc(p)?PF(e,n,i,c,p,f):_F(e,n,i,c,p,f)}function Uk(e){return Ss(e)}function Bk(e,n,i,c){if(!Uk(i))return De(!0);let[p]=[Vt()],f=tm(c,[p,"_"],Nt(e,n,i.contains,p));return ji(f,De(i.maxContains))}function jf(e,n,i,c){if(!Uk(i))return!0;let p=rd(c,(f)=>kt(e,n,i.contains,f));return us(p,i.maxContains)}function Gk(e,n,i,c,p,f){let g=Ls(p)?p.minContains:1;return jf(e,n,p,f)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:g,maxContains:p.maxContains}})}function Kk(e,n,i,c){return ji(c,De(i.maximum))}function Uf(e,n,i,c){return us(c,i.maximum)}function Hk(e,n,i,c,p,f){return Uf(e,n,p,f)||n.AddError({keyword:"maximum",schemaPath:i,instancePath:c,params:{comparison:"<=",limit:p.maximum}})}function Wk(e,n,i,c){return ji(bt(c,"length"),De(i.maxItems))}function Bf(e,n,i,c){return us(c.length,i.maxItems)}function zk(e,n,i,c,p,f){return Bf(e,n,p,f)||n.AddError({keyword:"maxItems",schemaPath:i,instancePath:c,params:{limit:p.maxItems}})}function Vk(e,n,i,c){return uv(c,De(i.maxLength))}function Gf(e,n,i,c){return ny(c,i.maxLength)}function Qk(e,n,i,c,p,f){return Gf(e,n,p,f)||n.AddError({keyword:"maxLength",schemaPath:i,instancePath:c,params:{limit:p.maxLength}})}function Jk(e,n,i,c){return ji(bt(Ui(c),"length"),De(i.maxProperties))}function Kf(e,n,i,c){return us(Ee(c).length,i.maxProperties)}function Xk(e,n,i,c,p,f){return Kf(e,n,p,f)||n.AddError({keyword:"maxProperties",schemaPath:i,instancePath:c,params:{limit:p.maxProperties}})}function Yk(e){return Ss(e)}function LF(e,n,i,c){let[p,f]=[Vt(),Vt()],g=tm(c,[p,f],gn(Nt(e,n,i.contains,p),n.AddIndex(f)));return Iu(g,De(i.minContains))}function NF(e,n,i,c){let[p]=[Vt()],f=tm(c,[p,"_"],Nt(e,n,i.contains,p));return Iu(f,De(i.minContains))}function Zk(e,n,i,c){if(!Yk(i))return De(!0);return n.UseUnevaluated()?LF(e,n,i,c):NF(e,n,i,c)}function Hf(e,n,i,c){if(!Yk(i))return!0;let p=rd(c,(f,g)=>kt(e,n,i.contains,f)&&n.AddIndex(g));return ga(p,i.minContains)}function eA(e,n,i,c,p,f){return Hf(e,n,p,f)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:p.minContains}})}function tA(e,n,i,c){return Iu(c,De(i.minimum))}function Wf(e,n,i,c){return ga(c,i.minimum)}function rA(e,n,i,c,p,f){return Wf(e,n,p,f)||n.AddError({keyword:"minimum",schemaPath:i,instancePath:c,params:{comparison:">=",limit:p.minimum}})}function nA(e,n,i,c){return Iu(bt(c,"length"),De(i.minItems))}function zf(e,n,i,c){return ga(c.length,i.minItems)}function oA(e,n,i,c,p,f){return zf(e,n,p,f)||n.AddError({keyword:"minItems",schemaPath:i,instancePath:c,params:{limit:p.minItems}})}function sA(e,n,i,c){return av(c,De(i.minLength))}function Vf(e,n,i,c){return oy(c,i.minLength)}function iA(e,n,i,c,p,f){return Vf(e,n,p,f)||n.AddError({keyword:"minLength",schemaPath:i,instancePath:c,params:{limit:p.minLength}})}function aA(e,n,i,c){return Iu(bt(Ui(c),"length"),De(i.minProperties))}function Qf(e,n,i,c){return ga(Ee(c).length,i.minProperties)}function uA(e,n,i,c,p,f){return Qf(e,n,p,f)||n.AddError({keyword:"minProperties",schemaPath:i,instancePath:c,params:{limit:p.minProperties}})}function cA(e,n,i,c){return dv(c,De(i.multipleOf))}function Jf(e,n,i,c){return ty(c,i.multipleOf)}function mA(e,n,i,c,p,f){return Jf(e,n,p,f)||n.AddError({keyword:"multipleOf",schemaPath:i,instancePath:c,params:{multipleOf:p.multipleOf}})}function DF(e,n,i,c){return Ri(e,n,[i.not],c,Mn(ro(bt("results","length"),De(1))))}function qF(e,n,i,c){return Mn(Nt(e,n,i.not,c))}function pA(e,n,i,c){return n.UseUnevaluated()?DF(e,n,i,c):qF(e,n,i,c)}function Xf(e,n,i,c){let p=new An;return!kt(e,p,i.not,c)&&n.Merge([p])}function lA(e,n,i,c,p,f){return Xf(e,n,p,f)||n.AddError({keyword:"not",schemaPath:i,instancePath:c,params:{}})}function FF(e,n,i,c){return Ri(e,n,i.oneOf,c,ro(bt("results","length"),De(1)))}function jF(e,n,i,c){let[p]=[Vt()],f=pv(i.oneOf.map((x)=>Nt(e,n,x,c))),g=tm(f,[p,"_"],ro(p,De(!0)));return ro(g,De(1))}function dA(e,n,i,c){return n.UseUnevaluated()?FF(e,n,i,c):jF(e,n,i,c)}function fA(e,n,i,c){let p=i.oneOf.reduce((f,g)=>{let x=new An;return kt(e,x,g,c)?[...f,x]:f},[]);return _(p.length,1)&&n.Merge(p)}function hA(e,n,i,c,p,f){let g=[],x=[],I=p.oneOf.reduce((E,T,k)=>{let A=new Cn,L=`${i}/oneOf/${k}`,q=tr(e,A,L,c,T,f);if(q)x.push(k);if(!q)g.push(A);return q?[...E,A]:E},[]),b=_(I.length,1)&&n.Merge(I);if(!b&&_(x.length,0))g.forEach((E)=>E.GetErrors().forEach((T)=>n.AddError(T)));return b||n.AddError({keyword:"oneOf",schemaPath:i,instancePath:c,params:{passingSchemas:x}})}function gA(e,n,i,c){let p=wo(gt(i.pattern)?es(i.pattern):i.pattern);return gr(bt(p,"test"),[c])}function Yf(e,n,i,c){return(gt(i.pattern)?es(i.pattern):i.pattern).test(c)}function yA(e,n,i,c,p,f){return Yf(e,n,p,f)||n.AddError({keyword:"pattern",schemaPath:i,instancePath:c,params:{pattern:p.pattern}})}function xA(e,n,i,c){return Sn(an(i.patternProperties).map(([p,f])=>{let[g,x]=[Vt(),Vt()],I=wo(es(p)),b=Mn(gr(bt(I,"test"),[g])),E=Nn(e,n,f,x),T=n.AddKey(g),k=n.UseUnevaluated()?hr(b,gn(E,T)):hr(b,E);return cs(dy(c),De(0),[`[${g}, ${x}]`,"_"],k)}))}function IA(e,n,i,c){return tn(an(i.patternProperties),0,([p,f])=>{let g=es(p);return tn(an(c),0,([x,I])=>!g.test(x)||ho(e,n,f,I)&&n.AddKey(x))})}function bA(e,n,i,c,p,f){return En(an(p.patternProperties),0,([g,x])=>{let I=`${i}/patternProperties/${g}`,b=es(g);return En(an(f),0,([E,T])=>{let k=`${c}/${E}`;return!b.test(E)||go(e,n,I,k,x,T)&&n.AddKey(E)})})}function EA(e,n,i,c){return Sn(i.prefixItems.map((p,f)=>{let g=ji(bt(c,"length"),De(f)),x=Nn(e,n,p,`${c}[${f}]`),I=n.AddIndex(De(f)),b=n.UseUnevaluated()?gn(x,I):x;return hr(g,b)}))}function SA(e,n,i,c){return _(c.length,0)||tn(i.prefixItems,0,(p,f)=>us(c.length,f)||ho(e,n,p,c[f])&&n.AddIndex(f))}function wA(e,n,i,c,p,f){return _(f.length,0)||En(p.prefixItems,0,(g,x)=>{let I=`${i}/prefixItems/${x}`,b=`${c}/${x}`;return us(f.length,x)||go(e,n,I,b,g,f[x])&&n.AddIndex(x)})}function Kp(e,n){return e.includes(n)||Ko().exactOptionalPropertyTypes}function TA(e,n){return sd(bt(e,n))}function Zf(e,n){return Gt(e[n])}function RA(e,n,i,c){let p=Zo(i)?i.required:[],f=an(i.properties).map(([g,x])=>{let I=Mn(Bi(c,De(g))),b=Nn(e,n,x,bt(c,g)),E=n.AddKey(De(g)),T=n.UseUnevaluated()?gn(b,E):b,k=p.includes(g)?T:hr(I,T);return Kp(p,g)?k:hr(TA(c,g),k)});return Sn(f)}function kA(e,n,i,c){let p=Zo(i)?i.required:[];return tn(an(i.properties),0,([g,x])=>{let I=!pe(c,g)||ho(e,n,x,c[g])&&n.AddKey(g);return Kp(p,g)?I:Zf(c,g)||I})}function AA(e,n,i,c,p,f){let g=Zo(p)?p.required:[];return En(an(p.properties),0,([I,b])=>{let E=`${i}/properties/${I}`,T=`${c}/${I}`,k=()=>!pe(f,I)||go(e,n,E,T,b,f[I])&&n.AddKey(I);return Kp(g,I)?k():Zf(f,I)||k()})}function CA(e,n,i,c){let[p,f]=[Vt(),Vt()];return cs(Ui(c),De(0),[p,f],Nt(e,n,i.propertyNames,p))}function PA(e,n,i,c){return tn(Ee(c),0,(p,f)=>kt(e,n,i.propertyNames,p))}function $A(e,n,i,c,p,f){let g=[];return En(Ee(f),0,(I,b)=>{let E=`${c}/${I}`,T=`${i}/propertyNames`,k=tr(e,n,T,E,p.propertyNames,I);if(!k)g.push(I);return k})||n.AddError({keyword:"propertyNames",schemaPath:i,instancePath:c,params:{propertyNames:g}})}function MA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return qs(e,n,p,c)}function vA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Xe(p)&&kt(e,n,p,c)}function OA(e,n,i,c,p,f){let g=e.RecursiveRef(p)??!1;return Xe(g)&&tr(e,n,"#",c,g,f)}function UF(e,n,i,c){let p=Ks(["context","value"],qs(e,n,i,"value")),f=Ks(["context","value"],rm([Ps("nextContext",ad("CheckContext",[])),Ps("result",gr(p,["nextContext","value"])),hy("result",n.Merge("[nextContext]")),nm("result")]));return gr(f,["context",c])}function BF(e,n,i,c){return qs(e,n,i,c)}function _A(e,n,i,c){let p=e.Ref(i)??!1;return n.UseUnevaluated()?UF(e,n,p,c):BF(e,n,p,c)}function LA(e,n,i,c){let p=e.Ref(i)??!1,f=new An,g=Xe(p)&&kt(e,f,p,c);if(g)n.Merge([f]);return g}function NA(e,n,i,c,p,f){let g=e.Ref(p)??!1,x=new Cn,I=Xe(g)&&tr(e,x,"#",c,g,f);if(I)n.Merge([x]);if(!I)x.GetErrors().forEach((b)=>n.AddError(b));return I}function DA(e,n,i,c){return Sn(i.required.map((p)=>Bi(c,De(p))))}function qA(e,n,i,c){return tn(i.required,0,(p)=>pe(c,p))}function FA(e,n,i,c,p,f){let g=[];return En(p.required,0,(I)=>{let b=pe(f,I);if(!b)g.push(I);return b})||n.AddError({keyword:"required",schemaPath:i,instancePath:c,params:{requiredProperties:g}})}function jA(e,n,i,c){return _(i,"object")?cy(c):_(i,"array")?em(c):_(i,"boolean")?tv(c):_(i,"integer")?rv(c):_(i,"number")?uy(c):_(i,"null")?nv(c):_(i,"string")?py(c):_(i,"bigint")?ay(c):_(i,"constructor")?iv(c):_(i,"function")?sv(c):_(i,"symbol")?ov(c):_(i,"undefined")?sd(c):_(i,"void")?sd(c):De(!0)}function eh(e,n,i,c,p){return _(i,"object")?Go(p):_(i,"array")?Be(p):_(i,"boolean")?sn(p):_(i,"integer")?Zc(p):_(i,"number")?Ot(p):_(i,"null")?uo(p):_(i,"string")?gt(p):_(i,"bigint")?vr(p):_(i,"constructor")?ed(p):_(i,"function")?as(p):_(i,"symbol")?td(p):_(i,"undefined")?Gt(p):_(i,"void")?Gt(p):!0}function GF(e,n,i,c){return ud(i.map((p)=>jA(e,n,p,c)))}function UA(e,n,i,c,p){return ya(i,(f)=>eh(e,n,f,c,p))}function BA(e,n,i,c){return Be(i.type)?GF(e,n,i.type,c):jA(e,n,i.type,c)}function GA(e,n,i,c){return Be(i.type)?UA(e,n,i.type,i,c):eh(e,n,i.type,i,c)}function KA(e,n,i,c,p,f){return(Be(p.type)?UA(e,n,p.type,p,f):eh(e,n,p.type,p,f))||n.AddError({keyword:"type",schemaPath:i,instancePath:c,params:{type:p.type}})}function HA(e,n,i,c){let[p,f]=[Vt(),Vt()],g=gr(bt("context","GetIndices"),[]),x=gr(bt("indices","has"),[p]),I=Nt(e,n,i.unevaluatedItems,f),b=gr(bt("context","AddIndex"),[p]),E=cs(c,De(0),[f,p],gn(hr(x,I),b));return gr(Ks(["context"],rm([Ps("indices",g),nm(E)])),["context"])}function WA(e,n,i,c){let p=n.GetIndices();return tn(c,0,(f,g)=>(p.has(g)||kt(e,n,i.unevaluatedItems,f))&&n.AddIndex(g))}function zA(e,n,i,c,p,f){let g=n.GetIndices(),x=[];return En(f,0,(b,E)=>{let T=new Cn,k=(g.has(E)||tr(e,T,i,c,p.unevaluatedItems,b))&&n.AddIndex(E);if(!k)x.push(E);return k})||n.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:c,params:{unevaluatedItems:x}})}function VA(e,n,i,c){let[p,f]=[Vt(),Vt()],g=gr(bt("context","GetKeys"),[]),x=gr(bt("keys","has"),[p]),I=gr(bt("context","AddKey"),[p]),b=Nt(e,n,i.unevaluatedProperties,f),E=cs(dy(c),De(0),[`[${p}, ${f}]`,"_"],hr(x,gn(b,I)));return gr(Ks(["context"],rm([Ps("keys",g),nm(E)])),["context"])}function QA(e,n,i,c){let p=n.GetKeys();return tn(an(c),0,([f,g])=>p.has(f)||kt(e,n,i.unevaluatedProperties,g)&&n.AddKey(f))}function JA(e,n,i,c,p,f){let g=n.GetKeys(),x=[];return En(an(f),0,([b,E])=>{let T=new Cn,k=g.has(b)||tr(e,T,i,c,p.unevaluatedProperties,E)&&n.AddKey(b);if(!k)x.push(b);return k})||n.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:c,params:{unevaluatedProperties:x}})}function th(e){return!_(e.uniqueItems,!1)}function XA(e,n,i,c){if(!th(i))return De(!0);let p=bt(ad("Set",[gr(bt(c,"map"),[bt("Hashing","Hash")])]),"size"),f=bt(c,"length");return ro(p,f)}function YA(e,n,i,c){if(!th(i))return!0;let p=new Set(c.map(pd)).size,f=c.length;return _(p,f)}function ZA(e,n,i,c,p,f){if(!th(p))return!0;let g=new Set,x=f.reduce((b,E,T)=>{let k=pd(E);if(g.has(k))return[...b,T];return g.add(k),b},[]);return _(x.length,0)||n.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:c,params:{duplicateItems:x}})}function kc(e,n){return Sc(e)&&(Be(e.type)&&qi(e.type.length,0)&&tn(e.type,0,(i)=>_(i,n))||_(e.type,n))}function KF(e){return kc(e,"object")}function HF(e){return pn(e)&&(So(e)||oc(e)||sc(e)||Ua(e)||Ds(e)||Ns(e)||Ga(e)||sa(e)||fc(e)||Zo(e)||Ti(e))}function WF(e){return kc(e,"array")}function zF(e){return pn(e)&&(ja(e)||_s(e)||Ss(e)||lc(e)||Ba(e)||Ls(e)||ii(e)||Yo(e)||Si(e)||Ii(e))}function VF(e){return kc(e,"string")}function QF(e){return pn(e)&&(oa(e)||dc(e)||na(e)||ia(e))}function JF(e){return kc(e,"number")||kc(e,"bigint")}function XF(e){return pn(e)&&(Xo(e)||pc(e)||uc(e)||Jo(e)||hc(e))}function Nn(e,n,i,c){return n.UseUnevaluated()?gn(gn(n.Push(),Nt(e,n,i,c)),n.Pop()):Nt(e,n,i,c)}function Nt(e,n,i,c){e.Push(i);let p=[];if(vs(i))return OR(e,n,i,c);if(Sc(i))p.push(BA(e,n,i,c));if(HF(i)){let g=[];if(Zo(i))g.push(DA(e,n,i,c));if(So(i))g.push(TR(e,n,i,c));if(oc(i))g.push(jR(e,n,i,c));if(sc(i))g.push(GR(e,n,i,c));if(Ua(i))g.push(WR(e,n,i,c));if(Ns(i))g.push(xA(e,n,i,c));if(Ds(i))g.push(RA(e,n,i,c));if(Ga(i))g.push(CA(e,n,i,c));if(sa(i))g.push(aA(e,n,i,c));if(fc(i))g.push(Jk(e,n,i,c));let x=Sn(g),I=hr(Mn(cy(c)),x);p.push(KF(i)?x:I)}if(zF(i)){let g=[];if(ja(i))g.push(ER(e,n,i,c));if(Ss(i))g.push(qR(e,n,i,c));if(_s(i))g.push(qk(e,n,i,c));if(lc(i))g.push(Bk(e,n,i,c));if(Ba(i))g.push(Wk(e,n,i,c));if(Ls(i))g.push(Zk(e,n,i,c));if(ii(i))g.push(nA(e,n,i,c));if(Yo(i))g.push(EA(e,n,i,c));if(Ii(i))g.push(XA(e,n,i,c));let x=Sn(g),I=hr(Mn(em(c)),x);p.push(WF(i)?x:I)}if(QF(i)){let g=[];if(dc(i))g.push(Vk(e,n,i,c));if(oa(i))g.push(sA(e,n,i,c));if(na(i))g.push(Ok(e,n,i,c));if(ia(i))g.push(gA(e,n,i,c));let x=Sn(g),I=hr(Mn(py(c)),x);p.push(VF(i)?x:I)}if(XF(i)){let g=[];if(uc(i))g.push(ek(e,n,i,c));if(Jo(i))g.push(rk(e,n,i,c));if(pc(i))g.push(Kk(e,n,i,c));if(Xo(i))g.push(tA(e,n,i,c));if(hc(i))g.push(cA(e,n,i,c));let x=Sn(g),I=hr(Mn(hr(uy(c),ay(c))),x);p.push(JF(i)?x:I)}if(bc(i))p.push(_A(e,n,i,c));if(Ic(i))p.push(MA(e,n,i,c));if(ic(i))p.push(QR(e,n,i,c));if(fp(i))p.push(LR(e,n,i,c));if(hp(i))p.push(YR(e,n,i,c));if(cc(i))p.push(Lk(e,n,i,c));if(gc(i))p.push(pA(e,n,i,c));if(tc(i))p.push(AR(e,n,i,c));if(nc(i))p.push($R(e,n,i,c));if(yc(i))p.push(dA(e,n,i,c));if(Si(i))p.push(hr(Mn(em(c)),HA(e,n,i,c)));if(Ti(i))p.push(hr(Mn(my(c)),VA(e,n,i,c)));if(ec(i))p.push(xR(e,n,i,c));let f=Sn(p);return e.Pop(i),f}function ho(e,n,i,c){return n.Push()&&kt(e,n,i,c)&&n.Pop()}function kt(e,n,i,c){e.Push(i);let p=vs(i)?Af(e,n,i,c):(!Sc(i)||GA(e,n,i,c))&&(!(at(c)&&!Be(c))||(!Zo(i)||qA(e,n,i,c))&&(!So(i)||RR(e,n,i,c))&&(!oc(i)||UR(e,n,i,c))&&(!sc(i)||KR(e,n,i,c))&&(!Ua(i)||zR(e,n,i,c))&&(!Ns(i)||IA(e,n,i,c))&&(!Ds(i)||kA(e,n,i,c))&&(!Ga(i)||PA(e,n,i,c))&&(!sa(i)||Qf(e,n,i,c))&&(!fc(i)||Kf(e,n,i,c)))&&(!Be(c)||(!ja(i)||SR(e,n,i,c))&&(!Ss(i)||Pf(e,n,i,c))&&(!_s(i)||Fk(e,n,i,c))&&(!lc(i)||jf(e,n,i,c))&&(!Ba(i)||Bf(e,n,i,c))&&(!Ls(i)||Hf(e,n,i,c))&&(!ii(i)||zf(e,n,i,c))&&(!Yo(i)||SA(e,n,i,c))&&(!Ii(i)||YA(e,n,i,c)))&&(!gt(c)||(!dc(i)||Gf(e,n,i,c))&&(!oa(i)||Vf(e,n,i,c))&&(!na(i)||Ff(e,n,i,c))&&(!ia(i)||Yf(e,n,i,c)))&&(!(Ot(c)||vr(c))||(!uc(i)||vf(e,n,i,c))&&(!Jo(i)||Of(e,n,i,c))&&(!pc(i)||Uf(e,n,i,c))&&(!Xo(i)||Wf(e,n,i,c))&&(!hc(i)||Jf(e,n,i,c)))&&(!bc(i)||LA(e,n,i,c))&&(!Ic(i)||vA(e,n,i,c))&&(!ic(i)||JR(e,n,i,c))&&(!fp(i)||Cf(e,n,i,c))&&(!hp(i)||Mf(e,n,i,c))&&(!cc(i)||Nk(e,n,i,c))&&(!gc(i)||Xf(e,n,i,c))&&(!tc(i)||CR(e,n,i,c))&&(!nc(i)||MR(e,n,i,c))&&(!yc(i)||fA(e,n,i,c))&&(!Si(i)||(!Be(c)||WA(e,n,i,c)))&&(!Ti(i)||(!at(c)||QA(e,n,i,c)))&&(!ec(i)||IR(e,n,i,c));return e.Pop(i),p}function go(e,n,i,c,p,f){return n.Push()&&tr(e,n,i,c,p,f)&&n.Pop()}function tr(e,n,i,c,p,f){if(n.AtCapacity())return!1;e.Push(p);let g=vs(p)?_R(e,n,i,c,p,f):!!(+(!Sc(p)||KA(e,n,i,c,p,f))&+(!(at(f)&&!Be(f))||!!(+(!Zo(p)||FA(e,n,i,c,p,f))&+(!So(p)||kR(e,n,i,c,p,f))&+(!oc(p)||BR(e,n,i,c,p,f))&+(!sc(p)||HR(e,n,i,c,p,f))&+(!Ua(p)||VR(e,n,i,c,p,f))&+(!Ns(p)||bA(e,n,i,c,p,f))&+(!Ds(p)||AA(e,n,i,c,p,f))&+(!Ga(p)||$A(e,n,i,c,p,f))&+(!sa(p)||uA(e,n,i,c,p,f))&+(!fc(p)||Xk(e,n,i,c,p,f))))&+(!Be(f)||!!(+(!ja(p)||wR(e,n,i,c,p,f))&+(!Ss(p)||FR(e,n,i,c,p,f))&+(!_s(p)||jk(e,n,i,c,p,f))&+(!lc(p)||Gk(e,n,i,c,p,f))&+(!Ba(p)||zk(e,n,i,c,p,f))&+(!Ls(p)||eA(e,n,i,c,p,f))&+(!ii(p)||oA(e,n,i,c,p,f))&+(!Yo(p)||wA(e,n,i,c,p,f))&+(!Ii(p)||ZA(e,n,i,c,p,f))))&+(!gt(f)||!!(+(!dc(p)||Qk(e,n,i,c,p,f))&+(!oa(p)||iA(e,n,i,c,p,f))&+(!na(p)||_k(e,n,i,c,p,f))&+(!ia(p)||yA(e,n,i,c,p,f))))&+(!(Ot(f)||vr(f))||!!(+(!uc(p)||tk(e,n,i,c,p,f))&+(!Jo(p)||nk(e,n,i,c,p,f))&+(!pc(p)||Hk(e,n,i,c,p,f))&+(!Xo(p)||rA(e,n,i,c,p,f))&+(!hc(p)||mA(e,n,i,c,p,f))))&+(!bc(p)||NA(e,n,i,c,p,f))&+(!Ic(p)||OA(e,n,i,c,p,f))&+(!ic(p)||XR(e,n,i,c,p,f))&+(!fp(p)||NR(e,n,i,c,p,f))&+(!hp(p)||ZR(e,n,i,c,p,f))&+(!cc(p)||Dk(e,n,i,c,p,f))&+(!gc(p)||lA(e,n,i,c,p,f))&+(!tc(p)||PR(e,n,i,c,p,f))&+(!nc(p)||vR(e,n,i,c,p,f))&+(!yc(p)||hA(e,n,i,c,p,f))&+(!Si(p)||(!Be(f)||zA(e,n,i,c,p,f)))&+(!Ti(p)||(!at(f)||JA(e,n,i,c,p,f))))&&(!ec(p)||bR(e,n,i,c,p,f));return e.Pop(p),g}var e0=[0],Hp=new Map,Ac=new Map;function YF(){return`${e0[0]++}`}function ZF(e,n){if(!Hp.has(e))Hp.set(e,new Map);let i=Hp.get(e);if(i.has(n))return i.get(n);let c=YF();return i.set(n,c),c}function e1(e,n,i,c){return e.UseUnevaluated()?gr(`check_${i}`,["context",c]):gr(`check_${i}`,[c])}function t1(e,n,i,c){let p=Nt(e,n,i,"value");return n.UseUnevaluated()?Ps(`check_${c}`,Ks(["context","value"],p)):Ps(`check_${c}`,Ks(["value"],p))}function t0(){e0[0]=0,Hp.clear(),Ac.clear()}function r0(){return[...Ac.values()]}function qs(e,n,i,c){let p=ZF(i,e.LexicalBaseURL()),f=e1(n,i,p,c);if(Ac.has(p))return f;return Ac.set(p,""),Ac.set(p,t1(e,n,i,p)),f}function r1(e,n){return at(n)&&!xu(e)?n[e]:void 0}function n1(e,n){return e.reduce((i,c)=>r1(c,i),n)}function o1(e){if(_(e.length,0))return[];let n=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return n.length>0&&n[0]===""?n.slice(1):n}function s1(e,n){let i=o1(n);return n1(i,e)}var zp="https://json-schema.org";function o0(e,n){if(at(e)&&Os(e)&&_(e.$dynamicAnchor,n))return e;if(at(e))for(let i of Ee(e)){let c=o0(e[i],n);if(c)return c}return}function rh(e,n,i){if(_(e,i))return n.href;let c=pn(e)&&fo(e)?new URL(e.$id,n.href):n;if(Be(e))for(let p of e){let f=rh(p,c,i);if(!Gt(f))return f}else if(at(e))for(let p of Ee(e)){let f=rh(e[p],c,i);if(!Gt(f))return f}return}function i1(e,n,i){if(_(e.$id,i.hash))return e;let c=new URL(i.href,n.href);if(_(n.pathname,c.pathname))return i.hash.startsWith("#")?s0(e,i):e;return}function a1(e,n,i){let c=new URL(`#${e.$anchor}`,n.href),p=new URL(i.href,n.href);return _(c.href,p.href)?e:void 0}function u1(e,n,i){let c=new URL(`#${e.$dynamicAnchor}`,n.href),p=new URL(i.href,n.href);return _(c.href,p.href)?e:void 0}function s0(e,n){if(n.href.endsWith("#"))return e;if(!n.hash.startsWith("#"))return;let i=decodeURIComponent(n.hash.slice(1));if(!i.startsWith("/"))return;return s1(e,i)}function c1(e,n,i){if(fo(e)){let c=i1(e,n,i);if(!Gt(c))return c}if(rc(e)){let c=a1(e,n,i);if(!Gt(c))return c}if(Os(e)){let c=u1(e,n,i);if(!Gt(c))return c}return s0(e,i)}function m1(e,n,i){return e.reduce((c,p)=>{let f=Vp(p,n,i);return!Gt(f)?f:c},void 0)}function p1(e){return _(e,"const")||_(e,"enum")}function l1(e,n,i){return Ee(e).reduce((c,p)=>{if(p1(p))return c;let f=Vp(e[p],n,i);return!Gt(f)?f:c},void 0)}function Vp(e,n,i){let c=pn(e)&&fo(e)?new URL(e.$id,n.href):n;if(pn(e)){let p=c1(e,c,i);if(!Gt(p))return p}if(Be(e))return m1(e,c,i);if(at(e))return l1(e,c,i);return}function d1(e,n,i){return rh(e,new URL(n||".",zp),i)}function f1(e,n,i,c){let p=Qp(e,n,i,c,!1);return pn(p)&&fo(p)?p:void 0}function n0(e){return e.href.split("#")[0]}function h1(e,n){return pe(e,n)?e[n]:void 0}function g1(e,n,i){return Vp(e,n,i)}function y1(e,n,i){let c=n0(i);if(_(c,n0(n)))return;if(!pe(e,c))return;let p=e[c],f=pn(p)&&fo(p)?new URL(p.$id,c):new URL(c);return _(i.hash,"")?p:Vp(p,f,i)}function x1(e,n,i,c,p){if(!c.$ref.startsWith("#"))return;if(pe(e,"$schema"))return;let f=d1(n,i,p);if(Gt(f)||_(f,i))return;return{target:p,base:f,root:n}}function I1(e,n,i){let c=e[n];if(!pn(c))return;return{target:i,base:n,root:c}}function b1(e,n,i,c,p){let f=p?I1(e.context,c,i):void 0;if(!Gt(f))return f;return x1(e.root,e.lexicalSchema,e.referenceBase,n,i)}function E1(e,n,i,c,p,f){if(fo(p))return;let g=f1(e,n,i,c);if(!g||f.includes(g))return;return{target:p,resource:g}}function Qp(e,n,i,c,p=!0){let f=new URL(i||".",zp),g=p&&fo(n)?new URL(n.$id,f):f,x=new URL(c,g.href);return h1(e,c)??g1(n,g,x)??y1(e,g,x)}function S1(e,n,i,c,p,f){let g=new URL(i||".",zp),x=p.$dynamicRef.startsWith("#")?c:n,I=Qp(e,x,i,p.$dynamicRef,!1);if(Gt(I)){let T=new URL(p.$dynamicRef,g).hash;if(!T.startsWith("#/")&&T.startsWith("#")){let k=decodeURIComponent(T.slice(1));return f.find((L)=>_(L.$dynamicAnchor,k))??o0(n,k)}return}if(!pn(I)||!Os(I))return I;if(new URL(p.$dynamicRef,g).hash.startsWith("#/"))return I;return f.find((T)=>_(T.$dynamicAnchor,I.$dynamicAnchor))??I}function w1(e,n){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,c=n.$ref.startsWith("#")?e.lexicalSchema:i,p=Qp(e.context,c,e.referenceBase,n.$ref,!1);if(!p||!pn(p))return{schema:p};let f=new URL(n.$ref,e.referenceBase).href.split("#")[0],g=!_(f,e.resourceBase),x=b1(e,n,p,f,g),I=g?E1(e.context,e.root,e.referenceBase,f,p,e.ids):void 0;return{schema:p,retrievedResource:x,resolvedResource:I}}function T1(e,n){let i=xc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Qp(e.context,i,e.lexicalBase,n.$recursiveRef,!1)}function R1(e,n){return S1(e.context,e.root,e.lexicalBase,e.lexicalSchema,n,e.dynamicAnchors)}var Mr=function(e,n,i,c){if(i==="a"&&!c)throw TypeError("Private accessor was defined without a getter");if(typeof n==="function"?e!==n||!c:!n.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?c:i==="a"?c.call(e):c?c.value:n.get(e)},Ir,Xp,p0,ih,Jp,i0,a0,u0,c0,oh,sh,ah,uh,m0,l0;class ki{constructor(e,n){Ir.add(this),this.context=e,this.schema=n,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return Mr(this,Ir,"m",ih).call(this,this.ids)}Push(e){if(!pn(e))return;if(fo(e))Mr(this,Ir,"m",ah).call(this,e);if(rc(e))this.anchors.push(e);if(xc(e))this.recursiveAnchors.push(e);if(Os(e))this.dynamicAnchors.push(e);let n=this.retrievedResources.get(e);if(n)this.retrievedFrames.push({schema:n.root,base:n.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!pn(e))return;if(fo(e))Mr(this,Ir,"m",uh).call(this,e);if(rc(e))this.anchors.pop();if(xc(e))this.recursiveAnchors.pop();if(Os(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Mr(this,Ir,"m",l0).call(this,e)}Ref(e){let n=w1(Mr(this,Ir,"m",Xp).call(this),e);return Mr(this,Ir,"m",p0).call(this,n),n.schema}RecursiveRef(e){let n=T1(Mr(this,Ir,"m",Xp).call(this),e);if(n)this.pendingResource=!0;return n}DynamicRef(e){let n=R1(Mr(this,Ir,"m",Xp).call(this),e);if(n)this.pendingResource=!0;return n}}Ir=new WeakSet,Xp=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Mr(this,Ir,"m",a0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Mr(this,Ir,"m",i0).call(this),resourceBase:Mr(this,Ir,"m",Jp).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},p0=function(n){if(!Gt(n.schema))this.pendingResource=!0;if(!Gt(n.resolvedResource))Mr(this,Ir,"m",m0).call(this,n.resolvedResource.target,n.resolvedResource.resource);if(!Gt(n.retrievedResource))this.retrievedResources.set(n.retrievedResource.target,{base:n.retrievedResource.base,root:n.retrievedResource.root})},ih=function(n){let i=this.retrievedFrames[this.retrievedFrames.length-1],c=i?new URL(i.base):new URL(zp);return(i?n.slice(i.idDepth):n).reduce((f,g)=>new URL(g.$id,f),c).href},Jp=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(!n)return Mr(this,Ir,"m",ih).call(this,this.resourceIds);return this.resourceIds.slice(n.resourceDepth).reduce((i,c)=>new URL(c.$id,i),new URL(n.base)).href},i0=function(){if(this.retrievedFrames.length>0)return Mr(this,Ir,"m",Jp).call(this);let n=this.ids[this.ids.length-1];if(n&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(n.$id))return this.LexicalBaseURL();return Mr(this,Ir,"m",Jp).call(this)},a0=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(n)return this.ids.length>n.idDepth?this.ids[this.ids.length-1]:n.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},u0=function(n){n.forEach((i)=>Mr(this,Ir,"m",oh).call(this,i,!1))},c0=function(n){n.forEach((i)=>Mr(this,Ir,"m",sh).call(this,i,!1))},oh=function e(n,i=!0){if(vs(n))return;if(Be(n))return Mr(this,Ir,"m",u0).call(this,n);if(!pn(n))return;let c=n;if(!i&&fo(c))return;if(!i&&Os(c))this.dynamicAnchors.push(c);for(let p of Ee(c))Mr(this,Ir,"m",e).call(this,c[p],!1)},sh=function e(n,i=!0){if(vs(n))return;if(Be(n))return Mr(this,Ir,"m",c0).call(this,n);if(!pn(n))return;let c=n;if(!i&&fo(c))return;if(!i&&Os(c))this.dynamicAnchors.pop();for(let p of Ee(c))Mr(this,Ir,"m",e).call(this,c[p],!1)},ah=function(n){this.ids.push(n);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(n);Mr(this,Ir,"m",oh).call(this,n,!0)},uh=function(n){if(this.ids.pop(),this.resourceIds.length>0&&_(this.resourceIds[this.resourceIds.length-1],n))this.resourceIds.pop();Mr(this,Ir,"m",sh).call(this,n,!0)},m0=function(n,i){Mr(this,Ir,"m",ah).call(this,i),this.resolvedResources.set(n,i)},l0=function(n){if(!this.resolvedResources.has(n))return;let i=this.resolvedResources.get(n);Mr(this,Ir,"m",uh).call(this,i),this.resolvedResources.delete(n)};function k1(e){let n=e.Functions().join(`;
29
+ `),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${n}; return (value) => { ${i.join("; ")} }`}function A1(e,n){return Oy("CheckContext","Guard","Format","Hashing",e.External().identifier,n)(An,j,Va,Wi,e.External().variables)}function C1(e){let n=new ki(e.Context(),e.Schema()),i=new An;return(c)=>kt(n,i,e.Schema(),c)}function P1(e,n){return vy()?A1(e,n):C1(e)}class d0{constructor(e,n,i){this.isAccelerated=e,this.code=n,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class f0{constructor(e,n,i,c,p,f){this.context=e,this.schema=n,this.external=i,this.functions=c,this.entry=p,this.useUnevaluated=f}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=k1(this),n=P1(this,e);return new d0(vy(),e,n)}}function Yp(...e){let[n,i]=yn(e,{2:(I,b)=>[I,b],1:(I)=>[{},I]});gR(),t0();let c=new ki(n,i),p=new Tf(hR(n,i)),f=qs(c,p,i,"value"),g=r0(),x=yR();return new f0(n,i,x,g,f,p.UseUnevaluated())}function Zp(...e){let[n,i,c]=yn(e,{3:(E,T,k)=>[E,T,k],2:(E,T)=>[{},E,T]}),p=new ki(n,i),f=new Cn,g=tr(p,f,"#","",i,c),x=f.GetErrors(),I=By(),b=x.map((E)=>({...E,message:I(E)}));return[g,b]}function mh(...e){let[n,i,c]=yn(e,{3:(g,x,I)=>[g,x,I],2:(g,x)=>[{},g,x]}),p=new ki(n,i),f=new An;return kt(p,f,i,c)}function Xt(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return mh(n,i,c)}function ws(...e){let[n,i,c]=yn(e,{3:(g,x,I)=>[g,x,I],2:(g,x)=>[{},g,x]}),[p,f]=Zp(n,i,c);return f}class aa extends Error{constructor(e,n,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:n},writable:!1,configurable:!1,enumerable:!1})}}function h0(e,n,i){if(!Be(i))return i;return i.map((c)=>ln(e,n.items,c))}function g0(e,n,i){return ln({...e,...n.$defs},rn(n.$ref),i)}function v1(e,n){let i=pe(n,"unevaluatedProperties")?{additionalProperties:n.unevaluatedProperties}:{},c=Eo(e,n),p=In(c);return Je(p)?cp(p,i):p}function y0(e,n,i){let c=v1(e,n);return ln(e,c,i)}function el(e){return pe(e,"additionalProperties")?e.additionalProperties:void 0}function x0(e,n,i){if(!at(i)||Be(i))return i;let c=el(n);for(let p of Ee(i)){if(pe(n.properties,p)){i[p]=ln(e,n.properties[p],i[p]);continue}if(sn(c)&&_(c,!0)||kr(c)&&Xt(e,c,i[p])){i[p]=ln(e,c,i[p]);continue}delete i[p]}return i}function I0(e,n,i){if(!at(i))return i;let c=el(n),[p,f]=[new RegExp(mn(n)),pr(n)];for(let g of Ee(i)){if(p.test(g)){i[g]=ln(e,f,i[g]);continue}if(sn(c)&&_(c,!0)||kr(c)&&Xt(e,c,i[g])){i[g]=ln(e,c,i[g]);continue}delete i[g]}return i}function b0(e,n,i){return pe(e,n.$ref)?ln(e,e[n.$ref],i):i}function E0(e,n,i){if(!Be(i))return i;let c=Math.min(i.length,n.items.length);for(let p=0;p<c;p++)i[p]=ln(e,n.items[p],i[p]);return qi(i.length,c)?i.slice(0,c):i}function Dr(e){return Ia(e)}function S0(e,n,i){for(let c of n.anyOf){let p=ln(e,c,Dr(i));if(Xt(e,c,p))return p}return i}function ln(e,n,i){return St(n)?h0(e,n,i):Jt(n)?g0(e,n,i):He(n)?y0(e,n,i):Je(n)?x0(e,n,i):Kt(n)?I0(e,n,i):jt(n)?b0(e,n,i):ct(n)?E0(e,n,i):be(n)?S0(e,n,i):i}function O1(e,n){for(let i of Ee(e)){if(pe(n,i))continue;n[i]=e[i]}return n}function _1(e){let n={};for(let i of Ee(e))n[i]=Cc(e[i]);return n}function L1(e){return ph(JT(e))}function ph(e){return e.map((n)=>Cc(n))}function Cc(e){let n=St(e)?W(Cc(e.items),ba(e)):He(e)?wn(ph(e.allOf)):be(e)?m(L1(e.anyOf)):Je(e)?s(_1(e.properties)):Kt(e)?ys(Ys(e),Cc(pr(e))):ct(e)?Lr(ph(e.items)):e;return O1(e,n)}function Qa(e){return Cc(e)}function Ao(...e){let[n,i,c]=yn(e,{3:(f,g,x)=>[f,g,x],2:(f,g)=>[{},f,g]}),p=Ko().unionPrioritySort?Qa(i):i;return ln(n,p,c)}function ao(e){return at(e)&&pe(e,"value")}function Ge(e){return{value:e}}function br(){return}function N1(e){return Be(e)?Ge(e):Ge([e])}function D1(e){return _(e,!0)?Ge(BigInt(1)):Ge(BigInt(0))}var q1=/^-?(0|[1-9]\d*)n$/,F1=/^-?(0|[1-9]\d*)\.\d+$/,j1=/^-?(0|[1-9]\d*)$/;function U1(e){return q1.test(e)}function B1(e){return F1.test(e)}function G1(e){return j1.test(e)}function K1(e){let n=e.toLowerCase();return U1(e)?Ge(BigInt(e.slice(0,e.length-1))):B1(e)?Ge(BigInt(e.split(".")[0])):G1(e)?Ge(BigInt(e)):_(n,"false")?Ge(BigInt(0)):_(n,"true")?Ge(BigInt(1)):br()}function tl(e){return vr(e)?Ge(e):sn(e)?D1(e):Ot(e)?Ge(BigInt(Math.trunc(e))):uo(e)?Ge(BigInt(0)):gt(e)?K1(e):Gt(e)?Ge(BigInt(0)):br()}function H1(e){return _(e,BigInt(0))?Ge(!1):_(e,BigInt(1))?Ge(!0):br()}function W1(e){return _(e,0)?Ge(!1):_(e,1)?Ge(!0):br()}function z1(e){return _(e.toLowerCase(),"false")?Ge(!1):_(e.toLowerCase(),"true")?Ge(!0):_(e,"0")?Ge(!1):_(e,"1")?Ge(!0):br()}function w0(e){return vr(e)?H1(e):sn(e)?Ge(e):Ot(e)?W1(e):uo(e)?Ge(!1):gt(e)?z1(e):Gt(e)?Ge(!1):br()}function V1(e){return _(e,BigInt(0))?Ge(null):br()}function Q1(e){return _(e,!1)?Ge(null):br()}function J1(e){return _(e,0)?Ge(null):br()}function X1(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(null):br()}function Y1(e){return vr(e)?V1(e):sn(e)?Q1(e):Ot(e)?J1(e):uo(e)?Ge(null):gt(e)?X1(e):Gt(e)?Ge(null):br()}var T0=BigInt(Number.MAX_SAFE_INTEGER),R0=BigInt(Number.MIN_SAFE_INTEGER);function Z1(e){return e<=T0&&e>=R0?Ge(Number(e)):br()}function ej(e){return Ge(e?1:0)}function tj(e){let n=+e;if(Ot(n))return Ge(n);let i=e.toLowerCase();if(_(i,"false"))return Ge(0);if(_(i,"true"))return Ge(1);let c=tl(e);if(ao(c))return c.value<=T0&&c.value>=R0?Ge(Number(c.value)):br();return br()}function lh(e){return vr(e)?Z1(e):sn(e)?ej(e):Ot(e)?Ge(e):uo(e)?Ge(0):gt(e)?tj(e):Gt(e)?Ge(0):br()}function k0(e){return vr(e)?Ge(e.toString()):sn(e)?Ge(e.toString()):Ot(e)?Ge(e.toString()):uo(e)?Ge("null"):gt(e)?Ge(e):Gt(e)?Ge(""):br()}function rj(e){return _(e,BigInt(0))?Ge(void 0):br()}function nj(e){return _(e,!1)?Ge(void 0):br()}function oj(e){return _(e,0)?Ge(void 0):br()}function sj(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(void 0):br()}function A0(e){return vr(e)?rj(e):sn(e)?nj(e):Ot(e)?oj(e):uo(e)?Ge(void 0):gt(e)?sj(e):Gt(e)?Ge(e):br()}function C0(e,n,i){return N1(i).value.map((p)=>Fr(e,n.items,p))}function P0(e,n,i){let c=tl(i);return ao(c)?c.value:i}function $0(e,n,i){let c=w0(i);return ao(c)?c.value:i}function M0(e,n,i){return Fr({...e,...n.$defs},rn(n.$ref),i)}function v0(e,n,i){return Fr(e,In(n),i)}function O0(e,n,i){let c=lh(i);return ao(c)?Math.trunc(c.value):i}function _0(e,n,i){let c=Eo(e,n),p=In(c);return Fr(e,p,i)}function ij(e,n,i){let c=tl(i);return ao(c)&&_(n.const,c.value)?c.value:i}function aj(e,n,i){let c=w0(i);return ao(c)&&_(n.const,c.value)?c.value:i}function uj(e,n,i){let c=lh(i);return ao(c)&&_(n.const,c.value)?c.value:i}function cj(e,n,i){let c=k0(i);return ao(c)&&_(n.const,c.value)?c.value:i}function L0(e,n,i){if(_(n.const,i))return i;return Yy(n)?ij(e,n,i):Zy(n)?aj(e,n,i):dm(n)?uj(e,n,i):fm(n)?cj(e,n,i):_r()}function N0(e,n,i){let c=Y1(i);return ao(c)?c.value:i}function D0(e,n,i){let c=lh(i);return ao(c)?c.value:i}function rl(e,n,i,c){let p=Ee(c);for(let[f,g]of n)for(let x of p)if(!f.test(x))c[x]=Fr(e,i,c[x]);return c}function Pc(e,n,i){return nn(e)&&Gt(i[n])}function mj(e,n,i){let c=nd(n.properties),p=Ee(i);for(let[f,g]of c)for(let x of p){if(!f.test(x)||Pc(g,x,i))continue;i[x]=Fr(e,g,i[x])}return pe(n,"additionalProperties")&&at(n.additionalProperties)?rl(e,c,n.additionalProperties,i):i}function q0(e,n,i){return Go(i)?mj(e,n,i):i}function pj(e,n,i){let c=nd(n.patternProperties),p=Ee(i);for(let[f,g]of c)for(let x of p)if(f.test(x))i[x]=Fr(e,g,i[x]);return pe(n,"additionalProperties")&&at(n.additionalProperties)?rl(e,c,n.additionalProperties,i):i}function F0(e,n,i){return Go(i)?pj(e,n,i):i}function j0(e,n,i){return pe(e,n.$ref)?Fr(e,e[n.$ref],i):i}function U0(e,n,i){let c=k0(i);return ao(c)?c.value:i}function B0(e,n,i){return Fr(e,In(n),i)}function G0(e,n,i){if(!Be(i))return i;for(let c=0;c<Math.min(n.items.length,i.length);c++)i[c]=Fr(e,n.items[c],i[c]);return i}function K0(e,n,i){let c=A0(i);return ao(c)?c.value:i}function H0(e,n,i){if(n.anyOf.some((g)=>Xt(e,g,i)))return i;let f=n.anyOf.map((g)=>Fr(e,g,Dr(i))).find((g)=>Xt(e,n,g));return Gt(f)?i:f}function W0(e,n,i){let c=A0(i);return ao(c)?void 0:i}function Fr(e,n,i){return St(n)?C0(e,n,i):oo(n)?P0(e,n,i):_n(n)?$0(e,n,i):Jt(n)?M0(e,n,i):Zr(n)?v0(e,n,i):cn(n)?O0(e,n,i):He(n)?_0(e,n,i):yt(n)?L0(e,n,i):hs(n)?N0(e,n,i):wr(n)?D0(e,n,i):Je(n)?q0(e,n,i):Kt(n)?F0(e,n,i):jt(n)?j0(e,n,i):en(n)?U0(e,n,i):er(n)?B0(e,n,i):ct(n)?G0(e,n,i):Qo(n)?K0(e,n,i):be(n)?H0(e,n,i):so(n)?W0(e,n,i):i}function ns(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return Fr(n,i,c)}function z0(e,n,i){if(!Be(i))return i;for(let c=0;c<i.length;c++)i[c]=dn(e,n.items,i[c]);return i}function V0(e,n,i){return dn({...e,...n.$defs},rn(n.$ref),i)}function Q0(e,n){if(!Gt(n))return n;return as(e.default)?e.default():Dr(e.default)}function J0(e,n,i){let c=Eo(e,n),p=In(c);return dn(e,p,i)}function X0(e,n,i){if(!at(i))return i;let c=Ee(n.properties);for(let p of c){let f=dn(e,n.properties[p],i[p]);if(Gt(f)&&(nn(n.properties[p])||!pe(n.properties[p],"default")))continue;i[p]=f}if(!So(n)||sn(n.additionalProperties))return i;for(let p of Ee(i)){if(c.includes(p))continue;i[p]=dn(e,n.additionalProperties,i[p])}return i}function Y0(e,n,i){if(!at(i))return i;let[c,p]=[new RegExp(mn(n)),pr(n)];for(let f of Ee(i)){if(!(c.test(f)&&lo(p)))continue;i[f]=dn(e,p,i[f])}if(!So(n))return i;for(let f of Ee(i)){if(c.test(f))continue;i[f]=dn(e,n.additionalProperties,i[f])}return i}function Z0(e,n,i){return pe(e,n.$ref)?dn(e,e[n.$ref],i):i}function eC(e,n,i){if(!Be(i))return i;let[c,p]=[n.items,Math.max(n.items.length,i.length)];for(let f=0;f<p;f++)if(f<c.length)i[f]=dn(e,c[f],i[f]);return i}function tC(e,n,i){for(let c of n.anyOf){let p=dn(e,c,Dr(i));if(Xt(e,c,p))return p}return i}function dn(e,n,i){let c=lo(n)?Q0(n,i):i;return St(n)?z0(e,n,c):Jt(n)?V0(e,n,c):He(n)?J0(e,n,c):Je(n)?X0(e,n,c):Kt(n)?Y0(e,n,c):jt(n)?Z0(e,n,c):ct(n)?eC(e,n,c):be(n)?tC(e,n,c):c}function Fs(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return dn(n,i,c)}function Ja(e){return(...n)=>{let[i,c,p]=yn(n,{3:(f,g,x)=>[f,g,x],2:(f,g)=>[{},f,g]});return e.reduce((f,g)=>g(i,c,f),p)}}function lj(e,n,i){return n["~codec"].decode(i)}function dj(e,n,i){return n["~codec"].encode(i)}function Er(e,n,i,c){if(!On(i))return c;return _(e,"Decode")?lj(n,i,c):dj(n,i,c)}function fj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<c.length;p++)c[p]=Rr(e,n,i.items,c[p]);return Er(e,n,i,c)}function hj(e,n,i,c){let p=Er(e,n,i,c);if(!Be(p))return p;for(let f=0;f<p.length;f++)p[f]=Rr(e,n,i.items,p[f]);return p}function rC(e,n,i,c){return _(e,"Decode")?fj(e,n,i,c):hj(e,n,i,c)}function nC(e,n,i,c){return c=Rr(e,{...n,...i.$defs},rn(i.$ref),c),Er(e,n,i,c)}function oC(e){return e.reduce((n,i)=>({...n,...i}),{})}function sC(e,n){for(let i of n)if(!xa(e,i))return i;return e}function gj(e,n,i,c){if(_(i.allOf.length,0))return Er(e,n,i,c);let p=i.allOf.map((x)=>Rr(e,n,x,Ao(x,Dr(c)))),g=p.every((x)=>at(x))?oC(p):sC(c,p);return Er(e,n,i,g)}function yj(e,n,i,c){if(_(i.allOf.length,0))return Er(e,n,i,c);let p=Er(e,n,i,c),f=i.allOf.map((x)=>Rr(e,n,x,Ao(x,Dr(p))));if(f.every((x)=>at(x)))return oC(f);return sC(p,f)}function iC(e,n,i,c){return _(e,"Decode")?gj(e,n,i,c):yj(e,n,i,c)}function xj(e,n,i,c){if(!Go(c))return c;for(let p of Ee(i.properties)){if(!pe(c,p)||Pc(i.properties[p],p,c))continue;c[p]=Rr(e,n,i.properties[p],c[p])}return Er(e,n,i,c)}function Ij(e,n,i,c){let p=Er(e,n,i,c);if(!Go(p))return p;for(let f of Ee(i.properties)){if(!pe(p,f)||Pc(i.properties[f],f,p))continue;p[f]=Rr(e,n,i.properties[f],p[f])}return p}function aC(e,n,i,c){return _(e,"Decode")?xj(e,n,i,c):Ij(e,n,i,c)}function bj(e,n,i,c){if(!Go(c))return c;let p=new RegExp(mn(i));for(let f of Ee(c)){if(!p.test(f))continue;c[f]=Rr(e,n,pr(i),c[f])}return Er(e,n,i,c)}function Ej(e,n,i,c){let p=Er(e,n,i,c);if(!Go(p))return p;let f=new RegExp(mn(i));for(let g of Ee(p)){if(!f.test(g))continue;p[g]=Rr(e,n,pr(i),p[g])}return p}function uC(e,n,i,c){return _(e,"Decode")?bj(e,n,i,c):Ej(e,n,i,c)}function cC(e,n,i,c){return pe(n,i.$ref)?Rr(e,n,n[i.$ref],c):c}function mC(e,n,i,c){return _(e,"Decode")?Er(e,n,i,cC(e,n,i,c)):cC(e,n,i,Er(e,n,i,c))}function Sj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<Math.min(i.items.length,c.length);p++)c[p]=Rr(e,n,i.items[p],c[p]);return Er(e,n,i,c)}function wj(e,n,i,c){let p=Er(e,n,i,c);if(!Be(p))return c;for(let f=0;f<Math.min(i.items.length,p.length);f++)p[f]=Rr(e,n,i.items[f],p[f]);return p}function pC(e,n,i,c){return _(e,"Decode")?Sj(e,n,i,c):wj(e,n,i,c)}function Tj(e,n,i,c){for(let p of i.anyOf){if(!Xt(n,p,c))continue;let f=Rr(e,n,p,c);return Er(e,n,i,f)}return c}function Rj(e,n,i,c){let p=Er(e,n,i,c);for(let f of i.anyOf){let g=Rr(e,n,f,Dr(p));if(!Xt(n,f,g))continue;return g}return p}function lC(e,n,i,c){return _(e,"Decode")?Tj(e,n,i,c):Rj(e,n,i,c)}function Rr(e,n,i,c){return St(i)?rC(e,n,i,c):Jt(i)?nC(e,n,i,c):He(i)?iC(e,n,i,c):Je(i)?aC(e,n,i,c):Kt(i)?uC(e,n,i,c):jt(i)?mC(e,n,i,c):ct(i)?pC(e,n,i,c):be(i)?lC(e,n,i,c):Er(e,n,i,c)}class dC extends aa{constructor(e,n){super("Decode",e,n)}}function kj(e,n,i){if(!Xt(e,n,i))throw new dC(i,ws(e,n,i));return i}function Aj(e,n,i){let c=Ko().unionPrioritySort?Qa(n):n;return Rr("Decode",e,c,i)}var Cj=Ja([(e,n,i)=>Dr(i),(e,n,i)=>Fs(e,n,i),(e,n,i)=>ns(e,n,i),(e,n,i)=>Ao(e,n,i),(e,n,i)=>kj(e,n,i),(e,n,i)=>Aj(e,n,i)]);function dh(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return Cj(n,i,c)}class fC extends aa{constructor(e,n){super("Encode",e,n)}}function Pj(e,n,i){if(!Xt(e,n,i))throw new fC(i,ws(e,n,i));return i}function $j(e,n,i){let c=Ko().unionPrioritySort?Qa(n):n;return Rr("Encode",e,c,i)}var Mj=Ja([(e,n,i)=>Dr(i),(e,n,i)=>$j(e,n,i),(e,n,i)=>Fs(e,n,i),(e,n,i)=>ns(e,n,i),(e,n,i)=>Ao(e,n,i),(e,n,i)=>Pj(e,n,i)]);function fh(...e){let[n,i,c]=yn(e,{3:(p,f,g)=>[p,f,g],2:(p,f)=>[{},p,f]});return Mj(n,i,c)}function vj(e,n){return On(n)||Ci(e,n.items)}function Oj(e,n){return On(n)||hC({...e,...n.$defs},rn(n.$ref))}function _j(e,n){return On(n)||n.allOf.some((i)=>Ci(e,i))}function Lj(e,n){return On(n)||Ee(n.properties).some((i)=>Ci(e,n.properties[i]))}function Nj(e,n){return On(n)||Ci(e,pr(n))}function hC(e,n){if(hh.has(n.$ref))return!1;return hh.add(n.$ref),On(n)||pe(e,n.$ref)&&Ci(e,e[n.$ref])}function Dj(e,n){return On(n)||n.items.some((i)=>Ci(e,i))}function qj(e,n){return On(n)||n.anyOf.some((i)=>Ci(e,i))}function Ci(e,n){return St(n)?vj(e,n):Jt(n)?Oj(e,n):He(n)?_j(e,n):Je(n)?Lj(e,n):Kt(n)?Nj(e,n):jt(n)?hC(e,n):ct(n)?Dj(e,n):be(n)?qj(e,n):On(n)}var hh=new Set;function gh(...e){let[n,i]=yn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return hh.clear(),Ci(n,i)}class os extends Error{constructor(e,n){super(n);this.type=e}}function gC(e,n){return as(n.default)?n.default(n):at(n.default)?Dr(n.default):n.default}function yC(e,n){if(Ii(n)&&!lo(n))throw new os(n,"Arrays with uniqueItems constraints must specify a default annotation");let i=ii(n)?n.minItems:0;return Array.from({length:i},()=>Ur(e,n.items))}function xC(e,n){return Jo(n)?BigInt(n.exclusiveMinimum)+BigInt(1):Xo(n)?BigInt(n.minimum):BigInt(0)}function IC(e,n){return!1}function bC(e,n){let i=Ur(e,n.instanceType);return class{constructor(){Object.assign(this,i)}}}function EC(e,n){return Ur({...e,...n.$defs},rn(n.$ref))}function SC(e,n){return Ur(e,In(n))}function wC(e,n){let i=Ur(e,n.returnType);return()=>i}function TC(e,n){return Jo(n)&&Ot(n.exclusiveMinimum)?n.exclusiveMinimum+1:Xo(n)?n.minimum:0}function RC(e,n){let i=Eo(e,n),c=In(i);return Ur(e,c)}function kC(e,n){return n.const}function AC(e,n){throw new os(n,"Cannot create TNever types")}function CC(e,n){return null}function PC(e,n){return Jo(n)&&Ot(n.exclusiveMinimum)?n.exclusiveMinimum+1:Xo(n)?n.minimum:0}function $C(e,n){return(Gt(n.required)?[]:n.required).reduce((c,p)=>({...c,[p]:Ur(e,n.properties[p])}),{})}function MC(e,n){if(sa(n)&&!lo(n))throw new os(n,"Record with the minProperties constraint must have a default annotation");return{}}function vC(e,n){return pe(e,n.$ref)?Ur(e,e[n.$ref]):(()=>{throw new os(n,"Unable to deref Ref")})()}function OC(e,n){if((ia(n)||na(n))&&!lo(n))throw Error("Strings with format or pattern constraints must specify default");let c=oa(n)?n.minLength:0;return"".padEnd(c)}function _C(e,n){return Symbol()}function LC(e,n){let i=Au(n.pattern);if(en(i))throw new os(n,"Unable to create TemplateLiteral due to infinite type expansion");return Ur(e,i)}function NC(e,n){return Array.from({length:n.minItems},(i,c)=>Ur(e,n.items[c]))}function DC(e,n){return}function qC(e,n){if(_(n.anyOf.length,0))throw Error("Unable to create Union with no variants");return Ur(e,n.anyOf[0])}function FC(e,n){return}function Ur(e,n){return lo(n)?gC(e,n):St(n)?yC(e,n):oo(n)?xC(e,n):_n(n)?IC(e,n):Kr(n)?bC(e,n):Jt(n)?EC(e,n):Zr(n)?SC(e,n):Jr(n)?wC(e,n):cn(n)?TC(e,n):He(n)?RC(e,n):yt(n)?kC(e,n):no(n)?AC(e,n):hs(n)?CC(e,n):wr(n)?PC(e,n):Je(n)?$C(e,n):Kt(n)?MC(e,n):jt(n)?vC(e,n):en(n)?OC(e,n):gs(n)?_C(e,n):er(n)?LC(e,n):ct(n)?NC(e,n):Qo(n)?DC(e,n):be(n)?qC(e,n):so(n)?FC(e,n):void 0}function Ts(...e){let[n,i]=yn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return Ur(n,i)}class nl extends aa{constructor(e,n){super("Parse",e,n)}}function Fj(e,n,i){if(!Xt(e,n,i))throw new nl(i,ws(e,n,i));return i}var jC=Ja([(e,n,i)=>Dr(i),(e,n,i)=>Fs(e,n,i),(e,n,i)=>ns(e,n,i),(e,n,i)=>Ao(e,n,i),(e,n,i)=>Fj(e,n,i)]);var Uj=s({type:a("insert"),path:l(),value:Sr()}),Bj=Object({type:a("update"),path:l(),value:Sr()}),Gj=s({type:a("delete"),path:l()}),Fve=m([Uj,Bj,Gj]);class ol{constructor(e,n){this.hasCodec=gh(e,n),this.buildResult=Yp(e,n),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(Ko().correctiveParse)return jC(this.Context(),this.Type(),e);throw new nl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return ws(this.Context(),this.Type(),e)}Clean(e){return Ao(this.Context(),this.Type(),e)}Convert(e){return ns(this.Context(),this.Type(),e)}Create(){return Ts(this.Context(),this.Type())}Default(e){return Fs(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?dh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?fh(this.Context(),this.Type(),e):this.Parse(e)}}function xh(...e){let[n,i]=yn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return new ol(n,i)}var BC=new WeakMap,Wj=Symbol.for("TypeBox.Kind");function zj(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((n)=>typeof n==="string");return[]}function Vj(e,n){switch(n){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function Ih(e){try{return KC(e)}catch{return}}function Qj(e,n){switch(n){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isFinite(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isInteger(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function Jj(e,n){let i=n.properties,c=new Set(i?Object.keys(i):[]);if(i)for(let[p,f]of Object.entries(i)){if(!(p in e))continue;e[p]=ca(e[p],f)}if(n.additionalProperties&&typeof n.additionalProperties==="object")for(let[p,f]of Object.entries(e)){if(c.has(p))continue;e[p]=ca(f,n.additionalProperties)}}function Xj(e,n){if(Array.isArray(n.items)){for(let i=0;i<e.length;i++){let c=n.items[i];if(!c)continue;e[i]=ca(e[i],c)}return}if(n.items&&typeof n.items==="object")for(let i=0;i<e.length;i++)e[i]=ca(e[i],n.items)}function GC(e,n){for(let i of n)if(Ih(i)?.Check(e))return e;for(let i of n){let c=structuredClone(e),p=ca(c,i);if(Ih(i)?.Check(p))return p}return e}function ca(e,n){let i=e;if(Array.isArray(n.allOf))for(let f of n.allOf)i=ca(i,f);if(Array.isArray(n.anyOf))i=GC(i,n.anyOf);if(Array.isArray(n.oneOf))i=GC(i,n.oneOf);let c=zj(n),p=c.length>1&&c.some((f)=>Vj(i,f));if(c.length>0&&!p)for(let f of c){let g=Qj(i,f);if(g!==i){i=g;break}}if(c.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))Jj(i,n);if(c.includes("array")&&Array.isArray(i))Xj(i,n);return i}function sl(e,n){if(Array.isArray(e)){if(Array.isArray(n.items))for(let p=0;p<e.length;p++){let f=n.items[p];if(f)sl(e[p],f)}else if(n.items)for(let p of e)sl(p,n.items);return}if(typeof e!=="object"||e===null||!n.properties)return;let i=e,c=new Set(n.required??[]);for(let[p,f]of Object.entries(n.properties)){if(!(p in i))continue;if(i[p]===null&&!c.has(p)&&typeof f.$ref!=="string"&&Ih(f)?.Check(null)===!1)delete i[p];else sl(i[p],f)}}function KC(e){let n=e,i=BC.get(n);if(i)return i;let c=xh(e);return BC.set(n,c),c}function Yj(e){if(e.keyword==="required"){let c=e.params.requiredProperties?.[0];if(c){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${c}`:c}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function Zj(e,n){let i=e.find((c)=>c.name===n.name);if(!i)throw Error(`Tool "${n.name}" not found`);return Xa(i,n)}function Xa(e,n){let i=structuredClone(n.arguments);sl(i,e.parameters),ns(e.parameters,i);let c=KC(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Wj)){let g=ca(i,e.parameters);if(g!==i)if(typeof i==="object"&&i!==null&&typeof g==="object"&&g!==null){for(let x of Object.keys(i))delete i[x];Object.assign(i,g)}else return c.Check(g)?g:i}if(c.Check(i))return i;let p=c.Errors(i).map((g)=>` - ${Yj(g)}: ${g.message}`).join(`
30
+ `)||"Unknown validation error",f=`Validation failed for tool "${n.name}":
31
+ ${p}
32
+
33
+ Received arguments:
34
+ ${JSON.stringify(n.arguments,null,2)}`;throw Error(f)}var HC;function $c(){if(!HC)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return HC}async function WC(e,n,i,c,p,f){let g=QC(n,e),x=[...g],I={...n,messages:[...n.messages,...g]};await c({type:"agent_start"}),await c({type:"turn_start"});for(let b of g)await c({type:"message_start",message:b}),await c({type:"message_end",message:b});return await VC(I,x,i,p,c,f??$c()),x}async function zC(e,n,i,c,p){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let f=[],g={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await VC(g,f,n,c,i,p??$c()),f}async function VC(e,n,i,c,p,f){let g=e,x=i,I,b=!1,E=await x.getSteeringMessages?.()||[];while(!0){let T=!0;while(T||E.length>0){let A=[];if(I){let X=await x.prepareNextTurn?.(I);if(X)g=X.context??g,A=X.messages??[],x={...x,model:X.model??x.model,reasoning:X.thinkingLevel===void 0?x.reasoning:X.thinkingLevel==="off"?void 0:X.thinkingLevel};if(E.length===0)E=await x.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let X of QC(g,[...A,...E]))await p({type:"message_start",message:X}),await p({type:"message_end",message:X}),g.messages.push(X),n.push(X);E=[];let L=await x.prepareRequest?.({context:g,model:x.model,thinkingLevel:x.reasoning??"off"},c);if(L)g=L.context??g,x={...x,model:L.model??x.model,reasoning:L.thinkingLevel===void 0?x.reasoning:L.thinkingLevel==="off"?void 0:L.thinkingLevel};let q=await tU(g,x,c,p,f);if(n.push(q),q.stopReason==="error"||q.stopReason==="aborted"){I={message:q,toolResults:[],context:g,newMessages:n},await x.finishTurn?.(I,c),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:n});return}let Z=q.content.filter((X)=>X.type==="toolCall"),B=[];if(T=!1,Z.length>0){let X=q.stopReason==="length"?await rU(Z,p):await nU(g,q,x,c,p);B.push(...X.messages),T=!X.terminate;for(let ie of B)g.messages.push(ie),n.push(ie)}I={message:q,toolResults:B,context:g,newMessages:n};let V=await x.finishTurn?.(I,c);if(await p({type:"turn_end",message:q,toolResults:B}),V?.action==="end"){await p({type:"agent_end",messages:n});return}if(b=V?.action==="continue",E=await x.getSteeringMessages?.()||[],T||E.length>0)b=!1}let k=await x.getFollowUpMessages?.()||[];if(k.length>0){b=!1,E=k;continue}if(b){b=!1;continue}break}await p({type:"agent_end",messages:n})}function QC(e,n){let i=-1;for(let E=n.length-1;E>=0;E--)if(n[E].role==="system"){i=E;break}let c=n[i],p=c?n.map((E,T)=>T===i?bh(c,eU):E):n,f=Fo(ne([...e.messages,...p]),(e.tools??[]).map(nt)),g=f.toolsAdded.length===0&&f.toolsRemoved.length===0;if(c){if(g&&!c.toolsAdded?.length&&!c.toolsRemoved?.length)return n;return p.map((E,T)=>T===i?bh(c,f):E)}if(g)return n;let x=bh({role:"system",content:"",timestamp:Date.now()},f),I=n.findIndex((E)=>E.role!=="system"),b=I===-1?n.length:I;return[...n.slice(0,b),x,...n.slice(b)]}var eU={toolsAdded:[],toolsRemoved:[]};function bh(e,{toolsAdded:n,toolsRemoved:i}){let{toolsAdded:c,toolsRemoved:p,...f}=e;return{...f,...n.length>0?{toolsAdded:n}:{},...i.length>0?{toolsRemoved:i}:{}}}async function tU(e,n,i,c,p){let f=e.messages;if(n.transformContext)f=await n.transformContext(f,i);let g=await n.convertToLlm(f),x=ht({messages:g}),I=(n.getApiKey?await n.getApiKey(n.model.provider):void 0)||n.apiKey,b=await p(n.model,x,{...n,apiKey:I,signal:i}),E=async()=>Object.assign(await b.result(),{thinkingLevel:n.reasoning??"off"}),T=null,k=!1;for await(let L of b)switch(L.type){case"start":T=L.partial,e.messages.push(T),k=!0,await c({type:"message_start",message:{...T}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(T)T=L.partial,e.messages[e.messages.length-1]=T,await c({type:"message_update",assistantMessageEvent:L,message:{...T}});break;case"done":case"error":{let q=await E();if(k)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!k)await c({type:"message_start",message:{...q}});return await c({type:"message_end",message:q}),q}}let A=await E();if(k)e.messages[e.messages.length-1]=A;else e.messages.push(A),await c({type:"message_start",message:{...A}});return await c({type:"message_end",message:A}),A}async function rU(e,n){let i=[];for(let c of e){await n({type:"tool_execution_start",toolCallId:c.id,toolName:c.name,args:c.arguments});let p={toolCall:c,result:Us(`Tool call "${c.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Mc(p,n);let f=Eh(p);await Sh(f,n),i.push(f)}return{messages:i,terminate:!1}}async function nU(e,n,i,c,p){let f=n.content.filter((x)=>x.type==="toolCall"),g=f.some((x)=>e.tools?.find((I)=>I.name===x.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||g)return oU(e,n,f,i,c,p);return sU(e,n,f,i,c,p)}async function oU(e,n,i,c,p,f){let g=[],x=[];for(let I of i){await f({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let b=await XC(e,n,I,c,p),E;if(b.kind==="immediate")E={toolCall:I,result:b.result,isError:b.isError};else{let k=await ZC(b,p,YC(I,f));E=await eP(e,n,b,k,c,p)}await Mc(E,f);let T=Eh(E);if(await Sh(T,f),g.push(E),x.push(T),p?.aborted)break}return{messages:x,terminate:JC(g)}}async function sU(e,n,i,c,p,f){let g=[];for(let b of i){await f({type:"tool_execution_start",toolCallId:b.id,toolName:b.name,args:b.arguments});let E=await XC(e,n,b,c,p);if(E.kind==="immediate"){let T={toolCall:b,result:E.result,isError:E.isError};if(await Mc(T,f),g.push(T),p?.aborted)break;continue}if(g.push(async()=>{if(p?.aborted){let A={toolCall:b,result:Us("Operation aborted"),isError:!0};return await Mc(A,f),A}let T=await ZC(E,p,YC(b,f)),k=await eP(e,n,E,T,c,p);return await Mc(k,f),k}),p?.aborted)break}let x=await Promise.all(g.map((b)=>typeof b==="function"?b():Promise.resolve(b))),I=[];for(let b of x){let E=Eh(b);await Sh(E,f),I.push(E)}return{messages:I,terminate:JC(x)}}function JC(e){return e.length>0&&e.every((n)=>n.result.terminate===!0)}function iU(e,n){if(!e.prepareArguments)return n;let i=e.prepareArguments(n.arguments);if(i===n.arguments)return n;return{...n,arguments:i}}async function XC(e,n,i,c,p,f=e.tools??[]){let g=f.find((x)=>x.name===i.name);if(!g)return{kind:"immediate",result:Us(`Tool ${i.name} not found`),isError:!0};try{let x=iU(g,i),I=Xa(g,x);if(c.beforeToolCall){let b=await c.beforeToolCall({assistantMessage:n,toolCall:i,args:I,context:e},p);if(p?.aborted)return{kind:"immediate",result:Us("Operation aborted"),isError:!0};if(b?.block){let E=Us(b.reason||"Tool execution was blocked");if(b.terminate===!0)E.terminate=!0;return{kind:"immediate",result:E,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Us("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:g,args:I}}catch(x){return{kind:"immediate",result:Us(x instanceof Error?x.message:String(x)),isError:!0}}}function YC(e,n){return(i)=>n({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function ZC(e,n,i){let c=[],p=!0,f=performance.now(),g=()=>Math.round(performance.now()-f);try{let x=await e.tool.execute(e.toolCall.id,e.args,n,(b)=>{if(!p)return;c.push(Promise.resolve(i(b)))}),I=g();return p=!1,await Promise.all(c),{result:x,isError:x.isError===!0,durationMs:I}}catch(x){let I=g();return p=!1,await Promise.all(c),{result:Us(x instanceof Error?x.message:String(x)),isError:!0,durationMs:I}}finally{p=!1}}async function eP(e,n,i,c,p,f){let{result:g,isError:x}=c;if(p.afterToolCall)try{let I=await p.afterToolCall({assistantMessage:n,toolCall:i.toolCall,args:i.args,result:g,isError:x,context:e},f);if(I){let b=I.structuredContent??(I.content?void 0:g.structuredContent);if(g={...g,content:I.content??g.content,details:I.details??g.details,usage:I.usage??g.usage,terminate:I.terminate??g.terminate},b===void 0)delete g.structuredContent;else g.structuredContent=b;x=I.isError??x}}catch(I){g=Us(I instanceof Error?I.message:String(I)),x=!0}return{toolCall:i.toolCall,result:g,isError:x,durationMs:c.durationMs}}function Us(e){return{content:[{type:"text",text:e}],details:{}}}async function Mc(e,n){await n({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function Eh(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 Sh(e,n){await n({type:"message_start",message:e}),await n({type:"message_end",message:e})}function aU(e){return e.filter((n)=>n.role==="system"||n.role==="user"||n.role==="assistant"||n.role==="toolResult")}var uU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},cU={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 mU(e){let n=e?.tools?.slice()??[],i=e?.messages?.slice()??[],c=Gn(e?.systemPrompt,n.map(nt));if(i[0]?.role!=="system"&&c)i.unshift(c);return{get systemPrompt(){return Uo(i)},model:e?.model??cU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return n},set tools(p){n=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class wh{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 Th{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let n=e??{};this._state=mU(n.initialState),this.convertToLlm=n.convertToLlm??aU,this.transformContext=n.transformContext,this.streamFunction=n.streamFn??$c(),this.getApiKey=n.getApiKey,this.onPayload=n.onPayload,this.onResponse=n.onResponse,this.onProviderStreamEvent=n.onProviderStreamEvent,this.beforeToolCall=n.beforeToolCall,this.afterToolCall=n.afterToolCall,this.finishTurn=n.finishTurn,this.prepareRequest=n.prepareRequest,this.prepareNextTurn=n.prepareNextTurn,this.prepareNextTurnWithContext=n.prepareNextTurnWithContext,this.steeringQueue=new wh(n.steeringMode??"one-at-a-time"),this.followUpQueue=new wh(n.followUpMode??"one-at-a-time"),this.sessionId=n.sessionId,this.thinkingBudgets=n.thinkingBudgets,this.transport=n.transport??"auto",this.maxRetryDelayMs=n.maxRetryDelayMs,this.toolExecution=n.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=jr(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,n){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let i=this.normalizePromptInput(e,n);await this.runPromptMessages(i)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((n)=>n.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let n=this.steeringQueue.drain();if(n.length>0){await this.runPromptMessages(n,{skipInitialSteeringPoll:!0});return}let i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,n){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(n&&n.length>0)i.push(...n);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,n={}){await this.runWithLifecycle(async(i)=>{await WC(e,this.createContextSnapshot(),this.createLoopConfig(n),(c)=>this.processEvents(c),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await zC(this.createContextSnapshot(),this.createLoopConfig(),(n)=>this.processEvents(n),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let n=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(n)return n=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let n=new AbortController,i=()=>{},c=new Promise((p)=>{i=p});this.activeRun={promise:c,resolve:i,abortController:n},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(n.signal)}catch(p){await this.handleRunFailure(p,n.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,n){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:uU,stopReason:n?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let n=this.activeRun?.abortController.signal;if(!n)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,n)}}function we(e,...n){return Object.assign(e,{aliases:n})}function ma(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function pU(e){let n=[],i="";for(let c of e){if(!/[a-zA-Z0-9]/.test(c)){if(i)n.push(i);i="";continue}if(c>="A"&&c<="Z"&&i&&!/[A-Z]$/.test(i))n.push(i),i="";i+=c}if(i)n.push(i);return n}function tP(e,n){if(e.some((L)=>L.name===n))return n;let i=e.map((L)=>L.name),c=(L)=>i.filter((q)=>ma(q)===L),p=c(ma(n));if(p.length===1&&p[0])return p[0];if(p.length>1)return n;let f=n.split(/[.:/]/).pop()??n,g=f===n?[]:c(ma(f));if(g.length===1&&g[0])return g[0];let x=new Map;for(let L of e)for(let q of L.aliases??[]){let Z=ma(q);x.set(Z,(x.get(Z)??new Set).add(L.name))}let I=(L)=>[...new Set([...c(L),...x.get(L)??[]])],b=I(ma(f));if(b.length===1&&b[0])return b[0];if(b.length>1)return n;let E=pU(f),T=new Set;E.forEach((L,q)=>{T.add(ma(L));let Z=E[q+1];if(Z)T.add(ma(L+Z))});let k=new Set;for(let L of T)for(let q of I(L))k.add(q);let A=[...k];return A.length===1&&A[0]?A[0]:n}function v(e){return e}function Dn(e,n){let i=n.indexOf("/");if(i<=0)return;return e.getModel(n.slice(0,i),n.slice(i+1))}function tt(e){return`${e.provider}/${e.id}`}function lU(e,n,i){let c=async(f,g)=>{try{if(n){let I=f instanceof Request?f:void 0;n({at:Date.now(),method:g?.method??I?.method??"GET",url:typeof f==="string"?f:f instanceof URL?f.toString():f.url,headers:rP(g?.headers??I?.headers),body:dU(g?.body!==void 0?g.body:I?.body??void 0)})}}catch{}let x=await e(f,g);if(i)try{let I=Date.now(),{status:b,statusText:E}=x,T=rP(x.headers);if(!x.body)return i({at:I,status:b,statusText:E,headers:T,body:""}),x;let k="",A=new TextDecoder,L=new TransformStream({transform(B,V){V.enqueue(B),k+=A.decode(B,{stream:!0}),i({at:I,status:b,statusText:E,headers:T,body:k})},flush(){k+=A.decode(),i({at:I,status:b,statusText:E,headers:T,body:k})}}),q=x.body.pipeThrough(L),Z=new Response(q,x);try{Object.defineProperty(Z,"url",{value:x.url})}catch{}return Z}catch{}return x},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(c,{preconnect:p})}function rP(e){if(!e||typeof e!=="object")return{};let n={};if(e instanceof Headers)return e.forEach((c,p)=>{n[p]=c}),n;let i=Array.isArray(e)?e:Object.entries(e);for(let c of i)if(Array.isArray(c)&&typeof c[0]==="string"&&typeof c[1]==="string")n[c[0]]=c[1];return n}function dU(e){if(e===void 0||e===null)return"";if(typeof e==="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e))return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));return`<${typeof e==="object"&&typeof e.constructor==="function"?e.constructor.name:typeof e}: \u975E\u6587\u672C\u8BF7\u6C42\u4F53\uFF0C\u672A\u8BB0\u5F55\u539F\u6587>`}function fU(e,n){return tP(e,n)}function hU(e,n,i){let c=Date.now(),p=new WeakSet,f=(I)=>{if(!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;let b=Date.now(),E=Math.max(10,b-c);I.generationMs=E},g=async(I)=>{if(!i||!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;if(f(I),p.has(I))return;p.add(I),Object.assign(I,await i(I))},x=(I)=>{let b=I?.content;if(!Array.isArray(b))return;for(let E of b)if(E&&E.type==="toolCall"&&typeof E.name==="string")E.name=fU(n(),E.name)};return{async*[Symbol.asyncIterator](){for await(let I of e){let{partial:b,message:E}=I;x(b),await g(E),x(E),yield I}},result:async()=>{let I=await e.result();return f(I),await g(I),x(I),I}}}function vc(e,n){let i=(n??[]).filter((g)=>g.kind==="path").map((g)=>`<file path=${JSON.stringify(g.data)} />`),c=(n??[]).filter((g)=>g.kind==="text").map((g)=>`<file name=${JSON.stringify(g.name)}>
35
+ ${g.data}
36
+ </file>`),p=(n??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType}));return{merged:[...i,...c,...e.trim()?[e]:[]].join(`
37
+
38
+ `),images:p}}function Rh(e,n){let{merged:i,images:c}=vc(e,n);return{role:"user",content:c.length>0?[{type:"text",text:i},...c]:i,timestamp:Date.now()}}function nP(e){let n=new Set;for(let x of e.tools){let I=x.name.toLowerCase();if(n.has(I))throw Error(`Tool names collide ignoring case: ${x.name}`);n.add(I)}let i=new Th({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(x,I,b)=>{let{captureRequest:E,captureResponse:T}=e,k=E||T?{...b,fetch:lU(b?.fetch??globalThis.fetch,E?(L)=>E({...L,model:tt(x)}):void 0,T?(L)=>T({...L,model:tt(x)}):void 0)}:b,A=x.api==="openai-completions"||x.api==="openai-responses"?{...x,compat:{...x.compat,supportsDeveloperRole:!1}}:x;return hU(e.models.streamSimple(A,I,k),()=>i.state.tools,e.hooks.response)},convertToLlm:(x)=>x,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:x,model:I})=>{let b=x.messages.findIndex((A)=>A.role!=="system"),E=x.messages.slice(0,b===-1?x.messages.length:b),T=e.hooks.prepare,k=e.hooks.tools?.()??x.tools;if(k){i.state.tools=k;let A=E[0];if(A?.role==="system")E[0]={...A,toolsAdded:k.map(nt),toolsRemoved:void 0}}return{context:{...x,tools:k,messages:await T(E,k,I)}}}:void 0}),c=new Map,p=new Map,f=new WeakSet,g;return i.subscribe((x)=>{if(x.type==="message_update"&&x.message.role==="assistant"){p.clear(),e.hooks.draft(sP(x.message));return}if(x.type==="tool_execution_update"){let b=c.get(x.toolCallId)??_e(x.toolName,x.args),E=Array.isArray(x.partialResult?.content)?x.partialResult.content.map((T)=>T.type==="text"&&typeof T.text==="string"?T.text:"").join(""):"";p.set(x.toolCallId,{type:"tool_call",id:x.toolCallId,name:b.name,input:b.input,...b.source?{source:b.source}:{},output:E}),e.hooks.draft([...p.values()]);return}if(x.type==="tool_execution_end"){if(p.delete(x.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(x.type!=="message_end")return;if(f.has(x.message)){e.steerConsumed?.(x.message);return}let I=x.message.role==="user"&&g?{type:"user",text:g.text,...g.attachments?.length?{attachments:g.attachments}:{}}:gU(x.message);if(x.message.role==="user")g=void 0;if(I?.type==="assistant"){for(let b of I.parts)if(b.type==="tool_call")c.set(b.id,b)}if(I?.type==="tool_result"){let b=c.get(I.callID);if(b?.source)Object.assign(I,{name:b.name,source:b.source})}if(I)e.hooks.message(I,x.message);if(x.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(x,I)=>{g={text:x,attachments:I};let{merged:b,images:E}=vc(x,I);return i.prompt(b,E.length>0?E:void 0)},retry:async()=>{let x=i.state.messages;if(x.at(-1)?.role==="assistant")i.state.messages=x.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(x)=>{f.add(x),i.steer(x)},unsteer:(x)=>{let b=i.steeringQueue?.messages;if(!b)return!1;let E=b.indexOf(x);if(E<0){let k=JSON.stringify(x);E=b.findIndex((A)=>JSON.stringify(A)===k)}if(E<0)return!1;let[T]=b.splice(E,1);if(T)f.delete(T);return!0},abort:()=>i.abort()}}function kh(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 oP(e){let{name:i,source:c}=_e(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:i,...c?{source:c}:{},output:"\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002",isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:"\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"}],isError:!0,timestamp:Date.now()}}}function sP(e){return e.content.map((n)=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="thinking")return{type:"thinking",text:n.thinking};return{type:"tool_call",id:n.id,..._e(n.name,n.arguments)}})}function gU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((n)=>n.type==="text"?n.text:"").join("")};case"assistant":return{type:"assistant",parts:sP(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let n=e.content.filter((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...n.length>0?{images:n}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class pt extends Error{errors;constructor(e){super(e.map((n)=>n.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function R(e){return e}import{createHash as iP}from"crypto";import{existsSync as yU}from"fs";import{readFile as aP,realpath as il}from"fs/promises";import{dirname as xU,isAbsolute as uP,relative as cP,resolve as mP,sep as pP}from"path";var lP=[...Ag];class al extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((n)=>n.message).join("; ")}`);this.errors=e}}class ul{cache=new Map;pending=new Map;async entry(e,n){if(!e){if(n)throw Error("Plugin web entry requires a plugin source path");return}let i=xU(mP(e)),c=mP(i,n??"web.tsx");if(!n&&!yU(c))return;let p=cP(await il(i),await il(c));if(uP(p)||p===".."||p.startsWith(`..${pP}`))throw Error("Plugin web entry must stay inside its plugin directory");return c}async build(e,n){let i=this.pending.get(e);if(i)return i;let c=this.compile(e,n);this.pending.set(e,c);try{return await c}finally{this.pending.delete(e)}}async compile(e,n){let i=this.cache.get(e);if(i){let b=!0;for(let[E,T]of i.inputs){let k=await aP(E).catch(()=>{return});if(!k||iP("sha256").update(k).digest("hex")!==T){b=!1;break}}if(b)return i.source;this.cache.delete(e)}let c=await il(n),p=new Map,f=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:lP,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(b){b.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(E)=>{if(!lP.includes(E.path))throw Error(`Unsupported shared web import: ${E.path}`);return{path:E.path,external:!0}}),b.onLoad({filter:/.*/},async(E)=>{let T=cP(c,await il(E.path));if(uP(T)||T===".."||T.startsWith(`..${pP}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await aP(E.path);p.set(E.path,iP("sha256").update(k).digest("hex"));return})}}]}).catch((b)=>{let T=(b instanceof AggregateError?b.errors:[b]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${T.join("; ")}`,{cause:b})});if(!f.success)throw new al(f.logs.filter((b)=>b.level==="error").map((b)=>({file:b.position?.file??null,line:b.position?.line??null,message:b.message})));let g=f.outputs.find((b)=>b.kind==="entry-point"&&b.path.endsWith(".js")),x=f.outputs.find((b)=>b.path.endsWith(".css"));if(!g||f.outputs.some((b)=>b!==g&&b!==x))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let I=await g.text();return this.cache.set(e,{source:I,css:await x?.text(),inputs:p}),I}}function vo(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Rs(e){let n=e;if(typeof n.content==="string")return n.content;return n.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function cl(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
39
+
40
+ `)}function Ya(e){return e.content.map((n)=>n.type==="text"?n.text:"[image]").join("")}function Za(e){return e.role==="assistant"&&e.content.length>0}function ss(e){let n=[],i=new Map,c=0;for(let p of e){let f=p.raw;if(f.role==="assistant"){if(Za(f))c++;for(let g of f.content){if(g.type!=="toolCall")continue;let x={call:g,step:c,message:f};n.push(x),i.set(g.id,x)}}else if(f.role==="toolResult"){let g=i.get(f.toolCallId);if(g)g.result=f}}return n}var ml=new Set(["edit","write"]),dP=new Set(["grep","glob"]);function to(e,n){let i=_e(e.name,e.arguments).input?.[n];return typeof i==="string"?i:void 0}function fP(e){return[...new Set(ss(e).flatMap((n)=>ml.has(_e(n.call.name,n.call.arguments).name)&&n.result&&!n.result.isError&&to(n.call,"path")?[to(n.call,"path")]:[]))]}function Ah(e){return!e.result?"pending":e.result.isError?"error":"completed"}function pl(e){let n=[{source:"ASSISTANT_TOOL",text:`${_e(e.call.name,e.call.arguments).name}(${vo(_e(e.call.name,e.call.arguments).input)}) [${Ah(e)}, call=${e.call.id}]`}];if(e.result)n.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:Ya(e.result)});return n}function O(e){let n=0,i=0,c=0;for(let p of e){let f=p.codePointAt(0);if(f<=127)n++;else if(f>=19968&&f<=40959||f>=12288&&f<=12351||f>=65280&&f<=65519||f>=131072&&f<=173791)i++;else c++}return Math.max(0,Math.ceil(n/4+i+c/2))}var Ch=8192;function U(e){let n=e,i=0,c="";if(n.role==="system")c=typeof n.content==="string"?n.content:JSON.stringify(n.content);else if(n.role==="user")if(typeof n.content==="string")c=n.content;else for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else if(n.role==="assistant")for(let p of n.content)if(p.type==="text")c+=p.text;else if(p.type==="thinking")c+=p.thinking;else c+=`${p.name}${vo(p.arguments)}`;else if(n.role==="toolResult")for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else c=vo(e);return O(c)+16+i*Ch}function Pi(e=[]){return e.reduce((n,i)=>n+O(i.name+i.description+vo(i.parameters))+16,0)}function Pn(e,n){let i=e.replace(/\s+/g," ").trim();if(O(i)<=n)return i;let c=Math.min(i.length,n*4);while(c>0&&O(i.slice(0,c))>n-1)c=Math.floor(c*0.8);return`${i.slice(0,c).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function yo(e,n,i=Number.POSITIVE_INFINITY){if(O(e)<=n&&e.length<=i)return e;let c=`
41
+ [... omitted; use history tools for the full text ...]
42
+ `,p=Math.floor((n-O(c))/2);if(p<=0)return"";let f=(g)=>{let x=0,I=Math.max(0,Math.min(e.length,p*4,Math.floor((i-c.length)/2)));while(x<I){let b=Math.ceil((x+I)/2),E=g?e.slice(-b):e.slice(0,b);if(O(E)<=p)x=b;else I=b-1}if(!x)return"";return g?e.slice(-x).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,x).replace(/[\uD800-\uDBFF]$/,"")};return`${f(!1)}${c}${f(!0)}`}function ll(e,n){if(O(e.join(`
43
+ `))<=n)return e;let i=(E)=>`- [... ${E} steps omitted; use history tools for the full text ...]`,c=n-O(i(e.length)),p=[],f=[],g=0,x=0,I=e.length-1;while(x<=I){let E=p.length<=f.length,T=E?e[x]:e[I],k=O(`${T}
44
+ `);if(g+k>c)break;if(g+=k,E)p.push(e[x++]);else f.unshift(e[I--])}let b=I-x+1;return[...p,...b>0?[i(b)]:[],...f]}function ks(e){let n=[],i;for(let c of e){let p=c.entry;if(p.type==="run"&&p.state==="start"){i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},n.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=IU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!c.raw)continue;if(!i&&p.type==="user"&&p.notices&&n.length){n.at(-1)?.records.push(c);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},n.push(i);i.records.push(c)}for(let c of n)c.records=Ph(c.records);return n}function Ph(e){if(e.length<=1)return[...e];let n=[],i=[],c=new Set;for(let p=0;p<e.length;p++){let f=e[p];if(!f)continue;let g=f.raw?.role;if(g==="assistant"){let I=f.raw.content?.filter((b)=>b.type==="toolCall")??[];if(I.length>0)for(let b of I)c.add(b.id);if(n.push(f),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(g==="toolResult"){let x=f.raw;if(x.toolCallId)c.delete(x.toolCallId);if(n.push(f),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(g==="user"){if(n.length===0){n.push(f);continue}let x=e.slice(p+1).some((I)=>I.raw?.role==="assistant");if(c.size>0||x){i.push(f);continue}n.push(f);continue}n.push(f)}if(i.length>0)n.push(...i);return n}function IU(e,n){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=n.findLast((c)=>c.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&oi(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return oi(i)?"interrupted":"failed";default:return"interrupted"}}function pa(e){for(let n=e.length-1;n>=0;n--){let i=e[n]?.entry;if(i?.type==="compaction")return i.through}return 0}function dl(e,n){return e.end!==void 0&&e.end<=n&&e.records.every((i)=>i.entry.seq<=n)}function $h(e,n){return e.find((i)=>i.start<n&&!dl(i,n)&&i.records.some((c)=>c.entry.seq<=n))}function eu(e){let n=pa(e),c=ks(e).findLast((p)=>p.end!==void 0);if(!c?.end||c.end<=n)return;return c.end}function fl(e){let n=pa(e);return $h(ks(e),n)?.end}function Oc(e,n){let i=pa(e),c=ks(e).at(-1);if(!c||c.end!==void 0)return;let p=c.records.filter((E)=>E.entry.seq>i),f=[],g=new Set;for(let E of p){let T=E.raw,k=U(E.raw);if(T.role==="assistant"){for(let A of T.content)if(A.type==="toolCall")g.add(A.id)}else if(T.role==="toolResult")g.delete(T.toolCallId);if(Za(T)||!f.length||T.role==="user"&&f.at(-1)?.assistant)f.push({end:E.entry.seq,tokens:k,assistant:Za(T),pending:g.size});else{let A=f.at(-1);A.end=E.entry.seq,A.tokens+=k,A.pending=g.size}}let x=f.findLastIndex((E)=>E.assistant),I=0,b;for(let E=f.length-1;E>=0;E--){let T=f[E];if(E<x&&T.assistant&&T.pending===0&&(I<=n||b===void 0))b=T.end;if(I+=T.tokens,I>n&&b!==void 0)break}if(I<=n)return;return b}var hP=2000;function $i(e,n){let i=O(n);if(i<=hP)return n;let c=new TextEncoder().encode(n).length,p=n.split(`
45
+ `).length,f=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${c} bytes, ${p} lines, approximately ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
46
+ `),g="</user-text-reference>",x=hP-O(`${f}
47
+
48
+ ${g}`);if(x<=0)return n;let I=`${f}
49
+ ${yo(n,x,n.length-f.length-g.length-3)}
50
+ ${g}`;return I.length<n.length&&O(I)<i?I:n}function gP(e){let n=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return n;if(typeof n.content==="string"){let p=$i(e.entry.seq,n.content);return p===n.content?n:{...n,content:p}}let i=!1,c=n.content.map((p)=>{if(p.type!=="text")return p;let f=$i(e.entry.seq,p.text);if(f!==p.text)i=!0;return f===p.text?p:{...p,text:f}});return i?{...n,content:c}:n}function Mh(e,n=!1){let i=e.records.filter((A)=>A.entry.type==="user"&&!A.entry.notices&&A.raw.role==="user"),c=i.flatMap((A)=>{let L=A.raw.content;return typeof L==="string"?[]:L.filter((q)=>q.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,f=e.status==="open"?"interrupted":e.status,g="";if(i.length){let A=n?yo(i.map((L)=>Rs(L.raw)).join(`
51
+
52
+ `),600):i.map((L,q)=>`<user-message sequence="${q+1}">
53
+ ${$i(L.entry.seq,Rs(L.raw))}
54
+ </user-message>`).join(`
55
+
56
+ `);g=[`<chunk-input id="${e.id}" status="${f}"${n?' excerpt="true"':""}>`,A,...n?[p]:[],"</chunk-input>"].join(`
57
+ `)}let I=e.records.filter((A)=>A.raw.role==="assistant").at(-1)?.raw,b=I?cl(I):"",E=[];if(f!=="completed"){let A=ss(e.records),L=new Map(A.map((X)=>[X.call,X])),q=A.slice(-3),Z=new Set(q.map((X)=>X.message)),B=[],V=[];for(let X of e.records){let ie=X.raw;if(ie.role!=="assistant")continue;let Y=Z.has(ie);for(let z of ie.content)if(z.type==="text"&&ie!==I&&z.text.trim())if(Y)V.push(`ASSISTANT: ${Pn(z.text,50)}`);else B.push(`- ASSISTANT: ${Pn(z.text,50)}`);else if(z.type==="toolCall"){let ce=L.get(z);if(!ce)continue;if(Y){if(q.includes(ce))for(let he of pl(ce))V.push(`${he.source}: ${yo(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else B.push(`- ${z.name}(${Pn(vo(z.arguments),40)}) [${Ah(ce)}]`)}}E.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...B.length?[`Earlier steps, oldest first:
58
+ ${ll(B,n?300:800).join(`
59
+ `)}`]:[],...V)}let T=fP(e.records),k=[`<chunk-summary id="${e.id}" status="${f}" folded-messages="${e.records.length}"${n?' excerpt="true"':""}>`,b?n?yo(b,600):b:"No final assistant response was recorded.",...E,...T.length?[`Recorded file changes:
60
+ ${yo(T.join(`
61
+ `),250)}`]:[],...n&&f==="completed"?[p]:[],"</chunk-summary>"].join(`
62
+ `);return{input:g,images:c,summary:k,tokens:bU(g,k,c.length)}}function bU(e,n,i){return(e?O(e)+16:0)+O(n)+16+i*Ch}var EU=["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."],SU="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.",wU=1500,TU=80,RU=240;function yP(e,n,i){let c=[],p=0,f=Math.min(n.target,n.hard);for(let x=e.length-1;x>=0;x--){let I=e[x],b=Mh(I),E=p+b.tokens>f?Mh(I,!0):void 0,T=E&&E.tokens<b.tokens?E:b;if(!(!i&&x===e.length-1&&I.status!=="completed")&&p+T.tokens>n.hard)break;p+=T.tokens,c.push({run:I,content:T})}c.reverse();let g=e.slice(0,e.length-c.length);return{visible:c,archived:g,tokens:p}}function xP(e){let{runs:n,visible:i,archived:c,partial:p}=e,f=c.flatMap((I)=>{let b=I.records.filter((T)=>T.raw.role==="user"&&!(T.entry.type==="user"&&T.entry.notices)).map((T)=>Rs(T.raw));if(!b.length)return[];let E=I===n[0]?RU:TU;return[`- ${I.id} [${I.status}]: ${Pn(b.join(" / "),E)}`]}),g=new Map(n.map((I,b)=>[I,b+1])),x=[...i.map((I)=>g.get(I)??0),...p?[n.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...EU,...p?[SU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${c.length}`,`archived chunk IDs: ${c.length?c.map((I)=>I.id).join(", "):"none"}`,`visible sequences: ${x.length?`${x[0]}..${x.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...f.length?["archived requests, oldest first:",yo(f.join(`
63
+ `),wU)]:[],"</conversation-checkpoint>"].join(`
64
+ `)}function IP(e,n){let i=e.split(`
65
+ `),c=n.split(`
66
+ `),p=new Set(i),f=new Set(c),g=[...i.filter((I)=>I.trim()&&!f.has(I)).map((I)=>`- ${Pn(I,40)}`),...c.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`+ ${Pn(I,40)}`)],x=i.find((I)=>I.trim()&&f.has(I));return[...g.slice(0,6),...g.length>6?[`\u2026 ${g.length-6} more changed lines`]:[],...x&&g.every((I)=>I.startsWith("+"))?[`@ ${Pn(x,40)}`]:[]]}function hl(e,n){if(!n)return e;let i=n.endsWith("/")?n:`${n}/`;return e.startsWith(i)?e.slice(i.length):e}function kU(e){let n=e.arguments?.paths;if(!Array.isArray(n))return[];return n.flatMap((i)=>{let c=i&&typeof i==="object"?i.path:void 0;return typeof c==="string"?[c]:[]})}function AU(e,n){let i=to(e,"path");if(ml.has(e.name)&&i)return`file:${hl(i,n)}`;let c=to(e,"command");if(c)return`command:${c}`;return`${e.name}:${vo(e.arguments)}`}function CU(e,n){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},c=new Map;for(let f of ss(e)){let g=c.get(f.step)??[];g.push(f),c.set(f.step,g)}let p=new Map;for(let f of e){let g=f.raw;if(!Za(g))continue;let x=++i.steps,I=cl(g);if(I)i.narration.push({step:x,text:Pn(I,60)});for(let{call:b,result:E}of c.get(x)??[]){if(!E)continue;let T=_e(b.name,b.arguments),k={...b,name:T.name,arguments:T.input},A=AU(k,n),L=Ya(E);if(E.isError){let ie=to(k,"command"),Y=ie?`${k.name} \`${Pn(ie,40)}\``:`${k.name} ${A.startsWith("file:")?A.slice(5):Pn(vo(k.arguments),40)}`,z={step:x,key:A,what:Y,detail:yo(L.trim().split(`
67
+ `).slice(0,8).join(`
68
+ `),200)};i.errors.push(z);let ce=p.get(A)??[];ce.push(z),p.set(A,ce);continue}for(let ie of p.get(A)??[])ie.resolved=x;p.delete(A);let q=to(k,"path");if(ml.has(k.name)&&q){let ie=hl(q,n),Y=i.files.get(ie)??{count:0,first:x,last:x,diffs:[]};if(Y.count++,Y.last=x,Y.diffs.push({step:x,lines:k.name==="edit"?to(k,"old_string")!==void 0?IP(to(k,"old_string")??"",to(k,"new_string")??""):[]:IP("",to(k,"content")??"")}),Y.diffs.length>3)Y.diffs.shift();i.files.set(ie,Y);continue}let Z=k.name==="read"?[...q?[q]:[],...kU(k)]:[];if(Z.length){for(let ie of Z){let Y=hl(ie,n),z=i.reads.get(Y)??[];z.push(x),i.reads.set(Y,z)}continue}if(dP.has(k.name)){let ie=q?` in ${hl(q,n)}`:"",Y=k.name==="grep"&&to(k,"glob")?` (${to(k,"glob")})`:"",z=`${k.name} ${to(k,"pattern")??""}${ie}${Y}`.replace(/\s+/g," "),ce=i.searches.get(z)??{steps:[],head:""};ce.steps.push(x),ce.head=Pn(L.trim().split(`
69
+ `)[0]??"",25),i.searches.set(z,ce);continue}let B=to(k,"command");if(B){let ie=L.trim().split(`
70
+ `);i.commands.push({step:x,command:Pn(B,40),exit:"0",lines:ie.length,tail:ie.slice(-3).map((Y)=>Pn(Y,40))});continue}let V=`${k.name} ${Pn(vo(k.arguments),40)}`,X=i.other.get(V)??[];X.push(x),i.other.set(V,X)}}return i}function bP(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function _c(e,n,i){let c=(b,E)=>E===void 0||!b.length?b:ll(b,E),p=[`<work-state chunk="${n.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${n.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],f=[...e.files];p.push("",`## Modified files (${f.length})`),f.forEach(([b,E],T)=>{if(p.push(`- ${b}: ${E.count} change${E.count>1?"s":""} (step ${E.first}${E.last!==E.first?`-${E.last}`:""})`),T<f.length-i.diffFiles)return;for(let k of E.diffs)p.push(` step ${k.step}:`,...k.lines.map((A)=>` ${A}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((b)=>b.resolved?`- step ${b.step} ${b.what} (resolved at step ${b.resolved})${i.lists===void 0?`: ${b.detail.replace(/\n/g,`
71
+ `)}`:""}`:`- step ${b.step} ${b.what} (UNRESOLVED): ${b.detail.replace(/\n/g,`
72
+ `)}`)),p.push("","## Steps",...c(e.narration.map((b)=>`- ${b.step}. ${b.text}`),i.narration));let g=[...e.reads].map(([b,E])=>`- ${b} @ ${E.join(",")}`);p.push("",`## Files read (${g.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...c(g,i.lists));let x=[...e.searches].map(([b,E])=>`- ${b} \u2192 ${E.head||"(no output)"} (${bP(E.steps)})`);p.push("",`## Searches (${x.length})`,...c(x,i.lists));let I=e.commands.map((b)=>[`- ${b.step}. \`${b.command}\` exit=${b.exit}, ${b.lines} output lines, last ${b.tail.length}:`,...b.tail.map((E)=>` ${E}`)].join(`
73
+ `));if(p.push("",`## Commands (${I.length})`,...c(I,i.lists)),e.other.size){let b=[...e.other].map(([E,T])=>`- ${E} (${bP(T)})`);p.push("",`## Other tool calls (${b.length})`,...c(b,i.lists))}return p.push("</work-state>"),p.join(`
74
+ `)}function gl(e,n,i,c){let p=CU(e,c),f=_c(p,n,{diffFiles:Number.POSITIVE_INFINITY});if(O(f)<=i)return f;let g={...p,narration:[]};for(let b of[Number.POSITIVE_INFINITY,20,10,5]){let E=O(_c(g,n,{diffFiles:b}));if(E>i*0.7)continue;return _c(p,n,{narration:Math.max(500,i-E),diffFiles:b})}let x=Math.max(300,Math.floor(i*0.1)),I=O(_c(g,n,{diffFiles:0,lists:x}));return _c(p,n,{narration:Math.max(500,i-I),diffFiles:0,lists:x})}function yl(e){return{role:"user",content:e,timestamp:0}}function vh(e,n){return{role:"assistant",content:[{type:"text",text:e}],api:n.api,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function EP(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:yl(e.input)}function tu(e){let n=[];for(let i of e){let c=n.at(-1),p=i;if(c?.role==="user"&&p.role==="user"){let f=(g)=>typeof g.content==="string"?[{type:"text",text:g.content}]:g.content;n[n.length-1]={...p,content:[...f(c),{type:"text",text:`
75
+
76
+ `},...f(p)]};continue}n.push(i)}return n}function PU(e,n){if(typeof n!=="string")return n;if(e==="data"&&n.length>160)return`${n.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(n.length-96).toLocaleString()} \u5B57\u7B26]`;if(n.length>2400)return`${n.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(n.length-1600).toLocaleString()} \u5B57\u7B26]`;return n}function ke(e,n,i,c={}){let p=pa(e),f=ks(e),g=f.filter((de)=>dl(de,p)),x=$h(f,p),I=[],b=c.inspect?e.flatMap(({entry:de})=>{if(de.type!=="extension")return[];return[{id:`extension-${de.seq}`,label:de.display?.title??`${de.namespace}/${de.kind}`,detail:de.display?.text??`Extension ${de.namespace}/${de.kind} (schema ${de.schemaVersion})`,tokens:0}]}):[],E=0;for(let de of f){if(dl(de,p))continue;let se=[];for(let me of de.records){if(de===x&&me.entry.seq<=p)continue;let qe=me.raw.role==="user"?gP(me):me.raw;E+=U(qe),I.push(qe),se.push(qe)}if(c.inspect&&se.length)b.push({id:`recent-${de.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${de.id}`,tokens:se.reduce((me,qe)=>me+U(qe),0),detail:JSON.stringify(se,PU,2)})}if(!g.length&&!x)return{items:b,messages:tu(I),visible:0,archived:0,open:E,tokens:E,untrimmed:E};let T=yP(g,i,!!x),{visible:k,archived:A}=T,L=T.tokens,q=[],Z="",B="";if(x){let de=x.records.filter((me)=>me.entry.seq<=p),se=de.filter((me)=>me.entry.type==="user"&&!me.entry.notices&&me.raw.role==="user");if(se.length){Z=[`<chunk-input id="${x.id}" status="partial">`,...se.map((qe,xt)=>`<user-message sequence="${xt+1}">
77
+ ${$i(qe.entry.seq,Rs(qe.raw))}
78
+ </user-message>`),"</chunk-input>"].join(`
79
+ `);let me=se.flatMap((qe)=>{let xt=qe.raw.content;return typeof xt==="string"?[]:xt.filter((Qe)=>Qe.type==="image")});q.push(me.length?{role:"user",content:[{type:"text",text:Z},...me],timestamp:0}:yl(Z))}B=gl(de,x,i.index,c.cwd),q.push(vh(B,n))}let V=e.flatMap((de)=>{let se=de.raw;if(de.entry.seq>p||se?.role!=="toolResult"||se.toolName!=="skill")return[];return[yl(se.content.filter((me)=>me.type==="text").map((me)=>me.text).join(`
80
+ `))]}),X="",ie=()=>{X=xP({runs:g,visible:k.map((se)=>se.run),archived:A,partial:!!x,tokens:L,budget:i});let de=[yl(X)];for(let{content:se}of k){if(se.input)de.push(EP(se));de.push(vh(se.summary,n))}return[...de,...V,...q]},Y=(de)=>de.reduce((se,me)=>se+U(me),0),z=ie(),ce=Y(z)+E,he=ce,{trim:ve}=c;while(ve&&ve.fixed+ce>ve.limit){let de=x||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!de.length)break;let se=0,me=0;for(let qe of de)if(me++,se+=qe.content.tokens,se>=ve.fixed+ce-ve.limit)break;A=[...A,...k.slice(0,me).map((qe)=>qe.run)],k=k.slice(me),L-=se,z=ie(),ce=Y(z)+E}return{items:c.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:U(z[0]),detail:X},...k.map(({run:de,content:se})=>({id:de.id,label:`Chunk ${de.id}`,state:"sealed",tokens:(se.input?U(EP(se)):0)+U(vh(se.summary,n)),detail:[se.input,se.summary].filter(Boolean).join(`
81
+
82
+ `)})),...A.map((de)=>({id:de.id,label:`Chunk ${de.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...x?[{id:x.id,label:`Chunk ${x.id}`,state:"folded",tokens:Y(q),detail:[Z,B].filter(Boolean).join(`
83
+
84
+ `)}]:[],...b]:[],messages:tu([...z,...I]),visible:k.length,archived:A.length,open:E,tokens:ce,untrimmed:he}}function ru(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Oh=0.97,$U=0.97,SP=0.5,MU=0.05,vU=20000,OU=24000;function Lc(e){return{target:vU,hard:OU,index:Math.floor(ru(e)*MU)}}function _h(e){let n=e.usage;return n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite}class Nc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,n,i=()=>{return}){this.records=e;this.fold=n;this.cwd=i}budget(e){return Lc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let n=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(n>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,n/this.lastEstimate))}previewLimit(e){return Math.floor(ru(e)*Oh/this.ratio)}prepare(e,n,i,c){let p=ru(i),f=Lc(i),g=e.reduce((z,ce)=>z+U(ce),0)+Pi(n),x=this.records().at(-1)?.entry.seq??0,I=()=>c?[...c,...this.records().filter((z)=>z.entry.seq>x)]:this.records(),b=()=>ke(I(),i,f,{cwd:this.cwd(),trim:{fixed:g,limit:Math.floor(p*Oh/this.ratio)}}),E=I().findLast((z)=>z.raw?.role==="assistant"),T=E?I().filter((z)=>z.entry.seq>E.entry.seq&&z.raw):[],k=E?.raw,A=()=>E!==void 0&&(E.entry.seq===this.reshapedAfter||I().some((z)=>z.entry.type==="compaction"&&z.entry.seq>E.entry.seq)),L=this.dueSeal(i);if(L!==void 0)this.fold(L,!1),this.reshapedAfter=E?.entry.seq??-1;let q=b(),Z=T.reduce((z,ce)=>z+U(ce.raw),0);if(this.lastEstimate===0&&E&&k&&!A()){let z=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,ce=g+q.untrimmed-U(k)-Z;if(z>0&&ce>0)this.ratio=Math.min(2,Math.max(0.5,z/ce))}let V=((z)=>{let ce=g+z.untrimmed,he=g+z.tokens;return((E&&k&&!A()&&_h(k)>0?_h(k)+Math.round(this.ratio*Z):void 0)??Math.round(ce*this.ratio))-Math.round((ce-he)*this.ratio)})(q);if(V>p*$U){let z=V-q.open*this.ratio,ce=Math.max(1000,Math.floor((p*SP-z-f.index)/this.ratio)),he=E?.entry.seq??-1,ve=I().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,de=Math.max(this.lastFoldSeq,ve),me=(de>0?I().filter((qe)=>qe.entry.seq>de&&qe.raw?.role==="assistant").length:999)<=1;if(!me||this.consecutivePartialFolds<2){let qe=Oc(I(),ce);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=me?this.consecutivePartialFolds+1:1,q=b()}}else this.consecutivePartialFolds=0;this.lastEstimate=g+q.tokens;let X=q.messages,ie=g+q.tokens;if(Math.round(ie*this.ratio)>p)X=_U(X,Math.floor((p-g)/this.ratio)),ie=g+X.reduce((z,ce)=>z+U(ce),0);return this.lastEstimate=ie,{messages:tu([...e,...X]),estimate:ie}}settle(e){let n=this.dueSeal(e);if(n===void 0)return;this.fold(n,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let n=this.records();if(fl(n)===void 0){let i=n.findLast((x)=>x.raw?.role==="assistant"),c=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||n.some((x)=>x.entry.type==="compaction"&&x.entry.seq>i.entry.seq)),g=(i?n.filter((x)=>x.entry.seq>i.entry.seq&&x.raw):[]).reduce((x,I)=>x+U(I.raw),0);if(p||!c||_h(c)+g<Math.floor(ru(e)*Oh))return}return eu(n)}recover(e){let n=ru(e),i=Lc(e),c=ke(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((n*SP-(n-c.open*this.ratio)-i.index)/this.ratio),f=Oc(this.records(),p);if(f===void 0)return!1;return this.fold(f,!0),this.reshapedAfter=this.records().findLast((g)=>g.raw?.role==="assistant")?.entry.seq??-1,!0}}function _U(e,n){let i=e.reduce((p,f)=>p+U(f),0);if(i<=n)return e;let c=[];for(let p of e){let f=p;if(f.role!=="toolResult"||i<=n){c.push(p);continue}let g=U(p);if(g<=1500){c.push(p);continue}let x=Math.max(500,Math.floor(g/2)),I=f.content.map((T)=>{if(T.type!=="text")return T;return{...T,text:yo(T.text,x)}}),b={...f,content:I},E=U(b);i-=g-E,c.push(b)}return c}var LU=2000;function nu(e,n){let i=[];for(let c of n.replace(/\r\n/g,`
85
+ `).split(`
86
+ `))for(let p=0;p<Math.max(c.length,1);){let f=Math.min(c.length,p+LU);if(f<c.length&&/[\uD800-\uDBFF]/.test(c.charAt(f-1)))f--;i.push({source:e,text:c.slice(p,f)}),p=f>p?f:p+1}return i}function ou(e){let n=[],i=ss(e.records),c=new Map(i.map((f)=>[f.call,f])),p=new Set(i.flatMap((f)=>f.result?[f.result]:[]));for(let f of e.records){let g=f.raw;if(g.role==="user")n.push(...nu(f.entry.type==="user"&&f.entry.notices?"NOTICE":"USER",Rs(g)));else if(g.role==="assistant"){for(let x of g.content)if(x.type==="text"&&x.text.trim())n.push(...nu("ASSISTANT",x.text));else if(x.type==="toolCall"){let I=c.get(x);if(I)for(let b of pl(I))n.push(...nu(b.source,b.text))}}else if(g.role==="toolResult"&&!p.has(g))n.push(...nu(g.isError?"TOOL_ERROR":"TOOL_OUTPUT",Ya(g)))}return n.map((f,g)=>({chunk:e.id,line:g,...f}))}function Dc(e,n){let i=e.find((c)=>c.entry.seq===n);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return nu("USER",Rs(i.raw)).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function qc(e,n){let i=e.find((c)=>c.entry.seq===n)?.entry;if(i?.type!=="extension"||!i.display)return;return nu("EXTENSION",i.display.text).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Fc(e,n=""){return e.map((i,c)=>{let p=e[c-1],f=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${n}${f?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
87
+ `)}import{join as Ig}from"path";import{existsSync as UP}from"fs";import{realpath as BP}from"fs/promises";import{dirname as GP,isAbsolute as YU,join as KP,relative as ZU,resolve as Uh,sep as eB}from"path";import{existsSync as NU,watch as DU}from"fs";import{readdir as qU,stat as FU}from"fs/promises";import{basename as Lh,dirname as jU,join as wP,resolve as UU}from"path";class Nh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,n,i,c=150){this.host=e;this.slots=n;this.watching=i;this.debounceMs=c}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,n=[]){let i=[],c=[];for(let x of[...new Set(e)]){let I;try{I=await qU(x)}catch(b){if(b instanceof Error&&"code"in b&&b.code==="ENOENT")continue;throw b}for(let b of I.sort()){let E=wP(x,b),T=(await FU(E)).isDirectory()?wP(E,"index.ts"):E;if(!T.endsWith(".ts")||T.endsWith(".d.ts"))continue;try{c.push({definition:await this.read(T),path:T})}catch(k){let A=Lh(T)==="index.ts"?Lh(jU(T)):Lh(T,".ts");if(this.slots.has(A))throw Error(`Duplicate plugin: ${A}`);let L={id:A,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${A}; repair the file and reload`)}};i.push({definition:L,path:T}),this.slots.set(A,{definition:L,path:T,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let p=n.filter((x)=>![...c,...i].some((I)=>I.definition.id===x.definition.id)),f=[...p,...c],g=this.order(f.map(({definition:x})=>x));for(let x of g){let I=f.find((E)=>E.definition===x)?.path,b=p.some((E)=>E.definition===x);try{await this.host.install(x,I,b)}catch(E){this.slots.set(x.id,{definition:x,path:I,builtin:b,enabled:!0,error:E instanceof Error?E.message:String(E)})}}if(this.watching())for(let x of[...f,...i]){if(!NU(x.path))continue;let I=DU(x.path,()=>{let b=x.definition.id,E=this.debounceTimers.get(b);if(E)clearTimeout(E);let T=setTimeout(()=>{this.debounceTimers.delete(b),this.host.reload(b).catch((k)=>{let A=this.slots.get(b);if(A)A.error=k instanceof Error?k.message:String(k)})},this.debounceMs);T.unref?.(),this.debounceTimers.set(b,T)});I.on("error",(b)=>{let E=this.slots.get(x.definition.id);if(E)E.error=b.message,this.host.changed()}),this.watchers.push(I)}}order(e,n=!1){let i=new Map;for(let x of e){if(this.validate(x),i.has(x.id)||!n&&this.slots.has(x.id))throw Error(`Duplicate plugin: ${x.id}`);i.set(x.id,x)}let c=[],p=new Set,f=new Set,g=(x)=>{if(f.has(x.id))return;if(p.has(x.id))throw Error(`Plugin dependency cycle: ${x.id}`);p.add(x.id);for(let I of x.deps??[]){let b=i.get(I);if(b)g(b);else if(!this.slots.has(I))throw Error(`Missing plugin dependency: ${I}`)}p.delete(x.id),f.add(x.id),c.push(x)};for(let x of e)g(x);return c}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((n)=>typeof n!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let n=await import(`${UU(e)}?v=${++this.revision}`);if(!n.default)throw Error("Plugin module must export a default definition");return this.validate(n.default),n.default}}async function TP(e,n,i=!1){if(!Number.isSafeInteger(n)||n<1||n>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let c=new AbortController,p;try{return await Promise.race([i?Promise.resolve(e(c.signal)):Promise.resolve().then(()=>e(c.signal)),new Promise((f,g)=>{p=setTimeout(()=>{c.abort(),g(Error(`Plugin callback timed out after ${n}ms`))},n)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as BU}from"async_hooks";import{isDeepStrictEqual as RP}from"util";var la=new BU;function As(){let e=la.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function su(e){let n=structuredClone(e),i=(c)=>{if(!c||typeof c!=="object"||Object.isFrozen(c))return;Object.freeze(c);for(let p of Object.values(c))i(p)};return i(n),n}function kP(e,n){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Entry replacement must be a body");for(let I of["seq","time","session_id","raw"])if(I in n)throw Error(`Entry replacement contains protected field: ${I}`);let i=JSON.parse(JSON.stringify(n,(I,b)=>{if(typeof b==="function"||typeof b==="symbol"||typeof b==="number"&&!Number.isFinite(b))throw Error("Entry replacement must contain JSON values");return b}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let c=i,p=[];switch(e.type){case"user":p.push("text","attachments");break;case"assistant":p.push("parts","error");break;case"tool_result":p.push("output","images");break;case"extension":p.push("payload","display");break;case"notice_pending":p.push("notice");break;case"run":if(e.state==="end")p.push("error");break;case"compaction":break}let f={...e};for(let I of new Set([...Object.keys(e),...Object.keys(c)])){if(!p.includes(I)&&!RP(f[I],c[I]))throw Error(`Entry replacement changed protected field: ${I}`);if(["seq","time","session_id","raw"].includes(I))throw Error(`Entry replacement contains protected field: ${I}`)}let g=(I)=>I===void 0||typeof I==="string",x=!0;switch(e.type){case"user":x=typeof c.text==="string"&&(c.attachments===void 0||Array.isArray(c.attachments)&&c.attachments.every((I)=>I&&typeof I.name==="string"&&typeof I.mimeType==="string"&&Vc.includes(I.kind)&&typeof I.data==="string"));break;case"assistant":x=g(c.error)&&Array.isArray(c.parts)&&c.parts.every((I)=>I&&(["text","thinking"].includes(I.type)&&typeof I.text==="string"||I.type==="tool_call"&&typeof I.id==="string"&&typeof I.name==="string"&&("input"in I)));break;case"tool_result":x=typeof c.output==="string"&&(c.images===void 0||Array.isArray(c.images)&&c.images.every((I)=>I&&typeof I.mimeType==="string"&&typeof I.data==="string"));break;case"extension":{let I=c.display;x="payload"in c&&(I===void 0||I!==null&&typeof I==="object"&&("text"in I)&&typeof I.text==="string"&&(!("title"in I)||g(I.title)));break}case"notice_pending":{let b=["text"],E=f.notice,T=c.notice;if(x=!!T&&typeof T==="object"&&!Array.isArray(T),!x)break;let k=T;for(let A of new Set([...Object.keys(E),...Object.keys(k)]))if(b.includes(A)){if(typeof k[A]!=="string")x=!1}else if(!RP(E[A],k[A]))x=!1;break}case"run":x=g(c.error);break;case"compaction":break}if(!x)throw Error("Invalid entry replacement content");return i}function AP(e,n,i,c,p,f){let g=c;for(let x of i.generations)for(let I of x.hooks.get("entry.before_append")??[]){if(x.disabled)break;let b={phase:"before",violated:!1};try{let E=la.run(b,()=>{let T=su(g),k=performance.now(),A=I(T,{sessionID:p,seq:f});if(A&&(typeof A==="object"||typeof A==="function")&&"then"in A&&typeof A.then==="function")throw Promise.resolve(A).catch(()=>{}),Error("entry.before_append must be synchronous");let L=A===void 0?void 0:kP(g,A);if(b.violated)throw Error("entry.before_append attempted a database write");if(performance.now()-k>e)throw Error("entry.before_append exceeded budget");return L});if(E&&JSON.stringify(E)!==JSON.stringify(g))g=E;x.beforeFailures=0,x.failures=0}catch(E){x.failures=x.beforeFailures++,n(x,E)}}return g}function GU(e,n){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return n;if(e==="entry.after_append")return su(n);return structuredClone(n)}async function CP(e,n,i,c,p,f,g,x,I="end"){let b=f;for(let E of c){if(E.disabled)continue;let T=E.hooks.get(p)??[];for(let k of T){if(E.disabled)break;let A=E.hookOptions.get(k);if(p==="prompt.fragments"&&(A?.promptPosition??"end")!==I)continue;let L=p==="prompt.fragments"?JSON.stringify([g?.id,b]):void 0,q=L===void 0?void 0:E.promptCache.get(k)?.get(L);try{let Z=GU(p,b),B=A?.timeoutMs,V=typeof B==="function"?B({runtime:e.runtime,session:g,connection:x}):B,X=await n((ie)=>k(Z,{runtime:e.runtime,session:g,connection:x,signal:ie}),V);if(L!==void 0){let ie=X===void 0?b:X;if(!Array.isArray(ie)||ie.some((z)=>typeof z!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(ie))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let Y=E.promptCache.get(k)??new Map;Y.set(L,[...ie]),E.promptCache.set(k,Y)}if(E.failures=0,X!==void 0&&p!=="entry.after_append")b=X}catch(Z){if(q)b=structuredClone(q);if(i(E,Z),A?.errorMode==="propagate")throw Z}}}return b}class jc{host;generations;released=!1;constructor(e,n){this.host=e;this.generations=n}async invoke(e,n,i,c,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,n,i,c,p)}has(e,n){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((c)=>n===void 0||(i.hookOptions.get(c)?.promptPosition??"end")===n))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((n)=>({...n,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${n.name}`);return n.execute(...i)}})))}waiting(e){return this.generations.some((n)=>!n.disabled&&n.gates.some((i)=>i(e)))}resolveHistory(e,n){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let c of i.historyResolvers){let p=c(e,n);if(p)return p}}}policy(e){return this.generations.findLast((n)=>!n.disabled&&n.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as KU}from"fs";import{dirname as HU,resolve as PP}from"path";var Dh=new WeakMap;function $P(e){return[...e].map((n)=>{let i=Boolean(n.path&&(Boolean(n.definition.webEntry)||KU(PP(HU(PP(n.path)),"web.tsx"))));if(n.current&&!Dh.has(n.current))Dh.set(n.current,crypto.randomUUID());return{id:n.definition.id,description:n.definition.description,builtin:n.builtin??!1,web:n.enabled&&!n.current?.disabled?n.current?.web??[]:[],webBundle:i,webRevision:n.current?Dh.get(n.current):void 0,version:n.definition.version,deps:n.definition.deps??[],status:!n.enabled?"disabled":n.current?.disabled||!n.current?"error":"enabled",error:n.error??n.current?.error,registrations:n.current?[...[...n.current.hooks.keys()].map((c)=>({kind:"hook",name:c})),...n.current.tools.map((c)=>({kind:"tool",name:c.name})),...n.current.routes.map((c)=>({kind:"route",method:c.method,path:c.path})),...n.current.websockets.map((c)=>({kind:"websocket",path:c.path})),...n.current.commands.map((c)=>({kind:"command",id:c.id})),...n.current.web.map((c)=>({kind:"web",id:c.id})),...[...n.current.policies.keys()].map((c)=>({kind:"policy",id:c})),...n.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class qh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,n,i){this.host=e;this.deadline=n;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,n,i){let c=this.host.pin(),p=(async()=>{try{let f=[];for(let g of c.generations){if(g.disabled)continue;for(let x of g.hooks.get(e)??[]){let I=g.hookOptions.get(x)?.timeoutMs,b=typeof I==="function"?I({runtime:this.host.runtime,session:n,connection:i}):I;f.push(this.deadline((E)=>x(n,{runtime:this.host.runtime,session:n,connection:i,signal:E}),b,!0).catch((E)=>this.fail(g,E)))}}await Promise.all(f)}finally{await c.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,n,i){let c=i===void 0?void 0:su(i),p=(this.entryQueues.get(n)??Promise.resolve()).then(async()=>{try{if(c)await la.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",c,this.host.runtime.get(n)))}finally{await e.release()}});this.entryQueues.set(n,p),this.pending.add(p);let f=()=>{if(this.pending.delete(p),this.entryQueues.get(n)===p)this.entryQueues.delete(n)};p.then(f,f)}}function MP(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 WU(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 zU(e,n){let i=n.sessionID?e.get(n.sessionID):void 0;if(n.sessionID&&!i)throw Error("Completion session not found");let c=n.model??i?.model??e.options.defaultModel;if(typeof c!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=Dn(e.options.models,c);if(!p&&n.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(n.model===void 0||!p){let f=(await e.models()).models.filter((x)=>x.available===!0),g=p?tt(p):c;if(!f.some((x)=>x.id===g)){let x=f[0];if(x)p=Dn(e.options.models,x.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function vP(e,n){WU(n);let i=await zU(e,n),c=n.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(c)||c<=0||c>i.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(n.signal?.aborted)throw Error("Completion cancelled");let p="",f=!1;try{let g=[...n.system?[{role:"system",content:n.system,timestamp:Date.now()}]:[],{role:"user",content:n.prompt,timestamp:Date.now()}],x=e.options.models.streamSimple(i,{messages:g},{maxTokens:c,signal:n.signal});for await(let I of x){if(n.signal?.aborted)throw Error("cancelled");if(I.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${MP(I.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(I.type==="text_delta")p+=I.delta;if(I.type==="done"){if(I.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(I.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${I.reason}\uFF09`);f=!0}}}catch(g){if(n.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${MP(g instanceof Error?g.message:String(g))}`)}if(n.signal?.aborted)throw Error("Completion cancelled");if(!f)throw Error("Model completion ended without a stop response; retry");return{text:p,model:tt(i)}}var VU=["active","archived","all"];function OP(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function QU(e){let{projectID:n,children:i,archive:c,since:p}=e;if(n!==void 0&&n!==null&&typeof n!=="string")throw Error("sessions projectID must be a string or null");if(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(c!==void 0&&!VU.includes(c))throw Error("sessions archive must be active, archived or all");if(p!==void 0&&!Number.isFinite(p))throw Error("sessions since must be a finite timestamp in milliseconds")}function JU(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function _P(e){function n(i,c={}){let{types:p,bodies:f}=c;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let g=OP(c.limit),x=c.after??0;if(!Number.isSafeInteger(x)||x<0)throw Error("sessions after must be a non-negative integer");let I=(e.get(i)?.entries(x)??[]).filter((b)=>p===void 0||p.includes(b.type)).slice(0,g);return structuredClone(f===!1?I.map(JU):I)}return{list(i={}){QU(i);let c=i.limit===void 0?void 0:OP(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((f)=>i.projectID===void 0||f.projectID===i.projectID).filter((f)=>i.since===void 0||f.created>=i.since);return structuredClone(c===void 0?p:p.slice(0,c))},get(i){return structuredClone(e.get(i)?.info())},entries:n}}async function LP(e,n,i,c,p,f){let g={definition:n,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},x=e.runtime.store.db,I=new Map,b=!1,E=!0,T=()=>{if(!E||g.disposed)throw Error("Plugin registration scope is closed")},k=(B,V)=>{if(T(),!b){I.set(B,V);return}if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,B);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,B,V)},A={get:(B)=>{T();let V=I.has(B)?I.get(B):x.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(n.id,B)?.value;return V==null?void 0:JSON.parse(V)},set:(B,V)=>{let X=JSON.stringify(V);if(X===void 0)throw Error("Plugin KV values must be JSON serializable");k(B,X)},delete:(B)=>k(B,null)},L=()=>{if(T(),b)throw Error("Register resources during setup only")},q=[...n.migrations??[]].sort((B,V)=>B.version-V.version),Z=new Set;try{for(let B of q){if(!Number.isSafeInteger(B.version)||B.version<1||Z.has(B.version))throw Error("Plugin migration versions must be unique positive integers");if(Z.add(B.version),x.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(n.id,B.version))continue;x.transaction(()=>{if(B.sql!==void 0)x.run(B.sql);else B.up({...A,db:x});for(let[V,X]of I)if(X===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,V);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,V,X);x.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(n.id,B.version)})(),I.clear()}return await c(async()=>n.setup({runtime:e.runtime,sessions:_P(e.runtime),complete:(B)=>vP(e.runtime,B),kv:A,database:x,broadcast:(B)=>{e.runtime.emitEvent(B)},registerInputGate:(B)=>{L(),g.gates.push(B)},registerNoticeSource:(B,V)=>{if(L(),!B||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");g.noticeSources.set(B,{...V})},provide:(B,V)=>{if(L(),B.pluginID!==n.id)throw Error("Service key must belong to the providing plugin");if(g.services.has(B.name))throw Error(`Duplicate plugin service: ${B.name}`);if(!B.validate(V))throw Error(`Invalid plugin service: ${B.name}`);g.services.set(B.name,V)},on:(B,V,X)=>{if(L(),X?.promptPosition&&B!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let ie=g.hooks.get(B)??[];if(ie.push(V),g.hooks.set(B,ie),X)g.hookOptions.set(V,X)},registerHistoryResolver:(B)=>{L(),g.historyResolvers.push(B)},registerTool:(B,V)=>{if(L(),!B.name||["toolsearch","tool_search","tool_call"].includes(B.name.toLowerCase())||XU(e,p,n.id).has(B.name.toLowerCase())||g.tools.some((ie)=>ie.name.toLowerCase()===B.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${B.name}`);let X=i?"always":"defer";if(typeof V?.defer==="boolean")X=V.defer?"defer":"always";else if(V?.defer!==void 0)X=V.defer;g.tools.push({...B,defer:X,source:`plugin:${n.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(B)=>{if(L(),!(B.path.startsWith(`/api/plugins/${n.id}/`)||(n.routePrefixes??[]).some((V)=>B.path===V||B.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(B.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(g.routes.some((V)=>V.path===B.path&&V.method===B.method))throw Error("Duplicate plugin route");g.routes.push(B)},registerWebSocket:(B)=>{if(L(),!B.path.startsWith(`/api/plugins/${n.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(g.websockets.some((V)=>V.path===B.path))throw Error("Duplicate plugin WebSocket route");g.websockets.push(B)},registerCommand:(B)=>{L(),g.commands.push(B)},registerWebContribution:(B)=>{L(),g.web.push(B)},registerToolPolicy:(B,V)=>{L(),g.policies.set(B,V)},appendExtension:(B,V)=>{if(As(),T(),!b)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(B,V)},onDeactivate:(B)=>{L(),g.deactivators.push(B)},onDispose:(B)=>{L(),g.disposers.push(B)}})),x.transaction(()=>{for(let[B,V]of I)if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,B);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,B,V)})(),I.clear(),b=!0,g}catch(B){throw E=!1,await f(g),B}}function XU(e,n,i){let c=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,f]of n){if(p===i)continue;for(let g of f.current?.tools??[])c.add(g.name.toLowerCase())}return c}class Fh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let n of e.connections)n.close(1012,"Plugin changed");this.retired.add(e);for(let n of e.deactivators.splice(0).reverse())try{await this.deadline(n)}catch(i){e.error=i instanceof Error?i.message:String(i)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let n of e.disposers.reverse())try{await this.deadline(n)}catch(i){e.error=i instanceof Error?i.message:String(i)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function NP(e,n,i,c){for(let p of n){let f=p.current;if(!f||f.disabled||f.retired)continue;let g=f.websockets.find((x)=>x.path===c);if(!g)continue;return{connect:(x)=>{let I=!1;f.references++,f.connections.add(x);let b={send:(T)=>{if(I||f.retired||f.disabled)return;x.send(T)},close:(T,k)=>x.close(T,k)},E=async(T)=>{if(I||f.retired||f.disabled){x.close(1012,"Plugin unavailable");return}try{await i(T),f.failures=0}catch(k){if(f.failures++,f.error=k instanceof Error?k.message:String(k),x.close(1011,"Plugin callback failed"),f.failures>=e.failureThreshold){f.disabled=!0;for(let A of f.connections)A.close(1011,"Plugin disabled")}}};return{open:()=>E(()=>g.open?.(b)),message:(T)=>E(()=>g.message(b,T)),close:async()=>{if(I)return;I=!0,f.connections.delete(x);try{await i(()=>g.close?.(b))}catch(T){f.error=T instanceof Error?T.message:String(T)}finally{f.references--,await e.collect(f)}}}}}}return}function jh(e,n){let i=e.split("/"),c=new URL(n.url).pathname.split("/");if(i.length!==c.length)return;let p={};return i.every((g,x)=>{let I=c[x];if(I===void 0)return!1;if(!g.startsWith(":"))return I===g;try{p[g.slice(1)]=decodeURIComponent(I)}catch{return!1}return I.length>0})?p:void 0}async function DP(e,n,i,c,p){let f=e.pin();try{let g=f.generations.find((x)=>x.definition.id===i)?.commands.find((x)=>x.id===c);if(!g)throw new y("Plugin command is unavailable");return await n(()=>g.execute(p))}finally{await f.release()}}function qP(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.method===n.method&&jh(p.path,n)!==void 0))}finally{i.release()}}function FP(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.public===!0&&p.method===n.method&&jh(p.path,n)!==void 0))}finally{i.release()}}async function jP(e,n,i){let c=e.pin(),p=!0;try{for(let f of c.generations)for(let g of f.routes){if(g.method!==i.method)continue;let x=jh(g.path,i);if(x){let I=await n(()=>g.handler(i,x),g.timeoutMs);if(!I)return;if(I.body&&I.body instanceof ReadableStream){p=!1;let b=!1,E=()=>{if(b)return;b=!0,c.release()},T=I.body.getReader(),k=new ReadableStream({async pull(A){try{let{done:L,value:q}=await T.read();if(L)A.close(),E();else A.enqueue(q)}catch(L){A.error(L),E()}},async cancel(A){try{await T.cancel(A)}finally{E()}}});return new Response(k,{status:I.status,statusText:I.statusText,headers:I.headers})}return I}}return}finally{if(p)await c.release()}}class Bh{runtime;options;slots=new Map;retirement=new Fh(this.deadline.bind(this));observers=new qh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new ul;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,n={}){this.runtime=e;this.options=n;if(n.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(n.beforeAppendBudgetMs)||n.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new Nh(this,this.slots,()=>n.watch===!0,n.watchDebounceMs??150),this.timeoutMs=n.timeoutMs??5000,this.failureThreshold=n.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let n=this.slots.get(e.pluginID);if(!n?.enabled||!n.current||n.current.disabled||n.current.retired)throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=n.current.services.get(e.name);if(!e.validate(i))throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((n)=>n.enabled&&n.current&&!n.current.disabled&&n.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let n=this.pin();try{await n.invoke("project.delete",e)}finally{await n.release()}}exclusive(e){let n=this.serial.then(async()=>{let i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=n.then(()=>{},()=>{}),n}discover(e,n=[]){for(let i of e)this.directories.add(Uh(i));return this.catalog.discover(e,n).finally(()=>this.changed())}async pluginPath(e){let n=await BP(e),i=[...this.directories,KP(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((c)=>KP(c.directory,".basalt","plugins"))];for(let c of i){if(!UP(c))continue;let p=ZU(await BP(c),n);if(p&&p!==".."&&!p.startsWith(`..${eB}`)&&!YU(p)){if(!n.endsWith(".ts")||n.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return n}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let n=await this.pluginPath(e),i=await this.checkEntry(n);if(!i.ok)throw new pt(i.errors);let c=await this.catalog.read(n);return await this.installDefinition(c,n,!1),c.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let n=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:n.success,errors:n.logs.filter((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,n=!1){return this.catalog.order(e,n)}install(e,n,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,n,i)})}async installDefinition(e,n,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let c=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:n,builtin:i,enabled:c?.enabled!==0};if(p.enabled)p.current=await this.stage(e,i);this.slots.set(e.id,p)}reload(e){return this.exclusive(async()=>{let n=this.require(e);if(!n.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!n.builtin){let x=await this.checkEntry(n.path);if(!x.ok)throw new pt(x.errors)}let i=n.builtin&&!UP(n.path)?n.definition:await this.catalog.read(n.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!n.enabled)throw Error("Enable the plugin before reloading");let c=this.order([...this.slots.values()].map((x)=>x.definition.id===e?i:x.definition),!0),p=await this.stage(i),f=n.current;n.definition=i,n.current=p,n.error=void 0,n.discoveryFailed=!1;let g=new Map(this.slots);this.slots.clear();for(let x of c){let I=g.get(x.id);if(I)this.slots.set(x.id,I)}if(f)await this.retirement.retire(f)}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,n){return this.exclusive(async()=>{let i=this.require(e);if(n===i.enabled&&(!n||i.current&&!i.current.disabled))return;if(!n){for(let g of this.slots.values())if(g.enabled&&g.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${g.definition.id}`)}let c=n&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.definition;if(c.id!==e)throw Error("Enable cannot change plugin id");let p=n?await this.stage(c):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(n));let f=i.current;if(i.definition=c,n)i.discoveryFailed=!1;if(i.enabled=n,i.current=p,i.error=void 0,f)await this.retirement.retire(f)})}require(e){if(this.closed)throw Error("Plugin host is closed");let n=this.slots.get(e);if(!n)throw Error(`Plugin not found: ${e}`);return n}async stage(e,n=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let i of e.deps??[])if(i===e.id||!this.slots.get(i)?.current||this.slots.get(i)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${i}`);return LP(this,e,n,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,n,i){this.observers.notify(e,n,i)}resolveHistory(e,n){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let c of i.current.historyResolvers){let p=c(e,n);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((n)=>n.enabled&&n.current&&!n.current.disabled&&n.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((n)=>n.enabled&&n.current&&!n.current.disabled?[n.current]:[]);for(let n of e)n.references++;return new jc(this,e)}async invoke(e,n,i,c,p,f="end"){return CP(this,this.deadline.bind(this),this.fail.bind(this),e,n,i,c,p,f)}pinEntry(e){if(la.getStore()?.phase==="after")return;let n;for(let i of this.slots.values()){let c=i.current;if(!i.enabled||!c||c.disabled||e.type==="extension"&&e.namespace===c.definition.id)continue;if(!c.hooks.has("entry.before_append")&&!c.hooks.has("entry.after_append"))continue;n??=[],n.push(c),c.references++}if(!n)return;return new jc(this,n)}beforeEntry(e,n,i,c){return AP(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,n,i,c)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,n){if(e.failures++,e.error=n instanceof Error?n.message:String(n),e.failures>=this.failureThreshold){e.disabled=!0;for(let i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,n,i){this.observers.finishEntry(e,n,i)}deadline(e,n=this.timeoutMs,i=!1){return TP(e,n,i)}appendExtension(e,n){return As(),new Promise((i)=>{let c=this.runtime.get(e);if(!c)throw Error("Extension target session does not exist");if(!n.namespace||!n.kind||!Number.isSafeInteger(n.schemaVersion)||n.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...n});c.refreshEntries(),i(p)})}list(){return $P(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let n=this.require(e),i=await this.webBuilder.entry(n.path,n.definition.webEntry);if(i&&n.path)await this.webBuilder.build(i,GP(Uh(n.path)));return{ok:!0}}catch(n){if(n instanceof al)return{ok:!1,errors:n.errors};return{ok:!1,errors:[{file:null,line:null,message:n instanceof Error?n.message:String(n)}]}}}async webBundle(e){let n=this.slots.get(e);if(!n?.enabled||!n.path||n.current?.disabled)return;let i=await this.webBuilder.entry(n.path,n.definition.webEntry);if(!i)return;return this.webBuilder.build(i,GP(Uh(n.path)))}async webCSS(e){await this.webBundle(e);let n=this.slots.get(e);if(!n?.enabled||!n.path||n.current?.disabled)return;let i=await this.webBuilder.entry(n.path,n.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,n,i){return DP(this,this.deadline.bind(this),e,n,i)}hasRoute(e){return qP(this,e)}isPublicRoute(e){return FP(this,e)}route(e){return jP(this,this.deadline.bind(this),e)}websocket(e){return NP(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 HP}from"fs";import{join as tB}from"path";var rB=500,nB=1000,oB=3600000,sB=5000,iB=2000,aB=3,uB=1073741824;class Gh{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=tB(e.dataDir,Bo),this.features={...Wo(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let n=this.engineStatus,i=n?.backfill;if(!n||!i)return{...e,state:"backfilling"};if(i.state==="done"){let c=n.entries;return{...e,state:"ready",lag:n.lag,total:c,indexed:Math.max(0,c-n.lag)}}return{...e,lag:n.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...n.etaSec!==void 0?{etaSec:n.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let n of["","-wal"])try{e+=HP(this.indexPath+n).size}catch{}return e}budget(){let e=0;try{e=HP(this.options.store.path).size}catch{}return Math.max(uB,Math.round(e*0.6))}async setEnabled(e){if(this.closed||e===this.enabledFlag)return;if(this.enabledFlag=e,this.failure=void 0,this.restarts=0,e){if(this.clearTimer)clearInterval(this.clearTimer);if(this.clearTimer=void 0,this.usable)this.start();else this.idleMaintenance()}else await this.stopWorker(),this.idleMaintenance();this.pushStatus()}async rebuild(){if(!this.usable)return;await this.stopWorker(),Qn(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((n)=>{this.flushes.set(e,()=>n(this.status())),this.post({type:"flush",id:e})})}pause(e){let n=this.worker;if(!n)return e();Atomics.store(this.flags,$e,1),n.postMessage({type:"pause"}),Atomics.wait(this.flags,Tt,0,sB);try{return e()}finally{Atomics.store(this.flags,$e,0),Atomics.notify(this.flags,$e)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=$o(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,$e,0),Atomics.store(this.flags,Tt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(n)=>this.receive(e,n.data),e.onerror=(n)=>this.crashed(e,n.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,n){if(e!==this.worker){if(n.type==="stopped")this.stopped?.();return}switch(n.type){case"status":this.update(n.status);break;case"flushed":{this.update(n.status),this.flushes.get(n.id)?.(),this.flushes.delete(n.id);break}case"error":if(n.fatal)this.crashed(e,n.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,n,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<aB&&this.usable)this.restarts++,this.start();else this.failure=n,console.error("search index unavailable:",n),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,$e,0),Atomics.notify(this.flags,$e);let n=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([n,Bun.sleep(iB)]),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,rB-(performance.now()-this.lastPrune));this.pruneTimer=setTimeout(()=>{this.pruneTimer=void 0,this.prune()},e),this.pruneTimer.unref?.()}prune(){let e=this.engineStatus?.queueDone??0;if(e<=this.pruned)return;this.lastPrune=performance.now();try{this.options.store.db.query("DELETE FROM search_queue WHERE id <= ?").run(e),this.pruned=e}catch{}}idleMaintenance(){if(this.engineStatus=void 0,!this.enabledFlag)Qn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),oB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let n=Math.max(0,nB-(performance.now()-this.lastPush)),i=()=>{if(this.statusTimer=void 0,this.closed)return;let c=this.status(),p=JSON.stringify({...c,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(c)};if(n===0)i();else this.statusTimer=setTimeout(i,n),this.statusTimer.unref?.()}}import{existsSync as uu,mkdirSync as fB,readdirSync as ZP,readFileSync as QP,realpathSync as Kh,statSync as wl,writeFileSync as Hh}from"fs";import{dirname as Sl,isAbsolute as Wh,relative as e$,resolve as hB}from"path";import{existsSync as Uc}from"fs";import{dirname as dB,join as au}from"path";import{mkdirSync as cB,writeFileSync as mB}from"fs";import{tmpdir as pB}from"os";import{join as WP}from"path";var xl=2000,Pe=30000;function u(e){return{content:[{type:"text",text:e}],details:void 0}}function iu(e,n){return e.map((i,c)=>{let p=i.length>xl?`${i.slice(0,xl)}\u2026 [line truncated]`:i;return`${String(n+c).padStart(6)} ${p}`}).join(`
88
+ `)}function je(e,n){if(e.length<=n)return e;let i=Math.floor(n*0.4),c=n-i,p=e.length-i-c,f=e.slice(i,e.length-c).split(`
89
+ `).length-1;return`${e.slice(0,i)}
90
+
91
+ \u2026 [${p} characters, ~${f} lines omitted] \u2026
92
+
93
+ ${e.slice(-c)}`}var lB=0;function rt(e,n){if(e.length<=n)return e;let i=je(e,n);try{let c=WP(pB(),"basalt-output");cB(c,{recursive:!0});let p=WP(c,`${process.pid}-${Date.now().toString(36)}-${lB++}.txt`);return mB(p,e),`${i}
94
+ [Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return i}}var zP=120000,VP=600000,da;function Il(){if(da!==void 0)return da||void 0;let n=(process.env.PATH??"").split(";").map((c)=>c.trim()).filter(Boolean);for(let c of n){let p=au(c,"bash.exe");if(Uc(p))return da=p,p}for(let c of n){let p=au(c,"git.exe");if(Uc(p)){let f=dB(c),g=au(f,"bin","bash.exe");if(Uc(g))return da=g,g;let x=au(f,"usr","bin","bash.exe");if(Uc(x))return da=x,x}}let i=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?au(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?au(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let c of i)if(Uc(c))return da=c,c;da="";return}class bl{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let n=new Uint8Array(this.gbkPending.length+e.length);n.set(this.gbkPending),n.set(e,this.gbkPending.length);let i=0;while(i<n.length){if(n[i]<128){i+=1;continue}let p=n[i+1];if(p===void 0)break;let f=p>=48&&p<=57?4:2;if(i+f>n.length)break;i+=f}return this.gbkPending=n.slice(i),this.gbk.decode(n.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});if(this.isGbk)return this.decodeGbk(e);try{return this.utf8.decode(e,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(e)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(!this.isGbk)return this.utf8.decode();let e=this.gbkPending;return this.gbkPending=new Uint8Array(0),e.length>0?this.gbk.decode(e):""}}function fa(e,n){let i=process.platform==="win32",c=n??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(c==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(c==="bash")return{argv:[Il()??"bash","-c",e],shellName:"bash",isWindows:!0};if(c==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=Il();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,n){let i=await ze(e,n.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:c,isWindows:p}=fa(e,n.shell),f=Bun.spawn(c,{cwd:n.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...n.extraPath?{[Object.keys(process.env).find((ie)=>ie.toLowerCase()==="path")??"PATH"]:n.extraPath}:{}}}),g=!1,x=()=>{try{if(p)f.kill();else process.kill(-f.pid,"SIGKILL")}catch{}},I=setTimeout(()=>{g=!0,x()},n.timeout);n.signal?.addEventListener("abort",x,{once:!0});let b=Pe*2,E="",T="",k=0,A=0,L="",q=(ie=!1)=>{let Y=k-E.length-T.length,z=Y>0?`${E}
95
+ \u2026 [${Y} characters omitted] \u2026
96
+ ${T}`:E+T;if(!ie)return je(z,Pe);return rt(L.length===k?L:z,Pe)},Z=()=>{let ie=new bl;return async(Y)=>{for await(let ce of Y){let he=ie.decode(ce);if(k+=he.length,L.length<4000000)L+=he;if(E.length<b)E+=he;else T=(T+he).slice(-b);if(n.onOutput){let ve=performance.now();if(ve-A>=80)A=ve,n.onOutput(q())}}let z=ie.flush();if(z){if(k+=z.length,L.length<4000000)L+=z;if(E.length<b)E+=z;else T=(T+z).slice(-b)}}},B=Promise.all([Z()(f.stdout),Z()(f.stderr)]),V=await f.exited;if(clearTimeout(I),n.signal?.removeEventListener("abort",x),await Promise.race([B.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))T+=`
97
+ [background processes are still running; their later output is not captured]`;return{output:q(!0),code:g?null:V,timedOut:g}}class zh{seen=new Map;mark(e,n=wl(e).mtimeMs){this.seen.set(e,n)}check(e){let n=this.seen.get(e);if(n===void 0)return"unread";return wl(e).mtimeMs!==n?"changed":void 0}}var JP=2000,gB=500,yB=10485760,El=20,xB=6,IB=40000,bB=80000;function EB(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 t$(e,n,i=[],c){let p=(L)=>Wh(L)?L:hB(e,L),f=(L)=>{let q=e$(e,L);return q&&!q.startsWith("..")&&!Wh(q)?q:L},g=(L)=>{let q=L;while(!uu(q)&&Sl(q)!==q)q=Sl(q);let Z=Kh(q);if(i.some((B)=>uu(B)&&YP(Kh(B),Z))&&!YP(Kh(e),Z))throw Error("External directories are read-only")},x=(L,q,Z)=>{let B=p(L);if(!uu(B))throw Error(`No such file or directory: ${B}${RB(B)}`);let V=wl(B);if(V.isDirectory()){let me=ZP(B,{withFileTypes:!0}).map((Qe)=>Qe.isDirectory()?`${Qe.name}/`:Qe.name).sort(),qe=me.slice(0,gB),xt=me.length-qe.length;return u(`${qe.join(`
98
+ `)}${xt>0?`
99
+ \u2026 and ${xt} more entries`:""}`||"(empty directory)").content}let X=QP(B),ie=EB(X);if(ie){if(V.size>yB)throw Error(`${B} exceeds the 10 MB image limit (${V.size} bytes)`);return n.mark(B),[{type:"text",text:`Read image ${f(B)} (${ie}, ${V.size} bytes)`},{type:"image",data:X.toString("base64"),mimeType:ie}]}if(X.subarray(0,8192).includes(0))throw Error(`${B} looks like a binary file (${V.size} bytes)`);n.mark(B);let Y=X.toString("utf8");if(!Y)return u("(empty file)").content;let z=Y.replace(/\r?\n$/,"").split(/\r?\n/),ce=(q??1)-1;if(ce>=z.length)throw Error(`offset ${q} is past the end of the file (${z.length} lines)`);let he=Math.min(z.length,ce+(Z??JP)),ve=0,de=ce;while(de<he){let me=z[de]?.length??0;if(de>ce&&ve+me>IB)break;ve+=me,de++}let se=iu(z.slice(ce,de),ce+1);if(de<he)se+=`
100
+
101
+ (Showing lines ${ce+1}-${de} of ${z.length} (truncated at line ${de} due to safety budget). Use offset/limit to read specific windows.)`;else if(ce>0||de<z.length)se+=`
102
+
103
+ (Showing lines ${ce+1}-${de} of ${z.length}. Use offset/limit to read other parts.)`;return u(se).content},I=v({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
104
+ - path may be absolute or relative to the working directory.
105
+ - By default reads up to ${JP} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
106
+ - Lines longer than ${xl} characters are truncated.
107
+ - Reading a directory lists its entries (directories end with /).
108
+ - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
109
+ - To read several files at once, give paths instead of path (up to ${El}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
110
+ - Always read a file before editing or overwriting it.`,parameters:s({path:o(l({description:"File or directory path"})),offset:o(w({minimum:1,description:"1-based line number to start from"})),limit:o(w({minimum:1,description:"Maximum number of lines to return"})),paths:o(W(s({path:l({description:"File or directory path"}),offset:o(w({minimum:1,description:"1-based line number to start from"})),limit:o(w({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:El,description:"Several files or directories to read in one call, instead of path"}))}),async execute(L,q){let Z=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(Z.length===0)throw Error("Give path, or paths to read several files");if(Z.length===1){let Y=Z[0];return{content:x(Y.path,Y.offset,Y.limit),details:void 0}}if(Z.length>El)throw Error(`Read at most ${El} paths per call`);let B=[],V=[],X=0,ie=(Y)=>{let z=B.at(-1);if(Y.type==="text"&&z?.type==="text")z.text+=`
111
+
112
+ ${Y.text}`;else B.push(Y)};for(let Y of Z){let z=`==> ${f(p(Y.path))} <==`;if(X>=bB){ie({type:"text",text:`${z}
113
+ (Skipped due to total read safety budget; read in separate calls)`});continue}try{let ce=x(Y.path,Y.offset,Y.limit);for(let he=0;he<ce.length;he++){let ve=ce[he];if(!ve)continue;if(ve.type==="text")X+=ve.text.length,ie(he===0?{...ve,text:`${z}
114
+ ${ve.text}`}:ve);else ie(ve)}}catch(ce){let he=ce instanceof Error?ce.message:String(ce);V.push(he),ie({type:"text",text:`${z}
115
+ Error: ${he}`})}}if(V.length===Z.length)throw Error(V.join(`
116
+ `));return{content:B,details:void 0}}}),b=async(L,q,Z,B)=>{let V=B?.update,X=await rr(L,{cwd:e,timeout:120000,signal:Z,extraPath:c?.extraPath,shell:typeof c?.shell==="function"?c.shell():c?.shell,onOutput:V?(he)=>V(u(`${B.prefix}
117
+
118
+ $ ${L}
119
+ ${he.trimEnd()}`)):void 0}),ie=X.output.trimEnd()||"(no output)",Y=X.timedOut?"killed after 120s timeout":X.code===0?"exit code 0":`exit code ${X.code}`,z=X.timedOut||X.code!==0,ce=z?`
120
+ ${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
121
+
122
+ $ ${L}
123
+ ${ie}
124
+ [${Y}]${ce}`,failed:z}},E=(L,q=!1)=>{let Z=n.check(L);if(Z==="changed")return`Note: ${f(L)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(Z==="unread"&&q)return`Note: ${f(L)} existed and had not been read; it was replaced whole.`;return},T=v({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
125
+ - An existing file is replaced whole, including changes made since you last read it.
126
+ - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
127
+ - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
128
+ - Do not create documentation or README files unless asked.`,parameters:s({path:l({description:"File path"}),content:l({description:"The full file content"}),then_run:o(l({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(L,q,Z,B){let V=p(q.path);g(V);let X=uu(V),ie;if(X){if(wl(V).isDirectory())throw Error(`${V} is a directory`);ie=E(V,!0)}fB(Sl(V),{recursive:!0}),Hh(V,q.content),n.mark(V);let Y=q.content?q.content.split(`
129
+ `).length:0,z=`${X?"Overwrote":"Created"} ${f(V)} (${Y} lines)${ie?`
130
+ ${ie}`:""}`;if(q.then_run){let ce=await b(q.then_run,`${f(V)} was written as given`,Z,{prefix:z,update:B});if(z+=ce.out,ce.failed)return{...u(z),isError:!0}}return u(z)}}),k=(L,q,Z,B)=>{let V=p(L);if(!uu(V))throw Error(`File not found: ${V} (use write to create it)`);g(V);let X=E(V),ie=QP(V,"utf8"),Y=ie,z=Y.includes(`\r
131
+ `),ce=[],he=[],ve=0,de=0;return q.forEach((se,me)=>{let qe=B?`edits[${Z+me}]: `:"";try{if(se.old_string===se.new_string)throw Error(`${qe}old_string and new_string are identical`);if(!se.old_string)throw Error(`${qe}old_string is empty (use write to create or replace a whole file)`);let xt=z&&!se.old_string.includes(`\r
132
+ `),Qe=xt?se.old_string.replace(/\n/g,`\r
133
+ `):se.old_string,Yt=xt?se.new_string.replace(/\n/g,`\r
134
+ `):se.new_string,Fe=SB(Y,Qe).map((At)=>[At,At+Qe.length]);if(Fe.length===0)Fe=wB(Y,Qe);if(Fe.length===0)throw Error(`${qe}old_string not found in ${f(V)}; read the relevant lines and copy the exact text.${TB(Y,Qe)}`);if(Fe.length>1&&!se.replace_all){let At=Fe.map(([st])=>XP(Y,st)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${At}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=XP(Y,Fe[0][0]),Ft=se.replace_all?Fe:[Fe[0]],lt="",vt=0;for(let[At,st]of Ft)lt+=Y.slice(vt,At)+Yt,vt=st;Y=lt+Y.slice(vt),ve++,de+=Ft.length;let fr=Y.split(/\r?\n/),mr=Ue+Yt.split(/\r?\n/).length-1,Ut=Math.max(1,Ue-1),ot=Math.min(fr.length,mr+1);if(ot-Ut+1<=xB+2)ce.push(iu(fr.slice(Ut-1,ot),Ut));else ce.push(`${iu(fr.slice(Ut-1,Ue+1),Ut)}
135
+ \u2026 (${mr-Ue-3} lines as given)
136
+ ${iu(fr.slice(mr-2,ot),mr-1)}`)}catch(xt){he.push(xt instanceof Error?xt.message:String(xt))}}),{path:V,original:ie,content:Y,echoes:ce,applied:ve,total:de,count:q.length,note:X,failed:he}},A=v({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
137
+ - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
138
+ - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
139
+ - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
140
+ - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
141
+ - To create a file use write; to delete or move files use bash.
142
+ - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
143
+ - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:s({path:o(l({description:"File path (the default for edits items without their own path)"})),old_string:o(l({description:"The exact text to replace (only when edits is absent)"})),new_string:o(l({description:"The replacement text (only when edits is absent)"})),replace_all:o(D({description:"Replace every occurrence (default false)"})),edits:o(W(s({path:o(l({description:"The file of this replacement, when it is not path"})),old_string:l({description:"The exact text to replace"}),new_string:l({description:"The replacement text"}),replace_all:o(D({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:o(l({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(L,q,Z,B){let V=q.edits&&q.edits.length>0?q.edits.map((se)=>({path:se.path??q.path,step:se})):q.old_string!==void 0&&q.new_string!==void 0?[{path:q.path,step:{old_string:q.old_string,new_string:q.new_string,replace_all:q.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let X=V.length>1,ie=new Map;V.forEach((se,me)=>{if(!se.path)throw Error(`${X?`edits[${me}]: `:""}path is required`);let qe=p(se.path),xt=ie.get(qe)??{raw:se.path,steps:[],offset:me};xt.steps.push(se.step),ie.set(qe,xt)});let Y=[],z=[];for(let se of ie.values())try{let me=k(se.raw,se.steps,se.offset,X);if(me.applied>0)Y.push(me);z.push(...me.failed)}catch(me){let qe=me instanceof Error?me.message:String(me);z.push(`${X?`edits[${se.offset}]: `:""}${qe}`)}if(Y.length===0)throw Error(z.join(`
144
+ `));let ce=[];try{for(let se of Y)Hh(se.path,se.content),ce.push(se)}catch(se){for(let me of ce)Hh(me.path,me.original);throw se}for(let se of Y)n.mark(se.path);let ve=Y.map((se)=>{let me=se.total===1?"1 occurrence":`${se.total} occurrences`,qe=se.note?`
145
+ ${se.note}`:"";if(!X)return`Edited ${f(se.path)} (${me}).${qe}
146
+ ${se.echoes[0]}`;let xt=se.failed.length>0?`, ${se.failed.length} failed`:"";return`Edited ${f(se.path)} (${se.applied} edits${xt}, ${me}). Regions are shown as they were right after each edit; later edits may shift line numbers.${qe}
147
+ ${se.echoes.map((Qe,Yt)=>`--- edit ${Yt+1}
148
+ ${Qe}`).join(`
149
+ `)}`}).join(`
150
+
151
+ `),de=!1;if(q.then_run){let se=await b(q.then_run,"The edits above were applied",Z,{prefix:ve,update:B});if(ve+=se.out,se.failed)de=!0}if(z.length>0)ve+=`
152
+
153
+ ${z.length===1?"1 edit":`${z.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
154
+ - ${z.join(`
155
+ - `)}`,de=!0;return de?{...u(ve),isError:!0}:u(ve)}});return[we(I,"cat","view","read_file","view_file","open_file","open"),we(T,"write_file","create_file","new_file","save_file"),we(A,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function SB(e,n){let i=[];for(let c=e.indexOf(n);c!==-1;c=e.indexOf(n,c+n.length))i.push(c);return i}function XP(e,n){let i=1;for(let c=0;c<n;c++)if(e.charCodeAt(c)===10)i++;return i}function wB(e,n){let i=n.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),c=[],p=e.split(`
156
+ `),f=0;for(let I of p)c.push(f),f+=I.length+1;let g=p.map((I)=>I.replace(/\r$/,"").trimEnd()),x=[];for(let I=0;I+i.length<=g.length;I++)if(i.every((b,E)=>g[I+E]===b)){let b=I+i.length-1,E=c[b]+p[b].replace(/\r$/,"").length,T=n.endsWith(`
157
+ `)&&E<e.length?e[E]==="\r"?2:1:0;x.push([c[I],E+T]),I+=i.length-1}return x}function TB(e,n){let i=(x)=>x.replace(/\s+/g," ").trim(),c=i(n);if(!c)return"";let p=e.split(/\r?\n/),f=n.split(/\r?\n/).length;for(let x=0;x+f<=p.length;x++)if(i(p.slice(x,x+f).join(`
158
+ `))===c)return` A match ignoring whitespace exists at line ${x+1}; copy the exact indentation and line breaks from the read output:
159
+ ${je(iu(p.slice(x,x+f),x+1),4000)}`;let g=n.split(/\r?\n/).find((x)=>x.trim())?.trim();if(g){let x=p.findIndex((I)=>I.includes(g));if(x!==-1)return` Its first line appears at line ${x+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function RB(e){let n=Sl(e);if(!uu(n))return"";let c=e.slice(n.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!c)return"";let p=ZP(n).filter((f)=>{let g=f.toLowerCase().replace(/\.[^.]*$/,"");return g&&(g.includes(c)||c.includes(g))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function YP(e,n){let i=e$(e,n);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!Wh(i)}var Vh=20,Qh=80,kB=5,r$=(e)=>e!==void 0&&e>0?e:void 0;function Tl(e,n){let i=(f)=>{if(n)return n(f);if(f.source&&f.source!=="self"||f.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},c=v({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
160
+ - Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
161
+ - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),pattern:l({minLength:1,description:"Text to search for"}),also:o(W(l({minLength:1}),{maxItems:kB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:o(l({description:"Only search this chunk"})),seq:o(w({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:o(D({description:"Default false"})),head_limit:o(w({minimum:1,maximum:Vh,description:`Hits to return (default ${Vh})`})),offset:o(w({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(f,g){let x=i(g),I=r$(g.seq),b=()=>ks(x.records),E=`session_id=${x.sessionID}`,T=I!==void 0&&g.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
162
+ `:"",k;if(I!==void 0){let z=Dc(x.records,I)??qc(x.records,I);if(!z)throw Error(`No user message with seq ${I}`);k=[z]}else{let z=b(),ce=g.chunk_id?z.filter((he)=>he.id===g.chunk_id):z;if(g.chunk_id&&!ce.length)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);k=ce.map(ou)}let A=(z)=>g.case_sensitive?z:z.toLowerCase(),L=[g.pattern,...(g.also??[]).filter(Boolean)].map(A),q=g.head_limit??Vh,Z=g.offset??0,B=[],V=new Map,X=0;for(let z of k)z.forEach((ce,he)=>{let ve=A(ce.text);if(!L.every((se)=>ve.includes(se)))return;if(V.set(ce.chunk,(V.get(ce.chunk)??0)+1),X++,X<=Z||B.length>=q)return;let de=z.slice(Math.max(0,he-2),he+3);B.push(`${E} chunk ${ce.chunk} line ${ce.line}:
163
+ ${Fc(de," ")}`)});if(!X)return u(`${T}No matches`);if(!B.length)return u(`${T}No matches at offset ${Z} (total ${X})`);let ie=X-Z-B.length,Y=V.size>1?` (all matches by chunk: ${[...V].map(([z,ce])=>`${z} ${ce}`).join(", ")})`:"";return u(`${T}${B.join(`
164
+
165
+ `)}${ie>0?`
166
+
167
+ \u2026 ${ie} more matches${Y}; continue with offset=${Z+B.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=v({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),chunk_id:o(l({description:"Chunk to read"})),seq:o(w({description:"User message to read (from a user-text-reference)"})),offset:o(w({minimum:0,description:"First line (default 0)"})),limit:o(w({minimum:1,maximum:Qh,description:`Lines to return (default ${Qh})`}))}),async execute(f,g){let x=i(g),I=r$(g.seq),b=()=>ks(x.records),E=`session_id=${x.sessionID}`,T=I!==void 0&&g.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
168
+ `:"",k;if(I!==void 0){if(k=Dc(x.records,I)??qc(x.records,I),!k)throw Error(`No user message with seq ${I}`)}else if(g.chunk_id){let Z=b().find((B)=>B.id===g.chunk_id);if(!Z)throw Error(`No chunk ${g.chunk_id}. Chunk IDs look like r12.`);k=ou(Z)}else{let Z=b().map((B)=>`${E} ${B.id} (${B.status}, ${ou(B).length} lines)`);return u(Z.length?`Pass chunk_id or seq. Chunks in this session:
169
+ ${Z.join(`
170
+ `)}`:"This session has no history yet")}let A=g.offset??0,L=k.slice(A,A+(g.limit??Qh));if(!L.length)return u(`No lines at offset ${A} (total ${k.length})`);let q=k.length-A-L.length;return u(`${T}${E} ${I!==void 0?`seq=${I}`:g.chunk_id}
171
+ ${Fc(L)}${q>0?`
172
+
173
+ \u2026 ${q} more lines; continue with offset=${A+L.length}`:""}`)}});return[c,p]}import{statSync as AB}from"fs";import{isAbsolute as n$,relative as CB,resolve as o$}from"path";var Rl=200,PB=30000,kl=Bun.which("rg");async function Jh(e,n,i){let c=Bun.spawn(e,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,f,g]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(g>1)throw Error(f.trim()||`${e[0]} exited with ${g}`);return p}function s$(e){let n=(f)=>f?n$(f)?f:o$(e,f):e,i=(f)=>{let g=CB(e,f);return g&&!g.startsWith("..")&&!n$(g)?g:f},c=v({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
174
+ - Respects .gitignore and skips .git. Use it instead of find or ls -R.
175
+ - To search file contents, use grep.`,parameters:s({pattern:l({description:"Glob pattern, matched relative to path"}),path:o(l({description:"Directory to search (default: working directory)"}))}),async execute(f,g,x){let I=n(g.path),b;if(kl)b=(await Jh([kl,"--files","--hidden","--glob","!.git","--glob",g.pattern],I,x)).split(`
176
+ `).filter(Boolean);else{b=[];for await(let A of new Bun.Glob(g.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(A))b.push(A)}if(!b.length)return u("No files found");let E=b.map((A)=>{let L=o$(I,A);try{return{path:L,time:AB(L).mtimeMs}}catch{return{path:L,time:0}}});E.sort((A,L)=>L.time-A.time);let T=E.slice(0,Rl).map((A)=>i(A.path)),k=b.length-T.length;return u(`${T.join(`
177
+ `)}${k>0?`
178
+ \u2026 ${k} more files; narrow the pattern`:""}`)}}),p=v({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
179
+ - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
180
+ - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
181
+ - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
182
+ - Use this instead of running grep or rg through bash.`,parameters:s({pattern:l({description:"Regular expression"}),path:o(l({description:"File or directory to search (default: working directory)"})),glob:o(l({description:"Only search files matching this glob"})),output:o(m([a("files"),a("content"),a("count")],{description:"Output mode (default files)"})),ignore_case:o(D()),context:o(w({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(f,g,x){let I=n(g.path),b=g.output??"files",E;if(kl){let A=[kl,"--hidden","--glob","!.git","--max-columns","400","--max-columns-preview"];if(g.ignore_case)A.push("-i");if(g.glob)A.push("--glob",g.glob);if(b==="files")A.push("-l");else if(b==="count")A.push("-c");else if(A.push("-n","--no-heading"),g.context)A.push("-C",String(g.context));A.push("--",g.pattern,I),E=await Jh(A,e,x)}else{let A=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(g.ignore_case)A.push("-i");if(g.glob)A.push(`--include=${g.glob}`);if(b==="files")A.push("-l");else if(b==="count")A.push("-c");else if(A.push("-n"),g.context)A.push(`-C${g.context}`);A.push("--",g.pattern,I),E=await Jh(A,e,x)}let T=`${e}/`,k=E.split(`
183
+ `).filter(Boolean).map((A)=>A.startsWith(T)?A.slice(T.length):A).filter((A)=>b!=="count"||!A.endsWith(":0"));if(!k.length)return u("No matches");if(b==="files"&&k.length>Rl)return u(`${k.slice(0,Rl).join(`
184
+ `)}
185
+ \u2026 ${k.length-Rl} more files; narrow the search`);return u(rt(k.join(`
186
+ `),PB))}});return[we(c,"find","find_files","list_files","file_search","ls","list","list_dir"),we(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function i$(e){return we(v({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
187
+ Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
188
+ - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
189
+ - Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
190
+ - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:s({todos:W(s({content:l({minLength:1,description:"What to do, in imperative form"}),status:m(Cg.map((n)=>a(n)))}))}),async execute(n,i){let c=i.todos.map((g)=>({content:g.content,status:g.status}));e(c);let p=c.filter((g)=>g.status==="completed").length,f=c.find((g)=>g.status==="in_progress");return u(`Todo list updated (${p}/${c.length} completed${f?`; in progress: ${f.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function We(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}function a$(e){let n=We(e);return{target:n,hard:n,index:n}}class Al{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,n=()=>{return},i){this.records=e;this.cwd=n;if(i)this.defaultPolicy=new Nc(e,i,n)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??a$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??We(e)}prepare(e,n,i,c,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,n,i,c);let f=e.reduce((b,E)=>b+U(E),0)+Pi(n),g=Math.max(0,We(i)*this.recoveryRatio-f),x=ke(c??this.records(),i,a$(i),{cwd:this.cwd()}).messages,I=x.reduce((b,E)=>b+U(E),0);if(p&&I>g)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(I>g&&x.length>1){let b=x.shift();if(b)I-=U(b);while(x[0]?.role==="toolResult"){let E=x.shift();if(E)I-=U(E)}}if(I>g){let b=x.at(-1),E=b&&"content"in b&&typeof b.content==="string"?b.content:"[Context omitted: use history tools to retrieve earlier messages.]";x.length=0;let T=E;while(T&&U({role:"user",content:T,timestamp:0})>g)T=T.slice(Math.ceil(T.length/2));if(T)x.push({role:"user",content:T,timestamp:0});I=x.reduce((k,A)=>k+U(A),0)}return this.lastMessageCount=x.length,{messages:[...e,...x],estimate:f+I}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as u$,readFileSync as $B}from"fs";import{homedir as MB}from"os";import{dirname as vB,join as c$}from"path";var OB=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
191
+
192
+ # How to work
193
+
194
+ - Complete the task end to end. Keep going until the user's request is fully resolved before ending your turn: investigate, make the change, verify it. Do not stop halfway to report a plan or ask "should I continue?" when the next step is clear.
195
+ - Ask the user only when you are genuinely blocked: the request is ambiguous in a way that changes the outcome, or the action is destructive or irreversible. Otherwise make a reasonable choice, state the assumption briefly, and proceed.
196
+ - If the user only asks a question or asks for a plan or review, answer it; do not start changing files. For a review, lead with findings: bugs, risks, behavior regressions and missing tests, ordered by severity with file:line. Keep any summary short and after the findings.
197
+ - Do not use the todo tool for a single deliverable, even a complex one (implementing a feature, fixing a bug, writing a module and its tests): work through it directly with a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later. Never make reading, environment checks or the final summary into items, and update it only together with your next action, never as a turn of its own.
198
+
199
+ # Making changes
200
+
201
+ - Investigate before changing anything. Find the relevant code with grep/glob, read it, and understand how it is used. Edit from what you have actually seen: a read, or grep output with enough context to copy the text exactly.
202
+ - Verify unfamiliar technical entities instead of recalling them. When a task involves a library, API, tool or version you do not confidently recognize, check the project first: package manifests and lockfiles, \`--version\`, or the installed sources. A fluent answer built on an outdated memory looks right and is wrong. Never guess URLs; use only ones the user or the project gave you.
203
+ - Follow the conventions of the existing code: style, naming, structure, libraries, error handling, comment density, test layout. Before using a library, confirm the project already depends on it.
204
+ - Fix the root cause, not the symptom. Keep changes minimal and focused on the task; do not refactor, rename or "clean up" unrelated code, and do not add features that were not requested. Between two correct approaches, prefer the smaller one. Do not add backward-compatibility code unless something concrete needs it (persisted data, shipped behavior, external consumers, an explicit requirement).
205
+ - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
206
+ - Do not add comments that narrate the change ("added this", "fixed bug"). Comment only where the code is not self-explanatory, in the style of the surrounding code.
207
+
208
+ # Verifying
209
+
210
+ - Verify behaviour the way the user would see it. When asked to test a feature, or after a change with user-visible effects, run the real thing first: start the app or server with bash background=true, exercise the changed path (curl an endpoint, run the CLI with real input, or drive a web UI with the browser tools: open, act, then browser_screenshot and look at the image), and confirm the result matches the requirement. Unit tests complement this; they do not replace it, and "the tests pass" is not evidence the feature works.
211
+ - For code with no runnable surface (a library, a refactor, types, build config), or when the app cannot be started here, run the most specific tests, type checker, linter or build instead \u2014 find how in the project's README, package scripts, Makefile or CI config \u2014 and say what you could not exercise.
212
+ - Once the change is verified, stop: re-verify only after new changes, failures or a concrete unresolved concern. Do not re-run a check that already passed when nothing it covers has changed. Kill servers and close pages you started.
213
+ - Do not re-read a file after your own edit or re-check mkdir/delete/move results: an edit result already shows the new content, and a failing call reports an error. Re-read only if someone else changed the file.
214
+ - When a step fails, read the error and diagnose why before retrying. Do not loop on the same failing approach; after two failed attempts, step back and reconsider. If a tool call is blocked, do not retry it unchanged; follow the stated reason or ask the user.
215
+
216
+ # Tools
217
+
218
+ - Tool calls are the only way to act; describing an action does not perform it.
219
+ - Use the dedicated tools for files: read to view (paths reads several files in one call), edit for replacements (give edits for several changes, even across files), write to create or rewrite a file, grep to search contents, glob to find files. A quick read-only look (ls, cat, sed -n) may share a bash command with other work, such as listing a directory while checking tool versions; to only view or edit a file, use read and edit.
220
+ - Create files you will keep or edit later with write, passing then_run to run them or their tests in the same step. A file written by a bash heredoc has not been read through the tools, so a later edit of it costs an extra step; a heredoc is fine for a throwaway script that the same command runs.
221
+ - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
222
+ - In bash, search with rg / rg --files when it exists (much faster than grep/find). Do not join commands with echo or printf separators such as an echo '====' line; the output gets noisy. Do not use python or other scripts just to print or edit file contents when read, edit will do. Backticks and $() inside a command still execute, so escape text carefully.
223
+ - Put every tool call you already know into one response. Independent reads and searches run in parallel; calls that change things (edit, write, bash) run one after another in the order you give them, so you can edit a file and run its tests in the same response. Put all replacements of one logical change (for example an import, a helper and its call sites, plus the matching test) into one edit call's edits and pass then_run with the test command, instead of one edit per spot followed by a separate test run. Pass then_run to write as well. When probing behaviour, batch the checks into one script instead of one command each.
224
+ - Use bash for builds, tests, git, package managers and running programs. Each bash call starts in the project directory; use absolute or project-relative paths and chain dependent steps with &&.
225
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished, including dev servers you start to verify a change. Do not busy-wait or poll repeatedly.
226
+
227
+ # Honesty
228
+
229
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
230
+ - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
231
+ - When the user asks you to run something, run it, even when you can predict the result.
232
+ - If a step failed, was skipped or could not be verified, say which one and why.
233
+
234
+ # Safety
235
+
236
+ - Do not run destructive or irreversible commands (rm -rf on broad paths, git reset --hard, git push --force, dropping databases, killing unrelated processes) unless the user explicitly asked for exactly that.
237
+ - Never commit, push, create branches or rewrite git history unless the user asks. If asked to commit, write a concise message that explains why, matching the repository's existing style.
238
+ - Do not revert or overwrite changes you did not make; the user may be editing files at the same time. If a file changed unexpectedly, read it again and work with the new content.
239
+ - Never print, log or commit secrets such as API keys, tokens or passwords.
240
+
241
+ # Communication
242
+
243
+ - Reply in the same language the user writes in.
244
+ - Be concise and direct. No filler, no flattery, no restating the request. Do not narrate every tool call: a short sentence before a batch of related actions, and in a long run a brief progress note every few calls, is enough.
245
+ - Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
246
+ - Do not use emojis unless the user does or asks for them.
247
+ - When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
248
+ - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,_B=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
249
+
250
+ # Tools
251
+
252
+ - Use read to view files, edit to change them and write to create them; use grep/glob to search contents and find files in the working directory.
253
+ - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
254
+ - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
255
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
256
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
257
+
258
+ # Communication
259
+
260
+ - Reply in the same language the user writes in.
261
+ - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
262
+ - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,LB=["AGENTS.md","CLAUDE.md"],NB=20000;function m$(e){let n=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?OB:_B}],i=[];if(e.globalInstructions?.trim())i.push(Xh("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let c of DB(e.project.directory))i.push(Xh(c.path,c.content));if(e.project.instructions.trim())i.push(Xh(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)n.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
263
+
264
+ # Instructions from the user and project
265
+
266
+ The following instructions were written by the user or the project maintainers. Follow them; they override the defaults above when they conflict. More specific (deeper directory) instructions take precedence over general ones.
267
+
268
+ ${i.join(`
269
+
270
+ `)}`});return n.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
271
+
272
+ ${qB(e)}`}),n}function Xh(e,n){return`<instructions source="${e}">
273
+ ${je(n.trim(),NB)}
274
+ </instructions>`}function DB(e){let n=[],i=e;for(let c=0;c<20;c++){for(let f of LB){let g=c$(i,f);if(u$(g)){try{n.unshift({path:g,content:$B(g,"utf8")})}catch{}break}}if(u$(c$(i,".git"))||i===MB())break;let p=vB(i);if(p===i)break;i=p}return n}function qB(e){let n=e.now??new Date,i=n.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),c=n.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:f}=fa("",e.shell),g=[`Working directory: ${p}`,`Shell: ${f}`,`Date: ${i} (${c})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project){let x=FB(e.project.directory);g.push(x??"Git: not a git repository")}return`<environment>
275
+ ${g.join(`
276
+ `)}
277
+ </environment>`}function FB(e){let n=(...x)=>{try{let I=Bun.spawnSync(["git",...x],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0});return I.exitCode===0?I.stdout.toString().trim():void 0}catch{return}},i=n("rev-parse","--abbrev-ref","HEAD");if(i===void 0)return;let c=n("status","--short")??"",p=c?c.split(`
278
+ `):[],f=p.length>30?[...p.slice(0,30),`\u2026 ${p.length-30} more`]:p,g=n("log","--oneline","-5")??"";return[`Git branch: ${i}`,`Git status at session start:${f.length?`
279
+ ${f.join(`
280
+ `)}`:" clean"}`,g?`Recent commits:
281
+ ${g}`:"Recent commits: none"].join(`
282
+ `)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Tl(e.records,e.history):[],c=e.directory??process.cwd();return[...t$(c,new zh,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...s$(c),i$(e.onTodos),...i]}class Mi{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||!$g.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Pg.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let n=this.settings();if(e.scope==="global")if(e.mode===null)delete n.global;else n.global=e.mode;else{let i=e.scope==="tool"?n.tools:n.sources,c=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[c];else i[c]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(n)),n}partition(e){let n=this.settings();return e.map((c)=>{let p=c,f=p.source??"core",g=c.name.toLowerCase(),x=p.defer??"always",I="suggestion";if(n.global)x=n.global,I="global";if(Object.hasOwn(n.sources,f))x=n.sources[f]??x,I="source";if(Object.hasOwn(n.tools,g))x=n.tools[g]??x,I="tool";if(f==="core"||p.builtin&&p.defer!=="defer")x="always",I="suggestion";return{name:c.name,source:f,mode:x,origin:I,deferred:x==="defer"}})}}function Yh(e){return{name:e.name,description:e.description,parameters:e.parameters}}function jB(e,n,i){let c=e.prepareArguments?e.prepareArguments(i):i;return Xa(e,{type:"toolCall",id:n,name:e.name,arguments:c})}class Zh{retrieved=new Map;stub(e){let n=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${n}
283
+ (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:s({},{additionalProperties:!0}),execute:async(i,c,p,f)=>{let g=JSON.stringify(Yh(e)),x;try{x=jB(e,i,c??{})}catch(E){return{...u(`Invalid arguments for ${e.name}: ${String(E)}
284
+ Schema: ${g}`),isError:!0}}let I=await e.execute(i,x,p,f),b=I.content.map((E)=>E.type==="text"?{...E,text:rt(E.text,Pe)}:E);return{...I,content:b}}}}assemble(e,n,i){let c=new Set(n.filter((f)=>f.deferred).map((f)=>f.name));if(!c.size)return e;let p=e.filter((f)=>c.has(f.name)&&i(f.name)).sort((f,g)=>f.name<g.name?-1:f.name>g.name?1:0);return[...e.filter((f)=>!c.has(f.name)),...p.map((f)=>this.stub(f)),we(v({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:s({query:l(),max_results:o(w({minimum:1,maximum:100}))}),execute:async(f,g)=>{let x=g.query.trim().toLowerCase(),I=x.startsWith("select:")?x.slice(7).split(",").map((E)=>E.trim()):void 0,b=p.filter((E)=>i(E.name)&&(I?I.includes(E.name.toLowerCase()):`${E.name} ${E.description}`.toLowerCase().includes(x))).slice(0,g.max_results??5);return u(JSON.stringify(b.map((E)=>{let T=JSON.stringify(Yh(E)),k=this.retrieved.get(E.name);if(k?.schema===T)return{name:E.name,status:"\u5DF2\u53D6\u56DE",callID:k.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(E.name,{schema:T,callID:f}),Yh(E)})))}}),"tool_search")]}}async function Cl(e,n,i){let c=await n.setup(e),p=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!i)return c;if(i.has("session.setup"))c=await i.invoke("session.setup",c,e);if(i.has("tools.configure"))c=await i.invoke("tools.configure",c,e);let f=c.systemPrompt,g=c.systemParts?.at(-1);if(g?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let E=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),T=f.length-g.detail.length;f=f.slice(0,T)+E.join("")+g.detail}let x=await i.invoke("prompt.fragments",[],e),I=[...c.tools,...i.tools()],b=i.has("tools.visible")?await i.invoke("tools.visible",I,e):I;return{...c,systemPrompt:f+x.join(""),tools:b}}var UB=3,p$={attempts:1/0,delayMs:2000},BB=/\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 GB(e,n){if(e.stopReason!=="error")return!1;if(oi(e,n))return!1;return!BB.test(e.errorMessage??"")}function KB(e,n){return new Promise((i,c)=>{if(n.aborted)return c(n.reason);let p=setTimeout(()=>{n.removeEventListener("abort",f),i()},e),f=()=>{clearTimeout(p),c(n.reason)};n.addEventListener("abort",f,{once:!0})})}async function l$(e,n,i,c,p,f,g,x,I=!1){let b=I?void 0:await n?.invoke("run.start",{text:f},e);if(b)f=b.text;if(x.throwIfAborted(),f===void 0)await c.resume();else await c.prompt(f,g);let E=0,T=0;while(E<UB){let q=e.records.findLast((B)=>B.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!oi(q,p.contextWindow)){if(!GB(q,p.contextWindow)||T>=p$.attempts)return;T++,await KB(p$.delayMs,x),await c.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}x.throwIfAborted(),E++,await c.retry()}let A=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&A?.stopReason==="error"&&oi(A,p.contextWindow))throw Error(i.overflowError??"Context exceeds the request budget")}async function d$(e,n,i,c,p,f){f.throwIfAborted();let g,x;try{x=await Promise.race([Cl(e,n,i()),new Promise((k,A)=>{g=()=>A(f.reason),f.addEventListener("abort",g,{once:!0})})])}finally{if(g)f.removeEventListener("abort",g)}f.throwIfAborted();let I=i(),b=(k)=>{if(!I)return k;return{...k,execute:async(A,L,q,Z)=>{let B=c()??x.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=B?I.policy(B):void 0;if(B&&!V?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${B}`);let X=await I.invoke("tool.before_call",{name:k.name,callID:A,args:L},e);if(X.block)throw Error(X.block);let ie=await K.run(e,()=>k.execute(A,X.args,q,Z));return I.invoke("tool.after_result",ie,e)}}};if(I)x.tools=x.tools.map(b);let E=x.tools,T=()=>{if(!E.some((A)=>A.name==="history_grep")){if(e.records.some((L)=>L.entry.type==="compaction")){let q=Tl(()=>e.records,(Z)=>n.runtime?.resolveHistory?.(e.id,Z)).map(b);for(let Z of q)if(!E.some((B)=>B.name===Z.name))E.push(Z)}}let k=new Mi(n.store).partition(E);return x.tools=p.assemble(E,k,(A)=>e.permitsTool(A)),x.tools};return x.tools=T(),{setup:x,executionTools:E,assemble:T}}function f$(e,n,i,c,p,f,g){return{response:async(x)=>{let I=await n()?.invoke("model.after_response",x,e)??x;if(I.role==="assistant")for(let b of I.content){if(b.type!=="toolCall"||b.name.toLowerCase()!=="tool_call")continue;let E=b.arguments.name;if(typeof E==="string"){let T=g.find((k)=>k.name.toLowerCase()===E.toLowerCase());b.arguments.name=T?.name??E}}return I},payload:(x)=>n()?.invoke("model.before_request",x,e)??Promise.resolve(x),transformContext:(x)=>n()?.invoke("transformContext",x,e)??Promise.resolve(x),boundary:async()=>{if(c())return!0;let x=await n()?.invoke("step.after",{notices:[]},e);for(let b of x?.notices??[])e.notice(b);await f.work;let I=await f.flushNotices();if(I&&!p())e.agent?.steer(I)},prepare:async(x,I,b)=>{if(c())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let E=await n()?.invoke("model.check",{},e);if(E?.error)throw Error(E.error);let T=await n()?.invoke("step.before",{notices:[]},e);for(let B of T?.notices??[])e.notice(B);await f.work,await f.flushNotices();let k=await n()?.invoke("projection.before",e.records,e),A=await n()?.invoke("projection.prefix",[],e)??[],L=e.context.prepare([...x,...A],I,b,k,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&L.estimate>We(b))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=L.messages,Z=await n()?.invoke("projection.after",q,e)??q;return tu(Z)}}}async function h$(e,n,i){let c=n.store.pendingNotices(e.id);if(!c.length)return;let p=c,f=n.plugins?.pin();try{if(f){let A=await f.invoke("notice.deliver",c,e);p=c.map((L,q)=>({...L,text:A[q]?.text??L.text}))}}finally{await f?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let g=p.map((A)=>A.text).join(`
285
+ `),x=p.map((A)=>n.plugins?.noticeSource(A.sourceKind)),I=Math.max(800,...x.map((A)=>A?.summaryLimit??800)),b=g.length>I?`
286
+ [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",T=`${x.find((A)=>A?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
287
+ ${g.slice(0,I)}${b}`,k={role:"user",content:T,timestamp:Date.now()};return i({type:"user",text:T,notices:c.map(({text:A,...L})=>L)},k),k}class eg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,n,i,c,p,f,g,x){this.session=e;this.context=n;this.isStopped=i;this.isRunning=c;this.waiting=p;this.start=f;this.invalidateAgent=g;this.append=x}recover(){for(let e of this.context.store.pendingNotices(this.session.id)){if(e.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:e.dedupeKey,sourceKind:e.sourceKind,sourceID:e.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if(this.context.store.pendingNotices(this.session.id).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let n={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,n)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((i)=>{this.failure=i}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=h$(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((n)=>n.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var HB=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 tg(e){let n={};for(let[i,c]of Object.entries(e)){if(!HB.has(i.toLowerCase())){n[i]=c;continue}let p=/^bearer\s+/i.exec(c)?.[0];n[i]=p?`${p}***`:"***"}return n}function g$(e,n,i,c){let f=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((Y,z)=>({id:`system-${z}`,label:Y.label,detail:Y.detail,tokens:O(Y.detail)+(z===0?16:0)})),g=i.tools.map((Y)=>{let z=Y,ce=z.defer==="defer"||Y.description.includes("(Parameters not inlined: use toolsearch");return{name:Y.name,description:Y.description,group:z.group??"\u5185\u7F6E",schema:Y.parameters,deferred:ce}});f.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Pi(i.tools),detail:JSON.stringify(g,null,2)});let x=f.reduce((Y,z)=>Y+z.tokens,0),I=c!==void 0?e.records.filter((Y)=>Y.entry.seq<=c):e.records,b=ke(I,n,e.context.budget(n),{inspect:!0,cwd:i.cwd,trim:{fixed:x,limit:e.context.previewLimit(n)}}),E,T=0,k=0;for(let Y of I){if(Y.raw?.role!=="assistant")continue;let z=Y.raw.usage;E??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},E.input+=z.input,E.output+=z.output,E.cacheRead+=z.cacheRead,E.cacheWrite+=z.cacheWrite,E.cost+=z.cost.total;let ce=Y.entry.generationMs??Y.raw.generationMs;if(typeof ce==="number"&&ce>0&&z.output>0)T+=ce,k+=z.output}if(E&&T>0&&k>0)E.generationMs=T,E.tps=Number((k/(T/1000)).toFixed(1));let A=x+b.tokens,L=e.context.calibrationRatio??1,q=Math.round(A*L),Z=I.findLast((Y)=>Y.raw?.role==="assistant"),B=Z?.raw,X=(Z?I.filter((Y)=>Y.entry.seq>Z.entry.seq&&Y.raw):I.filter((Y)=>Y.raw)).length>0,ie;if(B){let Y=B.usage,z=Y.input+Y.cacheRead+Y.cacheWrite;if(z>0)ie=z}return{contextWindow:n.contextWindow,usableWindow:We(n),items:[...f,...b.items],calibratedTokens:q,calibrationRatio:L,lastInputTokens:ie,hasPendingOutput:X,tools:g,usage:E}}class dt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class oe extends Error{constructor(e="session"){super(`${e} is busy`)}}var rg="medium";class Pl{row;ctx;events;notices;lease;policyID;discovery=new Zh;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let n=await Cl(this,this.ctx,e);return new Mi(this.ctx.store).partition(n.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new oe;this.policyID=e,this.reset()}historyScope(e){if(this.lease)return this.lease.resolveHistory(this,e);return this.ctx.plugins?.resolveHistory(this,e)}permitsTool(e){let n=this.policyID??this.setup?.toolPolicy;if(!n)return this.info().parentID===null;return(this.lease?.policy(n)??this.ctx.plugins?.toolPolicy(n))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,n,i){this.row=e;this.ctx=n;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new eg(this,n,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=n.store.lastSeq(e.id);let c=n.store.lastEntry(e.id,"run");this.stopped=c?.type==="run"&&c.state==="end"&&c.reason==="aborted";let p=this.entries().findLast((g)=>g.type==="extension"&&g.namespace==="session"&&g.kind==="stop_requested"),f=this.entries().findLast((g)=>g.type==="run"&&g.state==="start");if(p&&p.seq>(f?.seq??0))this.stopped=!0;if(c?.type==="run"&&c.state==="start"){let g=this.records.some((I)=>I.entry.seq>c.seq&&I.entry.type==="user"),x=n.store.pendingNotices(e.id).some((I)=>I.wake&&I.recovery!=="discard");if(!this.stopped&&(g||x))this.recoveryStart=c.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new Al(()=>this.records,()=>this.cwd,(g,x)=>this.appendCompaction(g,x)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=Dn(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:tg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:tg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??rg}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:n,projectID:i,model:c,thinking:p,metadata:f,created:g,updated:x,todos:I}=this.row;return{id:e,title:n,projectID:i,model:c,thinking:p??rg,metadata:f,created:g,updated:x,archivedAt:this.row.archivedAt,status:this.status,todos:I,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let n=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,n)}entriesBefore(e,n){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-n));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,n,i){return this.ctx.store.entriesAround(this.row.id,e,n,i)}entriesFrom(e,n){return this.ctx.store.entriesFrom(this.row.id,e,n)}entries(e=0){return this.ctx.store.entries(this.row.id).filter((n)=>n.seq>e)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let n=(async()=>{let i=Dn(this.ctx.models,this.row.model);if(!i)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let c=this.ctx.plugins?.pin(),p;try{p=this.setup??await Cl(this,this.ctx,c)}finally{await c?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new Mi(this.ctx.store).partition(p.tools),(g)=>this.permitsTool(g));let f=g$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:f};return f})();if(e!==void 0)return n;this.snapshotInFlight=n;try{return await n}finally{if(this.snapshotInFlight===n)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new dt}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!Dn(this.ctx.models,e))throw new r(`unknown model ${e}`);let n=this.row.model;if(n===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:n,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let n=e?.trim()?e.trim():null;if(this.row.thinking===n)return;this.save({thinking:n}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,n){this.startRun(e,n)}steer(e,n){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,n);return}this.stopped=!1;let i=Rh(e,n),c=this.append({type:"user",text:e,...n?.length?{attachments:n}:{}},i);if(this.recallableSteers.set(c.seq,i),this.events.changed(),this.agent)this.agent.steer(i);else this.pendingSteers.push(i)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let n=this.records.find((f)=>f.entry.seq===e);if(n?.entry.type!=="user"||n.raw===void 0)return!1;if("notices"in n.entry&&n.entry.notices)return!1;let i=n.raw,c=this.pendingSteers.indexOf(i);if(c<0){let f=JSON.stringify(i);c=this.pendingSteers.findIndex((g)=>JSON.stringify(g)===f)}let p=!1;if(c>=0)this.pendingSteers.splice(c,1),p=!0;else p=this.agent?.unsteer(i)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[n,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(n),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,n,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new oe;if(e!==void 0)this.stopped=!1;let c=Dn(this.ctx.models,this.row.model);if(!c&&i===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let p=new AbortController;if(this.starting=p,!this.row.title&&e!==void 0)this.row={...this.row,title:WB(e,n)},this.ctx.store.updateSession(this.row);let f=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let g=this.append({type:"user",text:e,...n?.length?{attachments:n}:{}});this.pendingUserSeq=g.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let x=this.records.filter((T)=>T.entry.seq>f),I=x.filter((T)=>T.entry.type==="user"&&!T.raw);if(I.length>1)return{reason:"interrupted"};let b=I[0];if(b?.entry.type==="user"){if(x.some((T)=>T.entry.seq>b.entry.seq&&T.raw?.role==="assistant"))return{reason:"interrupted"};e=b.entry.text,n=b.entry.attachments,this.pendingUserSeq=b.entry.seq}for(let T of ss(x.filter((k)=>k.raw))){if(T.result)continue;let{body:k,raw:A}=oP(T.call);this.append(k,A)}if(!b&&this.waitingForInput())return{reason:"waiting_user"};let E=this.records.findLast((T)=>T.entry.seq>f&&T.raw)?.raw;if(!b&&E?.role==="assistant")return kh(E);if(!b&&!E&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!c)throw Error(`unknown model ${this.row.model}`);let g=await this.prepareAgent(c,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let x=this.pendingSteers.shift();if(x)g.steer(x)}return await l$(this,this.lease,this.setup,g,c,e,n,p.signal,i!==void 0&&e===void 0),kh(this.records.findLast((x)=>x.entry.seq>f&&x.raw?.role==="assistant")?.raw)}).then((g)=>p.signal.aborted?{reason:"aborted"}:g,(g)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(g)}).then(async(g)=>{try{if(!this.suspended&&g.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())g={reason:"waiting_user"};if(g.reason!=="interrupted")g=await this.lease?.invoke("run.end",{reason:g.reason,error:g.error},this)??g}}catch(x){g={reason:"error",error:String(x)}}finally{try{await this.lease?.release()}catch(x){g={reason:"error",error:String(x)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...g});let x=Dn(this.ctx.models,this.row.model);if(x)this.context.settle(x)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,n){if(!this.agent){let{setup:i,executionTools:c,assemble:p}=await d$(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,n);if(this.setup=i,this.row.parentID&&(!i.toolPolicy||!this.lease?.policy(i.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=i.cwd,this.agent=nP({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((f)=>!this.pendingSteers.includes(f.raw)).flatMap((f)=>f.raw?[f.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??rg,captureRequest:(f)=>{this.lastRequestSnapshot=f},captureResponse:(f)=>{this.lastResponseSnapshot=f},steerConsumed:(f)=>this.markSteerConsumed(f),hooks:{tools:p,...f$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,c),message:(f,g)=>{if(this.suspended&&g.role==="assistant"&&(g.stopReason==="aborted"||g.stopReason==="error"))return;if(g.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,g);let x=this.loaded?.find((I)=>I.entry.seq===this.pendingUserSeq);if(x)x.raw=g;this.pendingUserSeq=void 0;return}if(g.role==="assistant")this.context.calibrate(g);this.append(f,g)},draft:(f)=>{this.draftParts=f,this.events.draft(f)}}})}return this.agent}notice(e,n=!1){if(this.closed)return;if(n)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let n of e)this.loaded?.push(n);for(let{entry:n}of e)this.events.entry(n)}appendCompaction(e,n){this.assertWritable();let i=this.measureCompactionSavings(e,n);this.append({type:"compaction",through:e,partial:n,...i?{saved:i}:{}})}measureCompactionSavings(e,n){let i=Dn(this.ctx.models,this.row.model);if(!i)return;let c=this.context.budget(i),p=ke(this.records,i,c,{cwd:this.cwd}).tokens,f={entry:{type:"compaction",through:e,partial:n,seq:this.seq+1,time:0}},g=ke([...this.records,f],i,c,{cwd:this.cwd}).tokens;return{before:p,after:g}}compact(){this.assertWritable();let e=eu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,n){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,n);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function WB(e,n){let c=(e.trim()||n?.map((p)=>p.name).join(" ")||"").split(`
288
+ `)[0]?.trim()??"";return c.length>40?`${c.slice(0,40)}\u2026`:c}function or(e,n){let i=e.at(-1)?.entry.seq??0,c,p,f;for(let{entry:b}of e){if(b.type==="run"&&b.state==="start")c=b.seq;if(b.seq===n)if(b.type==="user"&&!b.notices)i=(c??b.seq)-1;else p=c;if(b.type==="run"&&b.state==="end"){if(p!==void 0&&c===p)f=b.seq;c=void 0}}let g=e.find((b)=>b.entry.seq===n)?.entry;if(n!==void 0&&!g)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(g&&!(g.type==="user"&&!g.notices)){if(p!==void 0&&f===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=f??g.seq}else if(n===void 0&&c!==void 0)i=e.findLast(({entry:b})=>b.type==="run"&&b.state==="end")?.entry.seq??0;let x=e.filter(({entry:b})=>b.seq<=i&&(b.type!=="compaction"||b.through<=i)),I=new Map(x.map(({entry:b},E)=>[b.seq,E+1]));return x.map((b,E)=>{let T=structuredClone(b);if(T.entry.seq=E+1,T.entry.type==="compaction"){let k=T.entry.through,A=x.findLast(({entry:L})=>L.seq<=k);T.entry.through=A?I.get(A.entry.seq)??0:0}return T})}function ir(e){let n=new Map,i=[];for(let c of e){if(c.type==="assistant"){for(let g of c.parts)if(g.type==="tool_call"&&g.name==="todo")n.set(g.id,g.input)}if(c.type!=="tool_result"||c.name!=="todo"||c.isError)continue;let p=n.get(c.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let f=[];for(let g of p.todos){if(!g||typeof g!=="object"||!("content"in g)||typeof g.content!=="string"||!("status"in g)||g.status!=="pending"&&g.status!=="in_progress"&&g.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");f.push({content:g.content,status:g.status})}i=f}return i}import{Buffer as Ml}from"buffer";import{createHash as y$}from"crypto";import{isDeepStrictEqual as $l}from"util";var Oi="@blob:";function cu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function vl(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(Oi)){let f=Ml.from(p.data,"base64");if(f.byteLength>0&&f.toString("base64")===p.data){let g=y$("sha256").update(f).digest("hex");return n.put(g,p.mimeType,new Uint8Array(f.buffer,f.byteOffset,f.byteLength)),i=!0,{...p,data:`${Oi}${g}`}}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(Oi)){let f=Ml.from(p.data,"base64");if(f.byteLength>0&&f.toString("base64")===p.data){let g=y$("sha256").update(f).digest("hex");return n.put(g,p.mimeType,new Uint8Array(f.buffer,f.byteOffset,f.byteLength)),i=!0,{...p,data:`${Oi}${g}`}}}return p});if(!i)return e;return{...e,images:c}}return e}function ha(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.startsWith(Oi)){let f=p.data.slice(Oi.length),g=n.get(f);if(g!==void 0)return i=!0,{...p,data:Ml.from(g.buffer,g.byteOffset,g.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.startsWith(Oi)){let f=p.data.slice(Oi.length),g=n.get(f);if(g!==void 0)return i=!0,{...p,data:Ml.from(g.buffer,g.byteOffset,g.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,images:c}}return e}function Bc(e,n){if(!cu(n))return n;if(e.type==="user"){let{merged:i,images:c}=vc(e.text,e.attachments),p=c.length>0?[{type:"text",text:i},...c]:i,f=Object.keys(n),{role:g,timestamp:x,content:I}=n;if(f.length===3&&g==="user"&&typeof x==="number"&&"content"in n&&$l(I,p))return{role:"user",timestamp:x};return n}if(e.type==="tool_result"){let{role:i,toolCallId:c,toolName:p,isError:f,timestamp:g,content:x}=n;if(i!=="toolResult"||c!==e.callID||typeof p!=="string"||f!==e.isError||typeof g!=="number")return n;let I=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in n?!$l(n.details,e.meta):e.meta!==void 0)return n;let{role:E,toolCallId:T,toolName:k,content:A,details:L,isError:q,timestamp:Z,...B}=n;if($l(x,I))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...B,timestamp:g};if(Array.isArray(x)){let V=e.images??[],X=0,ie=!0,Y=x.map((z)=>{if(cu(z)&&z.type==="image"){let ce=V[X++],he=Object.keys(z);if(ce&&he.length===3&&z.mimeType===ce.mimeType&&z.data===ce.data)return{type:"image",mimeType:z.mimeType};ie=!1}return z});if(ie&&X===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:Y,...B,timestamp:g}}return n}if(e.type==="assistant"){let{role:i,content:c}=n;if(i!=="assistant"||!Array.isArray(c)||c.length!==e.parts.length)return n;let p=!1,f=c.map((g,x)=>{let I=e.parts[x];if(cu(g)){if(g.type==="text"&&I?.type==="text"&&g.text===I.text){p=!0;let b={...g};return delete b.text,b}if(g.type==="thinking"&&I?.type==="thinking"&&g.thinking===I.text){p=!0;let b={...g};return delete b.thinking,b}if(g.type==="toolCall"&&I?.type==="tool_call"&&g.id===I.id&&g.name===I.name&&"arguments"in g&&$l(g.arguments,I.input)){p=!0;let b={...g};return delete b.id,delete b.name,delete b.arguments,b}}return g});if(!p)return n;return{...n,content:f}}return n}function ng(e,n){if(!cu(n))return n;if(e.type==="user"){let{role:i,timestamp:c}=n;if(i==="user"&&!("content"in n)&&typeof c==="number"&&Object.keys(n).length===2){let{merged:p,images:f}=vc(e.text,e.attachments);return{role:"user",content:f.length>0?[{type:"text",text:p},...f]:p,timestamp:c}}return n}if(e.type==="tool_result"){let{role:i,timestamp:c}=n;if(i==="toolResult"&&(!("content"in n)||!("toolCallId"in n))&&typeof c==="number"){let{role:f,toolName:g,content:x,timestamp:I,...b}=n,E;if(Array.isArray(x)){let T=e.images??[],k=0;E=x.map((A)=>{if(cu(A)&&A.type==="image"&&!("data"in A)){let L=T[k++];if(L)return{type:"image",mimeType:A.mimeType,data:L.data}}return A})}else E=[{type:"text",text:e.output},...(e.images??[]).map((T)=>({type:"image",mimeType:T.mimeType,data:T.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof g==="string"?g:e.name,content:E,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...b,timestamp:c}}return n}if(e.type==="assistant"){let{role:i,content:c}=n;if(i!=="assistant"||!Array.isArray(c))return n;let p=!1,f=c.map((g,x)=>{let I=e.parts[x];if(cu(g)){if(g.type==="text"&&!("text"in g)&&I?.type==="text"){p=!0;let{type:b,...E}=g;return{type:b,text:I.text,...E}}if(g.type==="thinking"&&!("thinking"in g)&&I?.type==="thinking"){p=!0;let{type:b,...E}=g;return{type:b,thinking:I.text,...E}}if(g.type==="toolCall"&&!("arguments"in g)&&I?.type==="tool_call"){p=!0;let{type:b,...E}=g;return{type:b,id:I.id,name:I.name,arguments:structuredClone(I.input),...E}}}return g});if(!p)return n;return{...n,content:f}}return n}function x$(e){let n=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),c={put(I,b,E){n.run(I,b,E)},get(I){return i.get(I)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),f=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),g=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),x=0;return e.transaction(()=>{for(let I of p){let b;try{b=JSON.parse(I.body)}catch{continue}let E=ha(b,c),T=vl(E,c),k=T===b?I.body:JSON.stringify(T),A=I.raw;if(I.raw!==null)try{let L=JSON.parse(I.raw),q=ng(E,L),Z=Bc(E,q);A=JSON.stringify(Z)}catch{A=I.raw}if(k!==I.body)f.run(k,A,I.session_id,I.seq),x++;else if(A!==I.raw)g.run(A,I.session_id,I.seq),x++}})(),x}import{Database as zB}from"bun:sqlite";import{chmodSync as I$,existsSync as VB,mkdirSync as QB}from"fs";import{dirname as JB}from"path";var og=[`
289
+ CREATE TABLE projects (
290
+ id TEXT PRIMARY KEY,
291
+ name TEXT NOT NULL,
292
+ directory TEXT NOT NULL UNIQUE,
293
+ instructions TEXT NOT NULL DEFAULT '',
294
+ created INTEGER NOT NULL,
295
+ updated INTEGER NOT NULL
296
+ );
297
+ CREATE TABLE automations (
298
+ id TEXT PRIMARY KEY,
299
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
300
+ name TEXT NOT NULL,
301
+ prompt TEXT NOT NULL,
302
+ schedule TEXT NOT NULL,
303
+ model TEXT NOT NULL,
304
+ enabled INTEGER NOT NULL,
305
+ created INTEGER NOT NULL,
306
+ updated INTEGER NOT NULL,
307
+ next_run INTEGER,
308
+ last_run INTEGER,
309
+ last_session_id TEXT
310
+ );
311
+ CREATE TABLE sessions (
312
+ id TEXT PRIMARY KEY,
313
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
314
+ automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
315
+ title TEXT NOT NULL DEFAULT '',
316
+ model TEXT NOT NULL,
317
+ todos TEXT NOT NULL DEFAULT '[]',
318
+ created INTEGER NOT NULL,
319
+ updated INTEGER NOT NULL
320
+ );
321
+ CREATE INDEX sessions_project ON sessions(project_id);
322
+ CREATE TABLE entries (
323
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
324
+ seq INTEGER NOT NULL,
325
+ time INTEGER NOT NULL,
326
+ body TEXT NOT NULL,
327
+ raw TEXT,
328
+ PRIMARY KEY (session_id, seq)
329
+ ) WITHOUT ROWID;
330
+ `,"","","",`
331
+ ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
332
+ ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
333
+ ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
334
+ CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
335
+ ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
336
+ ALTER TABLE sessions ADD COLUMN notice_floor_seq INTEGER NOT NULL DEFAULT 0;`,"ALTER TABLE sessions ADD COLUMN truncation_epoch INTEGER NOT NULL DEFAULT 0;",`CREATE TABLE plugin_kv (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
337
+ PRIMARY KEY (namespace, key));
338
+ CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
339
+ PRIMARY KEY (namespace, version));
340
+ CREATE TABLE plugin_settings (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL);`,"ALTER TABLE sessions ADD COLUMN thinking TEXT;","ALTER TABLE sessions ADD COLUMN metadata TEXT;","ALTER TABLE sessions ADD COLUMN archived_at INTEGER;",`CREATE TABLE search_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, seq INTEGER NOT NULL);
341
+ CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
342
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
343
+ END;
344
+ CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
345
+ INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
346
+ END;
347
+ CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
348
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
349
+ END;
350
+ CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
351
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
352
+ END;
353
+ CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
354
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
355
+ END;
356
+ CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
357
+ INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
358
+ END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
359
+ WHERE json_extract(body,'$.type')='compaction';
360
+ CREATE TABLE IF NOT EXISTS blobs (
361
+ hash TEXT PRIMARY KEY,
362
+ mime TEXT NOT NULL,
363
+ data BLOB NOT NULL
364
+ ) WITHOUT ROWID;
365
+ CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`];function b$(e,n){if(e!==":memory:")QB(JB(e),{recursive:!0});let i=new zB(e,{create:!0,strict:!0}),c=(f)=>new Proxy(function(...g){return Reflect.apply(f,this,g)},{apply(g,x,I){As();let b=[];n.push(b);let E=!1;try{let T=Reflect.apply(g,x,I);return E=!0,T}finally{n.pop();let T=n.at(-1);if(E&&T)T.push(...b);else for(let k of b)if(E)k.commit();else k.rollback()}},get(g,x){let I=Reflect.get(f,x);if(["deferred","immediate","exclusive"].includes(String(x))&&typeof I==="function")return c(I);return I}}),p=new Proxy(i,{get(f,g){let x=Reflect.get(f,g,f);if(typeof x!=="function")return x;return(...I)=>{As();let b=Reflect.apply(x,f,I);if(g==="transaction"&&typeof b==="function")return c(b);if(g!=="query"&&g!=="prepare")return b;if(!b||typeof b!=="object")throw Error("Invalid SQL statement");return new Proxy(b,{get(E,T,k){let A=Reflect.get(E,T,E);if(typeof A!=="function")return A;return(...L)=>{As();let q=Reflect.apply(A,E,L);return q===E?k:q}}})}}});if(e!==":memory:")I$(e,384);if(p.run("PRAGMA journal_mode = WAL"),p.run("PRAGMA synchronous = FULL"),p.run("PRAGMA foreign_keys = ON"),p.run("PRAGMA busy_timeout = 5000"),XB(p),p.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),p.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let f of["-wal","-shm"]){let g=e+f;if(VB(g))I$(g,384)}return p}function XB(e,n=og){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>n.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${n.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let c=i;c<n.length;c++)e.transaction(()=>{let p=n[c]??"",f=Array.isArray(p)?p:c>=4?YB(p):[p];for(let g of f)try{if(g.trim())e.run(g)}catch(x){if(!(x instanceof Error)||!/already exists|duplicate column name/i.test(x.message))throw x}e.run(`PRAGMA user_version = ${c+1}`)})()}function YB(e){let n=[],i=0,c=0,p=[],f=!1,g=0,x=(I)=>{let b=e.slice(i,I).trim();if(b)n.push(b);i=I+1,p=[],f=!1,g=0};while(c<e.length){let I=e[c];if(I==="'"||I==='"'||I==="`"||I==="["){let b=I==="["?"]":I;c++;while(c<e.length)if(e[c]===b)if(b!=="]"&&e[c+1]===b)c+=2;else break;else c++;c++;continue}if(I==="-"&&e[c+1]==="-"){let b=e.indexOf(`
366
+ `,c);c=b===-1?e.length:b+1;continue}if(I==="/"&&e[c+1]==="*"){let b=e.indexOf("*/",c+2);c=b===-1?e.length:b+2;continue}if(/[A-Za-z_]/.test(I)){let b=c+1;while(b<e.length&&/[A-Za-z0-9_$]/.test(e[b]))b++;let E=e.slice(c,b).toUpperCase();if(p.length<3)p.push(E),f=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(f){if(E==="BEGIN"||E==="CASE"&&g>0)g++;else if(E==="END"&&g>0)g--}c=b;continue}if(I===";"&&g===0)x(c);c++}return x(e.length),n}var Ol=(e)=>({...e}),_l=(e)=>{let n;if(e.metadata)try{n=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!n?.["automations.id"])n={...n,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:n,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};class Ll{path;plugins;entryTransactions=[];db;blobs;constructor(e){this.path=e;this.db=b$(e,this.entryTransactions),this.blobs={put:(n,i,c)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(n,i,c)},get:(n)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(n)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY updated DESC").all().map(Ol)}project(e){let n=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return n?Ol(n):void 0}projectByDirectory(e){let n=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return n?Ol(n):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.id)}deleteProject(e){this.db.query("DELETE FROM projects WHERE id = ?").run(e)}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(_l)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(_l)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(_l)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((n)=>n.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,n,i){this.db.transaction(()=>{let c=or(this.records(e),i);this.insertSession(n),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(c.length,n.id);let p=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:f,raw:g}of c){let{seq:x,time:I,...b}=f,E=b,T=vl(E,this.blobs),k=g===void 0?null:JSON.stringify(Bc(E,g));p.run(n.id,x,I,JSON.stringify(T),k)}})()}truncationEpoch(e){let n=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!n)throw Error("Session no longer exists");return n.truncation_epoch}truncateSession(e,n){this.db.transaction(()=>{this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,n,n),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(n-1,e.id),this.updateSession(e)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,n){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let c of e)i.run(n,c)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.db.query("DELETE FROM sessions WHERE id = ?").run(e)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,n,i,c){As();let p=this.plugins,f=p?.pinEntry(i),g;try{return g=this.db.transaction(()=>{let x=Math.max(n??0,this.lastSeq(e)+1),b=(f&&p?p.beforeEntry(f,i,e,x):void 0)??i,E=JSON.stringify(b),T=f?JSON.parse(E):b,k={...T,seq:x,time:Date.now()},A=vl(T,this.blobs),L=A===T&&!f?E:JSON.stringify(A),q=c===void 0?null:JSON.stringify(Bc(T,c));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,x,k.time,L,q),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return k})(),g}finally{if(f&&p){let x={commit:()=>p.finishEntry(f,e,g),rollback:()=>p.finishEntry(f,e)},I=this.entryTransactions.at(-1);if(I)I.push(x);else x.commit()}}}setEntryRaw(e,n,i){let c=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,n);if(!c)throw Error("pending message entry is missing or already completed");let p=ha(JSON.parse(c.body),this.blobs),f=Bc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(f),e,n).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,n=0){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,n).map((i)=>({...ha(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}))}deleteEntry(e,n){this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,n)}entriesRange(e,n,i=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,n,i).map((c)=>({...ha(JSON.parse(c.body),this.blobs),seq:c.seq,time:c.time}))}alignToUser(e,n){if(n<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,n)?.seq??1}alignToTurnEnd(e,n){let i=this.lastSeq(e),c=(I)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,I),p=c(n),f=p?.type==="run"&&p.state==="start"?n+1:n;if(f>=i)return i;let g=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,f,f);if(!g)return i;if(g.end)return g.seq;let x=c(g.seq-1);return x?.type==="run"&&x.state==="start"&&g.seq-1>f?g.seq-2:g.seq-1}entriesAround(e,n,i,c){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let f=Math.min(Math.max(1,n),p),g=this.alignToUser(e,Math.max(1,f-i)),x=this.alignToTurnEnd(e,Math.min(p,f+c));return this.window(e,g,x,p)}entriesFrom(e,n,i){let c=this.lastSeq(e),p=Math.max(1,n);if(p>c)return{entries:[],from:p,to:c,hasBefore:c>0,hasAfter:!1};let f=this.alignToTurnEnd(e,Math.min(c,p+i-1));return this.window(e,p,f,c)}window(e,n,i,c){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,n);return{entries:this.entriesRange(e,n,i+1),from:n,to:i,hasBefore:p!==null,hasAfter:i<c}}replayStart(e,n,i){let c=this.lastSeq(e),p=this.lastEntry(e,"compaction"),f=p?.type==="compaction"?p.through+1:1,g=Math.max(1,c-i+1,Math.min(f,c-n+1));return this.alignToUser(e,g)}records(e,n=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,n).map((i)=>{let c=ha(JSON.parse(i.body),this.blobs);return{entry:{...c,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:ng(c,JSON.parse(i.raw))}}})}lastEntry(e,n){let i=this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,n);return i?{...ha(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,n){let i=this.truncationEpoch(e),c=n;if(this.plugins){let p=this.plugins.pin();try{let f=await p.invoke("notice.enqueue",n,this.plugins.runtime.get(e));if(f===null)return!1;n={...f,dedupeKey:c.dedupeKey,wake:c.wake&&f.wake,recovery:c.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==i)return!1;if(this.entries(e).some((x)=>x.type==="notice_pending"&&x.notice.dedupeKey===n.dedupeKey||x.type==="user"&&x.notices?.some((I)=>I.dedupeKey===n.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:n}),!0})()}pendingNotices(e){let n=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,n),c=new Set;for(let f of i)if(f.type==="user"&&f.notices)for(let g of f.notices)c.add(g.dedupeKey);else if(f.type==="extension"&&f.namespace==="basalt.notice"&&f.kind==="discarded"&&f.payload&&typeof f.payload==="object"&&"dedupeKey"in f.payload&&typeof f.payload.dedupeKey==="string")c.add(f.payload.dedupeKey);let p=[];for(let f of i)if(f.type==="notice_pending"&&!c.has(f.notice.dedupeKey))p.push(f.notice);return p}}function fe(e){let n=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(n).toString("base64url")}`}import{existsSync as ZB,readdirSync as S$,statSync as w$}from"fs";import{join as T$}from"path";function Gc(e){try{return w$(e).size}catch{return 0}}function R$(e){try{return Math.round(w$(e).mtimeMs)}catch{return}}function k$(e){let n=0,i=0;try{let c=S$(e,{withFileTypes:!0});for(let p of c){let f=T$(e,p.name);if(p.isDirectory()){let g=k$(f);n+=g.bytes,i+=g.files}else if(p.isFile())n+=Gc(f),i+=1}}catch{return{bytes:0,files:0}}return{bytes:n,files:i}}function eG(e){if(!ZB(e))return[];try{return S$(e,{withFileTypes:!0}).flatMap((n)=>{let i=T$(tG(e),n.name),c=R$(i);if(n.isDirectory()){let p=k$(i);return[{name:n.name,kind:"directory",bytes:p.bytes,files:p.files,...c!==void 0?{modified:c}:{}}]}if(n.isFile())return[{name:n.name,kind:"file",bytes:Gc(i),...c!==void 0?{modified:c}:{}}];return[]}).sort((n,i)=>i.bytes-n.bytes||n.name.localeCompare(i.name))}catch{return[]}}function tG(e){return e}function Bs(e,n){let i=e.db.query(`PRAGMA ${n}`).get();if(!i)return 0;let c=Object.values(i)[0];return typeof c==="number"?c:0}function E$(e,n){try{let i=e.db.query(`PRAGMA ${n}`).get();if(!i)return;let c=Object.values(i)[0];return c!==void 0&&c!==null?String(c):void 0}catch{return}}var rG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},nG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function oG(e){let n=new Map;try{let i=new Map,c=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let f of c)i.set(f.name,f.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let f of p){let g=i.get(f.name)??f.name;if(g.startsWith("sqlite_autoindex_")){let I=g.slice(17),b=I.lastIndexOf("_");if(b>0)g=I.slice(0,b)}let x=n.get(g)??{bytes:0,pages:0};n.set(g,{bytes:x.bytes+(Number(f.bytes)||0),pages:x.pages+(Number(f.pages)||0)})}}catch{}return n}function sG(e){let n=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
367
+ count(*) AS total,
368
+ sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
369
+ sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
370
+ sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
371
+ sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
372
+ FROM sessions`).get(),c=e.db.query(`SELECT
373
+ count(*) AS total,
374
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
375
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
376
+ min(time) AS oldest_time,
377
+ max(time) AS newest_time
378
+ FROM entries`).get(),f=e.db.query(`SELECT
379
+ coalesce(json_extract(body, '$.type'), 'unknown') AS type,
380
+ count(*) AS count,
381
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
382
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes
383
+ FROM entries
384
+ GROUP BY type
385
+ ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((I)=>({type:String(I.type||"unknown"),count:Number(I.count)||0,bodyBytes:Number(I.body_bytes)||0,rawBytes:Number(I.raw_bytes)||0})),g=f.find((I)=>I.type==="compaction")?.count??0,x=[];try{let I=new Map,b=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let k of b)I.set(k.namespace,Number(k.max_ver)||0);let E=e.db.query(`SELECT
386
+ namespace,
387
+ count(*) AS keys,
388
+ coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
389
+ FROM plugin_kv
390
+ GROUP BY namespace
391
+ ORDER BY bytes DESC, keys DESC`).all(),T=new Set;for(let k of E){T.add(k.namespace);let A=I.get(k.namespace);x.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...A!==void 0?{migrationVersion:A}:{}})}for(let[k,A]of I.entries())if(!T.has(k))x.push({namespace:k,keys:0,bytes:0,migrationVersion:A})}catch{}return{projectCount:n,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(c?.total)||0,totalBodyBytes:Number(c?.body_bytes)||0,totalRawBytes:Number(c?.raw_bytes)||0,compactionCount:g,...c?.oldest_time?{oldestEntryTime:Number(c.oldest_time)}:{},...c?.newest_time?{newestEntryTime:Number(c.newest_time)}:{},entryTypes:f,pluginNamespaces:x}}function Nl(e,n){let i=Bs(e,"page_size"),c=Bs(e,"page_count"),p=Bs(e,"freelist_count"),f=e.db.query("PRAGMA journal_mode").get(),g=e.db.query("SELECT sqlite_version() AS v").get(),x=Bs(e,"synchronous"),I=Bs(e,"auto_vacuum"),b=Bs(e,"cache_size"),E=b<0?Math.abs(b)*1024:b*i,T=Bs(e,"foreign_keys")===1,k=Bs(e,"busy_timeout"),A=E$(e,"encoding")??"UTF-8",L=E$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?R$(e.path):void 0,Z=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),B=oG(e),V=eG(n);return{dataDir:n,databasePath:e.path,dataBytes:V.reduce((X,ie)=>X+ie.bytes,0),database:{size:Gc(e.path),walSize:Gc(`${e.path}-wal`),shmSize:Gc(`${e.path}-shm`),sqliteVersion:g?.v??"unknown",journalMode:f?.journal_mode??"unknown",synchronous:rG[x]??String(x),foreignKeys:T,busyTimeout:k,encoding:A,autoVacuum:nG[I]??String(I),cacheSizeBytes:E,pageSize:i,pageCount:c,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Bs(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:L},analytics:sG(e),entries:V,tables:Z.map(({name:X,sql:ie})=>{let Y=X.replaceAll('"','""'),z=e.db.query(`SELECT count(*) AS count FROM "${Y}"`).get().count,ce=e.db.query(`PRAGMA table_info("${Y}")`).all().map((se)=>se.name),he=e.db.query(`PRAGMA index_list("${Y}")`).all().length,ve=Boolean(ie&&/WITHOUT\s+ROWID/i.test(ie)),de=B.get(X);return{name:X,rows:z,...de?{bytes:de.bytes,pages:de.pages}:{},indexes:he,columns:ce,withoutRowid:ve}})}}function iG(e){let n;try{n=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(n.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),c=new Set;for(let f of i)for(let g of f.body.matchAll(/@blob:([0-9a-f]{64})/g)){let x=g[1];if(x)c.add(x)}let p=[];for(let f of n)if(!c.has(f.hash))p.push(f.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let f=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let g of p)f.run(g)})()}catch{return 0}return p.length}function A$(e,n,i){let c=Nl(e,n);if(i.vacuum)x$(e.db),iG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:c,after:Nl(e,n)}}var aG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Dl{plugins;builtinNames;registered=new Map;constructor(e,n){this.plugins=e;this.builtinNames=n}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let n=e.name.trim().toLowerCase();if(!n)throw Error("Tool name cannot be empty");if(aG.has(n))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((c)=>c.toLowerCase()),...this.list().map((c)=>c.name.toLowerCase())]).has(n))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(n,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function C$(e,n){let i=Vr(n);return{id:e,name:n.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:n.contextWindow,maxTokens:n.maxTokens}}async function P$(e,n){let c=(await e.options.models.getAvailable().catch(()=>[])).map((f)=>({...C$(tt(f),f),available:!0})),p=new Set(c.map((f)=>f.id));for(let f of[n,...e.list(!0,{archive:"all"}).map((g)=>g.model)]){if(p.has(f))continue;let g=Dn(e.options.models,f);if(!g)continue;p.add(f),c.push({...C$(f,g),available:!1})}return{models:c}}function $$(e,n){if(typeof n!=="string"||!Dn(e.options.models,n))throw new r(`unknown model ${n}`);return n}import{existsSync as uG,statSync as cG}from"fs";import{basename as mG,resolve as pG}from"path";class sg{runtime;sessions;emit;arm;constructor(e,n,i,c){this.runtime=e;this.sessions=n;this.emit=i;this.arm=c}requireProject(e){let n=this.runtime.store.project(e);if(!n)throw new y("no such project");return n}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new r("directory is required");let n=pG(e.directory.trim());if(!uG(n)||!cG(n).isDirectory())throw new r(`${n} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(n);if(i)return i;let c=Date.now(),p={id:fe("p"),name:e.name?.trim()||mG(n)||n,directory:n,instructions:e.instructions??"",created:c,updated:c};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,n){let c={...this.requireProject(e),...typeof n.name==="string"&&n.name.trim()?{name:n.name.trim()}:{},...typeof n.instructions==="string"?{instructions:n.instructions}:{},updated:Date.now()};this.runtime.store.updateProject(c);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:c}),c}async deleteProject(e){let n=this.requireProject(e),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new oe("a session in this project");await this.runtime.plugins.invokeProjectDelete(n),this.runtime.store.deleteProject(e);for(let p of i)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as vG,readFileSync as OG}from"fs";import{homedir as _G}from"os";import{join as mu}from"path";var D$=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),lG={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"]},dG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),ug={'"':['"'],"\u201C":["\u201D",'"']},ig=(e)=>e!==void 0&&/\s/.test(e),q$=(e)=>[...new Set(e)],Kc=(e)=>[...e].length;var fG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function hG(e,n){let i=e.trim().toLowerCase(),c=new Date(n),p=c.getFullYear(),f=c.getMonth(),g=c.getDate();if(i==="today")return{start:new Date(p,f,g).getTime(),end:new Date(p,f,g+1).getTime()};if(i==="yesterday")return{start:new Date(p,f,g-1).getTime(),end:new Date(p,f,g).getTime()};let x=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(x)return{start:n-Number(x[1])*fG[x[2]]};if(/^\d{4}$/.test(i))return{start:new Date(Number(i),0,1).getTime(),end:new Date(Number(i)+1,0,1).getTime()};let I=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!I)return null;let b=Number(I[1]),E=Number(I[3]);if(E<1||E>12)return null;if(I[4]===void 0){if(I[5]!==void 0)return null;return{start:new Date(b,E-1,1).getTime(),end:new Date(b,E,1).getTime()}}let T=Number(I[4]),k=Number(I[5]??0),A=Number(I[6]??0),L=Number(I[7]??0);if(k>23||A>59||L>59)return null;let q=new Date(b,E-1,T,k,A,L);if(q.getMonth()!==E-1||q.getDate()!==T)return null;if(I[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(b,E-1,T+1).getTime()}}var gG=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),cg=(e,n)=>e===void 0?n:n===void 0?e:Math.max(e,n),mg=(e,n)=>e===void 0?n:n===void 0?e:Math.min(e,n);function ag(e,n,i,c,p,f){let g=i.trim(),x=(b,E)=>e.diagnostics.push({code:b,message:E,filter:n});if(!g)return x("empty_filter",`${n}: \u7F3A\u5C11\u53D6\u503C`);if(c&&n!=="is")return x("unsupported_negation",`-${n}: \u4E0D\u652F\u6301\u53D6\u53CD`);let I=p?[g]:g.split(",").map((b)=>b.trim()).filter(Boolean);switch(n){case"in":case"project":for(let b of I){let E=b.toLowerCase();if(n==="in"&&E==="this")e.currentSession=!0;else if(n==="in"&&E==="title")e.fields.push("title");else e.projectID.push(b)}return;case"session":for(let b of I)if(b.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(b);return;case"from":case"role":for(let b of I){let E=lG[b.toLowerCase()];if(E)e.fields.push(...E);else x("bad_filter_value",`${n}:${b} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...I);return;case"model":e.model.push(...I);return;case"is":for(let b of I){let E=b.toLowerCase();if(E==="error")e.isError=!c;else if(E==="archived")e.archived=!c;else if(E==="compacted")e.compacted=!c;else x("bad_filter_value",`is:${b} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let b=hG(g,f);if(!b)return x("bad_filter_value",`${n}:${g} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(n==="after")e.after=cg(e.after,b.start);else if(n==="before")e.before=mg(e.before,b.start);else if(e.after=cg(e.after,b.start),b.end!==void 0)e.before=mg(e.before,b.end)}}}function yG(e,n){let i={},c=(L,q)=>{let Z=q$([...L??[],...q]);return Z.length?Z:void 0},p=c(e?.projectID,n.projectID),f=c(e?.sessionID,n.sessionID),g=c(e?.fields,n.fields),x=c(e?.tools,n.tools),I=c(e?.model,n.model);if(p)i.projectID=p;if(f)i.sessionID=f;if(g)i.fields=g;if(x)i.tools=x;if(I)i.model=I;let b=n.isError??e?.isError,E=n.archived??e?.archived,T=n.compacted??e?.compacted;if(b!==void 0)i.isError=b;if(E!==void 0)i.archived=E;if(T!==void 0)i.compacted=T;let k=cg(e?.after,n.after),A=mg(e?.before,n.before);if(k!==void 0)i.after=k;if(A!==void 0)i.before=A;if(k!==void 0&&A!==void 0&&k>=A)n.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function M$(e,n){let i=ug[e[n]]??['"'],c="",p=n+1;while(p<e.length){let f=e[p],g=e[p+1];if(f==="\\"&&g!==void 0&&(g==="\\"||g==='"'||g==="\u201C"||g==="\u201D")){c+=g,p+=2;continue}if(i.includes(f))return{text:c,next:p+1,closed:!0};c+=f,p++}return{text:c,next:p,closed:!1}}function v$(e){let n=e[e.length-1];if(e.length<2||!n||n.esc||n.c!==":"&&n.c!=="\uFF1A")return;let i=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(i.length!==e.length-1)return;let c=i.toLowerCase();return D$.has(c)?c:void 0}function O$(e,n,i){let c=e==="word"&&!i&&Kc(n)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(n)&&!/^\p{N}+$/u.test(n);return{kind:e,text:n,prefix:i,fuzzy:c}}function xG(e,n){let i=[],c=e.length,p=0;while(p<c){if(ig(e[p])){p++;continue}let f=!1;if(e[p]==="-"){if(p+1>=c||ig(e[p+1])){p++;continue}f=!0,p++}if(ug[e[p]]){let A=M$(e,p);if(p=A.next,!A.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let L=A.text.trim();if(L)i.push({kind:"term",negated:f,term:O$("phrase",L,!1)});continue}let g=[],x;while(p<c&&!ig(e[p])){let A=e[p],L=e[p+1];if(A==="\\"&&L!==void 0&&dG.has(L)){g.push({c:L,esc:!0}),p+=2;continue}let q=ug[A]?v$(g):void 0;if(q){let Z=M$(e,p);if(p=Z.next,!Z.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});x={key:q,value:Z.text,quoted:!0};break}g.push({c:A,esc:!1}),p++}if(x){i.push({kind:"filter",negated:f,...x});continue}let I=g.findIndex((A,L)=>L>0&&!A.esc&&(A.c===":"||A.c==="\uFF1A")),b=I>0?v$(g.slice(0,I+1)):void 0;if(b){i.push({kind:"filter",negated:f,key:b,value:g.slice(I+1).map((A)=>A.c).join(""),quoted:!1});continue}if(!f&&g.length===2&&g.every((A)=>!A.esc)&&g[0]?.c==="O"&&g[1]?.c==="R"){i.push({kind:"or"});continue}let E=g[g.length-1],T=g.length>1&&E!==void 0&&!E.esc&&E.c==="*",k=(T?g.slice(0,-1):g).map((A)=>A.c).join("");if(k)i.push({kind:"term",negated:f,term:O$("word",k,T)})}return i}var IG=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function _$(e){let n=[];return{rest:e.replace(IG,(c,p,f,g,x)=>{let I=g.toLowerCase();if(!D$.has(I))return c;let b=x.startsWith('"')&&x.length>=2;return n.push({key:I,value:b?x.slice(1,-1).replace(/\\(["\\])/g,"$1"):x,negated:f==="-",quoted:b}),p}).trim(),filters:n}}var L$={n:`
392
+ `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function bG(e){let n=[...e],i=0,c=(E)=>{let T=n.slice(i,i+E).join("");if(T.length!==E||!/^[0-9a-fA-F]+$/.test(T))return;return i+=E,String.fromCodePoint(Number.parseInt(T,16))},p=()=>{let E=n[i++];if(E===void 0)return{kind:"lit",ch:"\\"};if(E in L$)return{kind:"lit",ch:L$[E]};if("dDwWsS".includes(E))return{kind:"any"};if(E==="b"||E==="B")return{kind:"zero"};if(E>="1"&&E<="9"){while(n[i]!==void 0&&/\d/.test(n[i]))i++;return{kind:"any"}}if(E==="k"||E==="p"||E==="P"){let T=n[i];if(T==="<"||T==="{"){let k=T==="<"?">":"}",A=n.indexOf(k,i);i=A<0?n.length:A+1}return{kind:"any"}}if(E==="c")return i++,{kind:"any"};if(E==="x"){let T=c(2);return T===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:T}}if(E==="u"){if(n[i]==="{"){let k=n.indexOf("}",i),A=k<0?"":n.slice(i+1,k).join("");if(/^[0-9a-fA-F]{1,6}$/.test(A)&&Number.parseInt(A,16)<=1114111)return i=k+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(A,16))};return{kind:"lit",ch:"u"}}let T=c(4);return T===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:T}}return{kind:"lit",ch:E}},f=()=>{if(n[i]==="^")i++;while(i<n.length&&n[i]!=="]")i+=n[i]==="\\"?2:1;return i++,{kind:"any"}},g=()=>{let E="capture";if(n[i]==="?"){let k=n[i+1],A=n[i+2];if(k===":")E="plain",i+=2;else if(k==="="||k==="!")E="look",i+=2;else if(k==="<"&&(A==="="||A==="!"))E="look",i+=3;else if(k==="<"){let L=n.indexOf(">",i);i=L<0?n.length:L+1}else{E="opaque";while(i<n.length&&n[i]!==":"&&n[i]!==")")i++;if(n[i]===":")i++}}let T=b();if(n[i]===")")i++;if(E==="look")return{kind:"zero"};return{kind:"group",alts:T,opaque:E==="opaque"}},x=()=>{let E=n[i],T=1,k=!0;if(E==="*"||E==="?")T=0,i++;else if(E==="+")i++;else if(E==="{"){let A=/^\{(\d+)(?:,(\d*))?\}/.exec(n.slice(i,i+24).join(""));if(!A)return{quantified:!1,min:1};T=Number(A[1]),i+=A[0].length}else return{quantified:!1,min:1};if(n[i]==="?")i++;return{quantified:k,min:T}},I=()=>{let E=[];while(i<n.length){let T=n[i];if(T==="|"||T===")")break;i++;let k;if(T==="(")k=g();else if(T==="[")k=f();else if(T==="\\")k=p();else if(T===".")k={kind:"any"};else if(T==="^"||T==="$")k={kind:"zero"};else if(T==="*"||T==="+"||T==="?")k={kind:"zero"};else k={kind:"lit",ch:T};E.push({atom:k,...x()})}return E};function b(){let E=[I()];while(n[i]==="|")i++,E.push(I());return E}return b()}function N$(e){let n=[],i="",c=()=>{if(i)n.push([i]);i=""},p=(f)=>{for(let g of f){let x=g.atom;if(x.kind==="lit")if(g.min>=1){if(i+=x.ch,g.quantified)c()}else c();else if(x.kind==="group"&&!x.opaque&&g.min>=1)if(x.alts.length===1&&!g.quantified)p(x.alts[0]);else c(),n.push(...F$(x.alts));else c()}};return p(e),c(),n}function F$(e){if(e.length===1)return N$(e[0]);let n=[];for(let i of e){let c=N$(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!c.length)return[];n.push(c.reduce((p,f)=>Kc(f)>Kc(p)?f:p))}return[q$(n)]}var EG=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function SG(e){return!/^\s*$/.test(e)&&(Kc(e)>=2||EG.test(e))}function wG(e){let n;try{n=F$(bG(e))}catch{return[]}let i=n.filter((I)=>I.every(SG)),c=i.filter((I)=>I.length===1).map((I)=>I[0]),p=i.filter((I)=>{if(I.length!==1)return!0;let b=I[0];return!c.some((E)=>E!==b&&E.includes(b))}),f=new Set,g=p.filter((I)=>{let b=JSON.stringify(I);if(f.has(b))return!1;return f.add(b),!0}),x=(I)=>Math.min(...I.map(Kc));return g.sort((I,b)=>x(b)-x(I))}function TG(e){let n=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(n)}function RG(e,n){let i=`m${n?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(c){let p=c instanceof Error?c.message:String(c),f="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))f="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))f="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))f="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))f="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${f}`}}}function ql(e,n={}){let i=n.now??Date.now(),c=e.q??"",p=gG(),f=p.diagnostics,g,x=[];if(e.mode==="regex"){let q=_$(c);for(let Z of q.filters)ag(p,Z.key,Z.value,Z.negated,Z.quoted,i);g=q.rest}else{let q=_$(c),Z=/^\/([\s\S]+)\/$/.exec(q.rest);if(Z){for(let B of q.filters)ag(p,B.key,B.value,B.negated,B.quoted,i);g=Z[1]}else{x=[{include:[],exclude:[]}];for(let B of xG(c,f)){let V=x[x.length-1];if(B.kind==="or")x.push({include:[],exclude:[]});else if(B.kind==="filter")ag(p,B.key,B.value,B.negated,B.quoted,i);else(B.negated?V.exclude:V.include).push(B.term)}x=x.filter((B)=>B.include.length||B.exclude.length)}}let I=x.flatMap((q)=>[...q.include,...q.exclude]),b=g!==void 0?TG(g):I.some((q)=>/\p{Lu}/u.test(q.text)),E=e.caseSensitive??b,T=e.caseSensitive===void 0&&b,k,A;if(g){let q=RG(g,E);if("message"in q)A={code:"bad_regex",message:q.message};else{let Z=wG(g);k={source:g,flags:q.flags,literals:Z,deepScan:Z.length===0}}}let L=yG(e.filters,p);return{mode:g!==void 0?"regex":"text",branches:x,...k?{regex:k}:{},filters:L,currentSession:p.currentSession,caseSensitive:E,smartCase:T,wholeWord:e.wholeWord??!1,fuzzy:x.some((q)=>q.include.some((Z)=>Z.fuzzy)),hasPositive:k!==void 0||x.some((q)=>q.include.length>0),hasFilters:Object.keys(L).length>0||p.currentSession,...A?{error:A}:{},diagnostics:f}}var lg={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},j$=new WeakMap;function U$(e){let n=e.query("PRAGMA data_version").get()?.data_version??0,i=j$.get(e);if(i?.version===n)return i.terms;let c=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return j$.set(e,{version:n,terms:c}),c}var pg=32,kG=1024,Hc=(e)=>`"${e.replaceAll('"','""')}"`;function AG(e,n){let i=Array.from({length:n.length+1},(c,p)=>p);for(let c=0;c<e.length;c++){let p=[c+1];for(let f=0;f<n.length;f++)p.push(Math.min((p[f]??0)+1,(i[f+1]??0)+1,(i[f]??0)+Number(e[c]!==n[f])));i=p}return i[n.length]??e.length}function dg(e,n){let i=ft(n.trim());if(!i||i.length>64)return[];let c=U$(e),p=c.filter((x)=>x.t.startsWith(i)).slice(0,8).map((x)=>x.t);if(p.length>=8||i.length<4)return p;let f=i.length>=8?2:1,g=[];for(let x of c){if(Math.abs(x.t.length-i.length)>f)continue;if(AG(i,x.t)<=f)g.push(x.t);if(g.length>=8)break}return[...new Set([...p,...g])].slice(0,8)}function B$(e,n){let i=!1,c=[],p=[],f=n.filters,g=(Z,B)=>{if(!B?.length)return;p.push(`${Z} IN (${B.map(()=>"?").join(",")})`),c.push(...B)};if(g("s.project_id",f.projectID),f.sessionID?.length){p.push(`(${f.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let Z of f.sessionID)c.push(Z,Z)}if(f.archived!==void 0)p.push(`s.archived_at IS ${f.archived?"NOT ":""}NULL`);let x=p.length?p.join(" AND "):"1",I=[...c];if(g("r.kind",f.fields?.map((Z)=>Oe[Z])),g("r.tool",f.tools),f.model?.length){p.push(`(${f.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let Z of f.model)c.push(Z,Z)}if(f.isError!==void 0)p.push("r.err = ?"),c.push(Number(f.isError));if(f.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
393
+ SELECT max(json_extract(body,'$.through')) FROM store.entries
394
+ WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
395
+ ),0)) = ?`),c.push(Number(f.compacted));if(f.after!==void 0)p.push("r.time >= ?"),c.push(f.after);if(f.before!==void 0)p.push("r.time < ?"),c.push(f.before);let b=e.query("SELECT v FROM meta WHERE k='layout'").get(),E=b&&JSON.parse(b.v).msg==="trigram",T=!n.hasPositive||Boolean(n.regex?.deepScan),k=(Z)=>{let B=(ie)=>{let Y=ft(ie);if(!Z&&E){if([...Y].length<3){let se=[...Y].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(Y,`${Y}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(Y);if([...Y].length===1&&se.length>pg)se.length=pg,i=!0;if(!se.length)return Hc("__basalt_no_short_match__");return`(${se.map((me)=>Hc(me.term)).join(" OR ")})`}return Hc(Y)}let z=/^[\p{Script=Latin}\p{N}]+$/u.test(ie)?[Y]:qo(ie),ce=z.filter((se)=>!/^[a-z0-9]{1,2}$/.test(se)),he=ce.length?ce:z;if(!he.length){T=!0;return}let ve=he.map((se,me)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(se),xt=he.length>2&&me>0&&me<he.length-1;if(qe||xt){let Fe=e.query("SELECT n FROM term WHERE t=?").get(se)?.n??0;return{expression:Hc(se),frequency:Fe}}let Qe=[se],Yt=0;for(let Fe of U$(e)){if(!Fe.t.includes(se))continue;if(Yt+=Fe.n,Fe.t!==se)Qe.push(Fe.t);if(Qe.length>=pg){i=!0;break}}return{expression:`(${Qe.map(Hc).join(" OR ")})`,frequency:Yt}});return ve.sort((se,me)=>se.frequency-me.frequency),`(${ve.slice(0,(ve[0]?.frequency??1/0)<=kG?1:2).map((se)=>se.expression).join(" AND ")})`},V=n.regex?n.regex.literals:n.branches.map((ie)=>ie.include.map((Y)=>Y.text));if(n.regex){let ie=V.map((Y)=>Y.map(B));if(ie.some((Y)=>Y.some((z)=>!z)))return;return ie.map((Y)=>`(${Y.join(" OR ")})`).join(" AND ")||void 0}let X=V.map((ie)=>{let Y=ie.filter((z)=>!/^[a-z0-9]{1,2}$/i.test(z));return(Y.length?Y:ie).map(B)});if(X.some((ie)=>!ie.length||ie.some((Y)=>!Y)))return;return X.map((ie)=>`(${ie.join(" AND ")})`).join(" OR ")||void 0},A=k(!1),L=k(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:A,out:L,scan:T,where:p.length?p.join(" AND "):"1",bindings:c,forks:q,sessionWhere:x,sessionBindings:I,partial:i,candidateLimit:n.branches.some((Z)=>Z.include.length>0&&Z.include.every((B)=>[...B.text].length<2))?512:void 0}}function G$(e){let n=1/0,i=-1/0;for(let c of e)n=Math.min(n,c.relevance),i=Math.max(i,c.relevance);return e.map((c)=>({...c,relevance:n===i?-1:-(0.5+0.5*(i-c.relevance)/(i-n))}))}function Fl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(lg).map(([i,c])=>`WHEN ${Oe[i]} THEN ${c}`).join(" ")} ELSE 1 END) *
396
+ (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function K$(e,n,i,c){let p=Math.max(0,c-i)/86400000;return Math.max(0.000000001,-e)*lg[n]*(0.3+0.7/(1+p/30))}function fg(e,n){return e.sort((i,c)=>(n==="best"?c.score-i.score:0)||(n==="recent"?c.time-i.time:0)||(i.sessionID<c.sessionID?-1:Number(i.sessionID>c.sessionID))||c.seq-i.seq||i.field.localeCompare(c.field))}var gg=512;function H$(e,n,i){let c=performance.now(),p=n.partial;yg(e,n),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[f,g]of[["fts",n.msg],["fts_out",n.out]]){if(!g)continue;let x=n.candidateLimit??2000,I=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
397
+ ORDER BY ${n.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(g,n.candidateLimit?x+1:x);if(n.candidateLimit&&I.length>x)I.length=x,p=!0;else if(!n.candidateLimit&&I.length===x){let E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${f} WHERE ${f} MATCH ?
398
+ AND rowid NOT IN (SELECT value FROM json_each(?))`).all(g,JSON.stringify(I.map((T)=>T.doc)));for(let T of E)I.push(T)}let b=G$(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
399
+ FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(b))}return i?.("match",performance.now()-c),p}function W$(e,n,i,c,p){let f=performance.now();if(n.candidateLimit){let x=e.query(`
400
+ SELECT r.session_id,r.seq,${Fl(c)} AS score
401
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
402
+ ${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
403
+ WHERE ${n.where} LIMIT ${n.candidateLimit+1}
404
+ `).all(...n.bindings);if(x.length>n.candidateLimit)x.length=n.candidateLimit,n.partial=!0;let I=new Map;for(let b of x){let E=i?b.seq:0,T=JSON.stringify([b.session_id,E]),k=I.get(T);if(!k||b.score>k.score)I.set(T,{...b,seq:E})}return p?.("filter",performance.now()-f),[...I.values()].sort((b,E)=>E.score-b.score||(b.session_id<E.session_id?-1:Number(b.session_id>E.session_id))||E.seq-b.seq)}let g=e.query(`
405
+ SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Fl(c)}) AS score
406
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
407
+ ${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
408
+ WHERE ${n.where}
409
+ GROUP BY r.session_id${i?",r.seq":""}
410
+ ORDER BY score DESC,r.session_id,seq DESC LIMIT ${n.candidateLimit?n.candidateLimit+1:-1}
411
+ `).all(...n.bindings);return p?.("filter",performance.now()-f),g}var z$=new WeakMap,CG=`WITH RECURSIVE lineage(child,ancestor,through) AS (
412
+ SELECT id,forked_from_id,forked_from_seq FROM store.sessions
413
+ WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
414
+ UNION
415
+ SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
416
+ FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
417
+ WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
418
+ )`;function yg(e,n){if(!n.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${CG} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let i=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();z$.set(e,new Map(i.map((c)=>[c.ancestor,c.through])))}function hg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
419
+ SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
420
+ JOIN store.sessions ps ON ps.id=pr.session_id
421
+ WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
422
+ AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
423
+ AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
424
+ SELECT 1 FROM store.entries original JOIN store.entries copied
425
+ ON copied.session_id=r.session_id AND copied.seq=r.seq
426
+ WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
427
+ ))
428
+ ))`}function V$(e,n,i,c,p){let f=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let g=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,x=n.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
429
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${g>4000?"INDEXED BY ref_time":""}
430
+ ${x} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${n.where} AND ${hg(n)}
431
+ ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${c} OFFSET ?`).run(...n.bindings,...n.forks?n.bindings:[],i);let I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(I===c){let b=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(b)e.query(`
432
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${x}
433
+ WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
434
+ AND ${n.where} AND ${hg(n)} AND NOT EXISTS (
435
+ SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
436
+ )`).run(b.session_id,b.seq,...n.bindings,...n.forks?n.bindings:[]),I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-f),I}function Q$(e,n,i,c,p,f,g){let x=performance.now(),I=n.group==="none",b=n.sort==="recent"?"time DESC":"relevance DESC,time DESC",E=e.query(`
437
+ SELECT r.session_id,${I?"r.seq":"0"} AS seq,
438
+ max(${Fl(p)}) AS relevance,max(r.time) AS time
439
+ FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
440
+ WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
441
+ GROUP BY r.session_id${I?",r.seq":""}
442
+ ORDER BY ${b},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(f),c,i);return g?.("group",performance.now()-x),E}function J$(e,n,i,c,p,f){let g=performance.now(),x=p?n:{...n,forks:!1},I=e.query(`
443
+ SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
444
+ ${x.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
445
+ WHERE r.session_id=? ${c?"AND r.seq=?":""}
446
+ AND ${n.where} AND ${hg(x)}
447
+ ${n.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${n.candidateLimit+1}`:""}`).all(i.session_id,...c?[i.seq]:[],...n.bindings,...x.forks?n.bindings:[]);return f?.("filter",performance.now()-g),I}function xg(e,n,i,c){if(!n.forks)return[];let p=z$.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
448
+ SELECT DISTINCT r.session_id,s.title,e.body
449
+ FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
450
+ CROSS JOIN ref r ON r.session_id=l.child
451
+ JOIN store.sessions s ON s.id=r.session_id
452
+ LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
453
+ WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${n.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...n.bindings).filter((f)=>{if(i.seq===0)return f.title===c;if(!f.body)return!1;let g=JSON.parse(f.body);return Ke(g,!0).some((x)=>x.part===i.part&&x.kind===Qr[i.kind]&&x.text===c)}).map((f)=>f.session_id)}function PG(e,n){let i=n?e:ft(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let c="",p=[],f=[],g=0;for(let x of e){let I=n?x:ft(x);c+=I;for(let b=0;b<I.length;b++)p.push(g),f.push(g+x.length);g+=x.length}return{normalized:c,starts:p,ends:f}}function jl(e,n){if(n.regex){let I=new RegExp(n.regex.source,`${n.regex.flags}g`),b=[];for(let E of e.matchAll(I)){if(n.wholeWord&&!X$(e,E.index,E.index+E[0].length))continue;b.push([E.index,E.index+E[0].length])}return b.length?b:void 0}let{normalized:i,starts:c,ends:p}=PG(e,n.caseSensitive),f=(I)=>{let b=n.caseSensitive?I.text:ft(I.text),E=[],T=i.indexOf(b);while(T>=0&&b){let k=c?c[T]:T,A=p?p[T+b.length-1]:T+b.length,L=k===0||k!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(k-1,k))||/[a-z0-9][A-Z]/.test(e.slice(k-1,k+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(I.text));if(k!==void 0&&A!==void 0&&(!I.prefix||L)&&(!n.wholeWord||X$(e,k,A)))E.push([k,A]);T=i.indexOf(b,T+Math.max(1,b.length))}return E};if(!n.branches.length)return[];let g=[],x=!1;for(let I of n.branches){if(I.exclude.some((E)=>f(E).length))continue;let b=I.include.map(f);if(b.some((E)=>!E.length))continue;x=!0,g.push(...b.flat())}return x?g:void 0}function X$(e,n,i){let c=/[\p{L}\p{N}_]/u;return(n===0||!c.test(e.slice(n-1,n)))&&(i===e.length||!c.test(e.slice(i,i+1)))}function Ul(e,n){let i=e.split(`
454
+ `),c=new Set,p=0,f=i.map((g,x)=>{let I=p;if(n.some(([b,E])=>b<=I+g.length&&E>=I))for(let b=Math.max(0,x-1);b<=Math.min(i.length-1,x+1);b++)c.add(b);return p+=g.length+1,I});if(!c.size)c.add(0);return[...c].sort((g,x)=>g-x).slice(0,5).map((g)=>{let x=i[g]??"",I=f[g]??0,b=n.filter(([A,L])=>L>I&&A<I+x.length),E=Math.max(0,(b[0]?.[0]??I)-I-100),T=x.slice(E,E+300),k=b.map(([A,L])=>[Math.max(0,A-I-E),Math.min(T.length,L-I-E)]);return{text:T,line:g+1,ranges:k.filter(([A,L])=>A<L)}})}var Y$=3;function $G(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 Z$(e,n){return n.score-e.score||(e.sessionID<n.sessionID?-1:Number(e.sessionID>n.sessionID))||n.seq-e.seq}function MG(e,n){if(!e)return{offset:0,key:n,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===n&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let c="window"in i?i.window:0,p="seen"in i?i.seen:[],f="emitted"in i?i.emitted:[],g="after"in i?i.after:void 0;if(g!==void 0&&!$G(g))throw Error("invalid best cursor");let x=(I)=>Array.isArray(I)&&I.every((b)=>typeof b==="string"&&b.length<=1024);if(typeof c==="number"&&Number.isSafeInteger(c)&&c>=0&&x(p)&&x(f))return{offset:i.offset,key:n,now:i.now,window:c,seen:p,emitted:f,after:g}}}catch{}throw Error("invalid search cursor")}function Bn(e,n){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:n})).toString();return MG(e.cursor,i)}async function qr(e,n,i){let c="search"in e?e.search:e,p=performance.now(),f=(Fe)=>{if(!i.signal?.aborted)i.onEvent(Fe)};if(i.signal?.aborted)return;let g=Bn(n,i.sessionID);if(n.filters?.sessionID?.length===1)n={...n,group:"none"};let x=ql(n,{now:g.now});if(x.error){f({type:"error",...x.error});return}if(x.currentSession){if(!i.sessionID){f({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}x.filters.sessionID=[i.sessionID]}if(!n.deep&&x.regex?.deepScan){f({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let I=performance.now(),b=c.withIndex((Fe)=>B$(Fe,x));if(!b){f({type:"error",code:"unavailable",message:c.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}i.onTiming?.("plan",performance.now()-I);let E=b.partial,T=g.after,k=new Map,A=new Map,L=[],q=!1,Z=new Map,B=new WeakMap,V=new Map,X=new Map,{offset:ie,window:Y}=g,z=[...g.seen],ce=[...g.emitted],he=!1,ve=Math.max(1,Math.min(200,n.limit??30)),de=Math.min(b.candidateLimit??2000,n.group==="none"?gg:Math.min(2000,Math.max(gg,ve*32))),se=(Fe,Ue)=>{let Ft=k.get(Ue);if(Ft)return Ft;let lt=Fe.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Ue);if(lt)k.set(Ue,lt);return lt??void 0},me=(Fe,Ue,Ft)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(Ue.session_id))return;if(i.excludeEntry?.sessionID===Ue.session_id&&i.excludeEntry.seq===Ue.seq)return;let lt=se(Fe,Ue.session_id);if(!lt)return;let vt=Qr[Ue.kind];if(!vt)return;let fr=lt.title;if(Ue.seq!==0){let st=`${Ue.session_id}:${Ue.seq}`,Qt=X.get(st);if(!Qt){let on=Ft?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!Ft&&!on)return;let Ht=Ft??JSON.parse(on?.body??"null");Qt=Ke(Ht,!0),X.set(st,Qt)}let Zt=Qt.find((on)=>on.part===Ue.part&&on.kind===vt);if(!Zt)return;fr=Zt.text}let mr=jl(fr,x);if(!mr)return;let Ut=A.get(lt.id);if(Ut===void 0)Ut=Fe.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(lt.id)?.through??0,A.set(lt.id,Ut);let ot=Ue.seq>0&&Ue.seq<=Ut;if(x.filters.compacted!==void 0&&ot!==x.filters.compacted)return;let At={sessionID:lt.id,seq:Ue.seq,time:Ue.time,field:vt,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:K$(Ue.relevance,vt,Ue.time,g.now),flags:{archived:lt.archived_at!==null,compacted:ot,partial:fr.length>xi+wi}};return Z.set(At,{text:fr,ranges:mr}),L.push(At),q=!0,V.set(At,{doc:Ue.doc,part:Ue.part}),At},qe=(Fe)=>{let Ue=performance.now(),Ft=[...Fe].sort((ot,At)=>ot.time-At.time||ot.sessionID.localeCompare(At.sessionID)),lt=[],vt=new Map;for(let ot of Ft){let At=V.get(ot),Qt=k.get(ot.sessionID),Zt=new Set;while(Qt?.forked_from_id&&Qt.forked_from_seq!==null&&ot.seq<=Qt.forked_from_seq&&!Zt.has(Qt.id))Zt.add(Qt.id),Qt=k.get(Qt.forked_from_id)??c.withIndex((xo)=>se(xo,Qt?.forked_from_id??""));let on=`${Qt?.id??ot.sessionID}:${ot.seq}:${At?.part}:${At?.doc}`,Ht=vt.get(on);if(Ht){if(Ht.sessionID!==ot.sessionID)Ht.forks=[...new Set([...Ht.forks??[],ot.sessionID])]}else vt.set(on,ot),lt.push(ot)}let fr=[],mr=new Map,Ut=new Map;for(let ot of lt){let At=`${ot.sessionID}:${ot.seq}`,st=Ut.get(At);if(!st){Ut.set(At,ot),B.set(ot,[ot]);continue}let Qt=[...B.get(st)??[st],ot],Zt=ot.score>st.score?ot:st;if(Zt.forks=[...new Set([...st.forks??[],...ot.forks??[]])],!Zt.forks.length)Zt.forks=void 0;Zt.flags={archived:st.flags.archived||ot.flags.archived,compacted:st.flags.compacted||ot.flags.compacted,partial:st.flags.partial||ot.flags.partial},Ut.set(At,Zt),B.set(Zt,Qt)}for(let ot of fg([...Ut.values()],n.sort??"best")){let At=k.get(ot.sessionID);if(!At)continue;let st=n.group==="none"?void 0:mr.get(At.id);if(!st)st={session:{id:At.id,title:At.title,projectID:At.project_id,updated:At.updated},hits:[],more:0,...E&&n.group!=="none"?{moreIsLowerBound:!0}:{}},fr.push(st),mr.set(At.id,st);if(st.hits.length<Y$||n.group==="none")st.hits.push(ot);else st.more++}return i.onTiming?.("group",performance.now()-Ue),fr},xt=(Fe)=>{for(let Ue of Fe)for(let Ft of Ue.hits){if(i.allowedSessionIDs&&Ft.forks)Ft.forks=Ft.forks.filter((fr)=>i.allowedSessionIDs?.has(fr));let lt=performance.now(),vt=new Map;for(let fr of B.get(Ft)??[Ft]){let mr=Z.get(fr);if(!mr)continue;for(let Ut of Ul(mr.text,mr.ranges)){let ot=`${Ut.line}:${Ut.text}`,At=vt.get(ot);if(!At)vt.set(ot,Ut);else At.ranges=[...new Map([...At.ranges,...Ut.ranges].map((st)=>[st.join(":"),st])).values()]}}Ft.snippet=[...vt.values()],i.onTiming?.("snippet",performance.now()-lt)}},Qe=n.deep||b.scan,Yt=(Fe,Ue)=>{let Ft=se(Fe,Ue.session_id);if(!Ft)return[];let lt=J$(Fe,b,Ue,n.group==="none",Ft.forked_from_id!==null,i.onTiming);if(b.candidateLimit&&lt.length>b.candidateLimit)lt.length=b.candidateLimit,E=!0;let vt=L.length,fr=performance.now();for(let mr of lt){if(i.signal?.aborted)break;let Ut=me(Fe,mr);if(!Ut)continue;let ot=xg(Fe,b,mr,Z.get(Ut)?.text??"");if(ot.length)Ut.forks=ot}return i.onTiming?.("body",performance.now()-fr),L.slice(vt)};if(Qe){E=!1;let Fe=[],Ue=new Set,Ft=c.withIndex((st)=>{yg(st,b);for(let Ht of st.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())k.set(Ht.id,Ht);let Qt=new Set(st.query(`SELECT s.id FROM store.sessions s WHERE ${b.sessionWhere}`).all(...b.sessionBindings).map((Ht)=>Ht.id)),Zt=(Ht)=>{if(Ue.has(Ht.id))return;Ue.add(Ht.id);let xo=Ht.forked_from_id?k.get(Ht.forked_from_id):void 0;if(xo)Zt(xo);if(Qt.has(Ht.id))Fe.push(Ht)};for(let Ht of k.values())Zt(Ht);return(st.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
455
+ SELECT s.id FROM store.sessions s WHERE ${b.sessionWhere}
456
+ )`).get(...b.sessionBindings)?.n??0)+Qt.size})??0,lt=0,vt=0,fr=0;if(x.regex?.deepScan)f({type:"groups",groups:[]});let mr=new Set,Ut=new Set,ot=new Map,At=()=>{let st=qe(L),Qt=[];for(let Zt of st){let on=Zt.session.id,Ht=n.group==="none"?void 0:ot.get(on);if(n.group!=="none"&&Ut.has(on)&&!Ht)continue;if(!Ht){if(Ut.add(on),vt<g.offset){vt++;continue}if(fr>=ve){he=!0;break}fr++,ie++}if(n.group!=="none"){let xo=(Ht?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,Y$-(Ht?.shown??0));let pu=(Ht?.shown??0)+Zt.hits.length;Zt.more=xo-pu,ot.set(on,{shown:pu,count:xo})}Qt.push(Zt)}if(Qt.length)xt(Qt),f({type:"groups",groups:Qt});L.length=0,Z.clear(),V.clear(),X.clear()};for(let st of Fe){if(i.signal?.aborted||he)break;let Qt=-1,Zt;for(;;){if(i.signal?.aborted||he)break;let on=c.withIndex((Ht)=>{let xo=Ht.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(st.id,Math.max(0,Qt));if(Qt<0)xo.unshift({seq:0,time:st.updated,body:null});for(let Li of xo){if(i.signal?.aborted)break;let lu=Li.body?JSON.parse(Li.body):void 0;if(lu?.type==="assistant")Zt=lu.model;let sM=lu?Ke(lu,!0):[{part:0,kind:"title",text:st.title}];for(let _o of sM){if(i.signal?.aborted)break;let Cs={session_id:st.id,seq:Li.seq,part:_o.part,doc:Number(BigInt(Bun.hash(_o.text))&0x1fffffffffffffn),kind:Oe[_o.kind],tool:_o.tool??null,err:Number(_o.err??!1),model:_o.model??(_o.tool?Zt:void 0)??null,time:Li.time,relevance:-1};if(!Ht.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
457
+ JOIN store.sessions s ON s.id=r.session_id WHERE ${b.where}`).get(Cs.session_id,Cs.seq,Cs.kind,Cs.tool,Cs.err,Cs.model,Cs.time,...b.bindings))continue;let Gs=st,bg=new Set;while(Gs.forked_from_id&&Gs.forked_from_seq!==null&&Li.seq<=Gs.forked_from_seq&&!bg.has(Gs.id)){bg.add(Gs.id);let du=k.get(Gs.forked_from_id);if(!du)break;Gs=du}let Eg=`${Gs.id}:${Li.seq}:${_o.part}:${Bun.hash(_o.text)}`;if(mr.has(Eg))continue;let Sg=me(Ht,Cs,lu);if(Sg){if(mr.add(Eg),b.forks){let du=Ht.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(st.id,Li.seq,_o.part);if(du){let wg=xg(Ht,b,{...Cs,doc:du.doc},_o.text);if(wg.length)Sg.forks=wg}}}}}let pu=xo.at(-1);if(pu)Qt=pu.seq;return xo.length});if(on===void 0){f({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=on,f({type:"progress",scanned:lt,total:Ft}),i.signal?.aborted)return;if(At(),!on||he)break;await Bun.sleep(0)}}}else c.withIndex((Fe)=>{if(E=H$(Fe,b,i.onTiming)||E,x.regex?x.regex.literals.every((lt)=>lt.some((vt)=>[...vt].length<3)):x.branches.some((lt)=>lt.include.length>0&&lt.include.every((vt)=>[...vt.text].length<3)))Fe.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(n.sort!=="recent"){let lt=W$(Fe,b,n.group==="none",g.now,i.onTiming);if(E||=b.partial,b.candidateLimit&&lt.length>b.candidateLimit)lt.length=b.candidateLimit,E=!0;let vt=[];for(let mr of lt){if(i.signal?.aborted)return;let Ut=vt[ve]?.key.score;if(Ut!==void 0&&mr.score+0.000000000001<Ut)break;let ot=L.length,At=Yt(Fe,mr);L.splice(ot);let st=fg([...At],"best")[0];if(!st)continue;let Qt={score:st.score,sessionID:st.sessionID,seq:n.group==="none"?st.seq:0};if(g.after&&Z$(Qt,g.after)<=0)continue;if(vt.push({key:Qt,hits:At}),vt.sort((Zt,on)=>Z$(Zt.key,on.key)),vt.length>ve+1)vt.length=ve+1}he=vt.length>ve;let fr=vt.slice(0,ve);for(let mr of fr)L.push(...mr.hits);T=fr.at(-1)?.key;return}let Ft=0;for(;;){if(i.signal?.aborted)return;let lt=V$(Fe,b,Y,de,i.onTiming),vt=b.candidateLimit!==void 0&&Y+lt>=b.candidateLimit;E||=vt;let fr=Q$(Fe,n,ie,ve-Ft+1,g.now,z,i.onTiming);he=fr.length>ve-Ft;let mr=fr.slice(0,ve-Ft);if(!mr.length){if(lt<de||vt){he=!1;break}Y+=lt,ie=0,z=[...new Set([...z,...ce])],ce=[];continue}for(let Ut of mr)if(ie++,Yt(Fe,Ut).length){if(Ft++,n.group!=="none")ce.push(Ut.session_id)}if(Ft>=ve){he||=!vt&&lt>=de;break}if(!he){if(lt<de||vt)break;Y+=lt,ie=0,z=[...new Set([...z,...ce])],ce=[]}}});if(i.signal?.aborted)return;if(!Qe){let Fe=qe(L);xt(Fe),f({type:"groups",groups:Fe})}if(!q){let Fe=x.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)f({type:"suggest",terms:c.withIndex((Ue)=>dg(Ue,Fe))??[]})}f({type:"done",cursor:he?Buffer.from(JSON.stringify(!Qe&&n.sort!=="recent"?{...g,offset:0,window:0,seen:[],emitted:[],after:T}:{...g,offset:ie,window:Y,seen:z,emitted:ce})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:E,index:c.status()})}function Lo(e,n){return e.withIndex((i)=>dg(i,n))??[]}function eM(e,n,i){let c=v({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:s({query:o(m([l({maxLength:2000}),Tn()])),scope:o(m([a("session"),a("project"),a("all"),a(""),Tn()])),fields:o(m([W($r({type:"string",enum:[...Un]})),Tn()])),tool:o(m([l(),Tn()])),isError:o(m([D(),Tn()])),after:o(m([l(),J(),Tn()])),before:o(m([l(),J(),Tn()])),limit:o(m([w(),Tn()])),session:o(m([l(),Tn()])),seq:o(m([w(),Tn()])),around:o(m([w(),Tn()]))}),async execute(p,f,g){let x={query:f.query?.trim(),scope:f.scope||void 0,fields:f.fields?.length?f.fields:void 0,tool:f.tool?.trim(),isError:f.isError??void 0,after:f.after??void 0,before:f.before??void 0,limit:f.limit||void 0,session:f.session?.trim(),seq:f.seq??void 0,around:f.around??void 0},I=x.query?.trim(),b=!I&&Boolean(x.session?.trim())&&Number.isSafeInteger(x.seq)&&(x.seq??0)>=1;if(b&&x.around!==void 0&&(!Number.isInteger(x.around)||x.around<0||x.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(x.scope&&!["session","project","all"].includes(x.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(g?.aborted)throw Error("History search cancelled");let E=e.sessions().find((se)=>se.id===i);if(!E)throw Error("History session is unavailable");let T=(se)=>{if(se===void 0||se===0||typeof se==="string"&&!se.trim())return;if(typeof se==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(se))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let me=typeof se==="number"?se:Date.parse(se);if(!Number.isFinite(me)||Math.abs(me)>8640000000000000){if(typeof se==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return me},k=b?void 0:T(x.after),A=b?void 0:T(x.before);if(k!==void 0&&A!==void 0&&k>=A)throw Error("after must precede before");let L=[];if(b&&x.session&&x.seq!==void 0){if(!e.sessions().find((Qe)=>Qe.id===x.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let me=x.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(x.session,Math.max(1,x.seq-me),x.seq+me);if(!qe.some((Qe)=>Qe.seq===x.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:qe.map((Qe)=>{let Yt={...JSON.parse(Qe.body),seq:Qe.seq,time:Qe.time};return`[seq=${Qe.seq}]
458
+ ${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
459
+ `).slice(0,4000)}`}).join(`
460
+
461
+ `)||"No history content"}],details:{groups:L,count:qe.length}}}if(!I)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(x.limit)?Math.max(1,Math.min(30,Math.trunc(x.limit??10))):10,Z=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,B=new Set(e.sessions().filter((se)=>{if(x.scope==="session")return se.id===i;if((x.scope??"project")==="project"&&E.projectID)return se.projectID===E.projectID;return!0}).map((se)=>se.id)),V={q:I,filters:{tools:x.tool?.trim()?[x.tool.trim()]:void 0,isError:x.isError,after:k,before:A},group:"none",limit:q},X=ql(V);if(X.error)throw Error(X.error.message);if(x.fields?.length){if(X.filters.fields=x.fields.filter((se)=>(se in Oe)),X.filters.fields.length!==x.fields.length)throw Error("Unknown search field")}if((x.scope??"project")==="session")X.filters.sessionID=[i];else if((x.scope??"project")==="project"&&E.projectID)X.filters.projectID=[E.projectID];let ie=n.status().state!=="ready",Y=!1;if(!ie){let se=X.filters.fields??Object.keys(Oe).filter((xt)=>(xt in Oe)),me=se.filter((xt)=>xt!=="title"),qe=me.length?[me]:[];if(se.includes("title"))qe.push(["title"]);for(let xt of qe){if(L.length>=q&&Y)break;if(await qr(n,{...V,limit:Math.max(1,q-L.length),filters:{...X.filters,fields:xt}},{signal:g,excludeEntry:Z===void 0?void 0:{sessionID:i,seq:Z},sessionID:i,allowedSessionIDs:B,onEvent(Qe){if(Qe.type==="groups")L.push(...Qe.groups);if(Qe.type==="done")Y||=Boolean(Qe.cursor)||Qe.partial;if(Qe.type==="error")if(Qe.code==="unavailable")ie=!0;else throw Error(Qe.message)}}),ie)break}}let z=[],ce=0;if(ie){L.length=0;let se=performance.now()+2000;e:for(let me of e.sessions()){if(!B.has(me.id))continue;if(X.filters.sessionID&&!X.filters.sessionID.includes(me.id))continue;if(X.filters.projectID&&(!me.projectID||!X.filters.projectID.includes(me.projectID)))continue;let qe=Number.MAX_SAFE_INTEGER,xt=!0;for(;;){let Qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(me.id,qe);if(xt)Qe.push({body:"null",seq:0,time:me.updated}),xt=!1;if(!Qe.length)break;for(let Yt of Qe){if(Yt.seq>0)qe=Yt.seq;if(g?.aborted)throw Error("History search cancelled");if(ce>=1e4||performance.now()>se){Y=!0;break e}if(ce++,me.id===i&&Yt.seq===Z)continue;if(X.filters.after!==void 0&&Yt.time<X.filters.after||X.filters.before!==void 0&&Yt.time>=X.filters.before)continue;let Fe=Yt.seq===0?[{part:0,kind:"title",text:me.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Ue of Fe){if(X.filters.fields&&!X.filters.fields.includes(Ue.kind))continue;if(X.filters.tools&&(!Ue.tool||!X.filters.tools.includes(Ue.tool)))continue;if(X.filters.isError!==void 0&&Boolean(Ue.err)!==X.filters.isError)continue;let Ft=jl(Ue.text,X);if(!Ft)continue;if(L.length>=q&&Ue.kind!=="title"){Y=!0;break e}(Ue.kind==="title"?z:L).push({session:{id:me.id,title:me.title,projectID:me.projectID,updated:me.updated},more:0,hits:[{sessionID:me.id,seq:Yt.seq,time:Yt.time,field:Ue.kind,tool:Ue.tool,isError:Boolean(Ue.err),snippet:Ul(Ue.text,Ft),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(g?.aborted)throw Error("History search cancelled");if(z.length>Math.max(0,q-L.length))Y=!0;if(L.push(...z.slice(0,q)),L.sort((se,me)=>Number(se.hits[0]?.field==="title")-Number(me.hits[0]?.field==="title")),L.length>q)Y=!0;L.length=Math.min(L.length,q);let he=new Map;for(let se of L)for(let me of se.hits){let qe=he.get(se.session.id)??[];qe.push(`[${se.session.title.replace(/[\r\n]/g," ")} \xB7 ${me.sessionID} \xB7 ${me.seq} \xB7 ${new Date(me.time).toISOString()} \xB7 ${me.field}${me.tool?`/${me.tool}`:""}]
462
+ ${me.snippet.slice(0,3).map((xt)=>{let Qe=xt.text;for(let[Yt,Fe]of[...xt.ranges].sort((Ue,Ft)=>Ft[0]-Ue[0]))Qe=`${Qe.slice(0,Yt)}\u3010${Qe.slice(Yt,Fe)}\u3011${Qe.slice(Fe)}`;return Qe}).join(`
463
+ `)}`),he.set(se.session.id,qe)}let ve="";if(ie){if(ve="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",n.status().state==="disabled")ve="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let de=L.reduce((se,me)=>se+me.hits.length,0);return{content:[{type:"text",text:[ve,ie&&Y?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ce} \u6761`:"",[...he.values()].map((se)=>se.join(`
464
+
465
+ `)).join(`
466
+
467
+ `),de===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 ${de} \u6761\uFF1B${Y?"\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(`
468
+ `)}],details:{groups:L,count:de}}}});return Object.assign(c,{source:"history",builtin:!0,defer:"defer"})}async function tM(e,n){let i=n.projectID?e.store.project(n.projectID):void 0,c=i?.directory??process.cwd(),f=n.info().kind==="sub",g=()=>f||n.records.some((b)=>b.entry.type==="compaction"),x=e.options.tools??nr({directory:i?.directory,records:()=>n.records,history:(b)=>e.resolveHistory(n.id,b),onTodos:(b)=>n.setTodos(b),shell:()=>e.serverShell(),hasCompacted:g});if(e.options.tools===void 0)x.push(eM(e.store,e.search,n.id));let I=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:m$({project:i,globalInstructions:NG(e),shell:e.serverShell()});return{systemPrompt:I.map((b)=>b.detail).join(""),systemParts:I,tools:[...x,...e.tools.snapshot()],cwd:c}}var LG=[mu(".basalt","AGENTS.md"),mu(".agents","AGENTS.md"),mu(".opencode","AGENTS.md"),mu(".claude","CLAUDE.md"),mu(".codex","AGENTS.md")];function NG(e){let n=e.options.homeDir??_G();for(let i of LG){let c=mu(n,i);try{if(vG(c))return OG(c,"utf8")}catch{return}}return}class Hr{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 sg(this,this.sessions,(n)=>this.emit(n)),this.defaultModel=e.defaultModel,this.store=new Ll(Ig(e.dataDir,"basalt.db")),this.plugins=new Bh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Dl(this.plugins,()=>this.builtinToolNames()),this.search=new Gh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(n)=>this.emit({type:"search_status",status:n})});for(let n of this.store.allSessions()){let i=this.open(n,"restore");this.sessions.set(n.id,i),this.restored.add(i)}}static async create(e){let n=new Hr(e);try{return await n.initialize(),n}catch(i){throw await n.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Ig(this.options.dataDir,"plugins"),...this.projects().map((e)=>Ig(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 P$(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((c)=>c.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let n=[...this.sessions.values()];if(await Promise.all(n.map((c)=>c.noticesIdle())),n.some((c)=>c.status==="busy"||!e.includes(c)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Nl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>A$(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,n){return this.projectOperations.updateProject(e,n)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,n={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let c=n.archive??"active";return c==="all"||i.archivedAt!==null===(c==="archived")}).sort((i,c)=>c.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((n)=>n.info().parentID===e).map((n)=>n.info())}resolveHistory(e,n){let i=this.get(e);if(!i)throw new r("History session is unavailable");let c=i.historyScope(n);if(c)return c;if(n.source&&n.source!=="self"||n.session_id&&n.session_id!==i.id)throw new r("History source is unavailable");return{sessionID:i.id,records:i.records}}openStoredSession(e,n="restore"){let i=this.open(e,n);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let n=e.model??this.defaultModel;if(!Dn(this.options.models,n))throw new r(`unknown model ${n}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),c={id:fe("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:n,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(c);let p=this.open(c);return this.sessions.set(c.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,n,i){n={...n,archivedAt:null},this.store.copySession(e,n,i);let c=this.open(n);return this.sessions.set(n.id,c),this.plugins.notify("session.fork",c),this.emit({type:"session",session:c.info()}),c}truncateHistory(e,n){let i=this.sessions.get(e.id);if(!i)throw new y("no such session");if(i.assertWritable(),i.status==="busy")throw new oe;i.close();for(let p of this.sessions.values()){if(p.info().parentID!==e.id)continue;if(p.status==="busy")p.abort();p.close()}this.store.truncateSession(e,n);let c=this.open(e,"replay");return this.sessions.set(e.id,c),this.emit({type:"truncated",sessionID:e.id,after:n-1,truncationEpoch:this.store.truncationEpoch(e.id)}),c}setArchived(e,n){let i=this.sessions.get(e);if(!i)throw new y("no such session");if(i.info().parentID)throw new r("\u8BF7\u5F52\u6863\u6216\u6062\u590D\u6240\u5C5E\u4F1A\u8BDD\uFF08\u542B\u5B50\u4F1A\u8BDD\uFF09");let c=this.sessionTree(i);if(c.some((p)=>p.status==="busy"))throw new oe;if(i.isArchived===n)return i.info();this.store.setArchived(c.map((p)=>p.id),n?Date.now():null);for(let p of c)p.refreshArchive();for(let p of c)p.archiveChanged();return i.info()}sessionTree(e){let n=[e];for(let i=0;i<n.length;i++){let c=n[i];if(!c)continue;for(let p of this.sessions.values())if(p.info().parentID===c.id)n.push(p)}return n}deleteSession(e){let n=this.sessions.get(e);if(!n)throw new y("no such session");if(n.status==="busy")throw new oe;let i=this.sessionTree(n).slice(1),c=()=>{for(let p of i)p.close(),this.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});n.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",n),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return c();n.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(c)}open(e,n="create"){let i=e.id,c=new Pl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>tM(this,p)},{entry:(p)=>{this.emit({type:"entry",sessionID:i,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:i,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(p)=>this.emit({type:"draft",sessionID:i,parts:p}),changed:()=>{let p=this.sessions.get(i);if(p)this.emit({type:"session",session:p.info()})}});if(n!=="restore")this.plugins.notify(n==="create"?"session.create":"session.open",c);return c}get toolLoading(){return new Mi(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(!Hl.includes(e))throw new r(`Invalid shell type; must be ${Hl.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 $$(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let n of this.listeners)try{n(e)}catch(i){console.error("runtime listener failed",i)}}}var Re={now:()=>Date.now(),after(e,n){let i=setTimeout(n,e);return()=>clearTimeout(i)}};var rM=1048576,nM=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,n=30000,i,c){this.cwd=e;this.outputLimit=n;this.terminal=i;this.shellPreference=c}setTerminalObserver(e){this.terminal=e}start(e,n,i){let c=i?.observer,p=i?.clock??Re;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let Z=Xl(e);if(Z.length>0)throw Error(Yl(Z))}if(this.list().filter((Z)=>Z.state==="running").length>=nM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${nM}\uFF09`);let g=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:x,isWindows:I}=fa(e,g),b=Bun.spawn(x,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!I,windowsHide:!0}),E={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:b,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(E.id,E);let T=()=>{for(let Z of E.waiters.splice(0))Z()},k=async(Z,B)=>{let V=new bl;for await(let ie of Z){let Y=V.decode(ie);E.output+=Y,c?.output(Y,B);let z=Buffer.from(E.output);if(z.length>rM){let ce=z.length-rM;while(ce<z.length&&(z[ce]??0)>>6===2)ce++;let he=z.subarray(ce).toString(),ve=E.output.length-he.length;E.unreadDroppedBytes+=Buffer.byteLength(E.output.slice(Math.max(0,E.readAt-E.dropped),ve)),E.output=he,E.dropped+=ve}T()}let X=V.flush();if(E.output+=X,X)c?.output(X,B)},A,L=Promise.all([k(b.stdout,"stdout"),k(b.stderr,"stderr")]).catch((Z)=>{A=Z,this.kill(E)}),q=!1;if(E.done=(async()=>{if(E.code=await b.exited,E.timer?.(),this.kill(E),await L,A)throw A;if(E.state==="running")E.state="exited";if(q=!0,c?.end(E.state,E.code),!c&&E.state!=="killed")this.terminal?.(E);T()})().catch((Z)=>{if(E.state="exited",E.output+=`
469
+ [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(Z)}]`,!q)c?.end(E.state,E.code);if(c)throw Z;if(!c)this.terminal?.(E,Z);T()}),n!==void 0)E.timer=p.after(n,()=>{if(E.state==="running")E.state="timeout",this.kill(E)});return E}find(e){let n=this.jobs.get(e);if(!n)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return n}kill(e){try{if(process.platform==="win32"){let n=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(n.exitCode!==0&&n.exitCode!==128&&e.proc.exitCode===null)throw Error("\u65E0\u6CD5\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B\u6811\uFF0C\u8BF7\u68C0\u67E5\u8FDB\u7A0B\u6743\u9650")}else process.kill(-e.proc.pid,"SIGKILL")}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ESRCH"))throw n}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,n,i=0,c=!1,p){let f=this.find(e),g=n?new RegExp(n):void 0,x=Date.now()+i;p?.throwIfAborted();while(f.state==="running"){p?.throwIfAborted();let k=f.output.slice(Math.max(0,f.readAt-f.dropped));if((g?g.test(k):!c)||Date.now()>=x)break;await new Promise((A,L)=>{let q=()=>{clearTimeout(B);let V=f.waiters.indexOf(Z);if(V>=0)f.waiters.splice(V,1);L(p?.reason)},Z=()=>{clearTimeout(B),p?.removeEventListener("abort",q);let V=f.waiters.indexOf(Z);if(V>=0)f.waiters.splice(V,1);A()},B=setTimeout(Z,Math.max(0,x-Date.now()));f.waiters.push(Z),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let I=f.unreadDroppedBytes;f.unreadDroppedBytes=0;let b=f.output.slice(Math.max(0,f.readAt-f.dropped));f.readAt=f.dropped+f.output.length;let E=b.slice(-this.outputLimit),T=I+Buffer.byteLength(b.slice(0,b.length-E.length));return{job:f,output:`${T?`[truncated ${T} bytes]
470
+ `:""}${E}`}}async write(e,n,i=!1,c){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let f=p.proc.stdin;if(!f||typeof f==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(n){let g=await ze(n,c);if(g)throw Error(g);f.write(n)}if(i)await f.end();else await f.flush()}async stop(e){let n=this.find(e);if(n.state==="running")n.state="killed",this.kill(n);return await n.done,{id:n.id,state:n.state,code:n.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var Bl=new WeakMap,Gl=new WeakMap;function sr(e,n){let i=Bl.get(e);if(!i)i=n(),Bl.set(e,i);return i}function ar(e){Gl.set(e,(Gl.get(e)??0)+1)}function lr(e,n){let i=(Gl.get(n)??1)-1;if(Gl.set(n,i),i>0)return!1;if(n.close(),Bl.get(e)===n)Bl.delete(e);return!0}async function G(e){let n=await e.json();if(!n||typeof n!=="object"||Array.isArray(n))throw new r("expected a JSON object");return n}function P(e,n){let i=e[n];if(!i)throw new r(`${n} is required`);return i}var Wn=100,cr=1e4,DG=60000,qG=200,bn=()=>l(),oM=()=>o(w({minimum:1,maximum:cr})),Wc=()=>o(l({minLength:1,maxLength:128})),FG=m([s({click:m([bn(),s({selector:bn()})])}),s({type:s({label:bn(),text:bn()})}),s({waitText:bn(),timeoutMs:oM()}),s({expectText:bn(),within:o(bn())}),s({waitSelector:bn(),timeoutMs:oM()}),s({expectCount:s({selector:bn(),n:w({minimum:0})})}),s({snapshot:s({selector:bn(),depth:o(w({minimum:0,maximum:qG}))})}),s({expectCalls:s({onOpen:o(W(bn())),onClose:o(w({minimum:0}))})}),s({expectValue:s({label:bn(),value:bn()})})]),jG=s({status:w({minimum:100,maximum:599}),body:Sr(),delayMs:o(w({minimum:0,maximum:cr}))}),UG=m([a("paths"),a("request"),a("verify"),a("ui_test"),a("list"),a("docs"),a("check"),a("load"),a("reload"),a("enable"),a("disable")]),BG=m([a("page"),a("tab"),a("card"),a("sidebar")]),gi=s({action:UG,path:o(l({minLength:1,maxLength:4096})),method:o(bn()),body:o(ys(bn(),Sr())),importTimeoutMs:o(w({minimum:1,maximum:cr})),timeoutMs:o(w({minimum:1,maximum:DG})),sessionID:Wc(),scope:o(m([a("user"),a("all")])),id:Wc(),slot:Wc(),view:Wc(),codeBlock:Wc(),kind:o(BG),props:o(ys(bn(),Sr())),context:o(ys(bn(),Sr())),steps:o(W(FG,{maxItems:Wn})),mockRoutes:o(ys(bn(),jG)),topic:o(l({maxLength:100})),grep:o(l({minLength:1,maxLength:200}))});
471
+ export{r,y,si,ai,li,Br,Wr,Po,Un,ci,ui,pi,Bt,di,mi,hi,fi,To,_e,et,_t,K,ko,ze,Pt,W,o,s,$r,D,w,a,J,l,m,h,ae,Fn,Ro,Io,Co,Mo,we,v,tt,pt,R,O,U,ke,Pe,u,je,rt,rr,We,nr,dt,oe,or,ir,fe,Bn,qr,Lo,Hr,Re,Wt,sr,ar,lr,G,P,Oo,Wn,cr,gi};