@bkm016/basalt 0.1.7 → 0.1.8

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 (250) hide show
  1. package/README.md +1 -1
  2. package/{chunk-n981vx1t.js → chunk-0d51ggzj.js} +6 -6
  3. package/chunk-12trygzx.js +25 -0
  4. package/{chunk-s6dejhfj.js → chunk-26cz8et8.js} +1 -1
  5. package/{chunk-zxkq9m8e.js → chunk-2ek3wq4b.js} +2 -2
  6. package/chunk-2gcp3xdc.js +2 -0
  7. package/{chunk-x4874m8e.js → chunk-2ks2tnac.js} +2 -2
  8. package/{chunk-0javrjcm.js → chunk-2nrkqq45.js} +22 -22
  9. package/chunk-320174qe.js +2 -0
  10. package/{chunk-ey15ye2h.js → chunk-3hg7yn1t.js} +1 -1
  11. package/{chunk-benrzwea.js → chunk-3j2kkgsc.js} +1 -1
  12. package/{chunk-8x21n7y9.js → chunk-47vf66t6.js} +1 -1
  13. package/chunk-4n49ptbz.js +3 -0
  14. package/{chunk-7hr6zw2m.js → chunk-5gxj9560.js} +1 -1
  15. package/{chunk-g0t9c3gv.js → chunk-6vnjg5x9.js} +1 -1
  16. package/{chunk-dnx91jrd.js → chunk-7kjr9gdx.js} +2 -2
  17. package/{chunk-y8dkfpmj.js → chunk-7p6e2f5s.js} +3 -3
  18. package/{chunk-053vb71h.js → chunk-86xhmz7k.js} +1 -1
  19. package/{chunk-ebpyvs1d.js → chunk-91r5nvth.js} +2 -2
  20. package/{chunk-c7rcw9fb.js → chunk-adys4qq4.js} +4 -4
  21. package/{chunk-npez1492.js → chunk-ckjw3b61.js} +2 -2
  22. package/{chunk-f156y565.js → chunk-d37gemt2.js} +3 -3
  23. package/{chunk-j7yvh0ae.js → chunk-dcwdmpw2.js} +1 -1
  24. package/chunk-dvb5nd2x.js +2 -0
  25. package/{chunk-063vbmtp.js → chunk-e6c2mzxc.js} +2 -2
  26. package/{chunk-s7skpgm2.js → chunk-ef9yhnk3.js} +1 -1
  27. package/{chunk-ecf896fz.js → chunk-fpxc6qjr.js} +2 -2
  28. package/chunk-frt9k18g.js +480 -0
  29. package/{chunk-bdy4jksd.js → chunk-fzcmzbsq.js} +1 -1
  30. package/{chunk-q9dd6fhj.js → chunk-g3ed130w.js} +3 -3
  31. package/{chunk-d48bfd2e.js → chunk-h1kb8b49.js} +2 -2
  32. package/{chunk-arcqjt91.js → chunk-hd3x1w46.js} +1 -1
  33. package/{chunk-dpz4hwqb.js → chunk-j781n7ca.js} +2 -2
  34. package/{chunk-z02sj1je.js → chunk-jp5afrwm.js} +2 -2
  35. package/{chunk-r8vvcp6c.js → chunk-jyv9cae6.js} +1 -1
  36. package/{chunk-whj87h4r.js → chunk-k3q5jqjj.js} +3 -3
  37. package/{chunk-75434aay.js → chunk-k3rmjrf1.js} +1 -1
  38. package/{chunk-peja51xv.js → chunk-kgkrccr1.js} +2 -2
  39. package/{chunk-pg5nkf1y.js → chunk-kpvaqb7c.js} +2 -2
  40. package/{chunk-sjjtxpg2.js → chunk-ky55taar.js} +330 -288
  41. package/{chunk-10p3mb40.js → chunk-mr807v9n.js} +1 -1
  42. package/chunk-n015c8nx.js +2 -0
  43. package/chunk-ndt6rjt9.js +2 -0
  44. package/{chunk-gv7wqkey.js → chunk-nmtk9xra.js} +2 -2
  45. package/{chunk-d6p2hgxh.js → chunk-pehyqj8k.js} +1 -1
  46. package/{chunk-ca982n62.js → chunk-pkpj7s2k.js} +1 -1
  47. package/{chunk-fx7f4m3c.js → chunk-pn413hjw.js} +1 -1
  48. package/{chunk-6ptv4g5e.js → chunk-ppxv5q7y.js} +3 -3
  49. package/{chunk-8wj32837.js → chunk-qmdpgbg3.js} +1 -1
  50. package/{chunk-8wv5t0w6.js → chunk-rnt1ckk9.js} +6 -6
  51. package/{chunk-prgm07j4.js → chunk-t40fag3z.js} +2 -2
  52. package/{chunk-w67dvqtb.js → chunk-t66jqz12.js} +2 -2
  53. package/{chunk-39vwrg8n.js → chunk-v2srrqcv.js} +2 -2
  54. package/{chunk-n85qs7cs.js → chunk-x496kg3v.js} +1 -1
  55. package/{chunk-6kdgk70p.js → chunk-xjw78yey.js} +4 -4
  56. package/chunk-xy2bxwq8.js +2 -0
  57. package/{chunk-y69ewdn2.js → chunk-ypqjfv3a.js} +2 -2
  58. package/{chunk-f544p9rh.js → chunk-yyy2yp6f.js} +10 -10
  59. package/{chunk-8gw5bvh3.js → chunk-yzevjkms.js} +5 -5
  60. package/chunk-z3ch1wg6.js +16 -0
  61. package/chunk-zdyd8hbn.js +2 -0
  62. package/compiled.js +6 -6
  63. package/package.json +1 -1
  64. package/ui-test-worker.js +19 -19
  65. package/web/{chunk-kjacapzd.js → chunk-0j9a7811.js} +6 -6
  66. package/web/chunk-0jfda4jw.js +2 -0
  67. package/web/{chunk-z1geewdf.js → chunk-0zwc2rvh.js} +2 -2
  68. package/web/{chunk-ht4mx2dt.js → chunk-1gx0zpmp.js} +7 -7
  69. package/web/{chunk-q3jevm51.js → chunk-1s8zg6fb.js} +51 -51
  70. package/web/chunk-2axwda8c.js +89 -0
  71. package/web/chunk-2p3fkhy8.js +1 -0
  72. package/web/{chunk-tz4twwmw.js → chunk-33w36n91.js} +2 -2
  73. package/web/{chunk-1s53190z.js → chunk-3q0v8w45.js} +81 -81
  74. package/web/chunk-3sz5qcwj.js +1 -0
  75. package/web/chunk-433c80pc.js +1 -0
  76. package/web/chunk-48cnmhvd.js +106 -0
  77. package/web/{chunk-da7m1kva.js → chunk-4anjs6yp.js} +2 -2
  78. package/web/chunk-5r37rwq1.js +4 -0
  79. package/web/{chunk-pjz30xcp.js → chunk-6e38yf3a.js} +23 -23
  80. package/web/{chunk-xckxtfp8.js → chunk-7a4xk6j9.js} +72 -72
  81. package/web/chunk-7f1t7z72.js +2 -0
  82. package/web/chunk-7qq1ypvj.js +1 -0
  83. package/web/{chunk-h6k1x096.js → chunk-7tkgbbf9.js} +2 -2
  84. package/web/chunk-7x35g67d.js +78 -0
  85. package/web/{chunk-xbpc6x9m.js → chunk-823b7866.js} +15 -15
  86. package/web/chunk-85gdsmt4.js +1 -0
  87. package/web/{chunk-gyp6v7jd.js → chunk-8773nwdc.js} +2 -2
  88. package/web/{chunk-2cem4sv7.js → chunk-8dp7h6w8.js} +24 -24
  89. package/web/{chunk-y99ed8rd.js → chunk-8nv7q5ac.js} +9 -9
  90. package/web/chunk-8pzg8qw4.js +1 -0
  91. package/web/chunk-8wg44w91.js +2 -0
  92. package/web/chunk-9p5dfvav.js +1 -0
  93. package/web/chunk-9q9w9pay.js +1 -0
  94. package/web/chunk-a3teqvz2.js +39 -0
  95. package/web/chunk-bd8ftfxn.js +3 -0
  96. package/web/chunk-c03bt2pz.js +1 -0
  97. package/web/chunk-c1ha2xg6.js +8 -0
  98. package/web/chunk-cez1k71m.js +1 -0
  99. package/web/chunk-cgng31df.js +1 -0
  100. package/web/chunk-cn0tmwjs.js +2 -0
  101. package/web/{chunk-t6sq85s6.js → chunk-cn1xpg3q.js} +2 -2
  102. package/web/chunk-cvd4f51j.js +1 -0
  103. package/web/chunk-cybvxssy.js +1 -0
  104. package/web/{chunk-geh05ghh.js → chunk-cyjnert7.js} +19 -19
  105. package/web/{chunk-twdy2f67.js → chunk-d0m0h0eb.js} +1 -1
  106. package/web/{chunk-sn3tkwme.js → chunk-dgwkqcz6.js} +37 -37
  107. package/web/{chunk-nfvqjzz5.js → chunk-dtg5yhhs.js} +1 -1
  108. package/web/chunk-dynajx8x.js +2 -0
  109. package/web/{chunk-svh4n157.js → chunk-et8q775x.js} +4 -4
  110. package/web/chunk-f3vv7n52.js +1 -0
  111. package/web/{chunk-tmndcktk.js → chunk-f93pe4kb.js} +15 -15
  112. package/web/{chunk-5nda24gv.js → chunk-fe31sv6t.js} +1 -1
  113. package/web/chunk-fpa81dv7.js +62 -0
  114. package/web/{chunk-4q7wf0wd.js → chunk-fx4mackk.js} +9 -9
  115. package/web/chunk-g17n6asp.js +1 -0
  116. package/web/chunk-g9dzaw9e.js +30 -0
  117. package/web/chunk-gcwhx3av.js +1139 -0
  118. package/web/chunk-gf8vm6b5.js +1 -0
  119. package/web/chunk-gnmeyy4h.js +1 -0
  120. package/web/chunk-h5cfg3vv.js +2 -0
  121. package/web/{chunk-femhej5w.js → chunk-hbkasy6c.js} +46 -46
  122. package/web/chunk-hn7mhsbg.js +1 -0
  123. package/web/{chunk-tfn0rqg9.js → chunk-hstbgb83.js} +26 -26
  124. package/web/chunk-jjjtv2r1.js +2 -0
  125. package/web/chunk-jzte2phh.js +2 -0
  126. package/web/chunk-k8h8zx6r.js +24 -0
  127. package/web/chunk-m3ajw575.js +1 -0
  128. package/web/chunk-m5y2d4zv.js +1 -0
  129. package/web/chunk-mbwwj216.js +1 -0
  130. package/web/chunk-mf6xng5b.js +2 -0
  131. package/web/chunk-nky3bqfg.js +1 -0
  132. package/web/chunk-np33kmn4.js +1 -0
  133. package/web/chunk-nvk8mazs.js +1 -0
  134. package/web/chunk-nyw5ewgv.js +1 -0
  135. package/web/{chunk-dg3p8db5.js → chunk-p0cjvjdx.js} +1 -1
  136. package/web/chunk-p56dcqpr.js +1 -0
  137. package/web/chunk-pdn4r8x4.js +1 -0
  138. package/web/chunk-q1xxs319.js +41 -0
  139. package/web/chunk-qpt34d8d.js +1 -0
  140. package/web/{chunk-4fm55fgb.js → chunk-qq2v8h6d.js} +7 -7
  141. package/web/chunk-qskt3tqa.js +1 -0
  142. package/web/chunk-qt3n897m.js +4 -0
  143. package/web/chunk-r1rt48h9.js +1 -0
  144. package/web/{chunk-4sve9xrj.js → chunk-r4ffr96e.js} +1 -1
  145. package/web/chunk-r7tgd2fm.js +7 -0
  146. package/web/{chunk-gksf7cek.js → chunk-rbdvc8x7.js} +7 -7
  147. package/web/{chunk-q97hn4j5.js → chunk-rkjkynm3.js} +33 -33
  148. package/web/chunk-rznszqmy.js +1 -0
  149. package/web/chunk-s1pefd34.js +1 -0
  150. package/web/chunk-s38s9ff9.js +370 -0
  151. package/web/{chunk-n754s8xd.js → chunk-s7e93552.js} +8 -8
  152. package/web/chunk-sc29azev.js +1 -0
  153. package/web/{chunk-czjk218p.js → chunk-sda7cyrt.js} +52 -52
  154. package/web/chunk-svh2gkx8.js +2 -0
  155. package/web/chunk-t4jc4nac.js +1 -0
  156. package/web/chunk-t7g366a5.js +24 -0
  157. package/web/chunk-tj1fn8v2.js +1 -0
  158. package/web/{chunk-sy7e4dmq.js → chunk-tkp72r9b.js} +1 -1
  159. package/web/{chunk-5wbnjjhg.js → chunk-v14s4vgc.js} +1 -1
  160. package/web/chunk-v94v68xg.js +36 -0
  161. package/web/{chunk-0whceqes.js → chunk-vvvd3grf.js} +2 -2
  162. package/web/chunk-w37n09px.js +21 -0
  163. package/web/chunk-wcphswcx.js +2 -0
  164. package/web/{chunk-aangfjqc.js → chunk-wj3ymejj.js} +38 -38
  165. package/web/chunk-wwcnvyjh.css +1 -0
  166. package/web/{chunk-e8yj05t1.js → chunk-xabcx3ry.js} +6 -6
  167. package/web/chunk-xb9m0092.js +1 -0
  168. package/web/chunk-xfd3b01q.js +1 -0
  169. package/web/{chunk-4vjnrz87.js → chunk-xqyazzm7.js} +17 -17
  170. package/web/{chunk-bdydzbqk.js → chunk-xsz1dfm2.js} +23 -23
  171. package/web/chunk-z0zrp8n8.js +1 -0
  172. package/web/index.html +1 -1
  173. package/worker.js +1 -1
  174. package/chunk-654cny9a.js +0 -480
  175. package/chunk-8saewt61.js +0 -3
  176. package/chunk-a0c989ky.js +0 -2
  177. package/chunk-a5apjjcn.js +0 -16
  178. package/chunk-a81p46j7.js +0 -2
  179. package/chunk-agsfy9w7.js +0 -2
  180. package/chunk-d20p02ny.js +0 -2
  181. package/chunk-ejsneb6f.js +0 -2
  182. package/chunk-fmq3zwzk.js +0 -2
  183. package/chunk-rfb85nj7.js +0 -2
  184. package/chunk-rfdt992v.js +0 -25
  185. package/web/chunk-079091ar.js +0 -39
  186. package/web/chunk-083r4f80.js +0 -1
  187. package/web/chunk-0cng7r2x.js +0 -2
  188. package/web/chunk-0k0ande6.js +0 -1
  189. package/web/chunk-14deqqhr.js +0 -2
  190. package/web/chunk-2b63adsj.js +0 -89
  191. package/web/chunk-3baypnwn.js +0 -4
  192. package/web/chunk-4067nwjp.js +0 -19
  193. package/web/chunk-59678wmg.js +0 -1
  194. package/web/chunk-5k8sv4f5.js +0 -1
  195. package/web/chunk-5vjhvw1m.js +0 -2
  196. package/web/chunk-6ft5pz3c.js +0 -1
  197. package/web/chunk-7c8rwqtx.js +0 -1
  198. package/web/chunk-7qzz025k.js +0 -1
  199. package/web/chunk-7xbaqqd7.css +0 -1
  200. package/web/chunk-80eyv2mk.js +0 -1
  201. package/web/chunk-89paytbk.js +0 -4
  202. package/web/chunk-8ceej2g7.js +0 -1
  203. package/web/chunk-8nyhy122.js +0 -1
  204. package/web/chunk-989jq2h8.js +0 -2
  205. package/web/chunk-9w5tf22s.js +0 -1
  206. package/web/chunk-c3nn0vvc.js +0 -1
  207. package/web/chunk-cpwtt6ny.js +0 -1
  208. package/web/chunk-dsw5t58p.js +0 -1
  209. package/web/chunk-dv72fat3.js +0 -1
  210. package/web/chunk-dvvs1jjq.js +0 -3
  211. package/web/chunk-e131rg6p.js +0 -2
  212. package/web/chunk-ekw54h1q.js +0 -1
  213. package/web/chunk-hwsvhst3.js +0 -1
  214. package/web/chunk-k02b36g1.js +0 -62
  215. package/web/chunk-kkfrs7d1.js +0 -41
  216. package/web/chunk-kkyn8yhj.js +0 -106
  217. package/web/chunk-mh4rx5cf.js +0 -1
  218. package/web/chunk-n448vaba.js +0 -1
  219. package/web/chunk-n8j88qxy.js +0 -1
  220. package/web/chunk-nmpbsvwb.js +0 -2
  221. package/web/chunk-nws1s56b.js +0 -1
  222. package/web/chunk-p7126wwy.js +0 -7
  223. package/web/chunk-phnqnhj9.js +0 -1
  224. package/web/chunk-qg31p6cn.js +0 -1
  225. package/web/chunk-qhm3cfq9.js +0 -1
  226. package/web/chunk-qsd595b9.js +0 -1
  227. package/web/chunk-r7frwjqx.js +0 -2
  228. package/web/chunk-rddft5ce.js +0 -1139
  229. package/web/chunk-rgbdf2m9.js +0 -370
  230. package/web/chunk-rsbkbg6x.js +0 -78
  231. package/web/chunk-s2bs5vxh.js +0 -2
  232. package/web/chunk-sgwccs54.js +0 -1
  233. package/web/chunk-sjh8gtm9.js +0 -30
  234. package/web/chunk-t3658ehb.js +0 -2
  235. package/web/chunk-t81p4wqc.js +0 -24
  236. package/web/chunk-tewmsd7t.js +0 -1
  237. package/web/chunk-tf57s7ry.js +0 -1
  238. package/web/chunk-tqr80b5w.js +0 -2
  239. package/web/chunk-v282r683.js +0 -24
  240. package/web/chunk-v4vjjtn7.js +0 -1
  241. package/web/chunk-vbwdwcdp.js +0 -1
  242. package/web/chunk-vjngfh0q.js +0 -1
  243. package/web/chunk-vnt34mkb.js +0 -1
  244. package/web/chunk-wbgkwxrc.js +0 -1
  245. package/web/chunk-wjbk50hn.js +0 -2
  246. package/web/chunk-wjy848e2.js +0 -1
  247. package/web/chunk-wqsczy57.js +0 -36
  248. package/web/chunk-wvfmmw1v.js +0 -8
  249. package/web/chunk-x1jm4zsg.js +0 -1
  250. package/web/chunk-xmsb2g71.js +0 -1
package/chunk-654cny9a.js DELETED
@@ -1,480 +0,0 @@
1
- // @bun
2
- import{Bo,Vr,W}from"./chunk-w67dvqtb.js";import{Ho,He,Tt,qo,Jn,Go,Ai,Ei,gt,zo,Oe,Jr,Ke}from"./chunk-8gw5bvh3.js";import{qn,Pi,jr}from"./chunk-dpz4hwqb.js";import{Ce,te,Fo,Gn,I,zn,ht,Ie,dr,N,Me,jn,ft,pe,$t,ne,Kr,Wo,Le,re,ot,Vn,$o,ge,Ti,wi,ye,Kn,d,ki,Q,Qr,G,Ri}from"./chunk-n981vx1t.js";import{Qn,M,Xn,Ve,vi,Ht,Te}from"./chunk-z02sj1je.js";import{r,Xe}from"./chunk-bwawt15q.js";var Gg=r(function(nH,Bg){var PM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Zl=/[\n\r\u2028\u2029]/,$M=/[\s#!"$&'():;<=>@\\^`|~]/g;Bg.exports=function(n){var i=!1;return n.map(function(c){if(i&&typeof c==="string"&&Zl.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(Zl.test(c.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(c.pattern==="")return"''";return c.pattern.replace($M,"\\$&")}if("op"in c&&typeof c.op==="string"){if(PM.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(Zl.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 Xg=r(function(oH,Qg){var Vg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Kg=new RegExp("^"+Vg+"$"),Hg="|&;()<> \\t",MM="'([^']*?)'",Jg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Wg="\\$'"+Jg+"'",tm=new RegExp("\\$'"+Jg+"(?:(')|\\\\?$)","g"),vM="abeEfnrtv",OM=`\x07\b\x1B\x1B\f
3
- \r \v`,_M=/^#$/,ed="'",zg='"',Eu="$",ji="",LM=4294967296;for(em=0;em<4;em++)ji+=(LM*Math.random()).toString(16);var em,NM=new RegExp("^"+ji);function DM(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 qM(e,n,i){var c=typeof e==="function"?e(i):e[i];if(typeof c>"u"&&i!="")c="";else if(typeof c>"u")c="$";if(typeof c==="object")return n+ji+JSON.stringify(c)+ji;return n+c}var FM=/\\([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 jM(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 g=vM.indexOf(n);return g<0?n:OM.charAt(g)}function UM(e){return e.replace(FM,jM).split("\x00")[0]}function BM(e,n){return tm.lastIndex=n,!!tm.exec(e)[1]}function GM(e,n,i){if(!i)i={};var c=i.escape||"\\",p=i.splitUnquoted===!0?`
4
- `:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",g="(\\"+c+`['"$\\`+c+Hg+"]|\\$\\$|\\$(?!"+Wg.slice(2)+`)|[^\\s'"$`+Hg+"])+",y='"(?:\\'+c+'[\\s\\S]|[^"\\'+c+'])*"',x=new RegExp(["("+Vg+")","("+Wg+"|"+g+"|"+y+"|"+MM+")+"].join("|"),"g"),b=DM(e,x);if(b.length===0)return[];if(!n)n={};var S=!1;return b.map(function(T){var A=T[0];if(!A||S)return;if(Kg.test(A))return{op:A};var C=!1,P=!1,L="",q=[],X=!1,j=null,V=!1,J;function ee(){J+=1;var me,qe,It=A.charAt(J);if(It==="{"){if(J+=1,A.charAt(J)==="}")throw Error("Bad substitution: "+A.slice(J-2,J+1));var Je=1;me=J;while(Je>0&&me<A.length){if(A.charAt(me)==="{"&&A.charAt(me-1)==="$")Je+=1;else if(A.charAt(me)==="}")Je-=1;me+=1}if(Je!==0)throw Error("Bad substitution: "+A.slice(J));me-=1,qe=A.slice(J,me),J=me}else if(/[*@#?$!-]/.test(It))qe=It;else{var Yt=A.slice(J);if(me=Yt.match(/[^\w\d_]/),!me)qe=Yt,J=A.length;else qe=Yt.slice(0,me.index),J+=me.index-1}return qM(n,"",qe)}function ie(){if(j===null)return;if(j===0){if(L!=="")q[q.length]=L,L=""}else{q[q.length]=L,L="";for(var me=1;me<j;me+=1)q[q.length]=""}j=null}for(J=0;J<A.length;J++){var H=A.charAt(J);if(p&&H!==Eu)ie();if(V=V||!C&&(H==="*"||H==="?"),P)L+=H,P=!1;else if(C)if(H===C)C=!1;else if(C==ed)L+=H;else if(H===c)if(J+=1,H=A.charAt(J),H===zg||H===c||H===Eu)L+=H;else L+=c+H;else if(H===Eu)L+=ee();else L+=H;else if(H===zg||H===ed)C=H,X=!0;else if(Kg.test(H))return{op:A};else if(_M.test(H)){S=!0;var ce={comment:e.slice(T.index+J+1)};if(L.length)return[L,ce];return[ce]}else if(H===c)P=!0;else if(H===Eu&&A.charAt(J+1)===ed&&BM(A,J))ie(),X=!0,L+=UM(A.slice(J+2,tm.lastIndex-1)),J=tm.lastIndex-1;else if(H===Eu){var fe=ee();if(!p)L+=fe;else for(var _e=0;_e<fe.length;_e+=1){var be=fe.charAt(_e);if(p.indexOf(be)<0)ie(),L+=be;else if(j===null)j=be===" "||be==="\t"||be===`
5
- `?0:1;else if(be!==" "&&be!=="\t"&&be!==`
6
- `)j+=1}}else L+=H}if(V)return{op:"glob",pattern:L};if(p){if(j!==null&&j>0){q[q.length]=L,L="";for(var se=1;se<j;se+=1)q[q.length]=""}if(L!==""||X&&q.length===0)q[q.length]=L;return q}return L}).reduce(function(T,A){if(typeof A>"u")return T;return[].concat(A).forEach(function(C){T[T.length]=C}),T},[])}Qg.exports=function(n,i,c){var p=GM(n,i,c);if(typeof i!=="function")return p;return p.reduce(function(g,y){if(typeof y==="object")return g[g.length]=y,g;var x=y.split(RegExp("("+ji+".*?"+ji+")","g"));if(x.length===1)return g[g.length]=x[0],g;return x.filter(Boolean).forEach(function(b){g[g.length]=NM.test(b)?JSON.parse(b.split(ji)[1]):b}),g},[])}});var Uo={};Xe(Uo,{ArchivedError:()=>dt,BadRequestError:()=>t,BusyError:()=>oe,DEFAULT_TIMEOUT:()=>s$,FoldingPolicy:()=>Bc,MAX_ATTACHMENTS:()=>et,MAX_TIMEOUT:()=>i$,MAX_TOOL_OUTPUT:()=>Pe,NotFoundError:()=>f,PluginCheckError:()=>pt,ProcessRegistry:()=>Wt,Type:()=>oo,aliased:()=>we,budget:()=>Uc,calls:()=>ms,clip:()=>We,clipSaved:()=>nt,dataDir:()=>tt,definePlugin:()=>k,estimateMessage:()=>F,estimateTokens:()=>O,estimateTools:()=>Li,extensionTranscript:()=>Kc,findWindowsBash:()=>tr,foldPoint:()=>Fc,foldedThrough:()=>ya,formatLines:()=>Hc,gateShellCommand:()=>je,groupRuns:()=>Ms,historyTodos:()=>ir,newID:()=>ue,normalizeRunRecords:()=>Dh,processRegistry:()=>sr,project:()=>ke,projectUserText:()=>Ni,releaseProcesses:()=>lr,requestBody:()=>U,resolveShellCommand:()=>ba,retainProcesses:()=>ar,routeParam:()=>E,runShell:()=>rr,sealPoint:()=>iu,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>bl,text:()=>u,timerClock:()=>Re,tool:()=>v,toolSession:()=>K,transcript:()=>mu,usable:()=>$e,userTranscript:()=>Gc,validAttachment:()=>Pt,workState:()=>Sl});var Oo={};Xe(Oo,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>ER,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>TR,EventStream:()=>Qn,InMemoryCredentialStore:()=>Gn,InMemoryModelsStore:()=>zn,ModelsError:()=>I,StringEnum:()=>Dq,Type:()=>oo,appendAssistantMessageDiagnostic:()=>Te,calculateCost:()=>Q,clampThinkingLevel:()=>G,cleanupSessionResources:()=>Pi,collapseSystemMessages:()=>Le,contentText:()=>dr,createAssistantMessageDiagnostic:()=>Ht,createAssistantMessageEventStream:()=>Xn,createFauxCore:()=>bR,createInitialSystemMessage:()=>jn,createModels:()=>Kn,createProvider:()=>d,declarationsEqual:()=>Vn,defaultProviderAuthContext:()=>Fo,envApiKeyAuth:()=>h,extractDiagnosticError:()=>vi,fauxAssistantMessage:()=>Mo,fauxProvider:()=>Lo,fauxText:()=>Ln,fauxThinking:()=>Io,fauxToolCall:()=>gq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>Kr,getCurrentSystemPrompt:()=>Wo,getCurrentTools:()=>ne,getDeclaredTools:()=>ge,getInitialSystemMessage:()=>pe,getModelType:()=>ht,getOverflowPatterns:()=>vq,getSupportedThinkingLevels:()=>Qr,getSystemMessageText:()=>N,getToolStateChanges:()=>$o,hasApi:()=>ki,hasNonAdditiveToolChanges:()=>wi,hasToolRedefinitions:()=>Ti,isContextOverflow:()=>ua,isModelType:()=>Ie,isRecoverableLength:()=>Mq,isRetryableAssistantError:()=>kR,lazyApi:()=>te,lazyOAuth:()=>ae,lazyStream:()=>Ce,modelsAreEqual:()=>Ri,normalizeContext:()=>ft,parseJsonWithRepair:()=>Vr,parseStreamingJson:()=>W,reduceAssistantMessageFrames:()=>Cq,registerSessionResourceCleanup:()=>qn,renderSystemMessageUpdate:()=>Me,repairJson:()=>Bo,resolveTranscript:()=>re,resolveTranscriptTools:()=>ye,retryAssistantCall:()=>Nq,retryDelayMs:()=>RR,toToolDeclaration:()=>ot,uuidv7:()=>jr,validateToolArguments:()=>nu,validateToolCall:()=>SU,withoutInitialSystemMessage:()=>$t});var z={};Xe(z,{Counted:()=>md,Entries:()=>pn,EntriesRegExp:()=>pd,Every:()=>sn,EveryAll:()=>kn,GraphemeCount:()=>Iv,HasPropertyKey:()=>le,IsArray:()=>Be,IsBigInt:()=>Nr,IsBoolean:()=>mn,IsClassInstance:()=>fy,IsConstructor:()=>ud,IsDeepEqual:()=>Ta,IsEqual:()=>_,IsFunction:()=>ls,IsGreaterEqualThan:()=>Sa,IsGreaterThan:()=>Gi,IsInteger:()=>sm,IsLessEqualThan:()=>ds,IsLessThan:()=>wu,IsMaxLength:()=>hy,IsMinLength:()=>gy,IsMultipleOf:()=>dy,IsNull:()=>lo,IsNumber:()=>_t,IsObject:()=>ut,IsObjectNotArray:()=>Jo,IsString:()=>yt,IsSymbol:()=>cd,IsUndefined:()=>Bt,IsUnsafePropertyKey:()=>Tu,IsValueLike:()=>Ki,Keys:()=>Se,ShiftLeft:()=>bt,Some:()=>wa,SomeAll:()=>yy,Symbols:()=>xy,Values:()=>ld});var Xi={};Xe(Xi,{Hash:()=>Id,HashCode:()=>Yy});var Lt={};Xe(Lt,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Ae,ExtendsUnion:()=>Ud,IsExtendsFalse:()=>Kd,IsExtendsTrue:()=>Gd,IsExtendsTrueLike:()=>no,IsExtendsUnion:()=>Bd,Match:()=>br});var oo={};Xe(oo,{Any:()=>Ca,Array:()=>B,BigInt:()=>$u,Boolean:()=>D,Call:()=>pw,Capitalize:()=>xw,Codec:()=>hm,Conditional:()=>kw,Constructor:()=>hs,ConstructorParameters:()=>Cw,Cyclic:()=>xs,Decode:()=>rx,DecodeBuilder:()=>fm,Dependent:()=>Qi,Encode:()=>nx,EncodeBuilder:()=>dm,Enum:()=>By,Evaluate:()=>Tn,Exclude:()=>$w,Extends:()=>wn,ExtendsResult:()=>Lt,Extract:()=>vw,Function:()=>gs,Generic:()=>Zs,Identifier:()=>Mu,Immutable:()=>ox,Index:()=>Nw,Infer:()=>Pu,InstanceType:()=>aT,Instantiate:()=>Ao,Integer:()=>w,Interface:()=>WS,Intersect:()=>Cn,IsAny:()=>Mr,IsArray:()=>wt,IsBigInt:()=>uo,IsBoolean:()=>Wn,IsCall:()=>ja,IsCodec:()=>Hn,IsConstructor:()=>Zr,IsCyclic:()=>Qt,IsDependent:()=>Dr,IsEnum:()=>nn,IsEnumValue:()=>Uy,IsFunction:()=>en,IsGeneric:()=>Aa,IsIdentifier:()=>ux,IsImmutable:()=>Yi,IsInfer:()=>rn,IsInteger:()=>dn,IsIntersect:()=>ze,IsKind:()=>ve,IsLiteral:()=>xt,IsNever:()=>ao,IsNull:()=>bs,IsNumber:()=>kr,IsObject:()=>Qe,IsOptional:()=>un,IsParameter:()=>lx,IsReadonly:()=>ea,IsRecord:()=>Gt,IsRef:()=>jt,IsRefine:()=>gm,IsRest:()=>si,IsSchema:()=>Pr,IsString:()=>on,IsSymbol:()=>Es,IsTemplateLiteral:()=>ur,IsThis:()=>$m,IsTuple:()=>mt,IsUndefined:()=>es,IsUnion:()=>xe,IsUnknown:()=>tn,IsUnsafe:()=>lm,IsVoid:()=>co,KeyOf:()=>cT,Literal:()=>a,Lowercase:()=>Iw,Mapped:()=>yT,Module:()=>sR,Never:()=>zt,NonNullable:()=>ET,Null:()=>Pn,Number:()=>Y,Object:()=>s,Omit:()=>wT,Optional:()=>o,Parameter:()=>ta,Parameters:()=>kT,Partial:()=>CT,Pick:()=>LT,Readonly:()=>sx,ReadonlyObject:()=>bf,ReadonlyType:()=>qT,Record:()=>Ss,RecordKey:()=>oi,RecordPattern:()=>fn,RecordValue:()=>fr,Ref:()=>an,Refine:()=>ix,Required:()=>ZT,Rest:()=>na,ReturnType:()=>tR,Script:()=>cR,String:()=>l,Symbol:()=>Ma,TemplateLiteral:()=>dS,This:()=>Pm,Tuple:()=>Br,Uncapitalize:()=>bw,Undefined:()=>_a,Union:()=>m,Unknown:()=>Rr,Unsafe:()=>$r,Uppercase:()=>Ew,Void:()=>Mm,With:()=>hp});var eu={};Xe(eu,{Clear:()=>Bk,Entries:()=>KF,Get:()=>zF,Has:()=>WF,IsDate:()=>Xa,IsDateTime:()=>Tp,IsDuration:()=>Rp,IsEmail:()=>kp,IsHostname:()=>_p,IsIPv4:()=>Dp,IsIPv6:()=>qp,IsIdnEmail:()=>Lp,IsIdnHostname:()=>Np,IsIri:()=>jp,IsIriReference:()=>Fp,IsJsonPointer:()=>Bp,IsJsonPointerUriFragment:()=>Up,IsRegex:()=>Gp,IsRelativeJsonPointer:()=>Kp,IsTime:()=>Ya,IsUri:()=>zp,IsUriReference:()=>Hp,IsUriTemplate:()=>Wp,IsUrl:()=>Vp,IsUuid:()=>Jp,Reset:()=>Kk,Set:()=>HF,Test:()=>Gk});var bu="shell-guard",_g=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class f extends Error{constructor(e){super(e);this.name="NotFoundError"}}function Lg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Ng(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function RM(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 g=1;g<=n.length;g++){let y=i[g]??0;i[g]=Math.min((i[g]??0)+1,(i[g-1]??0)+1,p+(e[c-1]===n[g-1]?0:1)),p=y}}return i[n.length]??0}function Dg(e,n){let i=Lg(e);if(!i)return[];let c=Ng(e),p=[];for(let g of n){let y=g.id.indexOf("/"),x=y>=0?g.id.slice(y+1):"",S=[g.id,g.name,x].filter(Boolean).map((A)=>({compact:Lg(A),tokens:Ng(A)})).filter((A)=>A.compact.length>0),T=Number.POSITIVE_INFINITY;for(let A of S)if(A.compact===i)T=Math.min(T,0);else if(A.compact.includes(i)||i.includes(A.compact)){let C=Math.abs(A.compact.length-i.length);T=Math.min(T,1+C/Math.max(A.compact.length,i.length))}else{let C=0;for(let P of c)if(A.tokens.has(P))C++;if(C>0){let P=C/Math.max(c.size,A.tokens.size);T=Math.min(T,10+(1-P)*10)}}if(!Number.isFinite(T)&&i.length>=4){let A=Math.max(2,Math.floor(i.length*0.34));for(let C of S){if(Math.abs(C.compact.length-i.length)>A)continue;let P=RM(i,C.compact);if(P<=A)T=Math.min(T,100+P)}}if(Number.isFinite(T))p.push({model:g,score:T})}return p.sort((g,y)=>g.score-y.score||g.model.id.localeCompare(y.model.id))}function kM(e,n,i=5){return Dg(e,n).slice(0,Math.max(1,i)).map((c)=>c.model)}function pi(e,n){let i=Dg(e,n);if(i.length===0)return;let c=i.filter((g)=>g.score===0);if(c.length===1&&c[0])return c[0].model;if(c.length>1)return;let p=i.filter((g)=>g.score<10);if(p.length===1&&p[0])return p[0].model;return}function di(e,n){let i=[...n].sort((y,x)=>y.id.localeCompare(x.id)),c=(y)=>y.name===y.id?y.id:`${y.id} (${y.name})`,p=kM(e,i).map(c),g=i.map(c);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${g.length}): ${g.length>0?g.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
- `)}var mi=["openai-completions","openai-responses","anthropic-messages"];function Fr(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 Jl(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 AM(e){let n=e.trim();if(!n)return;let i,c,p=n,g=p.match(/\s*\[(.*?)\]\s*$/);if(g&&g.index!==void 0){p=p.slice(0,g.index).trim();let T=g[1]?.split(",").map((C)=>C.trim()).filter(Boolean)??[],A=0;for(let C of T){let P=C.indexOf("=");if(P>=0){let L=C.slice(0,P).trim().toLowerCase(),q=Fr(C.slice(P+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=Fr(C);if(A===0)i=L;else if(A===1)c=L;A++}}}else{let T=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(T?.[1]&&T[2])p=T[1].trim(),i=Fr(T[2])}let y=p.indexOf("="),x,b;if(y<0)x=p.trim(),b=x;else x=p.slice(0,y).trim(),b=p.slice(y+1).trim()||x;if(!x)return;let S={id:x,name:b};if(i!==void 0)S.contextWindow=i;if(c!==void 0)S.maxTokens=c;return S}function er(e){return e.split(/\r?\n/).map(AM).filter((n)=>n!==void 0)}function ko(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(Jl(n.contextWindow));if(n.maxTokens!==void 0)if(n.contextWindow!==void 0)c.push(Jl(n.maxTokens));else c.push(`max=${Jl(n.maxTokens)}`);return c.length>0?`${i} [${c.join(", ")}]`:i}).join(`
8
- `)}var qg=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var Mn=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],hi=["text","regex"],fi=["best","recent"],gi=["session","none"];var Ft=4,yi="https://basalt.work",bi=["https://basalt.work","https://www.basalt.work"],Wr=7420;var Ql=["auto","bash","powershell","cmd"];var Ro=["active","archived","all"];var Fg=["pending","in_progress","completed"],Xl="basalt-session",Zc=["image","text","path"];var jg=["defer","always"],Ug=["global","tool","source"];function Ee(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}}}function Si(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var et=10,CM=15000000;function Pt(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"&&Zc.includes(n.kind)&&typeof n.data==="string"&&n.data.length>0&&n.data.length<=CM}function Yl(e){return e?.map((n)=>({...n,id:`att_${crypto.randomUUID().slice(0,8)}`}))}var KM=Gg(),td=Xg();import{AsyncLocalStorage as HM}from"async_hooks";var K=new HM;var WM=3,Yg=160,zM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),VM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),ty=/^[A-Za-z_][A-Za-z0-9_]*=/,JM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),QM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),XM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,YM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),ZM=new Set(["command","builtin","nohup","time","exec"]),ev=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 rm(e){return{out:e.out,depth:e.depth+1}}function Zg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function rd(e,n,i,c){let p=e.length,g=0,y=n;while(y<p){let x=e.charAt(y);if(x==="\\"){y+=2;continue}if(x==="'"||x==='"'||x==="`"){let b=y+1;while(b<p){let S=e.charAt(b);if(S==="\\"){b+=2;continue}if(S===x)break;b++}y=b+1;continue}if(x===i)g++;else if(x===c){if(g--,g===0)return y+1}y++}return p}function tv(e){let n={text:"",subs:[],heredocs:[]},i=[],c=[],p=e.length,g=0,y=0,x=null,b=(S)=>{if(e.charAt(S)==="`"){let P=S+1;while(P<p){let L=e.charAt(P);if(L==="\\"){P+=2;continue}if(L==="`")break;P++}return n.subs.push(e.slice(S+1,P)),P<p?P+1:p}if(e.charAt(S+1)==="("){let P=rd(e,S+1,"(",")");if(e.charAt(S+2)==="(")return i.push(e.slice(S,P)),P;return n.subs.push(e.slice(S+2,P-1)),P}let A=rd(e,S+1,"{","}"),C=e.slice(S+2,A-1);for(let P=0;P<C.length;P++){let L=C.charAt(P);if(L==="\\"){P++;continue}if(L==="`"){let q=C.indexOf("`",P+1);n.subs.push(q<0?C.slice(P+1):C.slice(P+1,q)),P=q<0?C.length:q;continue}if(L==="$"&&C.charAt(P+1)==="("){let q=rd(C,P+1,"(",")");n.subs.push(C.slice(P+2,q-1)),P=q-1}}return A};while(g<p){let S=e.charAt(g);if(x==="'"){if(S==="'")x=null;i.push(S),g++;continue}if(x==='"'){if(S==="\\"){if(!'$`"\\\n'.includes(e.charAt(g+1)))i.push("\\");i.push(S,e.charAt(g+1)),g+=2;continue}if(S==='"'){x=null,i.push(S),g++;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=b(g);continue}i.push(S),g++;continue}if(S==="'"||S==='"'){x=S,i.push(S),g++;continue}if(S==="\\"){i.push(S,e.charAt(g+1)),g+=2;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=b(g);continue}if(S==="#"){let T=i.at(-1);if(T===void 0||`
9
- ;&|()`.includes(T)){while(g<p&&e.charAt(g)!==`
10
- `)g++;continue}i.push(S),g++;continue}if(S==="<"&&e.charAt(g+1)==="<"&&e.charAt(g+2)!=="<"){let T=g+2;if(e.charAt(T)==="-")T++;i.push(e.slice(g,T));let A=T;while(A<p&&(e.charAt(A)===" "||e.charAt(A)==="\t"))A++;let C="";while(A<p){let P=e.charAt(A);if(P==="'"||P==='"'){let L=e.indexOf(P,A+1);if(L<0)break;C+=e.slice(A+1,L),A=L+1;continue}if(P==="\\"){C+=e.charAt(A+1),A+=2;continue}if(` \r
11
- ;&|()<>`.includes(P))break;C+=P,A++}if(C)c.push(C);g=T;continue}if(S===`
12
- `){if(c.length>0){let T=XM.test(i.slice(y).join(""));g++;for(let A of c.splice(0)){let C=g,P=p;while(g<p){let L=e.indexOf(`
13
- `,g),q=L<0?p:L;if(e.slice(g,q).trim()===A){P=g,g=L<0?p:L+1;break}g=L<0?p:L+1}if(T&&P>C)n.heredocs.push(e.slice(C,P))}}else g++;i.push(";",`
14
- `),y=i.length;continue}i.push(S),g++}return n.text=i.join(""),n}function Su(e,n){if(n.depth>WM)return;let i=tv(e),c;try{c=td(i.text)}catch{return}let p=[];for(let g of c){if(typeof g==="string"){p.push({kind:"word",text:g});continue}if("pattern"in g){p.push({kind:"word",text:g.pattern});continue}if("op"in g)p.push({kind:"op",text:g.op})}rv(p,n);for(let g of i.subs)Su(g,rm(n));for(let g of i.heredocs)Su(g,rm(n))}function rv(e,n){let i=[],c=()=>{if(i.length>0)nv(i,n);i=[]};for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;if(g.kind==="op"){if(JM.has(g.text)){c();continue}if(QM.has(g.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(g.text)}c()}function nv(e,n){let i=0;for(;;){let y=e[i];if(y===void 0)return;if(VM.has(y)||ty.test(y)){i++;continue}let x=sv(Zg(y),e,i);if(x===i)break;i=x}let c=e[i];if(c===void 0)return;let p=Zg(c),g=e.slice(i+1);if(p==="git"){av(c,g,n);return}if(zM.has(p)){ov(g,n);return}if(p==="powershell"||p==="pwsh")ey(g,/^-(command|c)$/i,n);if(p==="cmd")ey(g,/^\/[ck]$/i,n)}function ey(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())Su(p,rm(i));return}}function ov(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 g=p[1]||e[i+1];if(g)Su(g,rm(n));return}if(c.startsWith("-")||c==="")continue;return}}function sv(e,n,i){if(ZM.has(e)){let g=i+1;while(n[g]?.startsWith("-"))g++;return g}let c=ev.get(e);if(!c)return i;let p=i+1;for(;;){let g=n[p];if(g===void 0)return p;if(c.includes(g)){p+=2;continue}if(ty.test(g)||g.startsWith("-")){p++;continue}return p}}function Vo(e,n){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(n))}function eo(e,n){return e.some((i)=>i===`--${n}`||i.startsWith(`--${n}=`))}var iv={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Vo(e,"f")||Vo(e,"i")||eo(e,"force")||eo(e,"interactive"))&&!(Vo(e,"n")||eo(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Vo(e,"f")||eo(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Vo(e,"f")||eo(e,"force")||Vo(e,"C")||eo(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)=>Vo(e,"f")||eo(e,"force")||eo(e,"force-with-lease")||eo(e,"force-if-includes")||eo(e,"delete")||eo(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)=>eo(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Vo(e,"D")||Vo(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)=>eo(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)=>Vo(e,"f")||eo(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"&&(Vo(e,"f")||eo(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function av(e,n,i){let c=0;for(;;){let b=n[c];if(b===void 0)break;if(YM.has(b)){c+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(b)||/^-[Cc].+/.test(b)||b.startsWith("-")){c++;continue}break}let p=n[c]?.toLowerCase();if(!p)return;let g=iv[p];if(!g)return;let y=g(n.slice(c+1));if(!y)return;let x=[e,...n.slice(c)].join(" ");i.out.push({rule:p,fragment:x.length>Yg?`${x.slice(0,Yg)}\u2026`:x,reason:y})}function od(e){let n={out:[],depth:0};return Su(e,n),n.out}function ry(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 nd=new Map;function uv(e,n,i,c,p){let g=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((y)=>{let x=(S)=>{if(!nd.delete(g))return;p?.removeEventListener("abort",b),y(S)},b=()=>{ny(e,g),x("aborted")};if(nd.set(g,{session:e,finish:x}),e.appendExtension({namespace:bu,kind:"requested",schemaVersion:1,payload:{id:g,sessionID:e.id,command:n.slice(0,4000),summary:c.slice(0,5).map(({fragment:S,reason:T})=>({fragment:S,reason:T})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)b();else p?.addEventListener("abort",b,{once:!0})})}function ny(e,n){try{e.appendExtension({namespace:bu,kind:"cancelled",schemaVersion:1,payload:{id:n,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Co(e,n,i){let c=nd.get(n);if(!c||c.session!==e){if(!cv(e,n))return"unknown";return ny(e,n),"expired"}return e.appendExtension({namespace:bu,kind:"answered",schemaVersion:1,payload:{id:n,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),c.finish(i?"approved":"denied"),"answered"}function cv(e,n){let i=!1;for(let c of e.entries()){if(c.type!=="extension"||c.namespace!==bu)continue;let p=c.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==n)continue;if(c.kind==="requested")i=!0;else if(c.kind==="answered"||c.kind==="cancelled")return!1}return i}function sd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${ry(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function je(e,n){let i=od(e);if(!i.at(0))return;let p=ry(i),g=K.getStore();if(g?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(n?.aborted)return`${sd(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let y=await uv(g,e,p,i,n);if(y==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${y==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{existsSync as mv,mkdirSync as pv,writeFileSync as lv}from"fs";import{homedir as dv}from"os";import{join as Ui}from"path";function tt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let n=dv();if(process.platform==="win32")return Ui(e.LOCALAPPDATA??Ui(n,"AppData","Local"),"basalt");if(process.platform==="darwin")return Ui(n,"Library","Application Support","basalt");return Ui(e.XDG_DATA_HOME??Ui(n,".local","share"),"basalt")}function fv(e){return Ui(e,".basalt","tmp")}function id(e){let n=fv(e);pv(n,{recursive:!0});let i=Ui(n,".gitignore");if(!mv(i))lv(i,`*
15
- !.gitignore
16
- `);return n}function nm(e){try{let n=id(e);return{TMPDIR:n,TEMP:n,TMP:n}}catch{return{}}}var ps={assign:0,create:0,clone:0,discard:0,update:0};function Bi(e,n,i){return e>=n&&e<=i}function iy(e){return e===8205}function hv(e){return Bi(e,55296,56319)}function oy(e){return Bi(e,127462,127487)}function ay(e){return Bi(e,65024,65039)}function uy(e){return Bi(e,768,879)||Bi(e,6832,6911)||Bi(e,7616,7679)||Bi(e,65056,65071)}function om(e){return e>65535?2:1}function sy(e,n){while(n<e.length){let i=e.codePointAt(n);if(uy(i)||ay(i))n+=om(i);else break}return n}function ad(e,n){let i=e.codePointAt(n),c=n+om(i);c=sy(e,c);while(c<e.length-1&&iy(e.codePointAt(c))){let p=e.codePointAt(c+1);c+=1+om(p),c=sy(e,c)}if(oy(i)&&c<e.length&&oy(e.codePointAt(c)))c+=om(e.codePointAt(c));return c}function cy(e){return e>=768&&(hv(e)||uy(e)||ay(e)||iy(e))}function my(e){let n=0,i=0;while(i<e.length)i=ad(e,i),n++;return n}function gv(e,n){let i=0,c=0;while(c<e.length)if(c=ad(e,c),++i>=n)return!0;return!1}function yv(e,n){let i=0,c=0;while(c<e.length)if(c=ad(e,c),++i>n)return!1;return!0}function py(e,n){if(n===0)return!0;if(e.length<n)return!1;let i=0;while(!0){if(cy(e.charCodeAt(i)))return gv(e,n);if(++i>=n)return!0}}function ly(e,n){if(e.length<=n)return!0;let i=0;while(!0){if(cy(e.charCodeAt(i)))return yv(e,n);if(++i>n)return!1}}function Be(e){return Array.isArray(e)}function Nr(e){return _(typeof e,"bigint")}function mn(e){return _(typeof e,"boolean")}function ud(e){if(Bt(e)||!ls(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 ls(e){return _(typeof e,"function")}function sm(e){return Number.isInteger(e)}function lo(e){return _(e,null)}function _t(e){return Number.isFinite(e)}function Jo(e){return ut(e)&&!Be(e)}function ut(e){return _(typeof e,"object")&&!lo(e)}function yt(e){return _(typeof e,"string")}function cd(e){return _(typeof e,"symbol")}function Bt(e){return _(e,void 0)}function _(e,n){return e===n}function Gi(e,n){return e>n}function wu(e,n){return e<n}function ds(e,n){return e<=n}function Sa(e,n){return e>=n}function dy(e,n){if(Nr(e)||Nr(n))return BigInt(e)%BigInt(n)===0n;let i=0.0000000001;if(!_t(e))return!0;if(sm(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 fy(e){if(!ut(e))return!1;let n=globalThis.Object.getPrototypeOf(e);if(lo(n))return!1;return _(typeof n.constructor,"function")&&!(_(n.constructor,globalThis.Object)||_(n.constructor.name,"Object"))}function Ki(e){return Nr(e)||mn(e)||lo(e)||_t(e)||yt(e)||Bt(e)}function Iv(e){return my(e)}function hy(e,n){return ly(e,n)}function gy(e,n){return py(e,n)}function sn(e,n,i){return e.every((c,p)=>p<n||i(c,p))}function kn(e,n,i){let c=!0;return e.forEach((p,g)=>{if(g>=n&&!i(p,g))c=!1}),c}function wa(e,n){return e.some((i,c)=>n(i,c))}function yy(e,n){let i=!1;return e.forEach((c,p)=>{if(n(c,p))i=!0}),i}function md(e,n){return e.reduce((i,c,p)=>n(c,p)?++i:i,0)}function bt(e,n,i){return _(e.length,0)?i():n(e[0],e.slice(1))}function Tu(e){return _(e,"__proto__")||_(e,"constructor")||_(e,"prototype")}function le(e,n){return Tu(n)?Object.prototype.hasOwnProperty.call(e,n):(n in e)}function pd(e){return Se(e).map((n)=>[new RegExp(`^${n}$`),e[n]])}function pn(e){return Object.entries(e)}function Se(e){return Object.getOwnPropertyNames(e)}function xy(e){return Object.getOwnPropertySymbols(e)}function ld(e){return Object.values(e)}function bv(e,n){if(!ut(n))return!1;let i=Se(e);return _(i.length,Se(n).length)&&i.every((c)=>Ta(e[c],n[c]))}function Ev(e,n){return Be(n)&&_(e.length,n.length)&&e.every((i,c)=>Ta(e[c],n[c]))}function Ta(e,n){return Be(e)?Ev(e,n):ut(e)?bv(e,n):_(e,n)}var Sv=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function wv(e){return Sv.test(e)}function En(e,n){return`(${e} && ${n})`}function xr(e,n){return`(${e} || ${n})`}function Un(e){return`!(${e})`}function im(e){return`Array.isArray(${e})`}function Iy(e){return`typeof ${e} === "bigint"`}function Tv(e){return`typeof ${e} === "boolean"`}function Rv(e){return`Number.isInteger(${e})`}function kv(e){return`${e} === null`}function by(e){return`Number.isFinite(${e})`}function Ey(e){return En(Sy(e),Un(im(e)))}function Sy(e){return`typeof ${e} === "object" && ${e} !== null`}function wy(e){return`typeof ${e} === "string"`}function Av(e){return`typeof ${e} === "symbol"`}function dd(e){return`${e} === undefined`}function Cv(e){return`typeof ${e} === "function"`}function Pv(e){return`Guard.IsConstructor(${e})`}function io(e,n){return`${e} === ${n}`}function Ty(e,n){return`${e} > ${n}`}function fd(e,n){return`${e} < ${n}`}function Hi(e,n){return`${e} <= ${n}`}function Ru(e,n){return`${e} >= ${n}`}function $v(e,n){return`Guard.IsMinLength(${e}, ${n})`}function Mv(e,n){return`Guard.IsMaxLength(${e}, ${n})`}function fs(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 vv(e,n,i){return`${e}.some((${n[0]}, ${n[1]}) => ${i})`}function Ov(e,n,i){return`((value) => { let result = false; value.forEach((${n[0]}, ${n[1]}) => { if (${i}) result = true }); return result })(${e})`}function am(e,n,i){return`${e}.reduce((result, ${n[0]}, ${n[1]}) => (${i}) ? ++result : result, 0)`}function Ry(e){return`Object.entries(${e})`}function Wi(e){return`Object.getOwnPropertyNames(${e})`}function zi(e,n){return _(n,'"__proto__"')||_(n,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${n})`:`${n} in ${e}`}function ky(e,n){return`Guard.IsDeepEqual(${e}, ${n})`}function _v(e){return`[${e.join(", ")}]`}function Qs(e,n){return`((${e.join(", ")}) => ${n})`}function Ir(e,n){return`${e}(${n.join(", ")})`}function hd(e,n){return`new ${e}(${n.join(", ")})`}function Et(e,n){return`${e}${wv(n)?`.${n}`:`[${De(n)}]`}`}function De(e){if(!Ki(e))throw Error("Unsupported Constant");return yt(e)?JSON.stringify(e):`${e}`}function Lv(e,n,i){return`(${e} ? ${n} : ${i})`}function um(e){return`{ ${e.join("; ")}; }`}function _s(e,n){return`const ${e} = ${n}`}function Ay(e,n){return`if(${e}) { ${n} }`}function cm(e){return`return ${e}`}function An(e){return _(e.length,0)?"true":e.reduce((n,i)=>En(n,i))}function gd(e){return _(e.length,0)?"false":e.reduce((n,i)=>xr(n,i))}function Nv(e,n){return`Guard.IsMultipleOf(${e}, ${n})`}function Dv(e){return e instanceof Boolean}function qv(e){return e instanceof Number}function Fv(e){return e instanceof String}function Cy(e){return globalThis.ArrayBuffer.isView(e)}function Py(e){return e instanceof globalThis.RegExp}function jv(e){return e instanceof globalThis.Date}function Uv(e){return e instanceof globalThis.Set}function Bv(e){return e instanceof globalThis.Map}var Kv={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Qo(){return Kv}function Xs(e){return Qo().immutableTypes?Object.freeze(e):e}function ln(e,n){return ps.assign+=1,Xs({...e,...n})}function Hv(e){return e}function Wv(e){return le(e,"~kind")||le(e,"~unsafe")}function zv(e){let n={};for(let i of Se(e)){if(Tu(i))continue;let c=Object.getOwnPropertyDescriptor(e,i);if(c.value=Vi(c.value),_(c.enumerable,!0))n[i]=c.value;else Object.defineProperty(n,i,c)}return n}function Vv(e){let n={};for(let i of Se(e)){if(Tu(i))continue;n[i]=Vi(e[i])}for(let i of xy(e))n[i]=Vi(e[i]);return n}function Jv(e){return fy(e)?Hv(e):Wv(e)?zv(e):Vv(e)}function Qv(e){return e.map((n)=>Vi(n))}function Xv(e){return e.slice()}function Yv(e){return new RegExp(e.source,e.flags)}function Zv(e){return new Map(Vi([...e.entries()]))}function eO(e){return new Set(Vi([...e.values()]))}function Vi(e){return Cy(e)?Xv(e):Py(e)?Yv(e):Bv(e)?Zv(e):Uv(e)?eO(e):Be(e)?Qv(e):ut(e)?Jv(e):e}function Ra(e){return ps.clone+=1,Vi(e)}function tO(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 $y(e,n){return{...e,...n}}function Mt(e,n,i={}){ps.create+=1;let c=$y(n,i),p=Qo().enumerableKind?$y(c,e):tO(c,e);return Xs(p)}function Xo(e,n){ps.discard+=1;let i={};for(let c of Se(e)){if(n.includes(c))continue;let p=Object.getOwnPropertyDescriptor(e,c);p.value=Ra(p.value),Object.defineProperty(i,c,p)}return Xs(i)}function St(e,n,i){ps.update+=1;let c=Qo(),p=Ra(e);for(let g of Object.keys(n))Object.defineProperty(p,g,{configurable:!0,writable:!0,enumerable:c.enumerableKind,value:n[g]});for(let g of Object.keys(i))Object.defineProperty(p,g,{configurable:!0,enumerable:!0,writable:!0,value:i[g]});return Xs(p)}function ve(e,n){return ut(e)&&le(e,"~kind")&&_(e["~kind"],n)}function Pr(e){return ut(e)}function Ne(e,n,i){return Mt({"~kind":"Deferred"},{type:"deferred",action:e,parameters:n,options:i},{})}function Ys(e){return ve(e,"Deferred")}function rO(e){return St(e,{"~readonly":!0},{})}function Au(e,n){return St(rO(e),{},n)}function My(e,n,i,c){let p=de(e,n,i);return Au(p,c)}function nO(e){return St(e,{"~optional":!0},{})}function Cu(e,n){return St(nO(e),{},n)}function vy(e,n,i,c){let p=de(e,n,i);return Cu(p,c)}function B(e,n){return Mt({"~kind":"Array"},{type:"array",items:e},n)}function wt(e){return ve(e,"Array")}function ka(e){return Xo(e,["~kind","type","items"])}function hs(e,n,i={}){return Mt({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:n},i)}function Zr(e){return ve(e,"Constructor")}function Oy(e){return Xo(e,["~kind","type","parameters","instanceType"])}function gs(e,n,i={}){return Mt({["~kind"]:"Function"},{type:"function",parameters:e,returnType:n},i)}function en(e){return ve(e,"Function")}function _y(e){return Xo(e,["~kind","type","parameters","returnType"])}function an(e,n){return Mt({["~kind"]:"Ref"},{$ref:e},n)}function jt(e){return ve(e,"Ref")}function Zs(e,n){return Mt({"~kind":"Generic"},{type:"generic",parameters:e,expression:n})}function Aa(e){return ve(e,"Generic")}function Ca(e){return Mt({["~kind"]:"Any"},{},e)}function Mr(e){return ve(e,"Any")}var Ly="(?!)";function zt(e){return Mt({"~kind":"Never"},{not:{}},e)}function ao(e){return ve(e,"Never")}function ys(e,n={}){return Ne("AddOptional",[e],n)}function Ji(e,n={}){return Cu(e,n)}function o(e){return Ji(e)}function un(e){return Pr(e)&&le(e,"~optional")}function Ny(e){return Se(e).filter((n)=>!un(e[n]))}function mm(e){return Se(e)}function pm(e){return ld(e)}function s(e,n={}){let i=Ny(e),c=i.length>0?{required:i}:{};return Mt({"~kind":"Object"},{type:"object",...c,properties:e},n)}function Qe(e){return ve(e,"Object")}function Dy(e){return Xo(e,["~kind","type","properties","required"])}function Rr(e){return Mt({["~kind"]:"Unknown"},{},e)}function tn(e){return ve(e,"Unknown")}function xs(e,n,i){let c=Se(e).reduce((p,g)=>({...p,[g]:St(e[g],{},{$id:g})}),{});return Mt({["~kind"]:"Cyclic"},{$defs:c,$ref:n},i)}function Qt(e){return ve(e,"Cyclic")}function $r(e){return St(e,{["~unsafe"]:null},{})}function lm(e){return Jo(e)&&le(e,"~unsafe")&&lo(e["~unsafe"])}function Sn(e,n){return n[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Pu(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p,p],1:(c)=>[c,Rr(),Rr()]});return Mt({["~kind"]:"Infer"},{type:"infer",name:n,extends:i},{})}function rn(e){return ve(e,"Infer")}function Qi(e,n,i,c={}){return Mt({"~kind":"Dependent"},{if:e,then:n,else:i},c)}function Dr(e){return ve(e,"Dependent")}function qy(e){return Xo(e,["~kind","if","then","else"])}function Fy(e){return Jo(e)}function jy(e){return Se(e).filter((i)=>isNaN(i)).reduce((i,c)=>[...i,e[c]],[])}function Uy(e){return yt(e)||_t(e)}function By(e,n){let i=Fy(e)?jy(e):e;return Mt({"~kind":"Enum"},{enum:i},n)}function nn(e){return ve(e,"Enum")}function Cn(e,n={}){return Mt({"~kind":"Intersect"},{allOf:e},n)}function ze(e){return ve(e,"Intersect")}function Gy(e){return Xo(e,["~kind","allOf"])}var yd=void 0;function oO(){try{return Hy("null")(),!0}catch{return!1}}function Ky(){if(Bt(yd))yd=oO();return yd&&Qo().useAcceleration}function Hy(...e){return new globalThis.Function(...e)}function Ur(){throw Error("Unreachable")}function sO(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 iO(e){return typeof e==="number"}var Bn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Bn||(Bn={}));var Pa=BigInt("14695981039346656037"),[aO,uO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],cO=Array.from({length:256}).map((e,n)=>BigInt(n)),Jy=new Float64Array(1),Qy=new DataView(Jy.buffer),Xy=new Uint8Array(Jy.buffer);function xn(e){Pa=Pa^cO[e],Pa=Pa*aO%uO}function mO(e){xn(Bn.Array);for(let n of e)ei(n)}function pO(e){xn(Bn.BigInt),Qy.setBigInt64(0,e);for(let n of Xy)xn(n)}function zy(e){xn(Bn.Boolean),xn(e?1:0)}function lO(e){xn(Bn.Constructor),ei(e.toString())}function dO(e){xn(Bn.Date),ei(e.getTime())}function fO(e){xn(Bn.Function),ei(e.toString())}function hO(e){xn(Bn.Null)}function Vy(e){xn(Bn.Number),Qy.setFloat64(0,e,!0);for(let n of Xy)xn(n)}function gO(e){xn(Bn.Object);for(let n of sO(e).sort())ei(n),ei(e[n])}function yO(e){xn(Bn.RegExp),xd(e.toString())}var xO=new TextEncoder;function xd(e){xn(Bn.String);for(let n of xO.encode(e))xn(n)}function IO(e){xn(Bn.Symbol),ei(e.toString())}function bO(e){xn(Bn.TypeArray);let n=new Uint8Array(e.buffer);for(let i=0;i<n.length;i++)xn(n[i])}function EO(e){return xn(Bn.Undefined)}function ei(e){return Cy(e)?bO(e):jv(e)?dO(e):Py(e)?yO(e):Dv(e)?zy(e.valueOf()):Fv(e)?xd(e.valueOf()):qv(e)?Vy(e.valueOf()):iO(e)?Vy(e):Be(e)?mO(e):mn(e)?zy(e):Nr(e)?pO(e):ud(e)?lO(e):lo(e)?hO(e):ut(e)?gO(e):yt(e)?xd(e):cd(e)?IO(e):Bt(e)?EO(e):ls(e)?fO(e):Ur()}function Yy(e){return Pa=BigInt("14695981039346656037"),ei(e),Pa}function Id(e){return Yy(e).toString(16).padStart(16,"0")}function Zy(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 SO=Zy;function ex(){return SO}class dm{constructor(e,n){this.type=e,this.decode=n}Encode(e){let n=this.type,i=Hn(n)?(g)=>this.decode(n["~codec"].decode(g)):this.decode,c=Hn(n)?(g)=>n["~codec"].encode(e(g)):e,p={decode:i,encode:c};return St(this.type,{"~codec":p},{})}}class fm{constructor(e){this.type=e}Decode(e){return new dm(this.type,e)}}function hm(e){return new fm(e)}function rx(e,n){return hm(e).Decode(n).Encode(()=>{throw Error("Encode not implemented")})}function nx(e,n){return hm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(n)}function Hn(e){return Pr(e)&&le(e,"~codec")&&ut(e["~codec"])&&le(e["~codec"],"encode")&&le(e["~codec"],"decode")}function ox(e){return $a(e)}function Yi(e){return Pr(e)&&le(e,"~immutable")}function Is(e,n={}){return Ne("AddReadonly",[e],n)}function Zi(e,n={}){return Au(e,n)}function sx(e){return Zi(e)}function ea(e){return Pr(e)&&le(e,"~readonly")}function TO(e,n){let i=gm(e)?[...e["~refine"],n]:[n];return St(e,{"~refine":i},{})}function ix(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,()=>"Refine Error"]});return TO(n,{check:i,error:c})}function RO(e){return Jo(e)&&le(e,"check")&&le(e,"error")&&ls(e.check)&&ls(e.error)}function gm(e){return Pr(e)&&le(e,"~refine")&&Be(e["~refine"])&&sn(e["~refine"],0,(n)=>RO(n))}var ax="-?(?:0|[1-9][0-9]*)n";function $u(e){return Mt({"~kind":"BigInt"},{type:"bigint"},e)}function uo(e){return ve(e,"BigInt")}function D(e){return Mt({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return ve(e,"Boolean")}function Mu(e){return Mt({"~kind":"Identifier"},{name:e})}function ux(e){return ve(e,"Identifier")}var ym="-?(?:0|[1-9][0-9]*)";function w(e){return Mt({"~kind":"Integer"},{type:"integer"},e)}function dn(e){return ve(e,"Integer")}class cx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function kO(e){return Nr(e)?"bigint":mn(e)?"boolean":_t(e)?"number":yt(e)?"string":(()=>{throw new cx(e)})()}function a(e,n){return Mt({"~kind":"Literal"},{type:kO(e),const:e},n)}function xm(e){return Nr(e)||mn(e)||_t(e)||yt(e)}function mx(e){return xt(e)&&Nr(e.const)}function px(e){return xt(e)&&mn(e.const)}function Im(e){return xt(e)&&_t(e.const)}function bm(e){return xt(e)&&yt(e.const)}function xt(e){return ve(e,"Literal")}function Pn(e){return Mt({"~kind":"Null"},{type:"null"},e)}function bs(e){return ve(e,"Null")}var Em="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Y(e){return Mt({"~kind":"Number"},{type:"number"},e)}function kr(e){return ve(e,"Number")}function Ma(e){return Mt({"~kind":"Symbol"},{type:"symbol"},e)}function Es(e){return ve(e,"Symbol")}function ta(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,g],1:(p)=>[p,Rr(),Rr()]});return Mt({"~kind":"Parameter"},{name:n,extends:i,equals:c},{})}function lx(e){return ve(e,"Parameter")}var Sm=".*";function l(e){return Mt({"~kind":"String"},{type:"string"},e)}function on(e){return ve(e,"String")}function m(e,n={}){return Mt({"~kind":"Union"},{anyOf:e},n)}function xe(e){return ve(e,"Union")}function dx(e){return Xo(e,["~kind","anyOf"])}function vu(e){let n=fx(e);return _(n.length,2)?n[0]:[]}function AO(e){return!0}function hx(e){return bt(e,(n,i)=>CO(n)?hx(i):!1,()=>!0)}function gx(e){return _(e.length,0)?!1:hx(e)}function CO(e){return xe(e)?gx(e.anyOf):xt(e)?AO(e.const):!1}function wm(e){return gx(e)}function Tm(e){return Mt({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function yx(e,n,i=[]){return bt(e,(c,p)=>yx(p,n,[...i,`${c}${n}`]),()=>i)}function PO(e,n){return _(e.length,0)?[`${n}`]:yx(e,n)}function xx(e,n,i=[]){return bt(n,(c,p)=>xx(e,p,[...i,...Ix(e,c)]),()=>i)}function Ix(e,n){return xe(n)?xx(e,n.anyOf):xt(n)?PO(e,n.const):Ur()}function bx(e,n){return bt(n,(i,c)=>bx(Ix(e,i),c),()=>e)}function $O(e){return e.map((n)=>a(n))}function MO(e){let n=bx([],e),i=$O(n);return m(i)}function vO(e){return _(e.length,0)?Ur():_(e.length,1)&&xt(e[0])?e[0]:MO(e)}function bd(e){let n=vu(e);return _(n.length,0)?l():wm(n)?vO(n):Tm(e)}function Ou(e){let n=bd(e);return ur(n)?l():n}function to(e,n){let c={[e]:n};return Mt({["~kind"]:"Record"},{type:"object",patternProperties:c})}function Ex(e){return to(Yo,e)}function Sx(e){return s({true:e,false:e})}function Br(e,n={}){let[i,c,p]=[e,e.length,!1];return Mt({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:c},n)}function mt(e){return ve(e,"Tuple")}function wx(e){return Xo(e,["~kind","type","items","minItems","additionalItems"])}function OO(e){return Xo(e,["~readonly"])}function Ed(e,n){return St(OO(e),{},n)}function Tx(e,n,i,c){let p=de(e,n,i);return Ed(p,c)}function Rx(e,n={}){return Ne("RemoveReadonly",[e],n)}function kx(e,n={}){return Ed(e,n)}function _O(e){return Xo(e,["~optional"])}function Sd(e,n){return St(_O(e),{},n)}function Ax(e,n,i,c){let p=de(e,n,i);return Sd(p,c)}function Cx(e,n={}){return Ne("RemoveOptional",[e],n)}function Rm(e,n={}){return Sd(e,n)}function wd(e){return e.reduceRight((i,c,p)=>({[p]:c,...i}),{})}function Px(e){let n=wd(e.items);return s(n)}function Td(e){return Qe(e)||mt(e)}function LO(e,n){return ea(e)?ea(n)?!0:!1:!1}function NO(e,n){return un(e)?un(n)?!0:!1:!1}function DO(e,n){let i=LO(e,n),c=NO(e,n),p=Ar([e,n]),g=kx(Rm(p));return i&&c?Zi(Ji(g)):i&&!c?Zi(g):!i&&c?Ji(g):g}function qO(e,n,i){return i in e?i in n?DO(e[i],n[i]):e[i]:(i in n)?n[i]:zt()}function FO(e,n){return[...new Set([...Se(e),...Se(n)])].reduce((p,g)=>({...p,[g]:qO(e,n,g)}),{})}function $x(e){return Qe(e)?e.properties:mt(e)?wd(e.items):{}}function Mx(e,n){let i=$x(e),c=$x(n),p=FO(i,c);return s(p)}function jO(e,n){let i=va(e,n);return _(i,Lu)?e:_(i,Nu)?n:_(i,_u)?n:zt()}function UO(e,n){let i=Td(e),c=Td(n);return i&&c?Mx(e,n):i&&!c?e:!i&&c?n:jO(e,n)}function vx(e,n){return ao(e)?e:Mr(e)?e:tn(e)?n:ao(n)?n:Mr(n)?n:tn(n)?e:UO(e,n)}function BO(e,n){return xe(e)||xe(n)}function GO(e,n){let i=To(e),c=To(n);return BO(i,c)?Ar([i,c]):vx(i,c)}function Ox(e,n,i=[]){return bt(n,(c,p)=>Ox(e,p,[...i,GO(c,e)]),()=>_(i.length,0)?[e]:i)}function _x(e,n,i=[]){return bt(e,(c,p)=>_x(p,n,[...i,...Du([c],n)]),()=>i)}function Du(e,n=[]){return bt(e,(i,c)=>xe(i)?Du(c,_x(i.anyOf,n)):Du(c,Ox(i,n)),()=>n)}function KO(e,n){let i=wn({},e,n);return no(i)?[]:[e]}function Lx(e,n,i=[]){return bt(e,(c,p)=>Lx(p,n,[...i,...KO(c,n)]),()=>i)}function km(e,n){let i=To(e),c=xe(i)?i.anyOf:[i],p=Lx(c,n);return ro(p)}function Zo(e,n,i){let c=Ar([e,n]),p=km(i,e);return ro([c,p])}function Yn(e,n=[]){return bt(e,(i,c)=>Yn(c,[...n,a(i)]),()=>ro(n))}function Ar(e){let n=Du(e),i=Rd(n);return ro(i)}function $n(e){let n=Ou(e);return To(n)}function ro(e){let n=Rd(e);return ti(n)}function To(e){return Dr(e)?Zo(e.if,e.then,e.else):nn(e)?Yn(e.enum):ze(e)?Ar(e.allOf):ur(e)?$n(e.pattern):xe(e)?ro(e.anyOf):e}function ti(e){return _(e.length,1)?e[0]:_(e.length,0)?zt():m(e)}function Nx(e,n){let i=Yn(e);return ri(i,n)}function Dx(e,n){return to(ni,n)}function qx(e,n){let i=Ar(e);return ri(i,n)}function Fx(e,n){return yt(e)||_t(e)?s({[e]:n}):_(e,!1)?s({false:n}):_(e,!0)?s({true:n}):s({})}function jx(e,n){return to(Oa,n)}function Ux(e,n){return le(e,"pattern")&&(yt(e.pattern)||e.pattern instanceof RegExp)?to(e.pattern.toString(),n):to(Yo,n)}function Bx(e,n){let i=vu(e);return wm(i)?ri($n(e),n):to(e,n)}function HO(e){return xe(e)?ra(e.anyOf):[e]}function ra(e,n=[]){return bt(e,(i,c)=>ra(c,[...n,...HO(i)]),()=>n)}function WO(e){return e.some((n)=>on(n)||kr(n)||dn(n))}function zO(e,n){return _(WO(e),!0)?to(Yo,n):void 0}function VO(e,n){return e.reduce((i,c)=>xt(c)&&(yt(c.const)||_t(c.const))?{...i,[c.const]:n}:i,{})}function JO(e,n){let i=VO(e,n);return s(i)}function Gx(e,n){let i=ra(e),c=zO(i,n);return Pr(c)?c:JO(i,n)}function ri(e,n){return Mr(e)?Ex(n):Wn(e)?Sx(n):nn(e)?Nx(e.enum,n):dn(e)?Dx(e,n):ze(e)?qx(e.allOf,n):xt(e)?Fx(e.const,n):kr(e)?jx(e,n):xe(e)?Gx(e.anyOf,n):on(e)?Ux(e,n):ur(e)?Bx(e.pattern,n):s({})}function kd(e,n,i){return ct([e])?St(ri(e,n),{},i):Am(e,n,i)}function Kx(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return kd(g,y,p)}var ni=`^${ym}$`,Oa=`^${Em}$`,Yo=`^${Sm}$`;function Am(e,n,i={}){return Ne("Record",[e,n],i)}function Ss(e,n,i={}){return kd(e,n,i)}function Hx(e,n){return to(e,n)}function Cm(e){return _(e,Yo)?l():_(e,ni)?w():_(e,Oa)?Y():bd(e)}function fn(e){return Se(e.patternProperties)[0]}function oi(e){let n=fn(e);return Cm(n)}function fr(e){return e.patternProperties[fn(e)]}function Gt(e){return ve(e,"Record")}function na(e){return Mt({"~kind":"Rest"},{type:"rest",items:e},{})}function si(e){return ve(e,"Rest")}function Pm(e){return Mt({["~kind"]:"This"},{$ref:"#"},e)}function $m(e){return ve(e,"This")}function _a(e){return Mt({"~kind":"Undefined"},{type:"undefined"},e)}function es(e){return ve(e,"Undefined")}function Mm(e){return Mt({"~kind":"Void"},{type:"void"},e)}function co(e){return ve(e,"Void")}function XO(e,n){return _(e,"Array")?B(n[0]):_(e,"Capitalize")?Om(n[0]):_(e,"ConstructorParameters")?qm(n[0]):_(e,"Evaluate")?uE(n[0]):_(e,"Exclude")?Fm(n[0],n[1]):_(e,"Extract")?jm(n[0],n[1]):_(e,"Index")?Uu(n[0],n[1]):_(e,"InstanceType")?Um(n[0]):_(e,"Lowercase")?_m(n[0]):_(e,"NonNullable")?Bm(n[0]):_(e,"Omit")?Gm(n[0],n[1]):_(e,"Parameters")?Km(n[0]):_(e,"Partial")?Hm(n[0]):_(e,"Pick")?Wm(n[0],n[1]):_(e,"Readonly")?zm(n[0]):_(e,"KeyOf")?Bu(n[0]):_(e,"Record")?Am(n[0],n[1]):_(e,"Required")?Vm(n[0]):_(e,"ReturnType")?Jm(n[0]):_(e,"Uncapitalize")?Lm(n[0]):_(e,"Uppercase")?Nm(n[0]):ju(an(e),n)}function oa(){throw Error("Unreachable")}function Qx(e,n=[]){return bt(e,(i,c)=>Qx(c,[...n,i[1]]),()=>n)}function Ls(e){return _(e.length,3)?[e[0],...Qx(e[1])]:[]}function Xx(e){return ta(e[0],e[2],e[4])}function Yx(e){return ta(e[0],e[2],e[2])}function Zx(e){return ta(e[0],Rr(),e[2])}function eI(e){return ta(e,Rr(),Rr())}function tI(e){return e}function rI(e){return Ls(e)}function nI(e){return e[1]}function oI(e){return Ls(e)}function sI(e){return e[1]}function iI(e){return XO(e[0],e[1])}function aI(e){return null}function uI(e){return l()}function cI(e){return Y()}function mI(e){return D()}function pI(e){return _a()}function lI(e){return Pn()}function dI(e){return w()}function fI(e){return $u()}function hI(e){return Rr()}function gI(e){return Ca()}function yI(e){return s({})}function xI(e){return zt()}function II(e){return Ma()}function bI(e){return Mm()}function EI(e){return Pm()}function SI(e){return a(BigInt(e))}function wI(e){return a(_(e,"true"))}function TI(e){return a(parseFloat(e))}function RI(e){return a(e)}function kI(e){return e[1]}function AI(e){return a(e)}function CI(e){return _(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function PI(e){return e[1]}function $I(e){return vm(e)}function MI(e){return _(e.length,6)?Qi(e[1],e[3],e[5]):Qi(e[1],e[3],Rr())}function vI(e){return e.length>0}function OI(e){return e.reduce((n,i)=>_(i.length,3)?[...n,[i[1]]]:[...n,[]],[])}function _I(e){return _(e.length,6)?[e[1],e[3],e[5]]:[]}function LI(e){return Be(e)&&_(e.length,3)?e[1]:e}function NI(e){return _(e.length,2)?e[1]:[]}function Wx(e,n){return n.reduce((i,c)=>{let p=c;return _(p.length,1)?Uu(i,p[0]):_(p.length,0)?B(i):oa()},e)}function zx(e,n){return _(n.length,3)?Dm(e,n[0],n[1],n[2]):e}function YO(e,n){return Be(n)&&_(n.length,0)?e:Qm(e,n)}function DI(e){let[n,i,c,p,g]=e;return YO(n?zx(Bu(Wx(i,c)),p):zx(Wx(i,c),p),g)}function Ad(e,n){return _(n.length,3)?(()=>{let[i,c,p]=n,g=Ad(c,p);if(_(i,"&"))return ze(g)?Cn([e,...g.allOf]):Cn([e,g]);if(_(i,"|"))return xe(g)?m([e,...g.anyOf]):m([e,g]);oa()})():e}function qI(e){return e}function FI(e){let[n,i]=e;return Ad(n,i)}function jI(e){return e}function UI(e){let[n,i]=e;return Ad(n,i)}function BI(e){return aE(e[1])}function GI(e){return e[1]}function KI(e){return Zs(e[0],e[2])}function HI(e){return _(e.length,4)?Pu(e[1],e[3]):_(e.length,2)?Pu(e[1],Rr()):oa()}function WI(e){return e}function zI(e){return`${e}`}function VI(e){return e}function JI(e){return e}function QI(e){return dn(e[3])?ni:kr(e[3])?Oa:Es(e[3])?Yo:on(e[3])?Yo:oa()}function XI(e){return e}function YI(e){return e.length>0}function ZI(e){return e.length>0}function eb(e){let[n,i,c,p,g]=e;return{[i]:n&&c?Is(ys(g)):n&&!c?Is(g):!n&&c?ys(g):g}}function tb(e){return e}function rb(e){return Ls(e)}function nb(e){return e.reduce((n,i)=>le(i,ni)||le(i,Oa)||le(i,Yo)?[n[0],ln(n[1],i)]:[ln(n[0],i),n[1]],[{},{}])}function ob(e){return nb(e[1])}function sb(e){let[n,i]=e,c=_(Se(i).length,0)?{}:{patternProperties:i};return s(n,c)}function ib(e){return _(e.length,5)?Is(ys(e[4])):_(e.length,3)?e[2]:_(e.length,4)?_(e[2],"readonly")?Is(e[3]):ys(e[3]):oa()}function ab(e){if(!Be(e)||!_(e.length,3))return e;let[n,i,c]=e;return n&&c?Is(ys(i)):n&&!c?Is(i):!n&&c?ys(i):i}function ub(e){return _(e.length,2)?na(e[1]):_(e.length,1)?e[0]:oa()}function cb(e){return Ls(e)}function mb(e){return Br(e[1])}function pb(e){return Is(ys(e[4]))}function lb(e){return Is(e[3])}function db(e){return ys(e[3])}function fb(e){return e[2]}function hb(e){return e}function gb(e){return _(e.length,2)?na(e[1]):_(e.length,1)?e[0]:oa()}function yb(e){return Ls(e)}function xb(e){return gs(e[1],e[4])}function Ib(e){return hs(e[2],e[5])}function Vx(e,n){return _(e,"remove")?Rx(n):_(e,"add")?Is(n):n}function bb(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function Jx(e,n){return _(e,"remove")?Cx(n):_(e,"add")?ys(n):n}function Eb(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function Sb(e){return _(e.length,2)?[e[1]]:[]}function wb(e){return Be(e[6])&&_(e[6].length,1)?qu(Mu(e[3]),e[5],e[6][0],Vx(e[1],Jx(e[8],e[10]))):qu(Mu(e[3]),e[5],an(e[3]),Vx(e[1],Jx(e[8],e[10])))}function Tb(e){return an(e)}function Rb(e){return BigInt(e)}function kb(e){return parseFloat(e)}function Ab(e){return _(e,"true")}function Cb(e){return e}function Pb(e){return null}function $b(e){return}function Mb(e){return{[e[0]]:e[2]}}function vb(e){return Ls(e)}function ZO(e){return e.reduce((n,i)=>ln(n,i),{})}function Ob(e){return ZO(e[1])}function _b(e){return Ls(e)}function Lb(e){return e[1]}function Nb(e){return e}function Db(e){return $u()}function qb(e){return l()}function Fb(e){return Y()}function jb(e){return w()}function Ub(e){return zt()}function Bb(e){return a(e)}function Gb(e){return e}function Kb(e){return m(e[1])}function Hb(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Wb(e){return[e[0],...e[1]]}function zb(e){return e}function Vb(e){return e[1]}function Jb(e){return Ls(e)}function Qb(e){return _(e.length,2)?e[1]:[]}function Xb(e){let n=e[2],i=e[3],[c,p]=e[4],g=_(Se(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Zs(n,Fu(i,c,g))}}function Yb(e){let n=e[2],[i,c]=e[3],p=_(Se(c).length,0)?{}:{patternProperties:c};return{[e[1]]:Fu(n,i,p)}}function Zb(e){return{[e[1]]:Zs(e[2],e[4])}}function eE(e){return{[e[1]]:e[3]}}function tE(e){return null}function rE(e){return e}function nE(e){return Ls(e)}function oE(e){return e[1]}function sE(e){let[n,i]=[e[0],e[1]];return cE(ln(n,nb(i)[0]))}function iE(e){return e}function Gu(e){return _(e.length,2)}function Rt(e,n,i){return Gu(e)?n(e[0],e[1]):i()}function r_(e,n){return _(n.indexOf(e),0)?[e,n.slice(e.length)]:[]}function Or(e,n){for(let i=0;i<e.length;i++){let c=r_(e[i],n);if(Gu(c))return c}return[]}function Cd(e,n){return Array.from({length:n-e+1},(i,c)=>String.fromCharCode(e+c))}var mE=[...Cd(97,122),...Cd(65,90)],Pd="0",$d=Cd(49,57),La=[Pd,...$d],pE=" ",Na=`
17
- `;var ii="_",Xm=".",lE="$",Ym="-";var dE="//",fE="/*",o_="*/";function hE(e){let n=e.indexOf(o_);return _(n,-1)?"":e.slice(n+2)}function gE(e){let n=e.indexOf(Na);return _(n,-1)?"":e.slice(n)}function s_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Zm(e){let n=s_(e);return n.startsWith(fE)?Zm(hE(n.slice(2))):n.startsWith(dE)?Zm(gE(n.slice(2))):n}function In(e){let n=e.trimStart();return n.startsWith(fE)?In(hE(n.slice(2))):n.startsWith(dE)?In(gE(n.slice(2))):n}function ep(e,n){return Rt(Or([e],n),(i,c)=>[i,c],()=>["",n])}function i_(e,n){return e.includes(n)}function Da(e,n,i,c=""){return Rt(Or(e,i),(p,g)=>i_(n,p)?Da(e,n,g,c):Da(e,n,g,`${c}${p}`),()=>[c,i])}function a_(e){return Or($d,e)}var u_=[...La,ii];function c_(e){return Da(u_,[ii],e)}function m_(e){return Rt(Or([Pd],e),(n,i)=>[n,i],()=>Rt(a_(e),(n,i)=>Rt(c_(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[]))}function tp(e){return m_(In(e))}function p_(e){return ep(Ym,e)}function l_(e){return Rt(p_(e),(n,i)=>Rt(tp(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function yE(e){return l_(In(e))}function d_(e){return Rt(yE(e),(n,i)=>Rt(Or(["n"],i),(c,p)=>[`${n}`,p],()=>[]),()=>[])}function Md(e){return d_(e)}function vd(e,n){return Or([e],n)}function Z(e,n){return _(e,"")?["",n]:e.startsWith(Na)?vd(e,Zm(n)):e.startsWith(pE)?vd(e,n):vd(e,In(n))}var xE=[...mE,ii,lE];function f_(e){return Or(xE,e)}var h_=[...xE,...La];function IE(e,n=""){return Rt(Or(h_,e),(i,c)=>IE(c,`${n}${i}`),()=>[n,e])}function g_(e){return Rt(f_(e),(n,i)=>Rt(IE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function Gr(e){return g_(In(e))}var y_=[...La,ii];function x_(e){return Gu(Or([Xm],e))}function bE(e){return Rt(Da(y_,[ii],e),(n,i)=>_(n,"")?[]:[n,i],()=>[])}function I_(e){return Rt(Or([Xm],e),(n,i)=>Rt(bE(i),(c,p)=>[`0${n}${c}`,p],()=>[]),()=>[])}function b_(e){return Rt(tp(e),(n,i)=>Rt(Or([Xm],i),(c,p)=>Rt(bE(p),(g,y)=>[`${n}${c}${g}`,y],()=>[`${n}`,p]),()=>[`${n}`,i]),()=>[])}function E_(e){return x_(e)?I_(e):b_(e)}function EE(e){return E_(In(e))}function S_(e){return ep(Ym,e)}function w_(e){return Rt(S_(e),(n,i)=>Rt(EE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function rp(e){return w_(In(e))}function T_(e){return _(e,"")?[]:[e.slice(0,1),e.slice(1)]}function SE(e,n){return bt(e,(i,c)=>n.startsWith(i)?!0:SE(c,n),()=>!1)}function ai(e,n,i=""){return Rt(T_(n),(c,p)=>SE(e,n)?[i,n]:ai(e,p,`${i}${c}`),()=>[])}function R_(e,n,i){return Rt(Or([e],i),(c,p)=>Rt(ai([n],p),(g,y)=>Rt(Or([n],y),(x,b)=>[`${g}`,b],()=>[]),()=>[]),()=>[])}function k_(e,n,i){return Rt(Or([e],i),(c,p)=>Rt(ai([Na,n],p),(g,y)=>Rt(Or([n],y),(x,b)=>[`${g}`,b],()=>[]),()=>[]),()=>[])}function wE(e,n,i,c){return i?R_(e,n,In(c)):k_(e,n,In(c))}function A_(e,n){return Or(e,n)}function C_(e,n){return wE(e,e,!1,n)}function P_(e,n){return Rt(A_(e,n),(i,c)=>C_(i,`${i}${c}`),()=>[])}function np(e,n){return P_(e,In(n))}function TE(e,n){return Rt(ai(e,n),(i,c)=>_(i,"")?[]:[i,c],()=>[])}var R=(e,n,i=()=>[])=>e.length===2?n(e):i(),M_=(e)=>R(R(Gr(e),([n,i])=>R(Z("extends",i),([c,p])=>R(vt(p),([g,y])=>R(Z("=",y),([x,b])=>R(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[Xx(n),i]),v_=(e)=>R(R(Gr(e),([n,i])=>R(Z("extends",i),([c,p])=>R(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Yx(n),i]),O_=(e)=>R(R(Gr(e),([n,i])=>R(Z("=",i),([c,p])=>R(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Zx(n),i]),__=(e)=>R(Gr(e),([n,i])=>[eI(n),i]),AE=(e)=>R(R(M_(e),([n,i])=>[n,i],()=>R(v_(e),([n,i])=>[n,i],()=>R(O_(e),([n,i])=>[n,i],()=>R(__(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[tI(n),i]),CE=(e,n=[])=>R(R(Z(",",e),([i,c])=>R(AE(c),([p,g])=>[[i,p],g])),([i,c])=>CE(c,[...n,i]),()=>[n,e]),L_=(e)=>R(R(R(AE(e),([n,i])=>R(CE(i),([c,p])=>R(R(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[rI(n),i]),Ld=(e)=>R(R(Z("<",e),([n,i])=>R(L_(i),([c,p])=>R(Z(">",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[nI(n),i]),PE=(e,n=[])=>R(R(Z(",",e),([i,c])=>R(vt(c),([p,g])=>[[i,p],g])),([i,c])=>PE(c,[...n,i]),()=>[n,e]),N_=(e)=>R(R(R(vt(e),([n,i])=>R(PE(i),([c,p])=>R(R(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[oI(n),i]),D_=(e)=>R(R(Z("<",e),([n,i])=>R(N_(i),([c,p])=>R(Z(">",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[sI(n),i]),q_=(e)=>R(R(Gr(e),([n,i])=>R(D_(i),([c,p])=>[[n,c],p])),([n,i])=>[iI(n),i]),$E=(e)=>R(R(R(Z(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[aI(n),i]),ME=(e)=>R(Z("string",e),([n,i])=>[uI(n),i]),vE=(e)=>R(Z("number",e),([n,i])=>[cI(n),i]),F_=(e)=>R(Z("boolean",e),([n,i])=>[mI(n),i]),j_=(e)=>R(Z("undefined",e),([n,i])=>[pI(n),i]),U_=(e)=>R(Z("null",e),([n,i])=>[lI(n),i]),OE=(e)=>R(Z("integer",e),([n,i])=>[dI(n),i]),B_=(e)=>R(Z("bigint",e),([n,i])=>[fI(n),i]),G_=(e)=>R(Z("unknown",e),([n,i])=>[hI(n),i]),K_=(e)=>R(Z("any",e),([n,i])=>[gI(n),i]),H_=(e)=>R(Z("object",e),([n,i])=>[yI(n),i]),W_=(e)=>R(Z("never",e),([n,i])=>[xI(n),i]),_E=(e)=>R(Z("symbol",e),([n,i])=>[II(n),i]),z_=(e)=>R(Z("void",e),([n,i])=>[bI(n),i]),V_=(e)=>R(Z("this",e),([n,i])=>[EI(n),i]),J_=(e)=>R(R(Z("${",e),([n,i])=>R(vt(i),([c,p])=>R(Z("}",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[kI(n),i]),Od=(e)=>R(ai(["${","`"],e),([n,i])=>[AI(n),i]),LE=(e)=>R(R(R(Od(e),([n,i])=>R(J_(i),([c,p])=>R(LE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R(R(Od(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R(R(Od(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[CI(n),i]),Nd=(e)=>R(R(Z("`",e),([n,i])=>R(LE(i),([c,p])=>R(Z("`",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[PI(n),i]),Q_=(e)=>R(Nd(e),([n,i])=>[$I(n),i]),X_=(e)=>R(R(R(Z("if",e),([n,i])=>R(vt(i),([c,p])=>R(Z("then",p),([g,y])=>R(vt(y),([x,b])=>R(Z("else",b),([S,T])=>R(vt(T),([A,C])=>[[n,c,g,x,S,A],C])))))),([n,i])=>[n,i],()=>R(R(Z("if",e),([n,i])=>R(vt(i),([c,p])=>R(Z("then",p),([g,y])=>R(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>[])),([n,i])=>[MI(n),i]),Y_=(e)=>R(Md(e),([n,i])=>[SI(n),i]),Z_=(e)=>R(R(Z("true",e),([n,i])=>[n,i],()=>R(Z("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[wI(n),i]),eL=(e)=>R(rp(e),([n,i])=>[TI(n),i]),tL=(e)=>R(np(["'",'"'],e),([n,i])=>[RI(n),i]),rL=(e)=>R(R(R(Z("keyof",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[vI(n),i]),NE=(e,n=[])=>R(R(R(Z("[",e),([i,c])=>R(vt(c),([p,g])=>R(Z("]",g),([y,x])=>[[i,p,y],x]))),([i,c])=>[i,c],()=>R(R(Z("[",e),([i,c])=>R(Z("]",c),([p,g])=>[[i,p],g])),([i,c])=>[i,c],()=>[])),([i,c])=>NE(c,[...n,i]),()=>[n,e]),nL=(e)=>R(NE(e),([n,i])=>[OI(n),i]),oL=(e)=>R(R(R(Z("extends",e),([n,i])=>R(vt(i),([c,p])=>R(Z("?",p),([g,y])=>R(vt(y),([x,b])=>R(Z(":",b),([S,T])=>R(vt(T),([A,C])=>[[n,c,g,x,S,A],C])))))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[_I(n),i]),sL=(e)=>R(R(R(Z("(",e),([n,i])=>R(vt(i),([c,p])=>R(Z(")",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R(ME(e),([n,i])=>[n,i],()=>R(vE(e),([n,i])=>[n,i],()=>R(F_(e),([n,i])=>[n,i],()=>R(j_(e),([n,i])=>[n,i],()=>R(U_(e),([n,i])=>[n,i],()=>R(OE(e),([n,i])=>[n,i],()=>R(B_(e),([n,i])=>[n,i],()=>R(G_(e),([n,i])=>[n,i],()=>R(K_(e),([n,i])=>[n,i],()=>R(H_(e),([n,i])=>[n,i],()=>R(W_(e),([n,i])=>[n,i],()=>R(_E(e),([n,i])=>[n,i],()=>R(z_(e),([n,i])=>[n,i],()=>R(V_(e),([n,i])=>[n,i],()=>R(Y_(e),([n,i])=>[n,i],()=>R(Z_(e),([n,i])=>[n,i],()=>R(eL(e),([n,i])=>[n,i],()=>R(tL(e),([n,i])=>[n,i],()=>R(Q_(e),([n,i])=>[n,i],()=>R(X_(e),([n,i])=>[n,i],()=>R(gL(e),([n,i])=>[n,i],()=>R(IL(e),([n,i])=>[n,i],()=>R(RL(e),([n,i])=>[n,i],()=>R(TL(e),([n,i])=>[n,i],()=>R(PL(e),([n,i])=>[n,i],()=>R(q_(e),([n,i])=>[n,i],()=>R($L(e),([n,i])=>[n,i],()=>[])))))))))))))))))))))))))))),([n,i])=>[LI(n),i]),iL=(e)=>R(R(R(Z("with",e),([n,i])=>R(ZE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[NI(n),i]),DE=(e)=>R(R(rL(e),([n,i])=>R(sL(i),([c,p])=>R(nL(p),([g,y])=>R(oL(y),([x,b])=>R(iL(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[DI(n),i]),qE=(e)=>R(R(R(Z("&",e),([n,i])=>R(DE(i),([c,p])=>R(qE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[qI(n),i]),FE=(e)=>R(R(DE(e),([n,i])=>R(qE(i),([c,p])=>[[n,c],p])),([n,i])=>[FI(n),i]),jE=(e)=>R(R(R(Z("|",e),([n,i])=>R(FE(i),([c,p])=>R(jE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[jI(n),i]),op=(e)=>R(R(FE(e),([n,i])=>R(jE(i),([c,p])=>[[n,c],p])),([n,i])=>[UI(n),i]),aL=(e)=>R(R(Z("readonly",e),([n,i])=>R(op(i),([c,p])=>[[n,c],p])),([n,i])=>[BI(n),i]),uL=(e)=>R(R(Z("|",e),([n,i])=>R(op(i),([c,p])=>[[n,c],p])),([n,i])=>[GI(n),i]),cL=(e)=>R(R(Ld(e),([n,i])=>R(Z("=",i),([c,p])=>R(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[KI(n),i]),mL=(e)=>R(R(R(Z("infer",e),([n,i])=>R(Gr(i),([c,p])=>R(Z("extends",p),([g,y])=>R(op(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>R(R(Z("infer",e),([n,i])=>R(Gr(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>[])),([n,i])=>[HI(n),i]),vt=(e)=>R(R(mL(e),([n,i])=>[n,i],()=>R(uL(e),([n,i])=>[n,i],()=>R(aL(e),([n,i])=>[n,i],()=>R(op(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[WI(n),i]),pL=(e)=>R(rp(e),([n,i])=>[zI(n),i]),lL=(e)=>R(Gr(e),([n,i])=>[VI(n),i]),dL=(e)=>R(np(["'",'"'],e),([n,i])=>[JI(n),i]),fL=(e)=>R(R(Z("[",e),([n,i])=>R(Gr(i),([c,p])=>R(Z(":",p),([g,y])=>R(R(OE(y),([x,b])=>[x,b],()=>R(vE(y),([x,b])=>[x,b],()=>R(ME(y),([x,b])=>[x,b],()=>R(_E(y),([x,b])=>[x,b],()=>[])))),([x,b])=>R(Z("]",b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[QI(n),i]),UE=(e)=>R(R(pL(e),([n,i])=>[n,i],()=>R(lL(e),([n,i])=>[n,i],()=>R(dL(e),([n,i])=>[n,i],()=>R(fL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[XI(n),i]),BE=(e)=>R(R(R(Z("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[YI(n),i]),GE=(e)=>R(R(R(Z("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[ZI(n),i]),KE=(e)=>R(R(BE(e),([n,i])=>R(UE(i),([c,p])=>R(GE(p),([g,y])=>R(Z(":",y),([x,b])=>R(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[eb(n),i]),sp=(e)=>R(R(R(Z(",",e),([n,i])=>R(Z(`
18
- `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z(";",e),([n,i])=>R(Z(`
19
- `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z(",",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R(R(Z(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R(R(Z(`
20
- `,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))))),([n,i])=>[tb(n),i]),HE=(e,n=[])=>R(R(sp(e),([i,c])=>R(KE(c),([p,g])=>[[i,p],g])),([i,c])=>HE(c,[...n,i]),()=>[n,e]),hL=(e)=>R(R(R(KE(e),([n,i])=>R(HE(i),([c,p])=>R(R(sp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[rb(n),i]),Dd=(e)=>R(R(Z("{",e),([n,i])=>R(hL(i),([c,p])=>R(Z("}",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[ob(n),i]),gL=(e)=>R(Dd(e),([n,i])=>[sb(n),i]),yL=(e)=>R(R(R(Gr(e),([n,i])=>R(Z("?",i),([c,p])=>R(Z(":",p),([g,y])=>R(Z("readonly",y),([x,b])=>R(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[n,i],()=>R(R(Gr(e),([n,i])=>R(Z(":",i),([c,p])=>R(Z("readonly",p),([g,y])=>R(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>R(R(Gr(e),([n,i])=>R(Z("?",i),([c,p])=>R(Z(":",p),([g,y])=>R(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>R(R(Gr(e),([n,i])=>R(Z(":",i),([c,p])=>R(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>[])))),([n,i])=>[ib(n),i]),RE=(e)=>R(R(yL(e),([n,i])=>[n,i],()=>R(R(BE(e),([n,i])=>R(vt(i),([c,p])=>R(GE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>[])),([n,i])=>[ab(n),i]),WE=(e)=>R(R(R(Z("...",e),([n,i])=>R(RE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(RE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[ub(n),i]),zE=(e,n=[])=>R(R(Z(",",e),([i,c])=>R(WE(c),([p,g])=>[[i,p],g])),([i,c])=>zE(c,[...n,i]),()=>[n,e]),xL=(e)=>R(R(R(WE(e),([n,i])=>R(zE(i),([c,p])=>R(R(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[cb(n),i]),IL=(e)=>R(R(Z("[",e),([n,i])=>R(xL(i),([c,p])=>R(Z("]",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[mb(n),i]),bL=(e)=>R(R(Gr(e),([n,i])=>R(Z("?",i),([c,p])=>R(Z(":",p),([g,y])=>R(Z("readonly",y),([x,b])=>R(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[pb(n),i]),EL=(e)=>R(R(Gr(e),([n,i])=>R(Z(":",i),([c,p])=>R(Z("readonly",p),([g,y])=>R(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[lb(n),i]),SL=(e)=>R(R(Gr(e),([n,i])=>R(Z("?",i),([c,p])=>R(Z(":",p),([g,y])=>R(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[db(n),i]),wL=(e)=>R(R(Gr(e),([n,i])=>R(Z(":",i),([c,p])=>R(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[fb(n),i]),kE=(e)=>R(R(bL(e),([n,i])=>[n,i],()=>R(EL(e),([n,i])=>[n,i],()=>R(SL(e),([n,i])=>[n,i],()=>R(wL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[hb(n),i]),VE=(e)=>R(R(R(Z("...",e),([n,i])=>R(kE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(kE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[gb(n),i]),JE=(e,n=[])=>R(R(Z(",",e),([i,c])=>R(VE(c),([p,g])=>[[i,p],g])),([i,c])=>JE(c,[...n,i]),()=>[n,e]),QE=(e)=>R(R(R(VE(e),([n,i])=>R(JE(i),([c,p])=>R(R(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[yb(n),i]),TL=(e)=>R(R(Z("(",e),([n,i])=>R(QE(i),([c,p])=>R(Z(")",p),([g,y])=>R(Z("=>",y),([x,b])=>R(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[xb(n),i]),RL=(e)=>R(R(Z("new",e),([n,i])=>R(Z("(",i),([c,p])=>R(QE(p),([g,y])=>R(Z(")",y),([x,b])=>R(Z("=>",b),([S,T])=>R(vt(T),([A,C])=>[[n,c,g,x,S,A],C])))))),([n,i])=>[Ib(n),i]),kL=(e)=>R(R(R(Z("+",e),([n,i])=>R(Z("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z("-",e),([n,i])=>R(Z("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[bb(n),i]),AL=(e)=>R(R(R(Z("+",e),([n,i])=>R(Z("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z("-",e),([n,i])=>R(Z("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[Eb(n),i]),CL=(e)=>R(R(R(Z("as",e),([n,i])=>R(vt(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Sb(n),i]),PL=(e)=>R(R(Z("{",e),([n,i])=>R(kL(i),([c,p])=>R(Z("[",p),([g,y])=>R(Gr(y),([x,b])=>R(Z("in",b),([S,T])=>R(vt(T),([A,C])=>R(CL(C),([P,L])=>R(Z("]",L),([q,X])=>R(AL(X),([j,V])=>R(Z(":",V),([J,ee])=>R(vt(ee),([ie,H])=>R($E(H),([ce,fe])=>R(Z("}",fe),([_e,be])=>[[n,c,g,x,S,A,P,q,j,J,ie,ce,_e],be]))))))))))))),([n,i])=>[wb(n),i]),$L=(e)=>R(Gr(e),([n,i])=>[Tb(n),i]),ML=(e)=>R(Md(e),([n,i])=>[Rb(n),i]),vL=(e)=>R(rp(e),([n,i])=>[kb(n),i]),OL=(e)=>R(R(Z("true",e),([n,i])=>[n,i],()=>R(Z("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[Ab(n),i]),_L=(e)=>R(np(['"',"'"],e),([n,i])=>[Cb(n),i]),LL=(e)=>R(Z("null",e),([n,i])=>[Pb(n),i]),NL=(e)=>R(Z("undefined",e),([n,i])=>[$b(n),i]),XE=(e)=>R(R(UE(e),([n,i])=>R(Z(":",i),([c,p])=>R(qd(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Mb(n),i]),YE=(e,n=[])=>R(R(sp(e),([i,c])=>R(XE(c),([p,g])=>[[i,p],g])),([i,c])=>YE(c,[...n,i]),()=>[n,e]),DL=(e)=>R(R(R(XE(e),([n,i])=>R(YE(i),([c,p])=>R(R(sp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[vb(n),i]),ZE=(e)=>R(R(Z("{",e),([n,i])=>R(DL(i),([c,p])=>R(Z("}",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Ob(n),i]),eS=(e,n=[])=>R(R(Z(",",e),([i,c])=>R(qd(c),([p,g])=>[[i,p],g])),([i,c])=>eS(c,[...n,i]),()=>[n,e]),qL=(e)=>R(R(R(qd(e),([n,i])=>R(eS(i),([c,p])=>R(R(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[_b(n),i]),FL=(e)=>R(R(Z("[",e),([n,i])=>R(qL(i),([c,p])=>R(Z("]",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Lb(n),i]),qd=(e)=>R(R(ML(e),([n,i])=>[n,i],()=>R(vL(e),([n,i])=>[n,i],()=>R(OL(e),([n,i])=>[n,i],()=>R(_L(e),([n,i])=>[n,i],()=>R(LL(e),([n,i])=>[n,i],()=>R(NL(e),([n,i])=>[n,i],()=>R(ZE(e),([n,i])=>[n,i],()=>R(FL(e),([n,i])=>[n,i],()=>[])))))))),([n,i])=>[Nb(n),i]),jL=(e)=>R(Z("-?(?:0|[1-9][0-9]*)n",e),([n,i])=>[Db(n),i]),UL=(e)=>R(Z(".*",e),([n,i])=>[qb(n),i]),BL=(e)=>R(Z("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([n,i])=>[Fb(n),i]),GL=(e)=>R(Z("-?(?:0|[1-9][0-9]*)",e),([n,i])=>[jb(n),i]),KL=(e)=>R(Z("(?!)",e),([n,i])=>[Ub(n),i]),HL=(e)=>R(TE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([n,i])=>[Bb(n),i]),WL=(e)=>R(R(jL(e),([n,i])=>[n,i],()=>R(UL(e),([n,i])=>[n,i],()=>R(BL(e),([n,i])=>[n,i],()=>R(GL(e),([n,i])=>[n,i],()=>R(KL(e),([n,i])=>[n,i],()=>R(zL(e),([n,i])=>[n,i],()=>R(HL(e),([n,i])=>[n,i],()=>[]))))))),([n,i])=>[Gb(n),i]),zL=(e)=>R(R(Z("(",e),([n,i])=>R(Fd(i),([c,p])=>R(Z(")",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Kb(n),i]),tS=(e)=>R(R(R(_d(e),([n,i])=>R(Z("|",i),([c,p])=>R(tS(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R(R(_d(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[]))),([n,i])=>[Hb(n),i]),_d=(e)=>R(R(WL(e),([n,i])=>R(Fd(i),([c,p])=>[[n,c],p])),([n,i])=>[Wb(n),i]),Fd=(e)=>R(R(tS(e),([n,i])=>[n,i],()=>R(_d(e),([n,i])=>[n,i],()=>[])),([n,i])=>[zb(n),i]),fx=(e)=>R(R(Z("^",e),([n,i])=>R(Fd(i),([c,p])=>R(Z("$",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Vb(n),i]),rS=(e,n=[])=>R(R(Z(",",e),([i,c])=>R(vt(c),([p,g])=>[[i,p],g])),([i,c])=>rS(c,[...n,i]),()=>[n,e]),VL=(e)=>R(R(R(vt(e),([n,i])=>R(rS(i),([c,p])=>R(R(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Jb(n),i]),nS=(e)=>R(R(R(Z("extends",e),([n,i])=>R(VL(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Qb(n),i]),JL=(e)=>R(R(Z("interface",e),([n,i])=>R(Gr(i),([c,p])=>R(Ld(p),([g,y])=>R(nS(y),([x,b])=>R(Dd(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[Xb(n),i]),QL=(e)=>R(R(Z("interface",e),([n,i])=>R(Gr(i),([c,p])=>R(nS(p),([g,y])=>R(Dd(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[Yb(n),i]),XL=(e)=>R(R(Z("type",e),([n,i])=>R(Gr(i),([c,p])=>R(Ld(p),([g,y])=>R(Z("=",y),([x,b])=>R(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[Zb(n),i]),YL=(e)=>R(R(Z("type",e),([n,i])=>R(Gr(i),([c,p])=>R(Z("=",p),([g,y])=>R(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[eE(n),i]),ZL=(e)=>R(R(R(Z("export",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[tE(n),i]),oS=(e)=>R(R(R(Z(";",e),([n,i])=>R(Z(`
21
- `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>R(R(Z(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>R(R(Z(`
22
- `,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[rE(n),i]),sS=(e,n=[])=>R(R(oS(e),([i,c])=>R(jd(c),([p,g])=>[[i,p],g])),([i,c])=>sS(c,[...n,i]),()=>[n,e]),eN=(e)=>R(R(R(jd(e),([n,i])=>R(sS(i),([c,p])=>R(R(oS(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>R([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[nE(n),i]),jd=(e)=>R(R(ZL(e),([n,i])=>R(R(JL(i),([c,p])=>[c,p],()=>R(QL(i),([c,p])=>[c,p],()=>R(XL(i),([c,p])=>[c,p],()=>R(YL(i),([c,p])=>[c,p],()=>[])))),([c,p])=>R($E(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[oE(n),i]),tN=(e)=>R(R(jd(e),([n,i])=>R(eN(i),([c,p])=>[[n,c],p])),([n,i])=>[sE(n),i]),iS=(e)=>R(R(tN(e),([n,i])=>[n,i],()=>R(cL(e),([n,i])=>[n,i],()=>R(vt(e),([n,i])=>[n,i],()=>[]))),([n,i])=>[iE(n),i]);function aS(e){let n=Nd(`\`${e}\``);return _(n.length,2)?n[0]:Ur()}function nN(e){return e.join("|")}function oN(e){return e.slice(1,e.length-1)}function sN(e,n,i){return ui(n,`${i}${e}`)}function iN(e,n){return ui(e,`${n}${ax}`)}function aN(e,n){return ui(e,`${n}${ym}`)}function uN(e,n){return ui(e,`${n}${Em}`)}function cN(e,n){return Ku(m([a("false"),a("true")]),e,n)}function mN(e,n){return ui(e,`${n}${Sm}`)}function pN(e,n,i){return ui(n,`${i}${oN(e)}`)}function lN(e,n,i){let c=Hu(e,{});return Ku(c,n,i)}function dN(e,n,i){let c=Yn(e);return Ku(c,n,i)}function uS(e,n,i,c=[]){return bt(e,(p,g)=>uS(g,n,i,[...c,Ku(p,[],"")]),()=>ui(n,`${i}(${nN(c)})`))}function Ku(e,n,i){return nn(e)?dN(e.enum,n,i):dn(e)?aN(n,i):xt(e)?sN(e.const,n,i):uo(e)?iN(n,i):Wn(e)?cN(n,i):kr(e)?uN(n,i):on(e)?mN(n,i):ur(e)?pN(e.pattern,n,i):mS(e)?lN(e.parameters[0],n,i):xe(e)?uS(e.anyOf,n,i):Ly}function ui(e,n){return bt(e,(i,c)=>Ku(i,c,n),()=>n)}function fN(e){return`^${ui(e,"")}$`}function cS(e){let n=fN(e);return Tm(n)}function Hu(e,n){return ct(e)?St(cS(e),{},n):vm(e,n)}function pS(e,n,i,c){let p=ho(e,n,i);return Hu(p,c)}function vm(e,n={}){return Ne("TemplateLiteral",[e],n)}function mS(e){return Pr(e)&&le(e,"action")&&_(e.action,"TemplateLiteral")}function lS(e){return Hu(e,{})}function hN(e){let n=aS(e);return lS(n)}function dS(e,n={}){let i=yt(e)?hN(e):lS(e);return St(i,{},n)}function ur(e){return ve(e,"TemplateLiteral")}function Ud(e){return Mt({["~kind"]:"ExtendsUnion"},{inferred:e})}function Bd(e){return ut(e)&&le(e,"~kind")&&le(e,"inferred")&&_(e["~kind"],"ExtendsUnion")&&ut(e.inferred)}function Ae(e){return Mt({["~kind"]:"ExtendsTrue"},{inferred:e})}function Gd(e){return ut(e)&&le(e,"~kind")&&le(e,"inferred")&&_(e["~kind"],"ExtendsTrue")&&ut(e.inferred)}function Ze(){return Mt({["~kind"]:"ExtendsFalse"},{})}function Kd(e){return ut(e)&&le(e,"~kind")&&_(e["~kind"],"ExtendsFalse")}function no(e){return Bd(e)||Gd(e)}function br(e,n,i){return no(e)?n(e.inferred):i()}function gN(e,n,i,c){return br(kt(e,i,c),(p)=>Ae(ln(ln(e,p),{[n]:i})),()=>Ze())}function yN(e,n){return Ae(e)}function xN(e,n,i,c,p){return br(kt(e,n,i),(g)=>br(kt(g,n,c),(y)=>Ae(y),()=>Ze()),()=>br(kt(e,n,p),(g)=>Ae(g),()=>Ze()))}function IN(e,n,i){let c=Yn(i);return kt(e,n,c)}function fS(e,n,i){return bt(i,(c,p)=>br(kt(e,n,c),(g)=>fS(g,n,p),()=>Ze()),()=>Ae(e))}function bN(e,n,i){let c=$n(i);return kt(e,n,c)}function hS(e,n,i){return bt(i,(c,p)=>br(kt(e,n,c),(g)=>Ae(g),()=>hS(e,n,p)),()=>Ze())}function Dt(e,n,i){return Mr(i)?yN(e,n):Dr(i)?xN(e,n,i.if,i.then,i.else):nn(i)?IN(e,n,i.enum):rn(i)?gN(e,i.name,n,i.extends):ze(i)?fS(e,n,i.allOf):ur(i)?bN(e,n,i.pattern):xe(i)?hS(e,n,i.anyOf):tn(i)?Ae(e):Ze()}function gS(e,n,i){return rn(i)?Dt(e,n,i):Mr(i)?Ae(e):tn(i)?Ae(e):Ud(e)}function EN(e,n){let i=Yi(e),c=Yi(n);return i&&c?!0:!i&&c?!0:i&&!c?!1:!0}function yS(e,n,i,c){return wt(c)?EN(n,c)?kt(e,i,c.items):Ze():Dt(e,n,c)}function xS(e,n,i){return uo(i)?Ae(e):Dt(e,n,i)}function IS(e,n,i){return Wn(i)?Ae(e):Dt(e,n,i)}function SN(e,n,i,c,p){let g=rn(c)?n:c,y=rn(c)?c:n,x=un(n),b=un(c);return!x&&b?Ze():br(kt(e,g,y),(S)=>Wu(S,i,p),()=>Ze())}function wN(e,n,i,c){return bt(c,(p,g)=>SN(e,n,i,p,g),()=>un(n)?Ae(e):Ze())}function TN(e,n,i){return bt(n,(c,p)=>wN(e,c,p,i),()=>Ae(e))}function Wu(e,n,i){return TN(e,n,i)}function ip(e,n,i){return co(i)?Ae(e):kt(e,n,i)}function bS(e,n,i,c){return Mr(c)?Ae(e):tn(c)?Ae(e):Zr(c)?br(Wu(e,n,c.parameters),(p)=>ip(p,i,c.instanceType),()=>Ze()):Ze()}function ES(e,n,i,c,p){return br(kt(e,n,p),()=>kt(e,i,p),()=>kt(e,c,p))}function SS(e,n,i){let c=Yn(n);return kt(e,c,i)}function wS(e,n,i,c){return Mr(c)?Ae(e):tn(c)?Ae(e):en(c)?br(Wu(e,n,c.parameters),(p)=>ip(p,i,c.returnType),()=>Ze()):Ze()}function TS(e,n,i){return dn(i)?Ae(e):kr(i)?Ae(e):Dt(e,n,i)}function RS(e,n,i){let c=Ar(n);return kt(e,c,i)}function ap(e,n,i){return n===i?Ae(e):Ze()}function RN(e,n,i){return xt(i)?ap(e,n,i.const):uo(i)?Ae(e):Dt(e,a(n),i)}function kN(e,n,i){return xt(i)?ap(e,n,i.const):Wn(i)?Ae(e):Dt(e,a(n),i)}function AN(e,n,i){return xt(i)?ap(e,n,i.const):kr(i)?Ae(e):Dt(e,a(n),i)}function CN(e,n,i){return xt(i)?ap(e,n,i.const):on(i)?Ae(e):Dt(e,a(n),i)}function kS(e,n,i){return Nr(n.const)?RN(e,n.const,i):mn(n.const)?kN(e,n.const,i):_t(n.const)?AN(e,n.const,i):yt(n.const)?CN(e,n.const,i):Ur()}function AS(e,n,i){return rn(i)?Dt(e,n,i):Ae(e)}function CS(e,n,i){return bs(i)?Ae(e):Dt(e,n,i)}function PS(e,n,i){return kr(i)?Ae(e):Dt(e,n,i)}function PN(e,n,i){return un(n)?un(i)?Ae(e):Ze():Ae(e)}function $N(e,n,i){return rn(i)&&ao(i.extends)?Ze():br(kt(e,n,i),(c)=>PN(c,n,i),()=>Ze())}function MN(e,n){return e.reduce((i,c)=>(c in n)?no(n[c])?{...i,...n[c].inferred}:Ur():Ur(),{})}function vN(e,n,i){let c={};for(let y of Se(i))c[y]=y in n?$N({},n[y],i[y]):un(i[y])?rn(i[y])?Ae(ln(e,{[i[y].name]:i[y].extends})):Ae(e):Ze();let p=ld(c).every((y)=>no(y)),g=p?MN(Se(c),c):{};return p?Ae(g):Ze()}function ON(e,n,i){let c=vN(e,n,i);return no(c)?Ae(ln(e,c.inferred)):Ze()}function _N(e,n,i){return ON(e,n,i)}function LN(e,n){return Se(n).reduce((i,c)=>({...i,[c]:le(e,c)?xe(i[c])?m([...i[c].anyOf,n[c]]):m([e[c],n[c]]):n[c]}),e)}function $S(e,n,i,c){return bt(n,(p,g)=>br(kt({},e[p],i),(y)=>$S(e,g,i,LN(c,y)),()=>Ze()),()=>Ae(c))}function NN(e,n,i,c){let p=Se(n);return $S(n,p,c,e)}function MS(e,n,i){return Gt(i)?NN(e,n,fn(i),fr(i)):Qe(i)?_N(e,n,i.properties):Dt(e,s(n),i)}function DN(e,n){return _(Se(n).length,0)?Ae(e):Ze()}function qN(e,n,i,c,p){return kt(e,i,p)}function vS(e,n,i,c){return Gt(c)?qN(e,Cm(n),i,Cm(fn(c)),fr(c)):Qe(c)?DN(e,c.properties):Mr(c)?Ae(e):tn(c)?Ae(e):Ze()}function OS(e,n,i){return on(i)?Ae(e):Dt(e,n,i)}function _S(e,n,i){return Es(i)?Ae(e):Dt(e,n,i)}function LS(e,n,i){let c=$n(n);return kt(e,c,i)}function Hd(e,n){return Mt({"~kind":"Inferrable"},{name:e,type:n},{})}function zu(e){return ut(e)&&le(e,"~kind")&&le(e,"name")&&le(e,"type")&&_(e["~kind"],"Inferrable")&&yt(e.name)&&ut(e.type)}function Wd(e){return si(e)?rn(e.items)?wt(e.items.extends)?Hd(e.items.name,e.items.extends.items):tn(e.items.extends)?Hd(e.items.name,e.items.extends):void 0:Ur():void 0}function up(e){return rn(e)?Hd(e.name,e.extends):void 0}function zd(e,n,i=[]){return bt(e,(c,p)=>br(kt({},c,n),()=>zd(p,n,[...i,c]),()=>{return}),()=>i)}function NS(e,n,i,c){let p=zd(i,c);return Be(p)?Ae(ln(e,{[n]:Br(p)})):Ze()}function cp(e,n,i,c){let p=zd(i,c);return Be(p)?Ae(ln(e,{[n]:m(p)})):Ze()}function FN(e){return[...e].reverse()}function Vd(e,n){return n?FN(e):e}function jN(e){let n=e.length>0?e[0]:void 0,i=Pr(n)?Wd(n):void 0;return Pr(i)}function UN(e,n,i,c,p,g){return br(kt(e,i,p),(y)=>DS(y,n,c,g),()=>Ze())}function BN(e,n,i,c,p){let g=Wd(c);return zu(g)?NS(e,g.name,Vd(i,n),g.type):bt(i,(y,x)=>UN(e,n,y,x,c,p),()=>Ze())}function GN(e,n,i,c){return bt(c,(p,g)=>BN(e,n,i,p,g),()=>_(i.length,0)?Ae(e):Ze())}function DS(e,n,i,c){return GN(e,n,i,c)}function KN(e,n,i){let c=ci(e,hr([],[]),i),p=jN(c);return DS(e,p,Vd(n,p),Vd(c,p))}function qS(e,n,i){let c=up(i);return zu(c)?cp(e,c.name,n,c.type):bt(n,(p,g)=>br(kt(e,p,i),(y)=>qS(y,g,i),()=>Ze()),()=>Ae(e))}function FS(e,n,i){let c=ci(e,hr([],[]),n);return mt(i)?KN(e,c,i.items):wt(i)?qS(e,c,i.items):Dt(e,Br(c),i)}function jS(e,n,i){return co(i)?Ae(e):es(i)?Ae(e):Dt(e,n,i)}function US(e,n,i){return bt(i,(c,p)=>br(kt(e,n,c),(g)=>Ae(g),()=>US(e,n,p)),()=>Ze())}function Jd(e,n,i){return bt(n,(c,p)=>br(US(e,c,i),(g)=>Jd(g,p,i),()=>Ze()),()=>Ae(e))}function BS(e,n,i){let c=up(i);return zu(c)?cp(e,c.name,n,c.type):xe(i)?Jd(e,n,i.anyOf):Jd(e,n,[i])}function GS(e,n,i){return rn(i)?Dt(e,n,i):Mr(i)?Ae(e):tn(i)?Ae(e):Ze()}function KS(e,n,i){return co(i)?Ae(e):Dt(e,n,i)}function kt(e,n,i){return Mr(n)?gS(e,n,i):wt(n)?yS(e,n,n.items,i):uo(n)?xS(e,n,i):Wn(n)?IS(e,n,i):Zr(n)?bS(e,n.parameters,n.instanceType,i):Dr(n)?ES(e,n.if,n.then,n.else,i):nn(n)?SS(e,n.enum,i):en(n)?wS(e,n.parameters,n.returnType,i):dn(n)?TS(e,n,i):ze(n)?RS(e,n.allOf,i):xt(n)?kS(e,n,i):ao(n)?AS(e,n,i):bs(n)?CS(e,n,i):kr(n)?PS(e,n,i):Qe(n)?MS(e,n.properties,i):Gt(n)?vS(e,fn(n),fr(n),i):on(n)?OS(e,n,i):Es(n)?_S(e,n,i):ur(n)?LS(e,n.pattern,i):mt(n)?FS(e,n.items,i):es(n)?jS(e,n,i):xe(n)?BS(e,n.anyOf,i):tn(n)?GS(e,n,i):co(n)?KS(e,n,i):Ze()}function HN(e,n){return Ar([...e,s(n)])}function Qd(e,n,i){return ct(e)?St(HN(e,n),{},i):Fu(e,n,i)}function HS(e,n,i,c,p){let g=ho(e,n,i),y=Vu(e,n,c);return Qd(g,y,p)}function Fu(e,n,i={}){return Ne("Interface",[e,n],i)}function qa(e){return Pr(e)&&le(e,"action")&&_(e.action,"Interface")}function WS(e,n,i={}){return Qd(e,n,i)}function WN(e,n,i){return e.includes(i)?!0:Ju([...e,i],n,n[i])}function zS(e,n,i){let c=pm(i);return sa(e,n,c)}function sa(e,n,i){return bt(i,(c,p)=>Ju(e,n,c)?!0:sa(e,n,p),()=>!1)}function Ju(e,n,i){return jt(i)?WN(e,n,i.$ref):wt(i)?Ju(e,n,i.items):Zr(i)?sa(e,n,[...i.parameters,i.instanceType]):en(i)?sa(e,n,[...i.parameters,i.returnType]):qa(i)?zS(e,n,i.parameters[1]):ze(i)?sa(e,n,i.allOf):Qe(i)?zS(e,n,i.properties):xe(i)?sa(e,n,i.anyOf):mt(i)?sa(e,n,i.items):Gt(i)?Ju(e,n,fr(i)):!1}function VS(e,n,i){return Ju(e,n,i)}function zN(e,n){return n.reduce((i,c)=>VS([c],e,e[c])?[...i,c]:i,[])}function JS(e){let n=mm(e);return zN(e,n)}function VN(e,n,i){return i.includes(n)?i:(n in e)?Qu(e,e[n],[...i,n]):Ur()}function QS(e,n,i){let c=pm(n);return Fa(e,c,i)}function Fa(e,n,i){return n.reduce((c,p)=>Qu(e,p,c),i)}function Qu(e,n,i){return jt(n)?VN(e,n.$ref,i):wt(n)?Qu(e,n.items,i):Zr(n)?Fa(e,[...n.parameters,n.instanceType],i):en(n)?Fa(e,[...n.parameters,n.returnType],i):qa(n)?QS(e,n.parameters[1],i):ze(n)?Fa(e,n.allOf,i):Qe(n)?QS(e,n.properties,i):xe(n)?Fa(e,n.anyOf,i):mt(n)?Fa(e,n.items,i):Gt(n)?Qu(e,fr(n),i):i}function XS(e,n,i){return Qu(e,i,[n])}function JN(e){return Ca()}function QN(e){return Se(e).reduce((n,i)=>({...n,[i]:ia(e[i])}),{})}function Xu(e){return e.reduce((n,i)=>[...n,ia(i)],[])}function ia(e){return jt(e)?JN(e.$ref):wt(e)?B(ia(e.items),ka(e)):Zr(e)?hs(Xu(e.parameters),ia(e.instanceType)):en(e)?gs(Xu(e.parameters),ia(e.returnType)):ze(e)?Cn(Xu(e.allOf)):Qe(e)?s(QN(e.properties)):Gt(e)?Ss(oi(e),ia(fr(e))):xe(e)?m(Xu(e.anyOf)):mt(e)?Br(Xu(e.items)):e}function XN(e,n){return n in e?ia(e[n]):Rr()}function YS(e){return XN(e.$defs,e.$ref)}function YN(e,n,i){let c=ho(e,hr([],[]),n),p=Vu({},hr([],[]),i);return Ar([...c,s(p)])}function ZN(e,n){return Se(e).filter((c)=>n.includes(c)).reduce((c,p)=>{let g=e[p],y=qa(g)?YN(e,g.parameters[0],g.parameters[1]):g;return{...c,[p]:y}},{})}function ZS(e,n,i){let c=XS(e,n,i),p=ZN(e,c);return xs(p,n)}function ew(e,n){return n in e?jt(e[n])?ew(e,e[n].$ref):e[n]:zt()}function ws(e,n){return ew(e,n)}function tw(e){return Qt(e)?YS(e):lm(e)?Rr():e}function wn(e,n,i){let c=tw(n),p=tw(i);return kt(e,c,p)}var _u=0,Yu=1,Lu=2,Nu=3;function va(e,n){let i=[wn({},e,n),wn({},n,e)];return no(i[0])&&no(i[1])?_u:no(i[0])&&Kd(i[1])?Lu:Kd(i[0])&&no(i[1])?Nu:Yu}function Xd(e,n,i=[],c=n){return bt(n,(p,g)=>{let y=va(e,p);return _(y,Lu)||_(y,_u)?c:_(y,Yu)?Xd(e,g,[...i,p],c):Xd(e,g,i,c)},()=>[...i,e])}function eD(e,n,i){let c=To(e);return Mr(c)?[c]:tn(c)?[c]:ao(c)?mp(n,i):Qe(c)?mp(n,[...i,c]):mp(n,Xd(c,i))}function mp(e,n=[]){return bt(e,(i,c)=>eD(i,c,n),()=>n)}function Rd(e){let n=mp(e);return ra(n)}function Yd(e,n){return St(To(e),{},n)}function rw(e,n,i,c){let p=de(e,n,i);return Yd(p,c)}function Zu(e,n=[]){return Ys(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)):Ys(e)&&_(e.action,"Mapped")?Ys(e.parameters[1])&&_(e.parameters[1].action,"KeyOf")&&jt(e.parameters[1].parameters[0])?[...n,e.parameters[1].parameters[0].$ref]:n:n}function tD(e,n){return e.reduce((i,c)=>[...i,n.includes(c.name)],[])}function sw(e,n,i=[]){return bt(e,(c,p)=>bt(n,(g,y)=>sw(p,y,[...i,[g,c]]),()=>i),()=>i)}function rD(e){return ur(e)?$n(e.pattern):nn(e)?Yn(e.enum):e}function nD(e){let n=rD(e);return xe(n)?[...n.anyOf]:[n]}function oD(e,n){return e.reduce((i,c)=>[...i,[...c,n]],[])}function nw(e,n){return n.reduce((i,c)=>[...i,...oD(e,c)],[])}function ow(e){return e.reduce((n,i)=>_(i[0],!0)?nw(n,nD(i[1])):nw(n,[i[1]]),[[]])}function iw(e,n,i){let c=Zu(i),p=tD(e,c),g=sw(n,p);return Ys(i)&&_(i.action,"Conditional")?ow(g):Ys(i)&&_(i.action,"Mapped")?ow(g):[n]}function sD(){return["(not-resolvable)",zt()]}function iD(){return["(not-generic)",zt()]}function aD(e,n,i){return[e,Zs(n,i)]}function uD(e,n,i){return n in e?aw(e,n,e[n],i):sD()}function aw(e,n,i,c){return Aa(i)?aD(n,i.parameters,i.expression):jt(i)?uD(e,i.$ref,c):iD()}function uw(e,n,i){return aw(e,"(anonymous)",n,i)}function cD(e,n,i){if(rn(n)||ja(n)||no(wn({},n,i)))return;let c={parameter:e,expect:i,actual:n};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:c})}function cw(e,n,i,c,p){let g=de(e,n,p);return cD(i,g,c),ln(e,{[i]:g})}function mD(e,n,i,c,p){let g=de(e,n,i.extends),y=de(e,n,i.equals);return bt(p,(x,b)=>Zd(cw(e,n,i.name,g,x),n,c,b),()=>Zd(cw(e,n,i.name,g,y),n,c,[]))}function Zd(e,n,i,c){return bt(i,(p,g)=>mD(e,n,p,g,c),()=>e)}function mw(e,n,i,c){return Zd(e,n,i,c)}var ef=0,tf=0;function pD(){if(wu(tf,Qo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function lD(){pD(),tf++,ef++}function dD(){if(ef--,_(ef,0))tf=0}function fD(e){return Gi(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function hD(e,n){return _(fD(e),n)}function gD(e,n,i,c,p,g){lD();try{let y=mw(e,n,c,g),x=de(y,hr([...n.callstack,i.$ref],n.visited),p);return de(y,hr([],[]),x)}finally{dD()}}function yD(e,n,i,c,p,g){return g.reduce((y,x)=>{let b=gD(e,n,i,c,p,x);return[...y,b]},[])}function xD(e,n,i,c,p,g){let y=iw(c,g,p),x=yD(e,n,i,c,p,y);return _(x.length,1)?x[0]:ro(x)}function pp(e,n,i,c){let p=ho(e,n,c),g=uw(e,i,c),y=g[0],x=g[1];return Aa(x)?hD(n,y)?ju(an(y),p):xD(e,n,an(y),x.parameters,x.expression,p):ju(i,p)}function ju(e,n){return Mt({["~kind"]:"Call"},{type:"call",target:e,arguments:n},{})}function pw(e,n){return pp({},hr([],[]),e,n)}function ja(e){return ve(e,"Call")}function ID(e){return Xo(e,["~immutable"])}function lw(e,n){return St(ID(e),{},n)}function dw(e,n,i,c){let p=de(e,n,i);return lw(p,c)}function fw(e,n){return e(n)}function hw(e,n){return yt(n)?a(fw(e,n)):a(n)}function gw(e,n){let i=$n(n);return Ns(e,i)}function yw(e,n){let i=n.map((c)=>Ns(e,c));return m(i)}function Ns(e,n){return xt(n)?hw(e,n.const):ur(n)?gw(e,n.pattern):xe(n)?yw(e,n.anyOf):n}function Om(e,n={}){return Ne("Capitalize",[e],n)}function xw(e,n={}){return rf(e,n)}function _m(e,n={}){return Ne("Lowercase",[e],n)}function Iw(e,n={}){return nf(e,n)}function Lm(e,n={}){return Ne("Uncapitalize",[e],n)}function bw(e,n={}){return of(e,n)}function Nm(e,n={}){return Ne("Uppercase",[e],n)}function Ew(e,n={}){return sf(e,n)}var bD=(e)=>e[0].toUpperCase()+e.slice(1),ED=(e)=>e.toLowerCase(),SD=(e)=>e[0].toLowerCase()+e.slice(1),wD=(e)=>e.toUpperCase();function rf(e,n){return ct([e])?St(Ns(bD,e),{},n):Om(e,n)}function nf(e,n){return ct([e])?St(Ns(ED,e),{},n):_m(e,n)}function of(e,n){return ct([e])?St(Ns(SD,e),{},n):Lm(e,n)}function sf(e,n){return ct([e])?St(Ns(wD,e),{},n):Nm(e,n)}function Sw(e,n,i,c){let p=de(e,n,i);return rf(p,c)}function ww(e,n,i,c){let p=de(e,n,i);return nf(p,c)}function Tw(e,n,i,c){let p=de(e,n,i);return of(p,c)}function Rw(e,n,i,c){let p=de(e,n,i);return sf(p,c)}function Dm(e,n,i,c,p={}){return Ne("Conditional",[e,n,i,c],p)}function kw(e,n,i,c,p={}){return af({},hr([],[]),e,n,i,c,p)}function TD(e,n,i,c,p,g){let y=wn(e,i,c);return Bd(y)?m([de(y.inferred,n,p),de(e,n,g)]):Gd(y)?de(y.inferred,n,p):de(e,n,g)}function af(e,n,i,c,p,g,y){return ct([i,c])?St(TD(e,n,i,c,p,g),{},y):Dm(i,c,p,g,y)}function Aw(e,n,i,c,p,g,y){let x=de(e,n,i),b=de(e,n,c);return af(e,n,x,b,p,g,y)}function qm(e,n={}){return Ne("ConstructorParameters",[e],n)}function Cw(e,n={}){return uf(e,n)}function RD(e){let n=Zr(e)?e.parameters:[],i=ci({},hr([],[]),n);return Br(i)}function uf(e,n){return ct([e])?St(RD(e),{},n):qm(e,n)}function Pw(e,n,i,c){let p=de(e,n,i);return uf(p,c)}function Fm(e,n,i={}){return Ne("Exclude",[e,n],i)}function $w(e,n,i={}){return ec(e,n,i)}function ec(e,n,i){return ct([e,n])?St(km(e,n),{},i):Fm(e,n,i)}function Mw(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return ec(g,y,p)}function jm(e,n,i={}){return Ne("Extract",[e,n],i)}function vw(e,n,i={}){return cf(e,n,i)}function kD(e,n){let i=wn({},e,n);return no(i)?[e]:[]}function Ow(e,n,i=[]){return bt(e,(c,p)=>Ow(p,n,[...i,...kD(c,n)]),()=>i)}function _w(e,n){let i=To(e),c=xe(i)?i.anyOf:[i],p=Ow(c,n);return ro(p)}function cf(e,n,i){return ct([e,n])?St(_w(e,n),{},i):jm(e,n,i)}function Lw(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return cf(g,y,p)}function AD(e){return e.reduce((n,i)=>xm(i)?[...n,a(i)]:n,[])}function Ua(e){let n=AD(e);return m(n)}function Uu(e,n,i={}){return Ne("Index",[e,n],i)}function Nw(e,n,i={}){let c=Be(n)?Ua(n):n;return mf(e,c,i)}function Dw(e,n){let i=ws(e,n);return go(i)}function qw(e,n,i){let c=Zo(e,n,i);return go(c)}function CD(e,n){let i=Se(e).filter((T)=>!le(n,T)),c=Se(n).filter((T)=>!le(e,T)),p=Se(e).filter((T)=>le(n,T)),g=i.reduce((T,A)=>({...T,[A]:e[A]}),{}),y=c.reduce((T,A)=>({...T,[A]:n[A]}),{}),x=p.reduce((T,A)=>({...T,[A]:Ar([e[A],n[A]])}),{}),b=ln(g,y);return ln(b,x)}function Fw(e){return e.reduce((n,i)=>CD(n,go(i)),{})}function jw(e){return e}function Uw(e){let n=Px(Br(e));return go(n)}function PD(e,n){return Se(e).filter((p)=>(p in n)).reduce((p,g)=>({...p,[g]:ro([e[g],n[g]])}),{})}function Bw(e,n){return bt(e,(i,c)=>Bw(c,PD(n,go(i))),()=>n)}function Gw(e){return bt(e,(n,i)=>Bw(i,go(n)),()=>Ur())}function go(e){return Qt(e)?Dw(e.$defs,e.$ref):Dr(e)?qw(e.if,e.then,e.else):ze(e)?Fw(e.allOf):xe(e)?Gw(e.anyOf):mt(e)?Uw(e.items):Qe(e)?jw(e.properties):{}}function Ba(e){let n=go(e);return s(n)}var $D=new RegExp("^(?:0|[1-9][0-9]*)$");function Ga(e){let n=`${e}`;return $D.test(n)?parseInt(n):e}function MD(e){return a(Ga(e))}function Kw(e){return e.map((n)=>Hw(n))}function Hw(e){return ze(e)?Cn(Kw(e.allOf)):xe(e)?m(Kw(e.anyOf)):xt(e)?MD(e.const):e}function Ww(e,n){let i=Hw(n),c=wn({},i,Y());return no(c)?e:xt(n)&&_(n.const,"length")?Y():zt()}function zw(e,n){let i=ws(e,n);return mo(i)}function Vw(e,n,i){let c=Zo(e,n,i);return mo(c)}function Jw(e){let n=Yn(e);return mo(n)}function Qw(e){let n=Ar(e);return mo(n)}function Xw(e){return[`${e}`]}function Yw(e){let n=$n(e);return mo(n)}function Zw(e){return e.reduce((n,i)=>[...n,...mo(i)],[])}function mo(e){return Qt(e)?zw(e.$defs,e.$ref):Dr(e)?Vw(e.if,e.then,e.else):nn(e)?Jw(e.enum):ze(e)?Qw(e.allOf):xt(e)?Xw(e.const):ur(e)?Yw(e.pattern):xe(e)?Zw(e.anyOf):[]}function Ka(e){return mo(e)}function tc(e,n){return n.map((i)=>rc(e,i))}function rc(e,n){return wt(n)?B(rc(e,n.items)):Zr(n)?hs(tc(e,n.parameters),rc(e,n.instanceType)):en(n)?gs(tc(e,n.parameters),rc(e,n.returnType)):mt(n)?Br(tc(e,n.items)):xe(n)?m(tc(e,n.anyOf)):ze(n)?Cn(tc(e,n.allOf)):$m(n)?s(e):n}function eT(e,n){return rc(e,n)}function vD(e,n){let i=n in e?e[n]:zt();return eT(e,i)}function tT(e,n){return n.reduce((i,c)=>[...i,vD(e,c)],[])}function OD(e,n){let i=Ka(n),c=tT(e,i);return ro(c)}var _D=new RegExp(ni);function LD(e){return e.filter((i)=>_D.test(i))}function ND(e){let n=mm(e),i=LD(n),c=tT(e,i);return ro(c)}function rT(e,n){return kr(n)?ND(e):OD(e,n)}function DD(e){return a(Ga(e))}function nT(e){return e.map((n)=>pf(n))}function pf(e){return ze(e)?Cn(nT(e.allOf)):xe(e)?m(nT(e.anyOf)):xt(e)?DD(e.const):e}function qD(e,n){return e.reduceRight((i,c,p)=>{let g=wn({},a(p),n);return no(g)?[c,...i]:i},[])}function FD(e,n){let i=pf(n),c=qD(e,i);return ti(c)}function jD(e){return ti(e)}function oT(e,n){return xt(n)&&_(n.const,"length")?a(e.length):kr(n)||dn(n)?jD(e):FD(e,n)}function sT(e,n){return wt(e)?Ww(e.items,n):Qe(e)?rT(e.properties,n):mt(e)?oT(e.items,n):zt()}function UD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function mf(e,n,i){return ct([e,n])?St(sT(UD(e),n),{},i):Uu(e,n,i)}function iT(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return mf(g,y,p)}function Um(e,n={}){return Ne("InstanceType",[e],n)}function aT(e,n={}){return lf(e,n)}function BD(e){return Zr(e)?e.instanceType:zt()}function lf(e,n){return ct([e])?St(BD(e),{},n):Um(e,n)}function uT(e,n,i,c={}){let p=de(e,n,i);return lf(p,c)}function Bu(e,n={}){return Ne("KeyOf",[e],n)}function cT(e,n={}){return df(e,n)}function mT(){return m([Y(),l(),Ma()])}function pT(e){return Y()}function GD(e){return e.reduce((i,c)=>xm(c)?[...i,a(Ga(c))]:Ur(),[])}function lT(e){let n=Se(e),i=GD(n);return ti(i)}function dT(e){return oi(e)}function fT(e){let n=e.map((i,c)=>a(c));return ti(n)}function hT(e){return Mr(e)?mT():wt(e)?pT(e.items):Qe(e)?lT(e.properties):Gt(e)?dT(e):mt(e)?fT(e.items):zt()}function KD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function df(e,n){return ct([e])?St(hT(KD(e)),{},n):Bu(e,n)}function gT(e,n,i,c){let p=de(e,n,i);return df(p,c)}function qu(e,n,i,c,p={}){return Ne("Mapped",[e,n,i,c],p)}function yT(e,n,i,c,p={}){return ff({},hr([],[]),e,n,i,c,p)}function HD(e){let n=$n(e);return lp(n)}function WD(e){return e.reduce((n,i)=>[...n,...lp(i)],[])}function zD(e){let n=Yn(e);return lp(n)}function VD(e){return _t(e)?[a(`${e}`)]:[a(e)]}function lp(e){return nn(e)?zD(e.enum):xt(e)?VD(e.const):ur(e)?HD(e.pattern):xe(e)?WD(e.anyOf):[e]}function xT(e){return lp(e)}function JD(e){return ur(e)?$n(e.pattern):e}function QD(e,n,i,c,p,g){let y=ln(e,{[i.name]:c}),x=de(y,n,p),b=JD(x),S=de(y,n,g);return Im(b)||bm(b)?{[b.const]:S}:{}}function XD(e,n,i,c,p,g){return c.reduce((y,x)=>[...y,QD(e,n,i,x,p,g)],[])}function YD(e){return e.reduce((n,i)=>[...n,s(i)],[])}function IT(e,n,i,c,p,g){let y=xT(c),x=XD(e,n,i,y,p,g),b=YD(x);return Ar(b)}function ff(e,n,i,c,p,g,y){return ct([c])?St(IT(e,n,i,c,p,g),{},y):qu(i,c,p,g,y)}function bT(e,n,i,c,p,g,y){let x=de(e,n,c);return ff(e,n,i,x,p,g,y)}function ZD(e,n,i){let c=ln(e,n);return Se(n).filter((g)=>i.includes(g)).reduce((g,y)=>({...g,[y]:ZS(c,y,n[y])}),{})}function eq(e,n,i){let c=ln(e,n);return Se(n).filter((g)=>!i.includes(g)).reduce((g,y)=>({...g,[y]:de(c,hr([],[]),n[y])}),{})}function tq(e,n,i){let c=JS(n),p=ZD(e,n,c),g=eq(e,n,c),y={...p,...g};return St(y,{},i)}function dp(e,n,i,c){return tq(e,i,c)}function Bm(e,n={}){return Ne("NonNullable",[e],n)}function ET(e,n={}){return hf(e,n)}function rq(e){let n=m([Pn(),_a()]);return ec(e,n,{})}function hf(e,n){return ct([e])?St(rq(e),{},n):Bm(e,n)}function ST(e,n,i,c){let p=de(e,n,i);return hf(p,c)}function Gm(e,n,i={}){return Ne("Omit",[e,n],i)}function wT(e,n,i={}){let c=Be(n)?Ua(n):n;return gf(e,c,i)}function fp(e){let n=Ba(e);return Qe(n)?n.properties:Ur()}function nq(e,n){return Se(e).reduce((c,p)=>n.includes(p)?c:{...c,[p]:e[p]},{})}function TT(e,n){let i=fp(e),c=Ka(n),p=nq(i,c);return s(p)}function gf(e,n,i){return ct([e,n])?St(TT(e,n),{},i):Gm(e,n,i)}function RT(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return gf(g,y,p)}function Km(e,n={}){return Ne("Parameters",[e],n)}function kT(e,n={}){return yf(e,n)}function oq(e){let n=en(e)?e.parameters:[],i=ci({},hr([],[]),n);return Br(i)}function yf(e,n){return ct([e])?St(oq(e),{},n):Km(e,n)}function AT(e,n,i,c){let p=de(e,n,i);return yf(p,c)}function Hm(e,n={}){return Ne("Partial",[e],n)}function CT(e,n={}){return xf(e,n)}function PT(e,n){let i=ws(e,n),c=Ts(i);return xs(ln(e,{[n]:c}),n)}function $T(e,n,i){let c=Zo(e,n,i);return Ts(c)}function MT(e){let n=Ar(e);return Ts(n)}function vT(e){let n=e.map((i)=>Ts(i));return m(n)}function OT(e){let n=Se(e).reduce((c,p)=>({...c,[p]:Ji(e[p])}),{});return s(n)}function Ts(e){return Qt(e)?PT(e.$defs,e.$ref):Dr(e)?$T(e.if,e.then,e.else):ze(e)?MT(e.allOf):xe(e)?vT(e.anyOf):Qe(e)?OT(e.properties):s({})}function xf(e,n){return ct([e])?St(Ts(e),{},n):Hm(e,n)}function _T(e,n,i,c){let p=de(e,n,i);return xf(p,c)}function Wm(e,n,i={}){return Ne("Pick",[e,n],i)}function LT(e,n,i={}){let c=Be(n)?Ua(n):n;return If(e,c,i)}function sq(e,n){return Se(e).reduce((c,p)=>n.includes(p)?ln(c,{[p]:e[p]}):c,{})}function NT(e,n){let i=fp(e),c=Ka(n),p=sq(i,c);return s(p)}function If(e,n,i){return ct([e,n])?St(NT(e,n),{},i):Wm(e,n,i)}function DT(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return If(g,y,p)}function zm(e,n={}){return Ne("ReadonlyObject",[e],n)}function bf(e,n={}){return Ef(e,n)}var qT=bf;function FT(e){return $a(B(e))}function jT(e,n){let i=ws(e,n),c=Rs(i);return xs(ln(e,{[n]:c}),n)}function UT(e,n,i){let c=Zo(e,n,i);return Rs(c)}function BT(e){let n=Ar(e);return Rs(n)}function GT(e){let n=Se(e).reduce((c,p)=>({...c,[p]:Zi(e[p])}),{});return s(n)}function KT(e){return $a(Br(e))}function HT(e){let n=e.map((i)=>Rs(i));return m(n)}function Rs(e){return wt(e)?FT(e.items):Qt(e)?jT(e.$defs,e.$ref):Dr(e)?UT(e.if,e.then,e.else):ze(e)?BT(e.allOf):Qe(e)?GT(e.properties):mt(e)?KT(e.items):xe(e)?HT(e.anyOf):e}function Ef(e,n){return ct([e])?St(Rs(e),{},n):zm(e)}function WT(e,n,i,c){let p=de(e,n,i);return Ef(p,c)}function zT(e,n,i,c){return n.visited.includes(c)?i:(c in e)?de(e,hr(n.callstack,[...n.visited,c]),e[c]):i}function VT(e,n){let i=ws(e,n),c=ks(i);return xs(ln(e,{[n]:c}),n)}function JT(e,n,i){let c=Zo(e,n,i);return ks(c)}function QT(e){let n=Ar(e);return ks(n)}function XT(e){let n=e.map((i)=>ks(i));return m(n)}function YT(e){let n=Se(e).reduce((c,p)=>({...c,[p]:Rm(e[p])}),{});return s(n)}function ks(e){return Qt(e)?VT(e.$defs,e.$ref):Dr(e)?JT(e.if,e.then,e.else):ze(e)?QT(e.allOf):xe(e)?XT(e.anyOf):Qe(e)?YT(e.properties):s({})}function Vm(e,n={}){return Ne("Required",[e],n)}function ZT(e,n={}){return Sf(e,n)}function Sf(e,n){return ct([e])?St(ks(e),{},n):Vm(e,n)}function eR(e,n,i,c){let p=de(e,n,i);return Sf(p,c)}function Jm(e,n={}){return Ne("ReturnType",[e],n)}function tR(e,n={}){return wf(e,n)}function iq(e){return en(e)?e.returnType:zt()}function wf(e,n){return ct([e])?St(iq(e),{},n):Jm(e,n)}function rR(e,n,i,c={}){let p=de(e,n,i);return wf(p,c)}function Qm(e,n){return Ne("With",[e,n],{})}function hp(e,n){return Tf(e,n)}function Tf(e,n){return ct([e])?St(e,{},n):Qm(e,n)}function nR(e,n,i,c){let p=de(e,n,i);return Tf(p,c)}function aq(e){return si(e)?mt(e.items)?Rf(e.items.items):rn(e.items)?[e]:jt(e.items)?[e]:[zt()]:[e]}function Rf(e){return e.reduce((i,c)=>[...i,...aq(c)],[])}function hr(e,n){return{callstack:e,visited:n}}function ct(e){return bt(e,(n,i)=>jt(n)?!1:ct(i),()=>!0)}function Vu(e,n,i){return Se(i).reduce((c,p)=>({...c,[p]:de(e,n,i[p])}),{})}function ci(e,n,i){let c=ho(e,n,i);return Rf(c)}function ho(e,n,i){return i.map((c)=>de(e,n,c))}function uq(e,n){let i=un(e)?Cu(n,{}):n,c=ea(e)?Au(i,{}):i;return Yi(e)?nc(c,{}):c}function cq(e,n,i,c,p){return _(i,"AddImmutable")?oR(e,n,c[0],p):_(i,"RemoveImmutable")?dw(e,n,c[0],p):_(i,"AddReadonly")?My(e,n,c[0],p):_(i,"RemoveReadonly")?Tx(e,n,c[0],p):_(i,"AddOptional")?vy(e,n,c[0],p):_(i,"RemoveOptional")?Ax(e,n,c[0],p):_(i,"Capitalize")?Sw(e,n,c[0],p):_(i,"Conditional")?Aw(e,n,c[0],c[1],c[2],c[3],p):_(i,"ConstructorParameters")?Pw(e,n,c[0],p):_(i,"Evaluate")?rw(e,n,c[0],p):_(i,"Exclude")?Mw(e,n,c[0],c[1],p):_(i,"Extract")?Lw(e,n,c[0],c[1],p):_(i,"Index")?iT(e,n,c[0],c[1],p):_(i,"InstanceType")?uT(e,n,c[0],p):_(i,"Interface")?HS(e,n,c[0],c[1],p):_(i,"KeyOf")?gT(e,n,c[0],p):_(i,"Lowercase")?ww(e,n,c[0],p):_(i,"Mapped")?bT(e,n,c[0],c[1],c[2],c[3],p):_(i,"Module")?dp(e,n,c[0],p):_(i,"NonNullable")?ST(e,n,c[0],p):_(i,"Pick")?DT(e,n,c[0],c[1],p):_(i,"Parameters")?AT(e,n,c[0],p):_(i,"Partial")?_T(e,n,c[0],p):_(i,"Omit")?RT(e,n,c[0],c[1],p):_(i,"ReadonlyObject")?WT(e,n,c[0],p):_(i,"Record")?Kx(e,n,c[0],c[1],p):_(i,"Required")?eR(e,n,c[0],p):_(i,"ReturnType")?rR(e,n,c[0],p):_(i,"TemplateLiteral")?pS(e,n,c[0],p):_(i,"Uncapitalize")?Tw(e,n,c[0],p):_(i,"Uppercase")?Rw(e,n,c[0],p):_(i,"With")?nR(e,n,c[0],c[1]):Ne(i,c,p)}function mq(e,n,i){let c=jt(i)?zT(e,n,i,i.$ref):wt(i)?B(de(e,n,i.items),ka(i)):ja(i)?pp(e,n,i.target,i.arguments):Zr(i)?hs(ho(e,n,i.parameters),de(e,n,i.instanceType),Oy(i)):en(i)?gs(ho(e,n,i.parameters),de(e,n,i.returnType),_y(i)):Dr(i)?Qi(de(e,n,i.if),de(e,n,i.then),de(e,n,i.else),qy(i)):ze(i)?Cn(ho(e,n,i.allOf),Gy(i)):Qe(i)?s(Vu(e,n,i.properties),Dy(i)):Gt(i)?Hx(fn(i),de(e,n,fr(i))):si(i)?na(de(e,n,i.items)):mt(i)?Br(ci(e,n,i.items),wx(i)):xe(i)?m(ho(e,n,i.anyOf),dx(i)):i;return uq(i,c)}function de(e,n,i){return Ys(i)?cq(e,n,i.action,i.parameters,i.options):mq(e,n,i)}function Ao(e,n){return de(e,hr([],[]),n)}function pq(e){return St(e,{"~immutable":!0},{})}function nc(e,n){return St(pq(e),{},n)}function oR(e,n,i,c){let p=de(e,n,i);return nc(p,c)}function aE(e,n={}){return Ne("AddImmutable",[e],n)}function $a(e,n={}){return nc(e,n)}function uE(e,n={}){return Ne("Evaluate",[e],n)}function Tn(e,n={}){return Yd(e,n)}function cE(e,n={}){return Ne("Module",[e],n)}function sR(e,n={}){return dp({},hr([],[]),e,n)}function lq(e,n){let i=va(e,n);return _(i,Nu)?1:_(i,Yu)?1:0}function iR(e,n,i=[]){return bt(n,(c,p)=>_(lq(e,c),1)?iR(e,p,[...i,c]):[...i,e,...n],()=>[...i,e])}function aR(e,n=[]){return bt(e,(i,c)=>aR(c,iR(i,n)),()=>n)}function uR(e){return aR(e)}function cR(...e){let[n,i,c]=Sn(e,{2:(y,x)=>yt(y)?[{},y,x]:[y,x,{}],3:(y,x,b)=>[y,x,b],1:(y)=>[{},y,{}]}),p=iS(i),g=Be(p)&&_(p.length,2)?de(n,hr([],[]),p[0]):zt();return St(g,{},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 g of n){let y=await i.env(g);if(p.throwIfAborted(),y)return{auth:{apiKey:y},source:g}}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 dR="faux",fR="faux",hR="faux-1",dq="Faux Model",fq="http://localhost:0",hq=3,mR=5,xp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Ln(e){return{type:"text",text:e}}function Io(e){return{type:"thinking",thinking:e}}function gq(e,n,i={}){return{type:"toolCall",id:i.id??Cf("tool"),name:e,arguments:n}}function yq(e){if(typeof e==="string")return[Ln(e)];return Array.isArray(e)?e:[e]}function Mo(e,n={}){return{role:"assistant",content:yq(e),api:dR,provider:fR,model:hR,usage:xp,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 gR(e){return Math.ceil(e.length/4)}function Cf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function yR(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(`
23
- `)}function xR(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(`
24
- `)}function xq(e){return[e.toolName,...e.content.map((n)=>yR([n]))].join(`
25
- `)}function Iq(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(`
26
- `);if(e.role==="user")return yR(e.content);if(e.role==="assistant")return xR(e.content);return xq(e)}function IR(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 bq(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?`
27
-
28
- `:"")+p.slice(i).join(`
29
-
30
- `);return IR(e,i)+Eq(c(e),c(n))}function Eq(e,n){let i=Math.min(e.length,n.length),c=0;while(c<i&&e[c]===n[c])c++;return c}function pR(e,n,i,c){let p=n.messages.map((C)=>`${C.role}:${Iq(C)}`),g=IR(p),y=Math.ceil(g/4),x=gR(xR(e.content)),b=y,S=0,T=0,A=i?.sessionId;if(A&&i?.cacheRetention!=="none"){let C=c.get(A);if(C){let P=bq(C,p);S=Math.ceil(P/4),T=Math.ceil((g-P)/4),b=Math.max(0,y-S)}else T=y;c.set(A,p)}return{...e,usage:{input:b,output:x,cacheRead:S,cacheWrite:T,totalTokens:b+x+S+T,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function kf(e,n,i){let c=[],p=0;while(p<e.length){let g=n+Math.floor(Math.random()*(i-n+1)),y=Math.max(1,g*4);c.push(e.slice(p,p+y)),p+=y}return c.length>0?c:[""]}function Sq(e,n,i,c){let p=structuredClone(e);return{...p,api:n,provider:i,model:c,timestamp:p.timestamp??Date.now(),usage:p.usage??xp}}function lR(e,n){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:xp,stopReason:"deferred",deferred:n,timestamp:Date.now()}}function gp(e,n,i,c){return{role:"assistant",content:[],api:n,provider:i,model:c,usage:xp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function oc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Af(e,n){if(!n||n<=0)return new Promise((c)=>queueMicrotask(c));let i=gR(e)/n*1000;return new Promise((c)=>setTimeout(c,i))}async function yp(e,n,i,c,p,g){let y={...n,content:[],stopReason:"pending"};if(g?.aborted){let x=oc(y);e.push({type:"error",reason:"aborted",error:x}),e.end(x);return}e.push({type:"start",partial:{...y}});for(let x=0;x<n.content.length;x++){if(g?.aborted){let S=oc(y);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}let b=n.content[x];if(b.type==="thinking"){y.content=[...y.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:x,partial:{...y}});for(let S of kf(b.thinking,i,c)){if(await Af(S,p),g?.aborted){let T=oc(y);e.push({type:"error",reason:"aborted",error:T}),e.end(T);return}y.content[x].thinking+=S,e.push({type:"thinking_delta",contentIndex:x,delta:S,partial:{...y}})}e.push({type:"thinking_end",contentIndex:x,content:b.thinking,partial:{...y}});continue}if(b.type==="text"){y.content=[...y.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:x,partial:{...y}});for(let S of kf(b.text,i,c)){if(await Af(S,p),g?.aborted){let T=oc(y);e.push({type:"error",reason:"aborted",error:T}),e.end(T);return}y.content[x].text+=S,e.push({type:"text_delta",contentIndex:x,delta:S,partial:{...y}})}e.push({type:"text_end",contentIndex:x,content:b.text,partial:{...y}});continue}y.content=[...y.content,{type:"toolCall",id:b.id,name:b.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:x,partial:{...y}});for(let S of kf(JSON.stringify(b.arguments),i,c)){if(await Af(S,p),g?.aborted){let T=oc(y);e.push({type:"error",reason:"aborted",error:T}),e.end(T);return}e.push({type:"toolcall_delta",contentIndex:x,delta:S,partial:{...y}})}y.content[x].arguments=b.arguments,e.push({type:"toolcall_end",contentIndex:x,toolCall:b,partial:{...y}})}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 bR(e){let n=e.api??Cf(dR),i=e.provider??fR,c=Math.max(1,Math.min(e.tokenSize?.min??hq,e.tokenSize?.max??mR)),p=Math.max(c,e.tokenSize?.max??mR),g=[],y=e.tokensPerSecond,x={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},b=new Map,S=new Map,A=((e.models?.length)?e.models:[{id:hR,name:dq,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:fq,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})),C=async(V,J,ee,ie)=>{let H=typeof V==="function"?await V(J,ee,x,ie):V;return pR(Sq(H,n,i,ie.id),J,ee,b)},P=(V,J,ee)=>{let ie=Xn(),H=g.shift();return x.callCount++,queueMicrotask(async()=>{try{if(await ee?.onResponse?.({status:200,headers:{}},V),!H){let fe=gp(Error("No more faux responses queued"),n,i,V.id);fe=pR(fe,J,ee,b),ie.push({type:"error",reason:"error",error:fe}),ie.end(fe);return}if(ee?.deferred){let fe={provider:V.provider,modelId:V.id,api:V.api,id:Cf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};S.set(fe.id,{handle:fe,step:H,context:J,options:ee,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await yp(ie,lR(V,fe),c,p,y,ee.signal);return}let ce=await C(H,J,ee,V);await yp(ie,ce,c,p,y,ee?.signal)}catch(ce){let fe=gp(ce,n,i,V.id);ie.push({type:"error",reason:"error",error:fe}),ie.end(fe)}}),ie},L=(V,J,ee)=>P(V,J,ee),q=(V,J,ee)=>{let ie=Xn();return x.deferredFetchCount++,queueMicrotask(async()=>{try{await ee?.onResponse?.({status:200,headers:{}},V);let H=S.get(J.id);if(!H||H.handle.provider!==J.provider||H.handle.modelId!==J.modelId||H.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(H.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(H.pendingFetches>0){H.pendingFetches--,await yp(ie,lR(V,H.handle),c,p,y,ee?.signal);return}if(!H.final){let{deferred:ce,signal:fe,onResponse:_e,...be}=H.options??{};try{H.final=await C(H.step,H.context,be,H.model)}catch(se){H.final=gp(se,n,i,H.model.id)}}await yp(ie,H.final,c,p,y,ee?.signal)}catch(H){let ce=gp(H,n,i,V.id);ie.push({type:"error",reason:"error",error:ce}),ie.end(ce)}}),ie},X=async(V,J,ee)=>{x.cancelledDeferred.push(structuredClone(J));let ie=S.get(J.id);if(ie)ie.cancelled=!0;await ee?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return A[0];return A.find((J)=>J.id===V)}return{api:n,provider:i,models:A,stream:P,streamSimple:L,fetchDeferred:q,cancelDeferred:X,getModel:j,state:x,setResponses(V){g=[...V]},appendResponses(V){g.push(...V)},getPendingResponseCount(){return g.length}}}function Lo(e={}){let n=bR(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 wq(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 kq(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 sc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Ha(e){sc(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 $f(e){let n=JSON.stringify(e);if(n===void 0)throw Error("Tool-call arguments are not JSON-serializable");return n}var Aq=$f(W(""));function Mf(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)=>Mf(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)&&Mf(p,i[c]))}class ER{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:kq(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=Ha(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:wq(n)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let n=Ha(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=Ha(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=Ha(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=Ha(e);if(n.type!=="toolCall")throw Error(`toolcall_start event points to ${n.type} block at index ${e.contentIndex}`);let i=$f(n.arguments),c=i===Aq;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=W(n.catchupJson);if($f(i)!==n.snapshotArguments){let p=W(n.snapshotArguments);if(!Mf(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=Ha(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(sc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,n)}block(e,n){sc(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 g=Math.max(0,c.coveredChars-p);if(g>=n.length)return;let y=g===0?n:n.slice(g);return i==="text"?{type:"text_delta",contentIndex:e,delta:y}:{type:"thinking_delta",contentIndex:e,delta:y}}}function Pf(e,n,i,c,p){if(sc(i),i!==e.content.length){let g=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${g}`)}e.content.push(structuredClone(c)),n.set(i,p)}function aa(e,n,i,c,p){sc(i);let g=n.get(i),y=e.content[i];if(!g||!y)throw Error(`${p} frame has no started block at index ${i}`);if(g.kind!==c||y.type!==c)throw Error(`${p} frame expected ${c} block at index ${i}, found ${y.type}`);if(g.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:y,state:g}}function Cq(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`);Pf(n,c,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:g}=aa(n,c,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");g.text+=p.delta;break}case"text_end":{let{block:g,state:y}=aa(n,c,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");if(g.text=p.content,delete g.textSignature,p.textSignature!==void 0)g.textSignature=p.textSignature;y.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);Pf(n,c,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:g}=aa(n,c,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");g.thinking+=p.delta;break}case"thinking_end":{let{block:g,state:y}=aa(n,c,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");if(g.thinking=p.content,delete g.thinkingSignature,delete g.redacted,p.thinkingSignature!==void 0)g.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)g.redacted=p.redacted;y.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);Pf(n,c,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:g,state:y}=aa(n,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");y.json=p.json,g.arguments=W(p.json);break}case"toolcall_delta":{let{block:g,state:y}=aa(n,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call frame state");y.json+=p.delta;break}case"toolcall_end":{let{block:g,state:y}=aa(n,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(g.id=p.id,g.name=p.name,g.arguments=structuredClone(p.arguments),delete g.thoughtSignature,delete g.namespace,p.thoughtSignature!==void 0)g.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)g.namespace=p.namespace;y.ended=!0;break}}}if(!n)return;for(let[p,g]of c){if(g.kind!=="toolCall"||g.ended||g.json.length===0)continue;let y=n.content[p];if(y?.type!=="toolCall")throw Error("Unreachable tool-call frame state");y.arguments=W(g.json)}return n}var SR=[/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],Pq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,$q=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ua(e,n){if(e.stopReason==="error"&&e.errorMessage){if(!$q.some((c)=>c.test(e.errorMessage))){if(SR.some((c)=>c.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&Pq.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 Mq(e,n){return e.stopReason==="length"&&n>0&&e.usage.output<n}function vq(){return[...SR]}function wR(e){return new RegExp(e.join("|"),"i")}var Oq=wR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),_q=wR(["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"]),TR=60000;function RR(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??TR)}class Ip extends Error{constructor(){super("Aborted")}}function Lq(e,n){return new Promise((i,c)=>{if(n?.aborted){c(new Ip);return}let p=setTimeout(i,e);n?.addEventListener("abort",()=>{clearTimeout(p),c(new Ip)},{once:!0})})}async function Nq(e,n,i,c){let p=n?.enabled?n.maxRetries:0,g=0,y;for(;;){let x=await e();if(x.stopReason==="aborted"){if(y)await c?.onRetryFinished?.(!1,y.attempt);return x}if(x.stopReason!=="error"){if(y)await c?.onRetryFinished?.(!0,y.attempt);return x}if(g>=p||!kR(x)){if(y)await c?.onRetryFinished?.(!1,y.attempt,x.errorMessage);return x}g++,y={attempt:g,errorMessage:x.errorMessage||"Unknown error"};let b=RR(n,g);await c?.onRetryScheduled?.(g,p,b,y.errorMessage);try{await Lq(b,i)}catch(S){if(await c?.onRetryFinished?.(!1,g,y.errorMessage),S instanceof Ip){let{errorMessage:T,...A}=x;return{...A,stopReason:"aborted"}}throw S}await c?.onRetryAttemptStart?.()}}function kR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let n=e.errorMessage;if(Oq.test(n))return!1;return _q.test(n)}function Dq(e,n){return $r({type:"string",enum:e,...n?.description&&{description:n.description},...n?.default&&{default:n.default}})}function ic(e){return le(e,"~refine")&&Be(e["~refine"])&&sn(e["~refine"],0,(n)=>ut(n)&&le(n,"check")&&le(n,"error")&&ls(n.check)&&ls(n.error))}function hn(e){return ut(e)&&!Be(e)}function Ds(e){return mn(e)}function Ye(e){return hn(e)||Ds(e)}function Wa(e){return le(e,"additionalItems")&&Ye(e.additionalItems)}function Po(e){return le(e,"additionalProperties")&&Ye(e.additionalProperties)}function ac(e){return le(e,"allOf")&&Be(e.allOf)&&e.allOf.every((n)=>Ye(n))}function uc(e){return le(e,"$anchor")&&yt(e.$anchor)}function cc(e){return le(e,"anyOf")&&Be(e.anyOf)&&e.anyOf.every((n)=>Ye(n))}function bp(e){return le(e,"const")}function As(e){return le(e,"contains")&&Ye(e.contains)}function yo(e){return le(e,"default")}function mc(e){return le(e,"dependencies")&&ut(e.dependencies)&&Object.values(e.dependencies).every((n)=>Ye(n)||Be(n)&&n.every((i)=>yt(i)))}function pc(e){return le(e,"dependentRequired")&&ut(e.dependentRequired)&&Object.values(e.dependentRequired).every((n)=>Be(n)&&n.every((i)=>yt(i)))}function za(e){return le(e,"dependentSchemas")&&ut(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((n)=>Ye(n))}function qs(e){return le(e,"$dynamicAnchor")&&yt(e.$dynamicAnchor)}function lc(e){return le(e,"$dynamicRef")&&yt(e.$dynamicRef)}function dc(e){return le(e,"else")&&Ye(e.else)}function Ep(e){return le(e,"enum")&&Be(e.enum)}function fc(e){return le(e,"exclusiveMaximum")&&(_t(e.exclusiveMaximum)||Nr(e.exclusiveMaximum))}function ts(e){return le(e,"exclusiveMinimum")&&(_t(e.exclusiveMinimum)||Nr(e.exclusiveMinimum))}function ca(e){return le(e,"format")&&yt(e.format)}function xo(e){return le(e,"$id")&&yt(e.$id)}function hc(e){return le(e,"if")&&Ye(e.if)}function Fs(e){return le(e,"items")&&(Ye(e.items)||Be(e.items)&&e.items.every((n)=>Ye(n)))}function gc(e){return Fs(e)&&Be(e.items)}function yc(e){return le(e,"maximum")&&(_t(e.maximum)||Nr(e.maximum))}function xc(e){return le(e,"maxContains")&&_t(e.maxContains)}function Va(e){return le(e,"maxItems")&&_t(e.maxItems)}function Ic(e){return le(e,"maxLength")&&_t(e.maxLength)}function bc(e){return le(e,"maxProperties")&&_t(e.maxProperties)}function rs(e){return le(e,"minimum")&&(_t(e.minimum)||Nr(e.minimum))}function js(e){return le(e,"minContains")&&_t(e.minContains)}function li(e){return le(e,"minItems")&&_t(e.minItems)}function ma(e){return le(e,"minLength")&&_t(e.minLength)}function pa(e){return le(e,"minProperties")&&_t(e.minProperties)}function Ec(e){return le(e,"multipleOf")&&(_t(e.multipleOf)||Nr(e.multipleOf))}function Sc(e){return le(e,"not")&&Ye(e.not)}function wc(e){return le(e,"oneOf")&&Be(e.oneOf)&&e.oneOf.every((n)=>Ye(n))}function la(e){return le(e,"pattern")&&(yt(e.pattern)||e.pattern instanceof RegExp)}function Us(e){return le(e,"patternProperties")&&ut(e.patternProperties)&&Object.values(e.patternProperties).every((n)=>Ye(n))}function ns(e){return le(e,"prefixItems")&&Be(e.prefixItems)&&e.prefixItems.every((n)=>Ye(n))}function Bs(e){return le(e,"properties")&&ut(e.properties)&&Object.values(e.properties).every((n)=>Ye(n))}function Ja(e){return le(e,"propertyNames")&&(ut(e.propertyNames)||Ye(e.propertyNames))}function qq(e){return le(e,"$recursiveAnchor")&&mn(e.$recursiveAnchor)}function Tc(e){return qq(e)&&_(e.$recursiveAnchor,!0)}function Rc(e){return le(e,"$recursiveRef")&&yt(e.$recursiveRef)}function kc(e){return le(e,"$ref")&&yt(e.$ref)}function os(e){return le(e,"required")&&Be(e.required)&&e.required.every((n)=>yt(n))}function Ac(e){return le(e,"then")&&Ye(e.then)}function Cc(e){return le(e,"type")&&(yt(e.type)||Be(e.type)&&e.type.every((n)=>yt(n)))}function Ii(e){return le(e,"uniqueItems")&&mn(e.uniqueItems)}function Ci(e){return le(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function $i(e){return le(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function Fq(e){return Ci(e)||$i(e)||wa(Se(e),(n)=>Sp(e[n]))}function jq(e){return wa(e,(n)=>Sp(n))}function Sp(e){return Be(e)?jq(e):ut(e)?Fq(e):!1}function AR(e,n){return Sp(n)||wa(Se(e),(i)=>Sp(e[i]))}class vf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ir(Et("context","Push"),[])}Pop(){return Ir(Et("context","Pop"),[])}AddIndex(e){return Ir(Et("context","AddIndex"),[e])}AddKey(e){return Ir(Et("context","AddKey"),[e])}Merge(e){return Ir(Et("context","Merge"),[e])}}class _n{constructor(){let e=new Set,n=new Set;this.stack=[{indices:e,keys:n}]}Push(){let e=new Set,n=new Set;return this.stack.push({indices:e,keys:n}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let n of e)n.GetIndices().forEach((i)=>this.GetIndices().add(i)),n.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class Dn extends _n{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Qo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var wp={identifier:"External",variables:[]};function vo(e){let n=`External[${wp.variables.length}]`;return wp.variables.push(e),n}function CR(){wp.variables=[]}function PR(){return{...wp}}function $R(e,n,i,c){let p=vo(i["~refine"].map((g)=>g));return fs(p,De(0),["refinement","_"],Ir(Et("refinement","check"),[c]))}function MR(e,n,i,c){return sn(i["~refine"],0,(p,g)=>p.check(c))}function vR(e,n,i,c,p,g){return kn(p["~refine"],0,(y,x)=>y.check(g)||n.AddError({keyword:"~refine",schemaPath:i,instancePath:c,params:{index:x,message:y.error(g)}}))}var Uq=0;function Vt(){return`var_${Uq++}`}function Of(e){return Fs(e)&&Be(e.items)}function Bq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Zn(e,n,i.additionalItems,p),x=fd(g,De(i.items.length)),b=n.AddIndex(g);return fs(c,De(0),[p,g],xr(x,En(y,b)))}function Gq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Zn(e,n,i.additionalItems,p),x=fd(g,De(i.items.length));return fs(c,De(0),[p,g],xr(x,y))}function OR(e,n,i,c){if(!Of(i))return De(!0);return n.UseUnevaluated()?Bq(e,n,i,c):Gq(e,n,i,c)}function _R(e,n,i,c){if(!Of(i))return!0;return sn(c,0,(g,y)=>wu(y,i.items.length)||bo(e,n,i.additionalItems,g)&&n.AddIndex(y))}function LR(e,n,i,c,p,g){if(!Of(p))return!0;return sn(g,0,(x,b)=>{let S=`${i}/additionalItems`,T=`${c}/${b}`;return wu(b,p.items.length)||Eo(e,n,S,T,p.additionalItems,x)&&n.AddIndex(b)})}function ss(e){return new RegExp(e,"u")}function Kq(e,n){return!e.UseUnevaluated()&&(_(n,!0)||ut(n)&&_(Se(n).length,0))}function Hq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function _f(e){let n=[];if(Us(e))n.push(...Se(e.patternProperties));if(Bs(e))n.push(...Se(e.properties).map(Hq));return _(n.length,0)?"(?!)":`(${n.join("|")})`}function Wq(e,n,i){return os(n)&&Bs(n)&&!Us(n)&&_(n.additionalProperties,!1)&&_(Se(n.properties).length,n.required.length)}function zq(e,n,i){return io(Et(Ir(Et("Object","getOwnPropertyNames"),[i]),"length"),De(n.required.length))}function Vq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=vo(ss(_f(i))),x=Zn(e,n,i.additionalProperties,`${c}[${p}]`),b=Ir(Et(y,"test"),[p]),S=n.AddKey(p),T=n.UseUnevaluated()?xr(b,En(x,S)):xr(b,x);return fs(Wi(c),De(0),[p,g],T)}function NR(e,n,i,c){if(Kq(n,i.additionalProperties))return De(!0);return Wq(n,i,c)?zq(n,i,c):Vq(e,n,i,c)}function DR(e,n,i,c){let p=ss(_f(i));return sn(Se(c),0,(y,x)=>p.test(y)||bo(e,n,i.additionalProperties,c[y])&&n.AddKey(y))}function qR(e,n,i,c,p,g){let y=ss(_f(p)),x=[];return kn(Se(g),0,(S,T)=>{let A=`${i}/additionalProperties`,C=`${c}/${S}`,P=y.test(S)||Eo(e,n,A,C,p.additionalProperties,g[S])&&n.AddKey(S);if(!P)x.push(S);return P})||n.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:c,params:{additionalProperties:x}})}function Mi(e,n,i,c,p){let g=_s("results","[]"),y=i.map((T,A)=>_s(`context_${A}`,hd("CheckContext",[]))),x=i.map((T,A)=>_s(`condition_${A}`,Ir(Qs(["context"],Nt(e,n,T,c)),[`context_${A}`]))),b=i.map((T,A)=>Ay(`condition_${A}`,Ir(Et("results","push"),[`context_${A}`]))),S=cm(En(p,n.Merge("results")));return Ir(Qs([],um([g,...y,...x,...b,S])),[])}function Jq(e,n,i,c){return Mi(e,n,i.allOf,c,io(Et("results","length"),De(i.allOf.length)))}function Qq(e,n,i,c){return An(i.allOf.map((p)=>Nt(e,n,p,c)))}function FR(e,n,i,c){return n.UseUnevaluated()?Jq(e,n,i,c):Qq(e,n,i,c)}function jR(e,n,i,c){let p=i.allOf.reduce((g,y)=>{let x=new _n;return At(e,x,y,c)?[...g,x]:g},[]);return _(p.length,i.allOf.length)&&n.Merge(p)}function UR(e,n,i,c,p,g){let y=[],x=p.allOf.reduce((S,T,A)=>{let C=`${i}/allOf/${A}`,P=new Dn,L=mr(e,P,C,c,T,g);if(!L)y.push(P);return L?[...S,P]:S},[]),b=_(x.length,p.allOf.length)&&n.Merge(x);if(!b)y.forEach((S)=>S.GetErrors().forEach((T)=>n.AddError(T)));return b}function Xq(e,n,i,c){return Mi(e,n,i.anyOf,c,Ty(Et("results","length"),De(0)))}function Yq(e,n,i,c){return gd(i.anyOf.map((p)=>Nt(e,n,p,c)))}function BR(e,n,i,c){return n.UseUnevaluated()?Xq(e,n,i,c):Yq(e,n,i,c)}function GR(e,n,i,c){let p=i.anyOf.reduce((g,y)=>{let x=new _n;return At(e,x,y,c)?[...g,x]:g},[]);return Gi(p.length,0)&&n.Merge(p)}function KR(e,n,i,c,p,g){let y=[],x=p.anyOf.reduce((S,T,A)=>{let C=new Dn,P=`${i}/anyOf/${A}`,L=mr(e,C,P,c,T,g);if(!L)y.push(C);return L?[...S,C]:S},[]),b=Gi(x.length,0)&&n.Merge(x);if(!b)y.forEach((S)=>S.GetErrors().forEach((T)=>n.AddError(T)));return b||n.AddError({keyword:"anyOf",schemaPath:i,instancePath:c,params:{}})}function HR(e,n,i,c){return i?De(!0):De(!1)}function Lf(e,n,i,c){return i}function WR(e,n,i,c,p,g){return Lf(e,n,p,g)||n.AddError({keyword:"boolean",schemaPath:i,instancePath:c,params:{}})}function zR(e,n,i,c){return Ki(i.const)?io(c,De(i.const)):ky(c,vo(i.const))}function Nf(e,n,i,c){return Ki(i.const)?_(c,i.const):Ta(c,i.const)}function VR(e,n,i,c,p,g){return Nf(e,n,p,g)||n.AddError({keyword:"const",schemaPath:i,instancePath:c,params:{allowedValue:p.const}})}function JR(e){return!(js(e)&&_(e.minContains,0))}function Zq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Un(io(Et(c,"length"),De(0))),x=Ov(c,[p,g],En(Nt(e,n,i.contains,p),n.AddIndex(g)));return En(y,x)}function eF(e,n,i,c){let[p]=[Vt()],g=Un(io(Et(c,"length"),De(0))),y=vv(c,[p,"_"],Nt(e,n,i.contains,p));return En(g,y)}function QR(e,n,i,c){if(!JR(i))return De(!0);return n.UseUnevaluated()?Zq(e,n,i,c):eF(e,n,i,c)}function Df(e,n,i,c){if(!JR(i))return!0;return!_(c.length,0)&&yy(c,(p,g)=>At(e,n,i.contains,p)&&n.AddIndex(g))}function XR(e,n,i,c,p,g){return Df(e,n,p,g)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:1}})}function YR(e,n,i,c){let p=io(Et(Wi(c),"length"),De(0)),g=An(pn(i.dependencies).map(([y,x])=>{let b=Un(zi(c,De(y))),S=Nt(e,n,x,c),T=(A)=>An(A.map((C)=>zi(c,De(C))));return xr(b,Be(x)?T(x):S)}));return xr(p,g)}function ZR(e,n,i,c){let p=_(Se(c).length,0),g=sn(pn(i.dependencies),0,([y,x])=>!le(c,y)||(Be(x)?x.every((b)=>le(c,b)):At(e,n,x,c)));return p||g}function ek(e,n,i,c,p,g){let y=_(Se(g).length,0),x=kn(pn(p.dependencies),0,([b,S])=>{let T=`${i}/dependencies/${b}`;return!le(g,b)||(Be(S)?S.every((A)=>le(g,A)||n.AddError({keyword:"dependencies",schemaPath:i,instancePath:c,params:{property:b,dependencies:S}})):mr(e,n,T,c,S,g))});return y||x}function tk(e,n,i,c){let p=io(Et(Wi(c),"length"),De(0)),g=An(pn(i.dependentRequired).map(([y,x])=>{let b=Un(zi(c,De(y))),S=An(x.map((T)=>zi(c,De(T))));return xr(b,S)}));return xr(p,g)}function rk(e,n,i,c){let p=_(Se(c).length,0),g=sn(pn(i.dependentRequired),0,([y,x])=>!le(c,y)||x.every((b)=>le(c,b)));return p||g}function nk(e,n,i,c,p,g){let y=_(Se(g).length,0),x=kn(pn(p.dependentRequired),0,([b,S])=>!le(g,b)||kn(S,0,(T)=>le(g,T)||n.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:c,params:{property:b,dependencies:S}})));return y||x}function ok(e,n,i,c){let p=io(Et(Wi(c),"length"),De(0)),g=An(pn(i.dependentSchemas).map(([y,x])=>{let b=Un(zi(c,De(y))),S=Nt(e,n,x,c);return xr(b,S)}));return xr(p,g)}function sk(e,n,i,c){let p=_(Se(c).length,0),g=sn(pn(i.dependentSchemas),0,([y,x])=>!le(c,y)||At(e,n,x,c));return p||g}function ik(e,n,i,c,p,g){let y=_(Se(g).length,0),x=kn(pn(p.dependentSchemas),0,([b,S])=>{let T=`${i}/dependentSchemas/${b}`;return!le(g,b)||mr(e,n,T,c,S,g)});return y||x}function ak(e,n,i,c){let p=e.DynamicRef(i)??!1;return Gs(e,n,p,c)}function uk(e,n,i,c){let p=e.DynamicRef(i)??!1;return Ye(p)&&At(e,n,p,c)}function ck(e,n,i,c,p,g){let y=e.DynamicRef(p)??!1;return Ye(y)&&mr(e,n,"#",c,y,g)}function mk(e,n,i,c){return gd(i.enum.map((p)=>{if(Ki(p))return io(c,De(p));let g=vo(p);return ky(c,g)}))}function Ff(e,n,i,c){return wa(i.enum,(p)=>Ki(p)?_(c,p):Ta(c,p))}function pk(e,n,i,c,p,g){return Ff(e,n,p,g)||n.AddError({keyword:"enum",schemaPath:i,instancePath:c,params:{allowedValues:p.enum}})}function lk(e,n,i,c){return fd(c,De(i.exclusiveMaximum))}function jf(e,n,i,c){return wu(c,i.exclusiveMaximum)}function dk(e,n,i,c,p,g){return jf(e,n,p,g)||n.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:c,params:{comparison:"<",limit:p.exclusiveMaximum}})}function fk(e,n,i,c){return Ty(c,De(i.exclusiveMinimum))}function Uf(e,n,i,c){return Gi(c,i.exclusiveMinimum)}function hk(e,n,i,c,p,g){return Uf(e,n,p,g)||n.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:c,params:{comparison:">",limit:p.exclusiveMinimum}})}var tF=[0,31,28,31,30,31,30,31,31,30,31,30,31],rF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function nF(e){return e%4===0&&(e%100!==0||e%400===0)}function Xa(e){let n=rF.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&&nF(i)?29:tF[c])}var oF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Ya(e,n=!0){let i=oF.exec(e);if(!i)return!1;if(n&&!i[4]&&!i[5])return!1;let c=+i[1],p=+i[2],g=+i[3];if(c>23||p>59||g>60)return!1;if(i[5]){let T=+i[6],A=+i[7];if(T>23||A>59)return!1}if(g<60)return!0;let y=i[5]==="-"?-1:1,x=+(i[6]||0),b=+(i[7]||0);return((c*60+p-y*(x*60+b))%1440+1440)%1440===1439}function Tp(e){let n=e.split(/T/i);return n.length===2&&Xa(n[0])&&Ya(n[1])}var sF=/^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 Rp(e){return sF.test(e)}var iF=/^(?:[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 kp(e){return iF.test(e)}var gk=/^(?!-).*(?<!-)$/,yk=/^(?!..--)/,xk=/^[a-zA-Z0-9-]*$/;var Za=/[^\p{ASCII}]/u;var aF=/[0-9]/,Ik=/[\u{0660}-\u{0669}]/u,uF=/[\u{06f0}-\u{06f9}]/u,cF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,mF=/[\u{002d}\u{002b}]/u,Bf=/\p{Mn}/u,pF=/\p{Mc}/u;var bk=/[\p{Mn}\p{Mc}\p{Me}]/u,Gf=/\p{L}/u,lF=/\p{Nd}/u,Ek=/\p{Script=Greek}/u,Ap=/\p{Script=Hebrew}/u,Sk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,wk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Kf=/[\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,Tk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,dF=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,fF=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Rk=new RegExp([aF,uF].map((e)=>e.source).join("|"),"u"),kk=new RegExp([Gf,mF,cF,lF,Bf,pF,dF,fF].map((e)=>e.source).join("|"),"u");function Ak(e){return gk.test(e)&&yk.test(e)&&xk.test(e)}var is=36,$c=1,Mc=26,gF=38,yF=700,Pk=72,$k=128;function Hf(){throw null}function Cp(e){return e.toLowerCase().startsWith("xn--")}function Mk(e,n,i){e=i?Math.floor(e/yF):e>>1,e+=Math.floor(e/n);let c=0;while(e>(is-$c)*Mc>>1)e=Math.floor(e/(is-$c)),c+=is;return c+Math.floor((is-$c+1)*e/(e+gF))}function Pp(e){let n=[],i=$k,c=0,p=Pk,g=e.lastIndexOf("-");if(g>0)for(let x=0;x<g;x++){let b=e.charCodeAt(x);if(b>=128)Hf();n.push(b)}let y=g<0?0:g+1;while(y<e.length){let x=c,b=1,S=is;while(!0){if(y>=e.length)Hf();let A=e.charCodeAt(y++),C;if(A>=97&&A<=122)C=A-97;else if(A>=48&&A<=57)C=A-48+26;else Hf();c+=C*b;let P=S<=p?$c:S>=p+Mc?Mc:S-p;if(C<P)break;b*=is-P,S+=is}let T=n.length+1;p=Mk(c-x,T,x===0),i+=Math.floor(c/T),c%=T,n.splice(c,0,i),c++}return String.fromCodePoint(...n)}function Ck(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var xF=new RegExp(Za.source,"gu");function vk(e){let n=e.replace(xF,""),i=n.length,c=i>0?[n,"-"]:[],p=Array.from(e,(S)=>S.codePointAt(0)),g=$k,y=0,x=Pk,b=i;while(b<p.length){let S=1/0;for(let T of p)if(T>=g&&T<S)S=T;y+=(S-g)*(b+1),g=S;for(let T of p){if(T<g)y++;if(T===g){let A=y;for(let C=is;;C+=is){let P=C<=x?$c:C>=x+Mc?Mc:C-x;if(A<P)break;let L=P+(A-P)%(is-P);c.push(Ck(L)),A=Math.floor((A-P)/(is-P))}c.push(Ck(A)),x=Mk(y,b+1,b===i),y=0,b++}}y++,g++}return c.join("")}var IF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Ok=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,bF=/^(?:R|AL|AN)$/;function _k(e){if(Cp(e))try{return $p(Pp(e.slice(4).toLowerCase()))}catch{return!1}return $p(e)}function Lk(e){let n=String.fromCodePoint(e);return Rk.test(n)?"EN":Ik.test(n)?"AN":Bf.test(n)?"NSM":Ap.test(n)?"R":wk.test(n)?"AL":Gf.test(n)?"L":"ON"}function $p(e){for(let n of e)if(bF.test(Lk(n.codePointAt(0))))return!0;return!1}function Mp(e){let n=!1,i=Ok,c=!1,p=!1,g=!0;for(let y of e){let x=Lk(y.codePointAt(0));if(g){if(x!=="L"&&x!=="R"&&x!=="AL")return!1;n=x==="R"||x==="AL",i=n?IF:Ok,g=!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 EF(e){return Za.test(e)&&vk(e).length+4>63}function SF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function vp(e){if(EF(e))return!1;if($p(e)&&!Mp(e))return!1;let n=[...e],i=n.map((g)=>g.codePointAt(0)),c=i.length;if(SF(n))return!1;if(bk.test(n[0]))return!1;let p=!1;for(let g=0;g<c;g++){let y=i[g],x=n[g];if(Tk.test(x))return!1;if(!kk.test(x))return!1;if(Sk.test(x))p=!0;let b=i[g-1],S=i[g+1];switch(y){case 183:if(b!==108||S!==108)return!1;break;case 885:if(!S||!Ek.test(n[g+1]))return!1;break;case 1523:case 1524:if(!b||!Ap.test(n[g-1]))return!1;break;case 8204:if(!b||b<128&&!Kf.test(n[g-1]))return!1;break;case 8205:if(!b||!Kf.test(n[g-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function Op(e){if(!Cp(e))return!1;try{let n=e.slice(4).toLowerCase();if(n.lastIndexOf("-")===0)return!1;let i=Pp(n);if(!Za.test(i))return!1;return vp(i)}catch{return!1}}function wF(e){return e.length>0&&e.length<=63}function TF(e){return wF(e)&&(Op(e)||Ak(e))}function Fk(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 kF(e){return RF(e)&&(Op(e)||vp(e))}function AF(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 jk(e){if(e.length===0||e.includes(" "))return!1;let n=AF(e);if(n.length>253)return!1;let i=n.split("."),c=i.some((p)=>_k(p));return i.every((p)=>kF(p)&&(!c||Mp(p)))}function _p(e){return Fk(e)}var CF=/^(?:[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 Lp(e){return CF.test(e.normalize("NFC"))}function Np(e){return jk(e)}var PF=/^(?:(?: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 Dp(e){return PF.test(e)}var $F=/^(?:(?:(?:[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 qp(e){return $F.test(e)}var MF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,vF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Fp(e){return!MF.test(e)&&!vF.test(e)&&URL.canParse(e,"http://example.com")}var OF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,_F=/[\x00-\x20<>\^`{|}\\]/,LF=/%(?![0-9a-fA-F]{2})/;function NF(e){return e.length<2048?e.replace(OF,"[::1]"):e}function jp(e){if(_F.test(e))return!1;if(LF.test(e))return!1;return URL.canParse(NF(e))}var DF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Up(e){return DF.test(e)}var qF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Bp(e){return qF.test(e)}function Gp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var FF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Kp(e){return FF.test(e)}var jF=/^(?:[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 Hp(e){return jF.test(e)}var UF=/^(?:(?:[^\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 Wp(e){return UF.test(e)}var BF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function zp(e){return BF.test(e)}function Vp(e){return URL.canParse(e)}var GF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Jp(e){return GF.test(e)}var Er=new Map;function Bk(){Er.clear()}function KF(){return[...Er.entries()]}function HF(e,n){Er.set(e,n)}function WF(e){return Er.has(e)}function zF(e){return Er.get(e)}function Gk(e,n){return Er.get(e)?.(n)??!0}function Kk(){Bk(),Er.set("date-time",Tp),Er.set("date",Xa),Er.set("duration",Rp),Er.set("email",kp),Er.set("hostname",_p),Er.set("idn-email",Lp),Er.set("idn-hostname",Np),Er.set("ipv4",Dp),Er.set("ipv6",qp),Er.set("iri-reference",Fp),Er.set("iri",jp),Er.set("json-pointer-uri-fragment",Up),Er.set("json-pointer",Bp),Er.set("regex",Gp),Er.set("relative-json-pointer",Kp),Er.set("time",Ya),Er.set("uri-reference",Hp),Er.set("uri-template",Wp),Er.set("uri",zp),Er.set("url",Vp),Er.set("uuid",Jp)}Kk();function Hk(e,n,i,c){return Ir(Et("Format","Test"),[De(i.format),c])}function zf(e,n,i,c){return Gk(i.format,c)}function Wk(e,n,i,c,p,g){return zf(e,n,p,g)||n.AddError({keyword:"format",schemaPath:i,instancePath:c,params:{format:p.format}})}function zk(e,n,i,c){let p=Ac(i)?i.then:!0,g=dc(i)?i.else:!0;return Lv(Nt(e,n,i.if,c),Nt(e,n,p,c),Nt(e,n,g,c))}function Vk(e,n,i,c){let p=Ac(i)?i.then:!0,g=dc(i)?i.else:!0;return At(e,n,i.if,c)?At(e,n,p,c):At(e,n,g,c)}function Jk(e,n,i,c,p,g){let y=Ac(p)?p.then:!0,x=dc(p)?p.else:!0,b=new Dn,S=mr(e,b,`${i}/if`,c,p.if,g)?mr(e,b,`${i}/then`,c,y,g)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"then"}}):mr(e,n,`${i}/else`,c,x,g)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"else"}});if(S)n.Merge([b]);return S}function VF(e,n,i,c){return An(i.items.map((p,g)=>{let y=Hi(Et(c,"length"),De(g)),x=Zn(e,n,p,`${c}[${g}]`),b=n.AddIndex(De(g));return xr(y,En(x,b))}))}function JF(e,n,i,c){return An(i.items.map((p,g)=>{let y=Hi(Et(c,"length"),De(g)),x=Zn(e,n,p,`${c}[${g}]`);return xr(y,x)}))}function QF(e,n,i,c){return n.UseUnevaluated()?VF(e,n,i,c):JF(e,n,i,c)}function XF(e,n,i,c){return sn(i.items,0,(p,g)=>ds(c.length,g)||bo(e,n,p,c[g])&&n.AddIndex(g))}function YF(e,n,i,c,p,g){return kn(p.items,0,(y,x)=>{let b=`${i}/items/${x}`,S=`${c}/${x}`;return ds(g.length,x)||Eo(e,n,b,S,y,g[x])&&n.AddIndex(x)})}function ZF(e,n,i,c){let p=ns(i)?i.prefixItems.length:0,g=Zn(e,n,i.items,"element"),y=n.AddIndex("index");return fs(c,De(p),["element","index"],En(g,y))}function e1(e,n,i,c){let p=ns(i)?i.prefixItems.length:0,g=Zn(e,n,i.items,"element");return fs(c,De(p),["element","index"],g)}function t1(e,n,i,c){return n.UseUnevaluated()?ZF(e,n,i,c):e1(e,n,i,c)}function r1(e,n,i,c){let p=ns(i)?i.prefixItems.length:0;return sn(c,p,(g,y)=>bo(e,n,i.items,g)&&n.AddIndex(y))}function n1(e,n,i,c,p,g){let y=ns(p)?p.prefixItems.length:0;return kn(g,y,(x,b)=>{let S=`${i}/items`,T=`${c}/${b}`;return Eo(e,n,S,T,p.items,x)&&n.AddIndex(b)})}function Qk(e,n,i,c){return gc(i)?QF(e,n,i,c):t1(e,n,i,c)}function Xk(e,n,i,c){return gc(i)?XF(e,n,i,c):r1(e,n,i,c)}function Yk(e,n,i,c,p,g){return gc(p)?YF(e,n,i,c,p,g):n1(e,n,i,c,p,g)}function Zk(e){return As(e)}function eA(e,n,i,c){if(!Zk(i))return De(!0);let[p]=[Vt()],g=am(c,[p,"_"],Nt(e,n,i.contains,p));return Hi(g,De(i.maxContains))}function Vf(e,n,i,c){if(!Zk(i))return!0;let p=md(c,(g)=>At(e,n,i.contains,g));return ds(p,i.maxContains)}function tA(e,n,i,c,p,g){let y=js(p)?p.minContains:1;return Vf(e,n,p,g)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:y,maxContains:p.maxContains}})}function rA(e,n,i,c){return Hi(c,De(i.maximum))}function Jf(e,n,i,c){return ds(c,i.maximum)}function nA(e,n,i,c,p,g){return Jf(e,n,p,g)||n.AddError({keyword:"maximum",schemaPath:i,instancePath:c,params:{comparison:"<=",limit:p.maximum}})}function oA(e,n,i,c){return Hi(Et(c,"length"),De(i.maxItems))}function Qf(e,n,i,c){return ds(c.length,i.maxItems)}function sA(e,n,i,c,p,g){return Qf(e,n,p,g)||n.AddError({keyword:"maxItems",schemaPath:i,instancePath:c,params:{limit:p.maxItems}})}function iA(e,n,i,c){return Mv(c,De(i.maxLength))}function Xf(e,n,i,c){return hy(c,i.maxLength)}function aA(e,n,i,c,p,g){return Xf(e,n,p,g)||n.AddError({keyword:"maxLength",schemaPath:i,instancePath:c,params:{limit:p.maxLength}})}function uA(e,n,i,c){return Hi(Et(Wi(c),"length"),De(i.maxProperties))}function Yf(e,n,i,c){return ds(Se(c).length,i.maxProperties)}function cA(e,n,i,c,p,g){return Yf(e,n,p,g)||n.AddError({keyword:"maxProperties",schemaPath:i,instancePath:c,params:{limit:p.maxProperties}})}function mA(e){return As(e)}function o1(e,n,i,c){let[p,g]=[Vt(),Vt()],y=am(c,[p,g],En(Nt(e,n,i.contains,p),n.AddIndex(g)));return Ru(y,De(i.minContains))}function s1(e,n,i,c){let[p]=[Vt()],g=am(c,[p,"_"],Nt(e,n,i.contains,p));return Ru(g,De(i.minContains))}function pA(e,n,i,c){if(!mA(i))return De(!0);return n.UseUnevaluated()?o1(e,n,i,c):s1(e,n,i,c)}function Zf(e,n,i,c){if(!mA(i))return!0;let p=md(c,(g,y)=>At(e,n,i.contains,g)&&n.AddIndex(y));return Sa(p,i.minContains)}function lA(e,n,i,c,p,g){return Zf(e,n,p,g)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:p.minContains}})}function dA(e,n,i,c){return Ru(c,De(i.minimum))}function eh(e,n,i,c){return Sa(c,i.minimum)}function fA(e,n,i,c,p,g){return eh(e,n,p,g)||n.AddError({keyword:"minimum",schemaPath:i,instancePath:c,params:{comparison:">=",limit:p.minimum}})}function hA(e,n,i,c){return Ru(Et(c,"length"),De(i.minItems))}function th(e,n,i,c){return Sa(c.length,i.minItems)}function gA(e,n,i,c,p,g){return th(e,n,p,g)||n.AddError({keyword:"minItems",schemaPath:i,instancePath:c,params:{limit:p.minItems}})}function yA(e,n,i,c){return $v(c,De(i.minLength))}function rh(e,n,i,c){return gy(c,i.minLength)}function xA(e,n,i,c,p,g){return rh(e,n,p,g)||n.AddError({keyword:"minLength",schemaPath:i,instancePath:c,params:{limit:p.minLength}})}function IA(e,n,i,c){return Ru(Et(Wi(c),"length"),De(i.minProperties))}function nh(e,n,i,c){return Sa(Se(c).length,i.minProperties)}function bA(e,n,i,c,p,g){return nh(e,n,p,g)||n.AddError({keyword:"minProperties",schemaPath:i,instancePath:c,params:{limit:p.minProperties}})}function EA(e,n,i,c){return Nv(c,De(i.multipleOf))}function oh(e,n,i,c){return dy(c,i.multipleOf)}function SA(e,n,i,c,p,g){return oh(e,n,p,g)||n.AddError({keyword:"multipleOf",schemaPath:i,instancePath:c,params:{multipleOf:p.multipleOf}})}function i1(e,n,i,c){return Mi(e,n,[i.not],c,Un(io(Et("results","length"),De(1))))}function a1(e,n,i,c){return Un(Nt(e,n,i.not,c))}function wA(e,n,i,c){return n.UseUnevaluated()?i1(e,n,i,c):a1(e,n,i,c)}function sh(e,n,i,c){let p=new _n;return!At(e,p,i.not,c)&&n.Merge([p])}function TA(e,n,i,c,p,g){return sh(e,n,p,g)||n.AddError({keyword:"not",schemaPath:i,instancePath:c,params:{}})}function u1(e,n,i,c){return Mi(e,n,i.oneOf,c,io(Et("results","length"),De(1)))}function c1(e,n,i,c){let[p]=[Vt()],g=_v(i.oneOf.map((x)=>Nt(e,n,x,c))),y=am(g,[p,"_"],io(p,De(!0)));return io(y,De(1))}function RA(e,n,i,c){return n.UseUnevaluated()?u1(e,n,i,c):c1(e,n,i,c)}function kA(e,n,i,c){let p=i.oneOf.reduce((g,y)=>{let x=new _n;return At(e,x,y,c)?[...g,x]:g},[]);return _(p.length,1)&&n.Merge(p)}function AA(e,n,i,c,p,g){let y=[],x=[],b=p.oneOf.reduce((T,A,C)=>{let P=new Dn,L=`${i}/oneOf/${C}`,q=mr(e,P,L,c,A,g);if(q)x.push(C);if(!q)y.push(P);return q?[...T,P]:T},[]),S=_(b.length,1)&&n.Merge(b);if(!S&&_(x.length,0))y.forEach((T)=>T.GetErrors().forEach((A)=>n.AddError(A)));return S||n.AddError({keyword:"oneOf",schemaPath:i,instancePath:c,params:{passingSchemas:x}})}function CA(e,n,i,c){let p=vo(yt(i.pattern)?ss(i.pattern):i.pattern);return Ir(Et(p,"test"),[c])}function ih(e,n,i,c){return(yt(i.pattern)?ss(i.pattern):i.pattern).test(c)}function PA(e,n,i,c,p,g){return ih(e,n,p,g)||n.AddError({keyword:"pattern",schemaPath:i,instancePath:c,params:{pattern:p.pattern}})}function $A(e,n,i,c){return An(pn(i.patternProperties).map(([p,g])=>{let[y,x]=[Vt(),Vt()],b=vo(ss(p)),S=Un(Ir(Et(b,"test"),[y])),T=Zn(e,n,g,x),A=n.AddKey(y),C=n.UseUnevaluated()?xr(S,En(T,A)):xr(S,T);return fs(Ry(c),De(0),[`[${y}, ${x}]`,"_"],C)}))}function MA(e,n,i,c){return sn(pn(i.patternProperties),0,([p,g])=>{let y=ss(p);return sn(pn(c),0,([x,b])=>!y.test(x)||bo(e,n,g,b)&&n.AddKey(x))})}function vA(e,n,i,c,p,g){return kn(pn(p.patternProperties),0,([y,x])=>{let b=`${i}/patternProperties/${y}`,S=ss(y);return kn(pn(g),0,([T,A])=>{let C=`${c}/${T}`;return!S.test(T)||Eo(e,n,b,C,x,A)&&n.AddKey(T)})})}function OA(e,n,i,c){return An(i.prefixItems.map((p,g)=>{let y=Hi(Et(c,"length"),De(g)),x=Zn(e,n,p,`${c}[${g}]`),b=n.AddIndex(De(g)),S=n.UseUnevaluated()?En(x,b):x;return xr(y,S)}))}function _A(e,n,i,c){return _(c.length,0)||sn(i.prefixItems,0,(p,g)=>ds(c.length,g)||bo(e,n,p,c[g])&&n.AddIndex(g))}function LA(e,n,i,c,p,g){return _(g.length,0)||kn(p.prefixItems,0,(y,x)=>{let b=`${i}/prefixItems/${x}`,S=`${c}/${x}`;return ds(g.length,x)||Eo(e,n,b,S,y,g[x])&&n.AddIndex(x)})}function Qp(e,n){return e.includes(n)||Qo().exactOptionalPropertyTypes}function NA(e,n){return dd(Et(e,n))}function ah(e,n){return Bt(e[n])}function DA(e,n,i,c){let p=os(i)?i.required:[],g=pn(i.properties).map(([y,x])=>{let b=Un(zi(c,De(y))),S=Zn(e,n,x,Et(c,y)),T=n.AddKey(De(y)),A=n.UseUnevaluated()?En(S,T):S,C=p.includes(y)?A:xr(b,A);return Qp(p,y)?C:xr(NA(c,y),C)});return An(g)}function qA(e,n,i,c){let p=os(i)?i.required:[];return sn(pn(i.properties),0,([y,x])=>{let b=!le(c,y)||bo(e,n,x,c[y])&&n.AddKey(y);return Qp(p,y)?b:ah(c,y)||b})}function FA(e,n,i,c,p,g){let y=os(p)?p.required:[];return kn(pn(p.properties),0,([b,S])=>{let T=`${i}/properties/${b}`,A=`${c}/${b}`,C=()=>!le(g,b)||Eo(e,n,T,A,S,g[b])&&n.AddKey(b);return Qp(y,b)?C():ah(g,b)||C()})}function jA(e,n,i,c){let[p,g]=[Vt(),Vt()];return fs(Wi(c),De(0),[p,g],Nt(e,n,i.propertyNames,p))}function UA(e,n,i,c){return sn(Se(c),0,(p,g)=>At(e,n,i.propertyNames,p))}function BA(e,n,i,c,p,g){let y=[];return kn(Se(g),0,(b,S)=>{let T=`${c}/${b}`,A=`${i}/propertyNames`,C=mr(e,n,A,T,p.propertyNames,b);if(!C)y.push(b);return C})||n.AddError({keyword:"propertyNames",schemaPath:i,instancePath:c,params:{propertyNames:y}})}function GA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Gs(e,n,p,c)}function KA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Ye(p)&&At(e,n,p,c)}function HA(e,n,i,c,p,g){let y=e.RecursiveRef(p)??!1;return Ye(y)&&mr(e,n,"#",c,y,g)}function m1(e,n,i,c){let p=Qs(["context","value"],Gs(e,n,i,"value")),g=Qs(["context","value"],um([_s("nextContext",hd("CheckContext",[])),_s("result",Ir(p,["nextContext","value"])),Ay("result",n.Merge("[nextContext]")),cm("result")]));return Ir(g,["context",c])}function p1(e,n,i,c){return Gs(e,n,i,c)}function WA(e,n,i,c){let p=e.Ref(i)??!1;return n.UseUnevaluated()?m1(e,n,p,c):p1(e,n,p,c)}function zA(e,n,i,c){let p=e.Ref(i)??!1,g=new _n,y=Ye(p)&&At(e,g,p,c);if(y)n.Merge([g]);return y}function VA(e,n,i,c,p,g){let y=e.Ref(p)??!1,x=new Dn,b=Ye(y)&&mr(e,x,"#",c,y,g);if(b)n.Merge([x]);if(!b)x.GetErrors().forEach((S)=>n.AddError(S));return b}function JA(e,n,i,c){return An(i.required.map((p)=>zi(c,De(p))))}function QA(e,n,i,c){return sn(i.required,0,(p)=>le(c,p))}function XA(e,n,i,c,p,g){let y=[];return kn(p.required,0,(b)=>{let S=le(g,b);if(!S)y.push(b);return S})||n.AddError({keyword:"required",schemaPath:i,instancePath:c,params:{requiredProperties:y}})}function YA(e,n,i,c){return _(i,"object")?Ey(c):_(i,"array")?im(c):_(i,"boolean")?Tv(c):_(i,"integer")?Rv(c):_(i,"number")?by(c):_(i,"null")?kv(c):_(i,"string")?wy(c):_(i,"bigint")?Iy(c):_(i,"constructor")?Pv(c):_(i,"function")?Cv(c):_(i,"symbol")?Av(c):_(i,"undefined")?dd(c):_(i,"void")?dd(c):De(!0)}function uh(e,n,i,c,p){return _(i,"object")?Jo(p):_(i,"array")?Be(p):_(i,"boolean")?mn(p):_(i,"integer")?sm(p):_(i,"number")?_t(p):_(i,"null")?lo(p):_(i,"string")?yt(p):_(i,"bigint")?Nr(p):_(i,"constructor")?ud(p):_(i,"function")?ls(p):_(i,"symbol")?cd(p):_(i,"undefined")?Bt(p):_(i,"void")?Bt(p):!0}function l1(e,n,i,c){return gd(i.map((p)=>YA(e,n,p,c)))}function ZA(e,n,i,c,p){return wa(i,(g)=>uh(e,n,g,c,p))}function e0(e,n,i,c){return Be(i.type)?l1(e,n,i.type,c):YA(e,n,i.type,c)}function t0(e,n,i,c){return Be(i.type)?ZA(e,n,i.type,i,c):uh(e,n,i.type,i,c)}function r0(e,n,i,c,p,g){return(Be(p.type)?ZA(e,n,p.type,p,g):uh(e,n,p.type,p,g))||n.AddError({keyword:"type",schemaPath:i,instancePath:c,params:{type:p.type}})}function n0(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Ir(Et("context","GetIndices"),[]),x=Ir(Et("indices","has"),[p]),b=Nt(e,n,i.unevaluatedItems,g),S=Ir(Et("context","AddIndex"),[p]),T=fs(c,De(0),[g,p],En(xr(x,b),S));return Ir(Qs(["context"],um([_s("indices",y),cm(T)])),["context"])}function o0(e,n,i,c){let p=n.GetIndices();return sn(c,0,(g,y)=>(p.has(y)||At(e,n,i.unevaluatedItems,g))&&n.AddIndex(y))}function s0(e,n,i,c,p,g){let y=n.GetIndices(),x=[];return kn(g,0,(S,T)=>{let A=new Dn,C=(y.has(T)||mr(e,A,i,c,p.unevaluatedItems,S))&&n.AddIndex(T);if(!C)x.push(T);return C})||n.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:c,params:{unevaluatedItems:x}})}function i0(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Ir(Et("context","GetKeys"),[]),x=Ir(Et("keys","has"),[p]),b=Ir(Et("context","AddKey"),[p]),S=Nt(e,n,i.unevaluatedProperties,g),T=fs(Ry(c),De(0),[`[${p}, ${g}]`,"_"],xr(x,En(S,b)));return Ir(Qs(["context"],um([_s("keys",y),cm(T)])),["context"])}function a0(e,n,i,c){let p=n.GetKeys();return sn(pn(c),0,([g,y])=>p.has(g)||At(e,n,i.unevaluatedProperties,y)&&n.AddKey(g))}function u0(e,n,i,c,p,g){let y=n.GetKeys(),x=[];return kn(pn(g),0,([S,T])=>{let A=new Dn,C=y.has(S)||mr(e,A,i,c,p.unevaluatedProperties,T)&&n.AddKey(S);if(!C)x.push(S);return C})||n.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:c,params:{unevaluatedProperties:x}})}function ch(e){return!_(e.uniqueItems,!1)}function c0(e,n,i,c){if(!ch(i))return De(!0);let p=Et(hd("Set",[Ir(Et(c,"map"),[Et("Hashing","Hash")])]),"size"),g=Et(c,"length");return io(p,g)}function m0(e,n,i,c){if(!ch(i))return!0;let p=new Set(c.map(Id)).size,g=c.length;return _(p,g)}function p0(e,n,i,c,p,g){if(!ch(p))return!0;let y=new Set,x=g.reduce((S,T,A)=>{let C=Id(T);if(y.has(C))return[...S,A];return y.add(C),S},[]);return _(x.length,0)||n.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:c,params:{duplicateItems:x}})}function vc(e,n){return Cc(e)&&(Be(e.type)&&Gi(e.type.length,0)&&sn(e.type,0,(i)=>_(i,n))||_(e.type,n))}function d1(e){return vc(e,"object")}function f1(e){return hn(e)&&(Po(e)||mc(e)||pc(e)||za(e)||Bs(e)||Us(e)||Ja(e)||pa(e)||bc(e)||os(e)||$i(e))}function h1(e){return vc(e,"array")}function g1(e){return hn(e)&&(Wa(e)||Fs(e)||As(e)||xc(e)||Va(e)||js(e)||li(e)||ns(e)||Ci(e)||Ii(e))}function y1(e){return vc(e,"string")}function x1(e){return hn(e)&&(ma(e)||Ic(e)||ca(e)||la(e))}function I1(e){return vc(e,"number")||vc(e,"bigint")}function b1(e){return hn(e)&&(rs(e)||yc(e)||fc(e)||ts(e)||Ec(e))}function Zn(e,n,i,c){return n.UseUnevaluated()?En(En(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(Ds(i))return HR(e,n,i,c);if(Cc(i))p.push(e0(e,n,i,c));if(f1(i)){let y=[];if(os(i))y.push(JA(e,n,i,c));if(Po(i))y.push(NR(e,n,i,c));if(mc(i))y.push(YR(e,n,i,c));if(pc(i))y.push(tk(e,n,i,c));if(za(i))y.push(ok(e,n,i,c));if(Us(i))y.push($A(e,n,i,c));if(Bs(i))y.push(DA(e,n,i,c));if(Ja(i))y.push(jA(e,n,i,c));if(pa(i))y.push(IA(e,n,i,c));if(bc(i))y.push(uA(e,n,i,c));let x=An(y),b=xr(Un(Ey(c)),x);p.push(d1(i)?x:b)}if(g1(i)){let y=[];if(Wa(i))y.push(OR(e,n,i,c));if(As(i))y.push(QR(e,n,i,c));if(Fs(i))y.push(Qk(e,n,i,c));if(xc(i))y.push(eA(e,n,i,c));if(Va(i))y.push(oA(e,n,i,c));if(js(i))y.push(pA(e,n,i,c));if(li(i))y.push(hA(e,n,i,c));if(ns(i))y.push(OA(e,n,i,c));if(Ii(i))y.push(c0(e,n,i,c));let x=An(y),b=xr(Un(im(c)),x);p.push(h1(i)?x:b)}if(x1(i)){let y=[];if(Ic(i))y.push(iA(e,n,i,c));if(ma(i))y.push(yA(e,n,i,c));if(ca(i))y.push(Hk(e,n,i,c));if(la(i))y.push(CA(e,n,i,c));let x=An(y),b=xr(Un(wy(c)),x);p.push(y1(i)?x:b)}if(b1(i)){let y=[];if(fc(i))y.push(lk(e,n,i,c));if(ts(i))y.push(fk(e,n,i,c));if(yc(i))y.push(rA(e,n,i,c));if(rs(i))y.push(dA(e,n,i,c));if(Ec(i))y.push(EA(e,n,i,c));let x=An(y),b=xr(Un(xr(by(c),Iy(c))),x);p.push(I1(i)?x:b)}if(kc(i))p.push(WA(e,n,i,c));if(Rc(i))p.push(GA(e,n,i,c));if(lc(i))p.push(ak(e,n,i,c));if(bp(i))p.push(zR(e,n,i,c));if(Ep(i))p.push(mk(e,n,i,c));if(hc(i))p.push(zk(e,n,i,c));if(Sc(i))p.push(wA(e,n,i,c));if(ac(i))p.push(FR(e,n,i,c));if(cc(i))p.push(BR(e,n,i,c));if(wc(i))p.push(RA(e,n,i,c));if(Ci(i))p.push(xr(Un(im(c)),n0(e,n,i,c)));if($i(i))p.push(xr(Un(Sy(c)),i0(e,n,i,c)));if(ic(i))p.push($R(e,n,i,c));let g=An(p);return e.Pop(i),g}function bo(e,n,i,c){return n.Push()&&At(e,n,i,c)&&n.Pop()}function At(e,n,i,c){e.Push(i);let p=Ds(i)?Lf(e,n,i,c):(!Cc(i)||t0(e,n,i,c))&&(!(ut(c)&&!Be(c))||(!os(i)||QA(e,n,i,c))&&(!Po(i)||DR(e,n,i,c))&&(!mc(i)||ZR(e,n,i,c))&&(!pc(i)||rk(e,n,i,c))&&(!za(i)||sk(e,n,i,c))&&(!Us(i)||MA(e,n,i,c))&&(!Bs(i)||qA(e,n,i,c))&&(!Ja(i)||UA(e,n,i,c))&&(!pa(i)||nh(e,n,i,c))&&(!bc(i)||Yf(e,n,i,c)))&&(!Be(c)||(!Wa(i)||_R(e,n,i,c))&&(!As(i)||Df(e,n,i,c))&&(!Fs(i)||Xk(e,n,i,c))&&(!xc(i)||Vf(e,n,i,c))&&(!Va(i)||Qf(e,n,i,c))&&(!js(i)||Zf(e,n,i,c))&&(!li(i)||th(e,n,i,c))&&(!ns(i)||_A(e,n,i,c))&&(!Ii(i)||m0(e,n,i,c)))&&(!yt(c)||(!Ic(i)||Xf(e,n,i,c))&&(!ma(i)||rh(e,n,i,c))&&(!ca(i)||zf(e,n,i,c))&&(!la(i)||ih(e,n,i,c)))&&(!(_t(c)||Nr(c))||(!fc(i)||jf(e,n,i,c))&&(!ts(i)||Uf(e,n,i,c))&&(!yc(i)||Jf(e,n,i,c))&&(!rs(i)||eh(e,n,i,c))&&(!Ec(i)||oh(e,n,i,c)))&&(!kc(i)||zA(e,n,i,c))&&(!Rc(i)||KA(e,n,i,c))&&(!lc(i)||uk(e,n,i,c))&&(!bp(i)||Nf(e,n,i,c))&&(!Ep(i)||Ff(e,n,i,c))&&(!hc(i)||Vk(e,n,i,c))&&(!Sc(i)||sh(e,n,i,c))&&(!ac(i)||jR(e,n,i,c))&&(!cc(i)||GR(e,n,i,c))&&(!wc(i)||kA(e,n,i,c))&&(!Ci(i)||(!Be(c)||o0(e,n,i,c)))&&(!$i(i)||(!ut(c)||a0(e,n,i,c)))&&(!ic(i)||MR(e,n,i,c));return e.Pop(i),p}function Eo(e,n,i,c,p,g){return n.Push()&&mr(e,n,i,c,p,g)&&n.Pop()}function mr(e,n,i,c,p,g){if(n.AtCapacity())return!1;e.Push(p);let y=Ds(p)?WR(e,n,i,c,p,g):!!(+(!Cc(p)||r0(e,n,i,c,p,g))&+(!(ut(g)&&!Be(g))||!!(+(!os(p)||XA(e,n,i,c,p,g))&+(!Po(p)||qR(e,n,i,c,p,g))&+(!mc(p)||ek(e,n,i,c,p,g))&+(!pc(p)||nk(e,n,i,c,p,g))&+(!za(p)||ik(e,n,i,c,p,g))&+(!Us(p)||vA(e,n,i,c,p,g))&+(!Bs(p)||FA(e,n,i,c,p,g))&+(!Ja(p)||BA(e,n,i,c,p,g))&+(!pa(p)||bA(e,n,i,c,p,g))&+(!bc(p)||cA(e,n,i,c,p,g))))&+(!Be(g)||!!(+(!Wa(p)||LR(e,n,i,c,p,g))&+(!As(p)||XR(e,n,i,c,p,g))&+(!Fs(p)||Yk(e,n,i,c,p,g))&+(!xc(p)||tA(e,n,i,c,p,g))&+(!Va(p)||sA(e,n,i,c,p,g))&+(!js(p)||lA(e,n,i,c,p,g))&+(!li(p)||gA(e,n,i,c,p,g))&+(!ns(p)||LA(e,n,i,c,p,g))&+(!Ii(p)||p0(e,n,i,c,p,g))))&+(!yt(g)||!!(+(!Ic(p)||aA(e,n,i,c,p,g))&+(!ma(p)||xA(e,n,i,c,p,g))&+(!ca(p)||Wk(e,n,i,c,p,g))&+(!la(p)||PA(e,n,i,c,p,g))))&+(!(_t(g)||Nr(g))||!!(+(!fc(p)||dk(e,n,i,c,p,g))&+(!ts(p)||hk(e,n,i,c,p,g))&+(!yc(p)||nA(e,n,i,c,p,g))&+(!rs(p)||fA(e,n,i,c,p,g))&+(!Ec(p)||SA(e,n,i,c,p,g))))&+(!kc(p)||VA(e,n,i,c,p,g))&+(!Rc(p)||HA(e,n,i,c,p,g))&+(!lc(p)||ck(e,n,i,c,p,g))&+(!bp(p)||VR(e,n,i,c,p,g))&+(!Ep(p)||pk(e,n,i,c,p,g))&+(!hc(p)||Jk(e,n,i,c,p,g))&+(!Sc(p)||TA(e,n,i,c,p,g))&+(!ac(p)||UR(e,n,i,c,p,g))&+(!cc(p)||KR(e,n,i,c,p,g))&+(!wc(p)||AA(e,n,i,c,p,g))&+(!Ci(p)||(!Be(g)||s0(e,n,i,c,p,g)))&+(!$i(p)||(!ut(g)||u0(e,n,i,c,p,g))))&&(!ic(p)||vR(e,n,i,c,p,g));return e.Pop(p),y}var l0=[0],Xp=new Map,Oc=new Map;function E1(){return`${l0[0]++}`}function S1(e,n){if(!Xp.has(e))Xp.set(e,new Map);let i=Xp.get(e);if(i.has(n))return i.get(n);let c=E1();return i.set(n,c),c}function w1(e,n,i,c){return e.UseUnevaluated()?Ir(`check_${i}`,["context",c]):Ir(`check_${i}`,[c])}function T1(e,n,i,c){let p=Nt(e,n,i,"value");return n.UseUnevaluated()?_s(`check_${c}`,Qs(["context","value"],p)):_s(`check_${c}`,Qs(["value"],p))}function d0(){l0[0]=0,Xp.clear(),Oc.clear()}function f0(){return[...Oc.values()]}function Gs(e,n,i,c){let p=S1(i,e.LexicalBaseURL()),g=w1(n,i,p,c);if(Oc.has(p))return g;return Oc.set(p,""),Oc.set(p,T1(e,n,i,p)),g}function R1(e,n){return ut(n)&&!Tu(e)?n[e]:void 0}function k1(e,n){return e.reduce((i,c)=>R1(c,i),n)}function A1(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 C1(e,n){let i=A1(n);return k1(i,e)}var Zp="https://json-schema.org";function g0(e,n){if(ut(e)&&qs(e)&&_(e.$dynamicAnchor,n))return e;if(ut(e))for(let i of Se(e)){let c=g0(e[i],n);if(c)return c}return}function mh(e,n,i){if(_(e,i))return n.href;let c=hn(e)&&xo(e)?new URL(e.$id,n.href):n;if(Be(e))for(let p of e){let g=mh(p,c,i);if(!Bt(g))return g}else if(ut(e))for(let p of Se(e)){let g=mh(e[p],c,i);if(!Bt(g))return g}return}function P1(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("#")?y0(e,i):e;return}function $1(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 M1(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 y0(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 C1(e,i)}function v1(e,n,i){if(xo(e)){let c=P1(e,n,i);if(!Bt(c))return c}if(uc(e)){let c=$1(e,n,i);if(!Bt(c))return c}if(qs(e)){let c=M1(e,n,i);if(!Bt(c))return c}return y0(e,i)}function O1(e,n,i){return e.reduce((c,p)=>{let g=el(p,n,i);return!Bt(g)?g:c},void 0)}function _1(e){return _(e,"const")||_(e,"enum")}function L1(e,n,i){return Se(e).reduce((c,p)=>{if(_1(p))return c;let g=el(e[p],n,i);return!Bt(g)?g:c},void 0)}function el(e,n,i){let c=hn(e)&&xo(e)?new URL(e.$id,n.href):n;if(hn(e)){let p=v1(e,c,i);if(!Bt(p))return p}if(Be(e))return O1(e,c,i);if(ut(e))return L1(e,c,i);return}function N1(e,n,i){return mh(e,new URL(n||".",Zp),i)}function D1(e,n,i,c){let p=tl(e,n,i,c,!1);return hn(p)&&xo(p)?p:void 0}function h0(e){return e.href.split("#")[0]}function q1(e,n){return le(e,n)?e[n]:void 0}function F1(e,n,i){return el(e,n,i)}function j1(e,n,i){let c=h0(i);if(_(c,h0(n)))return;if(!le(e,c))return;let p=e[c],g=hn(p)&&xo(p)?new URL(p.$id,c):new URL(c);return _(i.hash,"")?p:el(p,g,i)}function U1(e,n,i,c,p){if(!c.$ref.startsWith("#"))return;if(le(e,"$schema"))return;let g=N1(n,i,p);if(Bt(g)||_(g,i))return;return{target:p,base:g,root:n}}function B1(e,n,i){let c=e[n];if(!hn(c))return;return{target:i,base:n,root:c}}function G1(e,n,i,c,p){let g=p?B1(e.context,c,i):void 0;if(!Bt(g))return g;return U1(e.root,e.lexicalSchema,e.referenceBase,n,i)}function K1(e,n,i,c,p,g){if(xo(p))return;let y=D1(e,n,i,c);if(!y||g.includes(y))return;return{target:p,resource:y}}function tl(e,n,i,c,p=!0){let g=new URL(i||".",Zp),y=p&&xo(n)?new URL(n.$id,g):g,x=new URL(c,y.href);return q1(e,c)??F1(n,y,x)??j1(e,y,x)}function H1(e,n,i,c,p,g){let y=new URL(i||".",Zp),x=p.$dynamicRef.startsWith("#")?c:n,b=tl(e,x,i,p.$dynamicRef,!1);if(Bt(b)){let A=new URL(p.$dynamicRef,y).hash;if(!A.startsWith("#/")&&A.startsWith("#")){let C=decodeURIComponent(A.slice(1));return g.find((L)=>_(L.$dynamicAnchor,C))??g0(n,C)}return}if(!hn(b)||!qs(b))return b;if(new URL(p.$dynamicRef,y).hash.startsWith("#/"))return b;return g.find((A)=>_(A.$dynamicAnchor,b.$dynamicAnchor))??b}function W1(e,n){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,c=n.$ref.startsWith("#")?e.lexicalSchema:i,p=tl(e.context,c,e.referenceBase,n.$ref,!1);if(!p||!hn(p))return{schema:p};let g=new URL(n.$ref,e.referenceBase).href.split("#")[0],y=!_(g,e.resourceBase),x=G1(e,n,p,g,y),b=y?K1(e.context,e.root,e.referenceBase,g,p,e.ids):void 0;return{schema:p,retrievedResource:x,resolvedResource:b}}function z1(e,n){let i=Tc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return tl(e.context,i,e.lexicalBase,n.$recursiveRef,!1)}function V1(e,n){return H1(e.context,e.root,e.lexicalBase,e.lexicalSchema,n,e.dynamicAnchors)}var _r=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)},Sr,nl,w0,fh,rl,x0,I0,b0,E0,lh,dh,hh,gh,S0,T0;class Oi{constructor(e,n){Sr.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 _r(this,Sr,"m",fh).call(this,this.ids)}Push(e){if(!hn(e))return;if(xo(e))_r(this,Sr,"m",hh).call(this,e);if(uc(e))this.anchors.push(e);if(Tc(e))this.recursiveAnchors.push(e);if(qs(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(!hn(e))return;if(xo(e))_r(this,Sr,"m",gh).call(this,e);if(uc(e))this.anchors.pop();if(Tc(e))this.recursiveAnchors.pop();if(qs(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();_r(this,Sr,"m",T0).call(this,e)}Ref(e){let n=W1(_r(this,Sr,"m",nl).call(this),e);return _r(this,Sr,"m",w0).call(this,n),n.schema}RecursiveRef(e){let n=z1(_r(this,Sr,"m",nl).call(this),e);if(n)this.pendingResource=!0;return n}DynamicRef(e){let n=V1(_r(this,Sr,"m",nl).call(this),e);if(n)this.pendingResource=!0;return n}}Sr=new WeakSet,nl=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:_r(this,Sr,"m",I0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:_r(this,Sr,"m",x0).call(this),resourceBase:_r(this,Sr,"m",rl).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},w0=function(n){if(!Bt(n.schema))this.pendingResource=!0;if(!Bt(n.resolvedResource))_r(this,Sr,"m",S0).call(this,n.resolvedResource.target,n.resolvedResource.resource);if(!Bt(n.retrievedResource))this.retrievedResources.set(n.retrievedResource.target,{base:n.retrievedResource.base,root:n.retrievedResource.root})},fh=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((g,y)=>new URL(y.$id,g),c).href},rl=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(!n)return _r(this,Sr,"m",fh).call(this,this.resourceIds);return this.resourceIds.slice(n.resourceDepth).reduce((i,c)=>new URL(c.$id,i),new URL(n.base)).href},x0=function(){if(this.retrievedFrames.length>0)return _r(this,Sr,"m",rl).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 _r(this,Sr,"m",rl).call(this)},I0=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},b0=function(n){n.forEach((i)=>_r(this,Sr,"m",lh).call(this,i,!1))},E0=function(n){n.forEach((i)=>_r(this,Sr,"m",dh).call(this,i,!1))},lh=function e(n,i=!0){if(Ds(n))return;if(Be(n))return _r(this,Sr,"m",b0).call(this,n);if(!hn(n))return;let c=n;if(!i&&xo(c))return;if(!i&&qs(c))this.dynamicAnchors.push(c);for(let p of Se(c))_r(this,Sr,"m",e).call(this,c[p],!1)},dh=function e(n,i=!0){if(Ds(n))return;if(Be(n))return _r(this,Sr,"m",E0).call(this,n);if(!hn(n))return;let c=n;if(!i&&xo(c))return;if(!i&&qs(c))this.dynamicAnchors.pop();for(let p of Se(c))_r(this,Sr,"m",e).call(this,c[p],!1)},hh=function(n){this.ids.push(n);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(n);_r(this,Sr,"m",lh).call(this,n,!0)},gh=function(n){if(this.ids.pop(),this.resourceIds.length>0&&_(this.resourceIds[this.resourceIds.length-1],n))this.resourceIds.pop();_r(this,Sr,"m",dh).call(this,n,!0)},S0=function(n,i){_r(this,Sr,"m",hh).call(this,i),this.resolvedResources.set(n,i)},T0=function(n){if(!this.resolvedResources.has(n))return;let i=this.resolvedResources.get(n);_r(this,Sr,"m",gh).call(this,i),this.resolvedResources.delete(n)};function J1(e){let n=e.Functions().join(`;
31
- `),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${n}; return (value) => { ${i.join("; ")} }`}function Q1(e,n){return Hy("CheckContext","Guard","Format","Hashing",e.External().identifier,n)(_n,z,eu,Xi,e.External().variables)}function X1(e){let n=new Oi(e.Context(),e.Schema()),i=new _n;return(c)=>At(n,i,e.Schema(),c)}function Y1(e,n){return Ky()?Q1(e,n):X1(e)}class R0{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 k0{constructor(e,n,i,c,p,g){this.context=e,this.schema=n,this.external=i,this.functions=c,this.entry=p,this.useUnevaluated=g}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=J1(this),n=Y1(this,e);return new R0(Ky(),e,n)}}function ol(...e){let[n,i]=Sn(e,{2:(b,S)=>[b,S],1:(b)=>[{},b]});CR(),d0();let c=new Oi(n,i),p=new vf(AR(n,i)),g=Gs(c,p,i,"value"),y=f0(),x=PR();return new k0(n,i,x,y,g,p.UseUnevaluated())}function sl(...e){let[n,i,c]=Sn(e,{3:(T,A,C)=>[T,A,C],2:(T,A)=>[{},T,A]}),p=new Oi(n,i),g=new Dn,y=mr(p,g,"#","",i,c),x=g.GetErrors(),b=ex(),S=x.map((T)=>({...T,message:b(T)}));return[y,S]}function xh(...e){let[n,i,c]=Sn(e,{3:(y,x,b)=>[y,x,b],2:(y,x)=>[{},y,x]}),p=new Oi(n,i),g=new _n;return At(p,g,i,c)}function Xt(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return xh(n,i,c)}function Cs(...e){let[n,i,c]=Sn(e,{3:(y,x,b)=>[y,x,b],2:(y,x)=>[{},y,x]}),[p,g]=sl(n,i,c);return g}class da 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 A0(e,n,i){if(!Be(i))return i;return i.map((c)=>gn(e,n.items,c))}function C0(e,n,i){return gn({...e,...n.$defs},an(n.$ref),i)}function tj(e,n){let i=le(n,"unevaluatedProperties")?{additionalProperties:n.unevaluatedProperties}:{},c=Ao(e,n),p=Tn(c);return Qe(p)?hp(p,i):p}function P0(e,n,i){let c=tj(e,n);return gn(e,c,i)}function il(e){return le(e,"additionalProperties")?e.additionalProperties:void 0}function $0(e,n,i){if(!ut(i)||Be(i))return i;let c=il(n);for(let p of Se(i)){if(le(n.properties,p)){i[p]=gn(e,n.properties[p],i[p]);continue}if(mn(c)&&_(c,!0)||Pr(c)&&Xt(e,c,i[p])){i[p]=gn(e,c,i[p]);continue}delete i[p]}return i}function M0(e,n,i){if(!ut(i))return i;let c=il(n),[p,g]=[new RegExp(fn(n)),fr(n)];for(let y of Se(i)){if(p.test(y)){i[y]=gn(e,g,i[y]);continue}if(mn(c)&&_(c,!0)||Pr(c)&&Xt(e,c,i[y])){i[y]=gn(e,c,i[y]);continue}delete i[y]}return i}function v0(e,n,i){return le(e,n.$ref)?gn(e,e[n.$ref],i):i}function O0(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]=gn(e,n.items[p],i[p]);return Gi(i.length,c)?i.slice(0,c):i}function zr(e){return Ra(e)}function _0(e,n,i){for(let c of n.anyOf){let p=gn(e,c,zr(i));if(Xt(e,c,p))return p}return i}function gn(e,n,i){return wt(n)?A0(e,n,i):Qt(n)?C0(e,n,i):ze(n)?P0(e,n,i):Qe(n)?$0(e,n,i):Gt(n)?M0(e,n,i):jt(n)?v0(e,n,i):mt(n)?O0(e,n,i):xe(n)?_0(e,n,i):i}function rj(e,n){for(let i of Se(e)){if(le(n,i))continue;n[i]=e[i]}return n}function nj(e){let n={};for(let i of Se(e))n[i]=_c(e[i]);return n}function oj(e){return Ih(uR(e))}function Ih(e){return e.map((n)=>_c(n))}function _c(e){let n=wt(e)?B(_c(e.items),ka(e)):ze(e)?Cn(Ih(e.allOf)):xe(e)?m(oj(e.anyOf)):Qe(e)?s(nj(e.properties)):Gt(e)?Ss(oi(e),_c(fr(e))):mt(e)?Br(Ih(e.items)):e;return rj(e,n)}function tu(e){return _c(e)}function _o(...e){let[n,i,c]=Sn(e,{3:(g,y,x)=>[g,y,x],2:(g,y)=>[{},g,y]}),p=Qo().unionPrioritySort?tu(i):i;return gn(n,p,c)}function po(e){return ut(e)&&le(e,"value")}function Ge(e){return{value:e}}function wr(){return}function sj(e){return Be(e)?Ge(e):Ge([e])}function ij(e){return _(e,!0)?Ge(BigInt(1)):Ge(BigInt(0))}var aj=/^-?(0|[1-9]\d*)n$/,uj=/^-?(0|[1-9]\d*)\.\d+$/,cj=/^-?(0|[1-9]\d*)$/;function mj(e){return aj.test(e)}function pj(e){return uj.test(e)}function lj(e){return cj.test(e)}function dj(e){let n=e.toLowerCase();return mj(e)?Ge(BigInt(e.slice(0,e.length-1))):pj(e)?Ge(BigInt(e.split(".")[0])):lj(e)?Ge(BigInt(e)):_(n,"false")?Ge(BigInt(0)):_(n,"true")?Ge(BigInt(1)):wr()}function al(e){return Nr(e)?Ge(e):mn(e)?ij(e):_t(e)?Ge(BigInt(Math.trunc(e))):lo(e)?Ge(BigInt(0)):yt(e)?dj(e):Bt(e)?Ge(BigInt(0)):wr()}function fj(e){return _(e,BigInt(0))?Ge(!1):_(e,BigInt(1))?Ge(!0):wr()}function hj(e){return _(e,0)?Ge(!1):_(e,1)?Ge(!0):wr()}function gj(e){return _(e.toLowerCase(),"false")?Ge(!1):_(e.toLowerCase(),"true")?Ge(!0):_(e,"0")?Ge(!1):_(e,"1")?Ge(!0):wr()}function L0(e){return Nr(e)?fj(e):mn(e)?Ge(e):_t(e)?hj(e):lo(e)?Ge(!1):yt(e)?gj(e):Bt(e)?Ge(!1):wr()}function yj(e){return _(e,BigInt(0))?Ge(null):wr()}function xj(e){return _(e,!1)?Ge(null):wr()}function Ij(e){return _(e,0)?Ge(null):wr()}function bj(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(null):wr()}function Ej(e){return Nr(e)?yj(e):mn(e)?xj(e):_t(e)?Ij(e):lo(e)?Ge(null):yt(e)?bj(e):Bt(e)?Ge(null):wr()}var N0=BigInt(Number.MAX_SAFE_INTEGER),D0=BigInt(Number.MIN_SAFE_INTEGER);function Sj(e){return e<=N0&&e>=D0?Ge(Number(e)):wr()}function wj(e){return Ge(e?1:0)}function Tj(e){let n=+e;if(_t(n))return Ge(n);let i=e.toLowerCase();if(_(i,"false"))return Ge(0);if(_(i,"true"))return Ge(1);let c=al(e);if(po(c))return c.value<=N0&&c.value>=D0?Ge(Number(c.value)):wr();return wr()}function bh(e){return Nr(e)?Sj(e):mn(e)?wj(e):_t(e)?Ge(e):lo(e)?Ge(0):yt(e)?Tj(e):Bt(e)?Ge(0):wr()}function q0(e){return Nr(e)?Ge(e.toString()):mn(e)?Ge(e.toString()):_t(e)?Ge(e.toString()):lo(e)?Ge("null"):yt(e)?Ge(e):Bt(e)?Ge(""):wr()}function Rj(e){return _(e,BigInt(0))?Ge(void 0):wr()}function kj(e){return _(e,!1)?Ge(void 0):wr()}function Aj(e){return _(e,0)?Ge(void 0):wr()}function Cj(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(void 0):wr()}function F0(e){return Nr(e)?Rj(e):mn(e)?kj(e):_t(e)?Aj(e):lo(e)?Ge(void 0):yt(e)?Cj(e):Bt(e)?Ge(e):wr()}function j0(e,n,i){return sj(i).value.map((p)=>Xr(e,n.items,p))}function U0(e,n,i){let c=al(i);return po(c)?c.value:i}function B0(e,n,i){let c=L0(i);return po(c)?c.value:i}function G0(e,n,i){return Xr({...e,...n.$defs},an(n.$ref),i)}function K0(e,n,i){return Xr(e,Tn(n),i)}function H0(e,n,i){let c=bh(i);return po(c)?Math.trunc(c.value):i}function W0(e,n,i){let c=Ao(e,n),p=Tn(c);return Xr(e,p,i)}function Pj(e,n,i){let c=al(i);return po(c)&&_(n.const,c.value)?c.value:i}function $j(e,n,i){let c=L0(i);return po(c)&&_(n.const,c.value)?c.value:i}function Mj(e,n,i){let c=bh(i);return po(c)&&_(n.const,c.value)?c.value:i}function vj(e,n,i){let c=q0(i);return po(c)&&_(n.const,c.value)?c.value:i}function z0(e,n,i){if(_(n.const,i))return i;return mx(n)?Pj(e,n,i):px(n)?$j(e,n,i):Im(n)?Mj(e,n,i):bm(n)?vj(e,n,i):Ur()}function V0(e,n,i){let c=Ej(i);return po(c)?c.value:i}function J0(e,n,i){let c=bh(i);return po(c)?c.value:i}function ul(e,n,i,c){let p=Se(c);for(let[g,y]of n)for(let x of p)if(!g.test(x))c[x]=Xr(e,i,c[x]);return c}function Lc(e,n,i){return un(e)&&Bt(i[n])}function Oj(e,n,i){let c=pd(n.properties),p=Se(i);for(let[g,y]of c)for(let x of p){if(!g.test(x)||Lc(y,x,i))continue;i[x]=Xr(e,y,i[x])}return le(n,"additionalProperties")&&ut(n.additionalProperties)?ul(e,c,n.additionalProperties,i):i}function Q0(e,n,i){return Jo(i)?Oj(e,n,i):i}function _j(e,n,i){let c=pd(n.patternProperties),p=Se(i);for(let[g,y]of c)for(let x of p)if(g.test(x))i[x]=Xr(e,y,i[x]);return le(n,"additionalProperties")&&ut(n.additionalProperties)?ul(e,c,n.additionalProperties,i):i}function X0(e,n,i){return Jo(i)?_j(e,n,i):i}function Y0(e,n,i){return le(e,n.$ref)?Xr(e,e[n.$ref],i):i}function Z0(e,n,i){let c=q0(i);return po(c)?c.value:i}function eC(e,n,i){return Xr(e,Tn(n),i)}function tC(e,n,i){if(!Be(i))return i;for(let c=0;c<Math.min(n.items.length,i.length);c++)i[c]=Xr(e,n.items[c],i[c]);return i}function rC(e,n,i){let c=F0(i);return po(c)?c.value:i}function nC(e,n,i){if(n.anyOf.some((y)=>Xt(e,y,i)))return i;let g=n.anyOf.map((y)=>Xr(e,y,zr(i))).find((y)=>Xt(e,n,y));return Bt(g)?i:g}function oC(e,n,i){let c=F0(i);return po(c)?void 0:i}function Xr(e,n,i){return wt(n)?j0(e,n,i):uo(n)?U0(e,n,i):Wn(n)?B0(e,n,i):Qt(n)?G0(e,n,i):nn(n)?K0(e,n,i):dn(n)?H0(e,n,i):ze(n)?W0(e,n,i):xt(n)?z0(e,n,i):bs(n)?V0(e,n,i):kr(n)?J0(e,n,i):Qe(n)?Q0(e,n,i):Gt(n)?X0(e,n,i):jt(n)?Y0(e,n,i):on(n)?Z0(e,n,i):ur(n)?eC(e,n,i):mt(n)?tC(e,n,i):es(n)?rC(e,n,i):xe(n)?nC(e,n,i):co(n)?oC(e,n,i):i}function us(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Xr(n,i,c)}function sC(e,n,i){if(!Be(i))return i;for(let c=0;c<i.length;c++)i[c]=yn(e,n.items,i[c]);return i}function iC(e,n,i){return yn({...e,...n.$defs},an(n.$ref),i)}function aC(e,n){if(!Bt(n))return n;return ls(e.default)?e.default():zr(e.default)}function uC(e,n,i){let c=Ao(e,n),p=Tn(c);return yn(e,p,i)}function cC(e,n,i){if(!ut(i))return i;let c=Se(n.properties);for(let p of c){let g=yn(e,n.properties[p],i[p]);if(Bt(g)&&(un(n.properties[p])||!le(n.properties[p],"default")))continue;i[p]=g}if(!Po(n)||mn(n.additionalProperties))return i;for(let p of Se(i)){if(c.includes(p))continue;i[p]=yn(e,n.additionalProperties,i[p])}return i}function mC(e,n,i){if(!ut(i))return i;let[c,p]=[new RegExp(fn(n)),fr(n)];for(let g of Se(i)){if(!(c.test(g)&&yo(p)))continue;i[g]=yn(e,p,i[g])}if(!Po(n))return i;for(let g of Se(i)){if(c.test(g))continue;i[g]=yn(e,n.additionalProperties,i[g])}return i}function pC(e,n,i){return le(e,n.$ref)?yn(e,e[n.$ref],i):i}function lC(e,n,i){if(!Be(i))return i;let[c,p]=[n.items,Math.max(n.items.length,i.length)];for(let g=0;g<p;g++)if(g<c.length)i[g]=yn(e,c[g],i[g]);return i}function dC(e,n,i){for(let c of n.anyOf){let p=yn(e,c,zr(i));if(Xt(e,c,p))return p}return i}function yn(e,n,i){let c=yo(n)?aC(n,i):i;return wt(n)?sC(e,n,c):Qt(n)?iC(e,n,c):ze(n)?uC(e,n,c):Qe(n)?cC(e,n,c):Gt(n)?mC(e,n,c):jt(n)?pC(e,n,c):mt(n)?lC(e,n,c):xe(n)?dC(e,n,c):c}function Ks(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return yn(n,i,c)}function ru(e){return(...n)=>{let[i,c,p]=Sn(n,{3:(g,y,x)=>[g,y,x],2:(g,y)=>[{},g,y]});return e.reduce((g,y)=>y(i,c,g),p)}}function Lj(e,n,i){return n["~codec"].decode(i)}function Nj(e,n,i){return n["~codec"].encode(i)}function Tr(e,n,i,c){if(!Hn(i))return c;return _(e,"Decode")?Lj(n,i,c):Nj(n,i,c)}function Dj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<c.length;p++)c[p]=Cr(e,n,i.items,c[p]);return Tr(e,n,i,c)}function qj(e,n,i,c){let p=Tr(e,n,i,c);if(!Be(p))return p;for(let g=0;g<p.length;g++)p[g]=Cr(e,n,i.items,p[g]);return p}function fC(e,n,i,c){return _(e,"Decode")?Dj(e,n,i,c):qj(e,n,i,c)}function hC(e,n,i,c){return c=Cr(e,{...n,...i.$defs},an(i.$ref),c),Tr(e,n,i,c)}function gC(e){return e.reduce((n,i)=>({...n,...i}),{})}function yC(e,n){for(let i of n)if(!Ta(e,i))return i;return e}function Fj(e,n,i,c){if(_(i.allOf.length,0))return Tr(e,n,i,c);let p=i.allOf.map((x)=>Cr(e,n,x,_o(x,zr(c)))),y=p.every((x)=>ut(x))?gC(p):yC(c,p);return Tr(e,n,i,y)}function jj(e,n,i,c){if(_(i.allOf.length,0))return Tr(e,n,i,c);let p=Tr(e,n,i,c),g=i.allOf.map((x)=>Cr(e,n,x,_o(x,zr(p))));if(g.every((x)=>ut(x)))return gC(g);return yC(p,g)}function xC(e,n,i,c){return _(e,"Decode")?Fj(e,n,i,c):jj(e,n,i,c)}function Uj(e,n,i,c){if(!Jo(c))return c;for(let p of Se(i.properties)){if(!le(c,p)||Lc(i.properties[p],p,c))continue;c[p]=Cr(e,n,i.properties[p],c[p])}return Tr(e,n,i,c)}function Bj(e,n,i,c){let p=Tr(e,n,i,c);if(!Jo(p))return p;for(let g of Se(i.properties)){if(!le(p,g)||Lc(i.properties[g],g,p))continue;p[g]=Cr(e,n,i.properties[g],p[g])}return p}function IC(e,n,i,c){return _(e,"Decode")?Uj(e,n,i,c):Bj(e,n,i,c)}function Gj(e,n,i,c){if(!Jo(c))return c;let p=new RegExp(fn(i));for(let g of Se(c)){if(!p.test(g))continue;c[g]=Cr(e,n,fr(i),c[g])}return Tr(e,n,i,c)}function Kj(e,n,i,c){let p=Tr(e,n,i,c);if(!Jo(p))return p;let g=new RegExp(fn(i));for(let y of Se(p)){if(!g.test(y))continue;p[y]=Cr(e,n,fr(i),p[y])}return p}function bC(e,n,i,c){return _(e,"Decode")?Gj(e,n,i,c):Kj(e,n,i,c)}function EC(e,n,i,c){return le(n,i.$ref)?Cr(e,n,n[i.$ref],c):c}function SC(e,n,i,c){return _(e,"Decode")?Tr(e,n,i,EC(e,n,i,c)):EC(e,n,i,Tr(e,n,i,c))}function Hj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<Math.min(i.items.length,c.length);p++)c[p]=Cr(e,n,i.items[p],c[p]);return Tr(e,n,i,c)}function Wj(e,n,i,c){let p=Tr(e,n,i,c);if(!Be(p))return c;for(let g=0;g<Math.min(i.items.length,p.length);g++)p[g]=Cr(e,n,i.items[g],p[g]);return p}function wC(e,n,i,c){return _(e,"Decode")?Hj(e,n,i,c):Wj(e,n,i,c)}function zj(e,n,i,c){for(let p of i.anyOf){if(!Xt(n,p,c))continue;let g=Cr(e,n,p,c);return Tr(e,n,i,g)}return c}function Vj(e,n,i,c){let p=Tr(e,n,i,c);for(let g of i.anyOf){let y=Cr(e,n,g,zr(p));if(!Xt(n,g,y))continue;return y}return p}function TC(e,n,i,c){return _(e,"Decode")?zj(e,n,i,c):Vj(e,n,i,c)}function Cr(e,n,i,c){return wt(i)?fC(e,n,i,c):Qt(i)?hC(e,n,i,c):ze(i)?xC(e,n,i,c):Qe(i)?IC(e,n,i,c):Gt(i)?bC(e,n,i,c):jt(i)?SC(e,n,i,c):mt(i)?wC(e,n,i,c):xe(i)?TC(e,n,i,c):Tr(e,n,i,c)}class RC extends da{constructor(e,n){super("Decode",e,n)}}function Jj(e,n,i){if(!Xt(e,n,i))throw new RC(i,Cs(e,n,i));return i}function Qj(e,n,i){let c=Qo().unionPrioritySort?tu(n):n;return Cr("Decode",e,c,i)}var Xj=ru([(e,n,i)=>zr(i),(e,n,i)=>Ks(e,n,i),(e,n,i)=>us(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>Jj(e,n,i),(e,n,i)=>Qj(e,n,i)]);function Eh(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Xj(n,i,c)}class kC extends da{constructor(e,n){super("Encode",e,n)}}function Yj(e,n,i){if(!Xt(e,n,i))throw new kC(i,Cs(e,n,i));return i}function Zj(e,n,i){let c=Qo().unionPrioritySort?tu(n):n;return Cr("Encode",e,c,i)}var eU=ru([(e,n,i)=>zr(i),(e,n,i)=>Zj(e,n,i),(e,n,i)=>Ks(e,n,i),(e,n,i)=>us(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>Yj(e,n,i)]);function Sh(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return eU(n,i,c)}function tU(e,n){return Hn(n)||_i(e,n.items)}function rU(e,n){return Hn(n)||AC({...e,...n.$defs},an(n.$ref))}function nU(e,n){return Hn(n)||n.allOf.some((i)=>_i(e,i))}function oU(e,n){return Hn(n)||Se(n.properties).some((i)=>_i(e,n.properties[i]))}function sU(e,n){return Hn(n)||_i(e,fr(n))}function AC(e,n){if(wh.has(n.$ref))return!1;return wh.add(n.$ref),Hn(n)||le(e,n.$ref)&&_i(e,e[n.$ref])}function iU(e,n){return Hn(n)||n.items.some((i)=>_i(e,i))}function aU(e,n){return Hn(n)||n.anyOf.some((i)=>_i(e,i))}function _i(e,n){return wt(n)?tU(e,n):Qt(n)?rU(e,n):ze(n)?nU(e,n):Qe(n)?oU(e,n):Gt(n)?sU(e,n):jt(n)?AC(e,n):mt(n)?iU(e,n):xe(n)?aU(e,n):Hn(n)}var wh=new Set;function Th(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return wh.clear(),_i(n,i)}class cs extends Error{constructor(e,n){super(n);this.type=e}}function CC(e,n){return ls(n.default)?n.default(n):ut(n.default)?zr(n.default):n.default}function PC(e,n){if(Ii(n)&&!yo(n))throw new cs(n,"Arrays with uniqueItems constraints must specify a default annotation");let i=li(n)?n.minItems:0;return Array.from({length:i},()=>Yr(e,n.items))}function $C(e,n){return ts(n)?BigInt(n.exclusiveMinimum)+BigInt(1):rs(n)?BigInt(n.minimum):BigInt(0)}function MC(e,n){return!1}function vC(e,n){let i=Yr(e,n.instanceType);return class{constructor(){Object.assign(this,i)}}}function OC(e,n){return Yr({...e,...n.$defs},an(n.$ref))}function _C(e,n){return Yr(e,Tn(n))}function LC(e,n){let i=Yr(e,n.returnType);return()=>i}function NC(e,n){return ts(n)&&_t(n.exclusiveMinimum)?n.exclusiveMinimum+1:rs(n)?n.minimum:0}function DC(e,n){let i=Ao(e,n),c=Tn(i);return Yr(e,c)}function qC(e,n){return n.const}function FC(e,n){throw new cs(n,"Cannot create TNever types")}function jC(e,n){return null}function UC(e,n){return ts(n)&&_t(n.exclusiveMinimum)?n.exclusiveMinimum+1:rs(n)?n.minimum:0}function BC(e,n){return(Bt(n.required)?[]:n.required).reduce((c,p)=>({...c,[p]:Yr(e,n.properties[p])}),{})}function GC(e,n){if(pa(n)&&!yo(n))throw new cs(n,"Record with the minProperties constraint must have a default annotation");return{}}function KC(e,n){return le(e,n.$ref)?Yr(e,e[n.$ref]):(()=>{throw new cs(n,"Unable to deref Ref")})()}function HC(e,n){if((la(n)||ca(n))&&!yo(n))throw Error("Strings with format or pattern constraints must specify default");let c=ma(n)?n.minLength:0;return"".padEnd(c)}function WC(e,n){return Symbol()}function zC(e,n){let i=Ou(n.pattern);if(on(i))throw new cs(n,"Unable to create TemplateLiteral due to infinite type expansion");return Yr(e,i)}function VC(e,n){return Array.from({length:n.minItems},(i,c)=>Yr(e,n.items[c]))}function JC(e,n){return}function QC(e,n){if(_(n.anyOf.length,0))throw Error("Unable to create Union with no variants");return Yr(e,n.anyOf[0])}function XC(e,n){return}function Yr(e,n){return yo(n)?CC(e,n):wt(n)?PC(e,n):uo(n)?$C(e,n):Wn(n)?MC(e,n):Zr(n)?vC(e,n):Qt(n)?OC(e,n):nn(n)?_C(e,n):en(n)?LC(e,n):dn(n)?NC(e,n):ze(n)?DC(e,n):xt(n)?qC(e,n):ao(n)?FC(e,n):bs(n)?jC(e,n):kr(n)?UC(e,n):Qe(n)?BC(e,n):Gt(n)?GC(e,n):jt(n)?KC(e,n):on(n)?HC(e,n):Es(n)?WC(e,n):ur(n)?zC(e,n):mt(n)?VC(e,n):es(n)?JC(e,n):xe(n)?QC(e,n):co(n)?XC(e,n):void 0}function Ps(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return Yr(n,i)}class cl extends da{constructor(e,n){super("Parse",e,n)}}function uU(e,n,i){if(!Xt(e,n,i))throw new cl(i,Cs(e,n,i));return i}var YC=ru([(e,n,i)=>zr(i),(e,n,i)=>Ks(e,n,i),(e,n,i)=>us(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>uU(e,n,i)]);var mU=s({type:a("insert"),path:l(),value:Rr()}),pU=Object({type:a("update"),path:l(),value:Rr()}),lU=s({type:a("delete"),path:l()}),AOe=m([mU,pU,lU]);class ml{constructor(e,n){this.hasCodec=Th(e,n),this.buildResult=ol(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(Qo().correctiveParse)return YC(this.Context(),this.Type(),e);throw new cl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Cs(this.Context(),this.Type(),e)}Clean(e){return _o(this.Context(),this.Type(),e)}Convert(e){return us(this.Context(),this.Type(),e)}Create(){return Ps(this.Context(),this.Type())}Default(e){return Ks(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Eh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Sh(this.Context(),this.Type(),e):this.Parse(e)}}function kh(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return new ml(n,i)}var eP=new WeakMap,hU=Symbol.for("TypeBox.Kind");function gU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((n)=>typeof n==="string");return[]}function yU(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 Ah(e){try{return rP(e)}catch{return}}function xU(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 IU(e,n){let i=n.properties,c=new Set(i?Object.keys(i):[]);if(i)for(let[p,g]of Object.entries(i)){if(!(p in e))continue;e[p]=ha(e[p],g)}if(n.additionalProperties&&typeof n.additionalProperties==="object")for(let[p,g]of Object.entries(e)){if(c.has(p))continue;e[p]=ha(g,n.additionalProperties)}}function bU(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]=ha(e[i],c)}return}if(n.items&&typeof n.items==="object")for(let i=0;i<e.length;i++)e[i]=ha(e[i],n.items)}function tP(e,n){for(let i of n)if(Ah(i)?.Check(e))return e;for(let i of n){let c=structuredClone(e),p=ha(c,i);if(Ah(i)?.Check(p))return p}return e}function ha(e,n){let i=e;if(Array.isArray(n.allOf))for(let g of n.allOf)i=ha(i,g);if(Array.isArray(n.anyOf))i=tP(i,n.anyOf);if(Array.isArray(n.oneOf))i=tP(i,n.oneOf);let c=gU(n),p=c.length>1&&c.some((g)=>yU(i,g));if(c.length>0&&!p)for(let g of c){let y=xU(i,g);if(y!==i){i=y;break}}if(c.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))IU(i,n);if(c.includes("array")&&Array.isArray(i))bU(i,n);return i}function pl(e,n){if(Array.isArray(e)){if(Array.isArray(n.items))for(let p=0;p<e.length;p++){let g=n.items[p];if(g)pl(e[p],g)}else if(n.items)for(let p of e)pl(p,n.items);return}if(typeof e!=="object"||e===null||!n.properties)return;let i=e,c=new Set(n.required??[]);for(let[p,g]of Object.entries(n.properties)){if(!(p in i))continue;if(i[p]===null&&!c.has(p)&&typeof g.$ref!=="string"&&Ah(g)?.Check(null)===!1)delete i[p];else pl(i[p],g)}}function rP(e){let n=e,i=eP.get(n);if(i)return i;let c=kh(e);return eP.set(n,c),c}function EU(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 SU(e,n){let i=e.find((c)=>c.name===n.name);if(!i)throw Error(`Tool "${n.name}" not found`);return nu(i,n)}function nu(e,n){let i=structuredClone(n.arguments);pl(i,e.parameters),us(e.parameters,i);let c=rP(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(hU)){let y=ha(i,e.parameters);if(y!==i)if(typeof i==="object"&&i!==null&&typeof y==="object"&&y!==null){for(let x of Object.keys(i))delete i[x];Object.assign(i,y)}else return c.Check(y)?y:i}if(c.Check(i))return i;let p=c.Errors(i).map((y)=>` - ${EU(y)}: ${y.message}`).join(`
32
- `)||"Unknown validation error",g=`Validation failed for tool "${n.name}":
33
- ${p}
34
-
35
- Received arguments:
36
- ${JSON.stringify(n.arguments,null,2)}`;throw Error(g)}var nP;function Nc(){if(!nP)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return nP}async function oP(e,n,i,c,p,g){let y=aP(n,e),x=[...y],b={...n,messages:[...n.messages,...y]};await c({type:"agent_start"}),await c({type:"turn_start"});for(let S of y)await c({type:"message_start",message:S}),await c({type:"message_end",message:S});return await iP(b,x,i,p,c,g??Nc()),x}async function sP(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 g=[],y={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await iP(y,g,n,c,i,p??Nc()),g}async function iP(e,n,i,c,p,g){let y=e,x=i,b,S=!1,T=await x.getSteeringMessages?.()||[];while(!0){let A=!0;while(A||T.length>0){let P=[];if(b){let J=await x.prepareNextTurn?.(b);if(J)y=J.context??y,P=J.messages??[],x={...x,model:J.model??x.model,reasoning:J.thinkingLevel===void 0?x.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(T.length===0)T=await x.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let J of aP(y,[...P,...T]))await p({type:"message_start",message:J}),await p({type:"message_end",message:J}),y.messages.push(J),n.push(J);T=[];let L=await x.prepareRequest?.({context:y,model:x.model,thinkingLevel:x.reasoning??"off"},c);if(L)y=L.context??y,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(y,x,c,p,g);if(n.push(q),q.stopReason==="error"||q.stopReason==="aborted"){b={message:q,toolResults:[],context:y,newMessages:n},await x.finishTurn?.(b,c),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:n});return}let X=q.content.filter((J)=>J.type==="toolCall"),j=[];if(A=!1,X.length>0){let J=q.stopReason==="length"?await RU(X,p):await kU(y,q,x,c,p);j.push(...J.messages),A=!J.terminate;for(let ee of j)y.messages.push(ee),n.push(ee)}b={message:q,toolResults:j,context:y,newMessages:n};let V=await x.finishTurn?.(b,c);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:n});return}if(S=V?.action==="continue",T=await x.getSteeringMessages?.()||[],A||T.length>0)S=!1}let C=await x.getFollowUpMessages?.()||[];if(C.length>0){S=!1,T=C;continue}if(S){S=!1;continue}break}await p({type:"agent_end",messages:n})}function aP(e,n){let i=-1;for(let T=n.length-1;T>=0;T--)if(n[T].role==="system"){i=T;break}let c=n[i],p=c?n.map((T,A)=>A===i?Ch(c,wU):T):n,g=$o(ne([...e.messages,...p]),(e.tools??[]).map(ot)),y=g.toolsAdded.length===0&&g.toolsRemoved.length===0;if(c){if(y&&!c.toolsAdded?.length&&!c.toolsRemoved?.length)return n;return p.map((T,A)=>A===i?Ch(c,g):T)}if(y)return n;let x=Ch({role:"system",content:"",timestamp:Date.now()},g),b=n.findIndex((T)=>T.role!=="system"),S=b===-1?n.length:b;return[...n.slice(0,S),x,...n.slice(S)]}var wU={toolsAdded:[],toolsRemoved:[]};function Ch(e,{toolsAdded:n,toolsRemoved:i}){let{toolsAdded:c,toolsRemoved:p,...g}=e;return{...g,...n.length>0?{toolsAdded:n}:{},...i.length>0?{toolsRemoved:i}:{}}}async function TU(e,n,i,c,p){let g=e.messages;if(n.transformContext)g=await n.transformContext(g,i);let y=await n.convertToLlm(g),x=ft({messages:y}),b=(n.getApiKey?await n.getApiKey(n.model.provider):void 0)||n.apiKey,S=await p(n.model,x,{...n,apiKey:b,signal:i}),T=async()=>Object.assign(await S.result(),{thinkingLevel:n.reasoning??"off"}),A=null,C=!1;for await(let L of S)switch(L.type){case"start":A=L.partial,e.messages.push(A),C=!0,await c({type:"message_start",message:{...A}});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(A)A=L.partial,e.messages[e.messages.length-1]=A,await c({type:"message_update",assistantMessageEvent:L,message:{...A}});break;case"done":case"error":{let q=await T();if(C)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!C)await c({type:"message_start",message:{...q}});return await c({type:"message_end",message:q}),q}}let P=await T();if(C)e.messages[e.messages.length-1]=P;else e.messages.push(P),await c({type:"message_start",message:{...P}});return await c({type:"message_end",message:P}),P}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:Ws(`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 Dc(p,n);let g=Ph(p);await $h(g,n),i.push(g)}return{messages:i,terminate:!1}}async function kU(e,n,i,c,p){let g=n.content.filter((x)=>x.type==="toolCall"),y=g.some((x)=>e.tools?.find((b)=>b.name===x.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||y)return AU(e,n,g,i,c,p);return CU(e,n,g,i,c,p)}async function AU(e,n,i,c,p,g){let y=[],x=[];for(let b of i){await g({type:"tool_execution_start",toolCallId:b.id,toolName:b.name,args:b.arguments});let S=await cP(e,n,b,c,p),T;if(S.kind==="immediate")T={toolCall:b,result:S.result,isError:S.isError};else{let C=await pP(S,p,mP(b,g));T=await lP(e,n,S,C,c,p)}await Dc(T,g);let A=Ph(T);if(await $h(A,g),y.push(T),x.push(A),p?.aborted)break}return{messages:x,terminate:uP(y)}}async function CU(e,n,i,c,p,g){let y=[];for(let S of i){await g({type:"tool_execution_start",toolCallId:S.id,toolName:S.name,args:S.arguments});let T=await cP(e,n,S,c,p);if(T.kind==="immediate"){let A={toolCall:S,result:T.result,isError:T.isError};if(await Dc(A,g),y.push(A),p?.aborted)break;continue}if(y.push(async()=>{if(p?.aborted){let P={toolCall:S,result:Ws("Operation aborted"),isError:!0};return await Dc(P,g),P}let A=await pP(T,p,mP(S,g)),C=await lP(e,n,T,A,c,p);return await Dc(C,g),C}),p?.aborted)break}let x=await Promise.all(y.map((S)=>typeof S==="function"?S():Promise.resolve(S))),b=[];for(let S of x){let T=Ph(S);await $h(T,g),b.push(T)}return{messages:b,terminate:uP(x)}}function uP(e){return e.length>0&&e.every((n)=>n.result.terminate===!0)}function PU(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 cP(e,n,i,c,p,g=e.tools??[]){let y=g.find((x)=>x.name===i.name);if(!y)return{kind:"immediate",result:Ws(`Tool ${i.name} not found`),isError:!0};try{let x=PU(y,i),b=nu(y,x);if(c.beforeToolCall){let S=await c.beforeToolCall({assistantMessage:n,toolCall:i,args:b,context:e},p);if(p?.aborted)return{kind:"immediate",result:Ws("Operation aborted"),isError:!0};if(S?.block){let T=Ws(S.reason||"Tool execution was blocked");if(S.terminate===!0)T.terminate=!0;return{kind:"immediate",result:T,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Ws("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:y,args:b}}catch(x){return{kind:"immediate",result:Ws(x instanceof Error?x.message:String(x)),isError:!0}}}function mP(e,n){return(i)=>n({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function pP(e,n,i){let c=[],p=!0,g=performance.now(),y=()=>Math.round(performance.now()-g);try{let x=await e.tool.execute(e.toolCall.id,e.args,n,(S)=>{if(!p)return;c.push(Promise.resolve(i(S)))}),b=y();return p=!1,await Promise.all(c),{result:x,isError:x.isError===!0,durationMs:b}}catch(x){let b=y();return p=!1,await Promise.all(c),{result:Ws(x instanceof Error?x.message:String(x)),isError:!0,durationMs:b}}finally{p=!1}}async function lP(e,n,i,c,p,g){let{result:y,isError:x}=c;if(p.afterToolCall)try{let b=await p.afterToolCall({assistantMessage:n,toolCall:i.toolCall,args:i.args,result:y,isError:x,context:e},g);if(b){let S=b.structuredContent??(b.content?void 0:y.structuredContent);if(y={...y,content:b.content??y.content,details:b.details??y.details,usage:b.usage??y.usage,terminate:b.terminate??y.terminate},S===void 0)delete y.structuredContent;else y.structuredContent=S;x=b.isError??x}}catch(b){y=Ws(b instanceof Error?b.message:String(b)),x=!0}return{toolCall:i.toolCall,result:y,isError:x,durationMs:c.durationMs}}function Ws(e){return{content:[{type:"text",text:e}],details:{}}}async function Dc(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 Ph(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 $h(e,n){await n({type:"message_start",message:e}),await n({type:"message_end",message:e})}function $U(e){return e.filter((n)=>n.role==="system"||n.role==="user"||n.role==="assistant"||n.role==="toolResult")}var MU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},vU={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 OU(e){let n=e?.tools?.slice()??[],i=e?.messages?.slice()??[],c=jn(e?.systemPrompt,n.map(ot));if(i[0]?.role!=="system"&&c)i.unshift(c);return{get systemPrompt(){return Wo(i)},model:e?.model??vU,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 Mh{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class vh{_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=OU(n.initialState),this.convertToLlm=n.convertToLlm??$U,this.transformContext=n.transformContext,this.streamFunction=n.streamFn??Nc(),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 Mh(n.steeringMode??"one-at-a-time"),this.followUpQueue=new Mh(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=Kr(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 oP(e,this.createContextSnapshot(),this.createLoopConfig(n),(c)=>this.processEvents(c),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await sP(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:MU,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 ga(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function _U(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 dP(e,n){if(e.some((L)=>L.name===n))return n;let i=e.map((L)=>L.name),c=(L)=>i.filter((q)=>ga(q)===L),p=c(ga(n));if(p.length===1&&p[0])return p[0];if(p.length>1)return n;let g=n.split(/[.:/]/).pop()??n,y=g===n?[]:c(ga(g));if(y.length===1&&y[0])return y[0];let x=new Map;for(let L of e)for(let q of L.aliases??[]){let X=ga(q);x.set(X,(x.get(X)??new Set).add(L.name))}let b=(L)=>[...new Set([...c(L),...x.get(L)??[]])],S=b(ga(g));if(S.length===1&&S[0])return S[0];if(S.length>1)return n;let T=_U(g),A=new Set;T.forEach((L,q)=>{A.add(ga(L));let X=T[q+1];if(X)A.add(ga(L+X))});let C=new Set;for(let L of A)for(let q of b(L))C.add(q);let P=[...C];return P.length===1&&P[0]?P[0]:n}function v(e){return e}function bn(e,n){let i=n.indexOf("/");if(i<=0)return;return e.getModel(n.slice(0,i),n.slice(i+1))}function rt(e){return`${e.provider}/${e.id}`}function LU(e,n,i){let c=async(g,y)=>{try{if(n){let b=g instanceof Request?g:void 0;n({at:Date.now(),method:y?.method??b?.method??"GET",url:typeof g==="string"?g:g instanceof URL?g.toString():g.url,headers:fP(y?.headers??b?.headers),body:NU(y?.body!==void 0?y.body:b?.body??void 0)})}}catch{}let x=await e(g,y);if(i)try{let b=Date.now(),{status:S,statusText:T}=x,A=fP(x.headers);if(!x.body)return i({at:b,status:S,statusText:T,headers:A,body:""}),x;let C="",P=new TextDecoder,L=new TransformStream({transform(j,V){V.enqueue(j),C+=P.decode(j,{stream:!0}),i({at:b,status:S,statusText:T,headers:A,body:C})},flush(){C+=P.decode(),i({at:b,status:S,statusText:T,headers:A,body:C})}}),q=x.body.pipeThrough(L),X=new Response(q,x);try{Object.defineProperty(X,"url",{value:x.url})}catch{}return X}catch{}return x},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(c,{preconnect:p})}function fP(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 NU(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 DU(e,n){return dP(e,n)}function qU(e,n,i){let c=Date.now(),p=new WeakSet,g=(b)=>{if(!b||typeof b!=="object"||!("role"in b)||b.role!=="assistant")return;let S=Date.now(),T=Math.max(10,S-c);b.generationMs=T},y=async(b)=>{if(!i||!b||typeof b!=="object"||!("role"in b)||b.role!=="assistant")return;if(g(b),p.has(b))return;p.add(b),Object.assign(b,await i(b))},x=(b)=>{let S=b?.content;if(!Array.isArray(S))return;for(let T of S)if(T&&T.type==="toolCall"&&typeof T.name==="string")T.name=DU(n(),T.name)};return{async*[Symbol.asyncIterator](){for await(let b of e){let{partial:S,message:T}=b;x(S),await y(T),x(T),yield b}},result:async()=>{let b=await e.result();return g(b),await y(b),x(b),b}}}function qc(e,n){let i=(n??[]).filter((x)=>x.kind==="path").map((x)=>`<file path=${JSON.stringify(x.data)} />`),c=(n??[]).filter((x)=>x.kind==="text").map((x)=>`<file name=${JSON.stringify(x.name)}>
37
- ${x.data}
38
- </file>`),p=(n??[]).filter((x)=>x.kind==="image").map((x)=>({type:"image",data:x.data,mimeType:x.mimeType})),g=(n??[]).filter((x)=>x.kind==="image"&&x.id).map((x)=>`<image id=${JSON.stringify(x.id)} name=${JSON.stringify(x.name)} />`);return{merged:[...i,...c,...g,...e.trim()?[e]:[]].join(`
39
-
40
- `),images:p}}function Oh(e,n){let{merged:i,images:c}=qc(e,n);return{role:"user",content:c.length>0?[{type:"text",text:i},...c]:i,timestamp:Date.now()}}function hP(e){let n=new Set;for(let x of e.tools){let b=x.name.toLowerCase();if(n.has(b))throw Error(`Tool names collide ignoring case: ${x.name}`);n.add(b)}let i=new vh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(x,b,S)=>{let{captureRequest:T,captureResponse:A}=e,C=T||A?{...S,fetch:LU(S?.fetch??globalThis.fetch,T?(L)=>T({...L,model:rt(x)}):void 0,A?(L)=>A({...L,model:rt(x)}):void 0)}:S,P=x.api==="openai-completions"||x.api==="openai-responses"?{...x,compat:{...x.compat,supportsDeveloperRole:!1}}:x;return qU(e.models.streamSimple(P,b,C),()=>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:b})=>{let S=x.messages.findIndex((P)=>P.role!=="system"),T=x.messages.slice(0,S===-1?x.messages.length:S),A=e.hooks.prepare,C=e.hooks.tools?.()??x.tools;if(C){i.state.tools=C;let P=T[0];if(P?.role==="system")T[0]={...P,toolsAdded:C.map(ot),toolsRemoved:void 0}}return{context:{...x,tools:C,messages:await A(T,C,b)}}}:void 0}),c=new Map,p=new Map,g=new WeakSet,y;return i.subscribe((x)=>{if(x.type==="message_update"&&x.message.role==="assistant"){p.clear(),e.hooks.draft(yP(x.message));return}if(x.type==="tool_execution_update"){let S=c.get(x.toolCallId)??Ee(x.toolName,x.args),T=Array.isArray(x.partialResult?.content)?x.partialResult.content.map((A)=>A.type==="text"&&typeof A.text==="string"?A.text:"").join(""):"";p.set(x.toolCallId,{type:"tool_call",id:x.toolCallId,name:S.name,input:S.input,...S.source?{source:S.source}:{},output:T}),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(g.has(x.message)){e.steerConsumed?.(x.message);return}let b=x.message.role==="user"&&y?{type:"user",text:y.text,...y.attachments?.length?{attachments:y.attachments}:{}}:FU(x.message);if(x.message.role==="user")y=void 0;if(b?.type==="assistant"){for(let S of b.parts)if(S.type==="tool_call")c.set(S.id,S)}if(b?.type==="tool_result"){let S=c.get(b.callID);if(S?.source)Object.assign(b,{name:S.name,source:S.source})}if(b)e.hooks.message(b,x.message);if(x.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(x,b)=>{y={text:x,attachments:b};let{merged:S,images:T}=qc(x,b);return i.prompt(S,T.length>0?T: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)=>{g.add(x),i.steer(x)},unsteer:(x)=>{let S=i.steeringQueue?.messages;if(!S)return!1;let T=S.indexOf(x);if(T<0){let C=JSON.stringify(x);T=S.findIndex((P)=>JSON.stringify(P)===C)}if(T<0)return!1;let[A]=S.splice(T,1);if(A)g.delete(A);return!0},abort:()=>i.abort()}}function _h(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 gP(e){let{name:i,source:c}=Ee(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 yP(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,...Ee(n.name,n.arguments)}})}function FU(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:yP(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 k(e){return e}import{createHash as xP}from"crypto";import{existsSync as jU}from"fs";import{readFile as IP,realpath as ll}from"fs/promises";import{dirname as UU,isAbsolute as bP,relative as EP,resolve as SP,sep as wP}from"path";var TP=[...qg];class dl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((n)=>n.message).join("; ")}`);this.errors=e}}class fl{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=UU(SP(e)),c=SP(i,n??"web.tsx");if(!n&&!jU(c))return;let p=EP(await ll(i),await ll(c));if(bP(p)||p===".."||p.startsWith(`..${wP}`))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 S=!0;for(let[T,A]of i.inputs){let C=await IP(T).catch(()=>{return});if(!C||xP("sha256").update(C).digest("hex")!==A){S=!1;break}}if(S)return i.source;this.cache.delete(e)}let c=await ll(n),p=new Map,g=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:TP,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(S){S.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(T)=>{if(!TP.includes(T.path))throw Error(`Unsupported shared web import: ${T.path}`);return{path:T.path,external:!0}}),S.onLoad({filter:/.*/},async(T)=>{let A=EP(c,await ll(T.path));if(bP(A)||A===".."||A.startsWith(`..${wP}`))throw Error("Plugin web imports must stay inside its plugin directory");let C=await IP(T.path);p.set(T.path,xP("sha256").update(C).digest("hex"));return})}}]}).catch((S)=>{let A=(S instanceof AggregateError?S.errors:[S]).map((C)=>C instanceof Error?C.message:String(C));throw Error(`Plugin web build failed: ${A.join("; ")}`,{cause:S})});if(!g.success)throw new dl(g.logs.filter((S)=>S.level==="error").map((S)=>({file:S.position?.file??null,line:S.position?.line??null,message:S.message})));let y=g.outputs.find((S)=>S.kind==="entry-point"&&S.path.endsWith(".js")),x=g.outputs.find((S)=>S.path.endsWith(".css"));if(!y||g.outputs.some((S)=>S!==y&&S!==x))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let b=await y.text();return this.cache.set(e,{source:b,css:await x?.text(),inputs:p}),b}}function jo(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function $s(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 hl(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
41
-
42
- `)}function ou(e){return e.content.map((n)=>n.type==="text"?n.text:"[image]").join("")}function su(e){return e.role==="assistant"&&e.content.length>0}function ms(e){let n=[],i=new Map,c=0;for(let p of e){let g=p.raw;if(g.role==="assistant"){if(su(g))c++;for(let y of g.content){if(y.type!=="toolCall")continue;let x={call:y,step:c,message:g};n.push(x),i.set(y.id,x)}}else if(g.role==="toolResult"){let y=i.get(g.toolCallId);if(y)y.result=g}}return n}var gl=new Set(["edit","write"]),RP=new Set(["grep","glob"]);function so(e,n){let i=Ee(e.name,e.arguments).input?.[n];return typeof i==="string"?i:void 0}function kP(e){return[...new Set(ms(e).flatMap((n)=>gl.has(Ee(n.call.name,n.call.arguments).name)&&n.result&&!n.result.isError&&so(n.call,"path")?[so(n.call,"path")]:[]))]}function Lh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function yl(e){let n=[{source:"ASSISTANT_TOOL",text:`${Ee(e.call.name,e.call.arguments).name}(${jo(Ee(e.call.name,e.call.arguments).input)}) [${Lh(e)}, call=${e.call.id}]`}];if(e.result)n.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:ou(e.result)});return n}function O(e){let n=0,i=0,c=0;for(let p of e){let g=p.codePointAt(0);if(g<=127)n++;else if(g>=19968&&g<=40959||g>=12288&&g<=12351||g>=65280&&g<=65519||g>=131072&&g<=173791)i++;else c++}return Math.max(0,Math.ceil(n/4+i+c/2))}var Nh=8192;function F(e){let n=e,i=0,c="";if(n.role==="system")c=typeof n.content==="string"?n.content:JSON.stringify(n.content);else if(n.role==="user")if(typeof n.content==="string")c=n.content;else for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else if(n.role==="assistant")for(let p of n.content)if(p.type==="text")c+=p.text;else if(p.type==="thinking")c+=p.thinking;else c+=`${p.name}${jo(p.arguments)}`;else if(n.role==="toolResult")for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else c=jo(e);return O(c)+16+i*Nh}function Li(e=[]){return e.reduce((n,i)=>n+O(i.name+i.description+jo(i.parameters))+16,0)}function Fn(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 So(e,n,i=Number.POSITIVE_INFINITY){if(O(e)<=n&&e.length<=i)return e;let c=`
43
- [... omitted; use history tools for the full text ...]
44
- `,p=Math.floor((n-O(c))/2);if(p<=0)return"";let g=(y)=>{let x=0,b=Math.max(0,Math.min(e.length,p*4,Math.floor((i-c.length)/2)));while(x<b){let S=Math.ceil((x+b)/2),T=y?e.slice(-S):e.slice(0,S);if(O(T)<=p)x=S;else b=S-1}if(!x)return"";return y?e.slice(-x).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,x).replace(/[\uD800-\uDBFF]$/,"")};return`${g(!1)}${c}${g(!0)}`}function xl(e,n){if(O(e.join(`
45
- `))<=n)return e;let i=(T)=>`- [... ${T} steps omitted; use history tools for the full text ...]`,c=n-O(i(e.length)),p=[],g=[],y=0,x=0,b=e.length-1;while(x<=b){let T=p.length<=g.length,A=T?e[x]:e[b],C=O(`${A}
46
- `);if(y+C>c)break;if(y+=C,T)p.push(e[x++]);else g.unshift(e[b--])}let S=b-x+1;return[...p,...S>0?[i(S)]:[],...g]}function Ms(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=BU(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=Dh(c.records);return n}function Dh(e){if(e.length<=1)return[...e];let n=[],i=[],c=new Set;for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;let y=g.raw?.role;if(y==="assistant"){let b=g.raw.content?.filter((S)=>S.type==="toolCall")??[];if(b.length>0)for(let S of b)c.add(S.id);if(n.push(g),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(y==="toolResult"){let x=g.raw;if(x.toolCallId)c.delete(x.toolCallId);if(n.push(g),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(y==="user"){if(n.length===0){n.push(g);continue}let x=e.slice(p+1).some((b)=>b.raw?.role==="assistant");if(c.size>0||x){i.push(g);continue}n.push(g);continue}n.push(g)}if(i.length>0)n.push(...i);return n}function BU(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"&&ua(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ua(i)?"interrupted":"failed";default:return"interrupted"}}function ya(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 Il(e,n){return e.end!==void 0&&e.end<=n&&e.records.every((i)=>i.entry.seq<=n)}function qh(e,n){return e.find((i)=>i.start<n&&!Il(i,n)&&i.records.some((c)=>c.entry.seq<=n))}function iu(e){let n=ya(e),c=Ms(e).findLast((p)=>p.end!==void 0);if(!c?.end||c.end<=n)return;return c.end}function bl(e){let n=ya(e);return qh(Ms(e),n)?.end}function Fc(e,n){let i=ya(e),c=Ms(e).at(-1);if(!c||c.end!==void 0)return;let p=c.records.filter((T)=>T.entry.seq>i),g=[],y=new Set;for(let T of p){let A=T.raw,C=F(T.raw);if(A.role==="assistant"){for(let P of A.content)if(P.type==="toolCall")y.add(P.id)}else if(A.role==="toolResult")y.delete(A.toolCallId);if(su(A)||!g.length||A.role==="user"&&g.at(-1)?.assistant)g.push({end:T.entry.seq,tokens:C,assistant:su(A),pending:y.size});else{let P=g.at(-1);P.end=T.entry.seq,P.tokens+=C,P.pending=y.size}}let x=g.findLastIndex((T)=>T.assistant),b=0,S;for(let T=g.length-1;T>=0;T--){let A=g[T];if(T<x&&A.assistant&&A.pending===0&&(b<=n||S===void 0))S=A.end;if(b+=A.tokens,b>n&&S!==void 0)break}if(b<=n)return;return S}var AP=2000;function Ni(e,n){let i=O(n);if(i<=AP)return n;let c=new TextEncoder().encode(n).length,p=n.split(`
47
- `).length,g=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${c} bytes, ${p} lines, approximately ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
48
- `),y="</user-text-reference>",x=AP-O(`${g}
49
-
50
- ${y}`);if(x<=0)return n;let b=`${g}
51
- ${So(n,x,n.length-g.length-y.length-3)}
52
- ${y}`;return b.length<n.length&&O(b)<i?b:n}function CP(e){let n=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return n;if(typeof n.content==="string"){let p=Ni(e.entry.seq,n.content);return p===n.content?n:{...n,content:p}}let i=!1,c=n.content.map((p)=>{if(p.type!=="text")return p;let g=Ni(e.entry.seq,p.text);if(g!==p.text)i=!0;return g===p.text?p:{...p,text:g}});return i?{...n,content:c}:n}function Fh(e,n=!1){let i=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),c=i.flatMap((P)=>{let L=P.raw.content;return typeof L==="string"?[]:L.filter((q)=>q.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,g=e.status==="open"?"interrupted":e.status,y="";if(i.length){let P=n?So(i.map((L)=>$s(L.raw)).join(`
53
-
54
- `),600):i.map((L,q)=>`<user-message sequence="${q+1}">
55
- ${Ni(L.entry.seq,$s(L.raw))}
56
- </user-message>`).join(`
57
-
58
- `);y=[`<chunk-input id="${e.id}" status="${g}"${n?' excerpt="true"':""}>`,P,...n?[p]:[],"</chunk-input>"].join(`
59
- `)}let b=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,S=b?hl(b):"",T=[];if(g!=="completed"){let P=ms(e.records),L=new Map(P.map((J)=>[J.call,J])),q=P.slice(-3),X=new Set(q.map((J)=>J.message)),j=[],V=[];for(let J of e.records){let ee=J.raw;if(ee.role!=="assistant")continue;let ie=X.has(ee);for(let H of ee.content)if(H.type==="text"&&ee!==b&&H.text.trim())if(ie)V.push(`ASSISTANT: ${Fn(H.text,50)}`);else j.push(`- ASSISTANT: ${Fn(H.text,50)}`);else if(H.type==="toolCall"){let ce=L.get(H);if(!ce)continue;if(ie){if(q.includes(ce))for(let fe of yl(ce))V.push(`${fe.source}: ${So(fe.text,fe.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${H.name}(${Fn(jo(H.arguments),40)}) [${Lh(ce)}]`)}}T.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...j.length?[`Earlier steps, oldest first:
60
- ${xl(j,n?300:800).join(`
61
- `)}`]:[],...V)}let A=kP(e.records),C=[`<chunk-summary id="${e.id}" status="${g}" folded-messages="${e.records.length}"${n?' excerpt="true"':""}>`,S?n?So(S,600):S:"No final assistant response was recorded.",...T,...A.length?[`Recorded file changes:
62
- ${So(A.join(`
63
- `),250)}`]:[],...n&&g==="completed"?[p]:[],"</chunk-summary>"].join(`
64
- `);return{input:y,images:c,summary:C,tokens:GU(y,C,c.length)}}function GU(e,n,i){return(e?O(e)+16:0)+O(n)+16+i*Nh}var KU=["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."],HU="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,zU=80,VU=240;function PP(e,n,i){let c=[],p=0,g=Math.min(n.target,n.hard);for(let x=e.length-1;x>=0;x--){let b=e[x],S=Fh(b),T=p+S.tokens>g?Fh(b,!0):void 0,A=T&&T.tokens<S.tokens?T:S;if(!(!i&&x===e.length-1&&b.status!=="completed")&&p+A.tokens>n.hard)break;p+=A.tokens,c.push({run:b,content:A})}c.reverse();let y=e.slice(0,e.length-c.length);return{visible:c,archived:y,tokens:p}}function $P(e){let{runs:n,visible:i,archived:c,partial:p}=e,g=c.flatMap((b)=>{let S=b.records.filter((A)=>A.raw.role==="user"&&!(A.entry.type==="user"&&A.entry.notices)).map((A)=>$s(A.raw));if(!S.length)return[];let T=b===n[0]?VU:zU;return[`- ${b.id} [${b.status}]: ${Fn(S.join(" / "),T)}`]}),y=new Map(n.map((b,S)=>[b,S+1])),x=[...i.map((b)=>y.get(b)??0),...p?[n.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...KU,...p?[HU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${c.length}`,`archived chunk IDs: ${c.length?c.map((b)=>b.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})`,...g.length?["archived requests, oldest first:",So(g.join(`
65
- `),WU)]:[],"</conversation-checkpoint>"].join(`
66
- `)}function MP(e,n){let i=e.split(`
67
- `),c=n.split(`
68
- `),p=new Set(i),g=new Set(c),y=[...i.filter((b)=>b.trim()&&!g.has(b)).map((b)=>`- ${Fn(b,40)}`),...c.filter((b)=>b.trim()&&!p.has(b)).map((b)=>`+ ${Fn(b,40)}`)],x=i.find((b)=>b.trim()&&g.has(b));return[...y.slice(0,6),...y.length>6?[`\u2026 ${y.length-6} more changed lines`]:[],...x&&y.every((b)=>b.startsWith("+"))?[`@ ${Fn(x,40)}`]:[]]}function El(e,n){if(!n)return e;let i=n.endsWith("/")?n:`${n}/`;return e.startsWith(i)?e.slice(i.length):e}function JU(e){let n=e.arguments?.paths;if(!Array.isArray(n))return[];return n.flatMap((i)=>{let c=i&&typeof i==="object"?i.path:void 0;return typeof c==="string"?[c]:[]})}function QU(e,n){let i=so(e,"path");if(gl.has(e.name)&&i)return`file:${El(i,n)}`;let c=so(e,"command");if(c)return`command:${c}`;return`${e.name}:${jo(e.arguments)}`}function XU(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 g of ms(e)){let y=c.get(g.step)??[];y.push(g),c.set(g.step,y)}let p=new Map;for(let g of e){let y=g.raw;if(!su(y))continue;let x=++i.steps,b=hl(y);if(b)i.narration.push({step:x,text:Fn(b,60)});for(let{call:S,result:T}of c.get(x)??[]){if(!T)continue;let A=Ee(S.name,S.arguments),C={...S,name:A.name,arguments:A.input},P=QU(C,n),L=ou(T);if(T.isError){let ee=so(C,"command"),ie=ee?`${C.name} \`${Fn(ee,40)}\``:`${C.name} ${P.startsWith("file:")?P.slice(5):Fn(jo(C.arguments),40)}`,H={step:x,key:P,what:ie,detail:So(L.trim().split(`
69
- `).slice(0,8).join(`
70
- `),200)};i.errors.push(H);let ce=p.get(P)??[];ce.push(H),p.set(P,ce);continue}for(let ee of p.get(P)??[])ee.resolved=x;p.delete(P);let q=so(C,"path");if(gl.has(C.name)&&q){let ee=El(q,n),ie=i.files.get(ee)??{count:0,first:x,last:x,diffs:[]};if(ie.count++,ie.last=x,ie.diffs.push({step:x,lines:C.name==="edit"?so(C,"old_string")!==void 0?MP(so(C,"old_string")??"",so(C,"new_string")??""):[]:MP("",so(C,"content")??"")}),ie.diffs.length>3)ie.diffs.shift();i.files.set(ee,ie);continue}let X=C.name==="read"?[...q?[q]:[],...JU(C)]:[];if(X.length){for(let ee of X){let ie=El(ee,n),H=i.reads.get(ie)??[];H.push(x),i.reads.set(ie,H)}continue}if(RP.has(C.name)){let ee=q?` in ${El(q,n)}`:"",ie=C.name==="grep"&&so(C,"glob")?` (${so(C,"glob")})`:"",H=`${C.name} ${so(C,"pattern")??""}${ee}${ie}`.replace(/\s+/g," "),ce=i.searches.get(H)??{steps:[],head:""};ce.steps.push(x),ce.head=Fn(L.trim().split(`
71
- `)[0]??"",25),i.searches.set(H,ce);continue}let j=so(C,"command");if(j){let ee=L.trim().split(`
72
- `);i.commands.push({step:x,command:Fn(j,40),exit:"0",lines:ee.length,tail:ee.slice(-3).map((ie)=>Fn(ie,40))});continue}let V=`${C.name} ${Fn(jo(C.arguments),40)}`,J=i.other.get(V)??[];J.push(x),i.other.set(V,J)}}return i}function vP(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function jc(e,n,i){let c=(S,T)=>T===void 0||!S.length?S:xl(S,T),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).`],g=[...e.files];p.push("",`## Modified files (${g.length})`),g.forEach(([S,T],A)=>{if(p.push(`- ${S}: ${T.count} change${T.count>1?"s":""} (step ${T.first}${T.last!==T.first?`-${T.last}`:""})`),A<g.length-i.diffFiles)return;for(let C of T.diffs)p.push(` step ${C.step}:`,...C.lines.map((P)=>` ${P}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((S)=>S.resolved?`- step ${S.step} ${S.what} (resolved at step ${S.resolved})${i.lists===void 0?`: ${S.detail.replace(/\n/g,`
73
- `)}`:""}`:`- step ${S.step} ${S.what} (UNRESOLVED): ${S.detail.replace(/\n/g,`
74
- `)}`)),p.push("","## Steps",...c(e.narration.map((S)=>`- ${S.step}. ${S.text}`),i.narration));let y=[...e.reads].map(([S,T])=>`- ${S} @ ${T.join(",")}`);p.push("",`## Files read (${y.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...c(y,i.lists));let x=[...e.searches].map(([S,T])=>`- ${S} \u2192 ${T.head||"(no output)"} (${vP(T.steps)})`);p.push("",`## Searches (${x.length})`,...c(x,i.lists));let b=e.commands.map((S)=>[`- ${S.step}. \`${S.command}\` exit=${S.exit}, ${S.lines} output lines, last ${S.tail.length}:`,...S.tail.map((T)=>` ${T}`)].join(`
75
- `));if(p.push("",`## Commands (${b.length})`,...c(b,i.lists)),e.other.size){let S=[...e.other].map(([T,A])=>`- ${T} (${vP(A)})`);p.push("",`## Other tool calls (${S.length})`,...c(S,i.lists))}return p.push("</work-state>"),p.join(`
76
- `)}function Sl(e,n,i,c){let p=XU(e,c),g=jc(p,n,{diffFiles:Number.POSITIVE_INFINITY});if(O(g)<=i)return g;let y={...p,narration:[]};for(let S of[Number.POSITIVE_INFINITY,20,10,5]){let T=O(jc(y,n,{diffFiles:S}));if(T>i*0.7)continue;return jc(p,n,{narration:Math.max(500,i-T),diffFiles:S})}let x=Math.max(300,Math.floor(i*0.1)),b=O(jc(y,n,{diffFiles:0,lists:x}));return jc(p,n,{narration:Math.max(500,i-b),diffFiles:0,lists:x})}function wl(e){return{role:"user",content:e,timestamp:0}}function jh(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 OP(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:wl(e.input)}function au(e){let n=[];for(let i of e){let c=n.at(-1),p=i;if(c?.role==="user"&&p.role==="user"){let g=(y)=>typeof y.content==="string"?[{type:"text",text:y.content}]:y.content;n[n.length-1]={...p,content:[...g(c),{type:"text",text:`
77
-
78
- `},...g(p)]};continue}n.push(i)}return n}function YU(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=ya(e),g=Ms(e),y=g.filter((be)=>Il(be,p)),x=qh(g,p),b=[],S=[],T=0;for(let be of g){if(Il(be,p))continue;let se=[];for(let me of be.records){if(be===x&&me.entry.seq<=p)continue;let qe=me.raw.role==="user"?CP(me):me.raw;T+=F(qe),b.push(qe),se.push(qe)}if(c.inspect&&se.length)S.push({id:`recent-${be.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${be.id}`,tokens:se.reduce((me,qe)=>me+F(qe),0),detail:JSON.stringify(se,YU,2)})}if(!y.length&&!x)return{items:S,messages:au(b),visible:0,archived:0,open:T,tokens:T,untrimmed:T};let A=PP(y,i,!!x),{visible:C,archived:P}=A,L=A.tokens,q=[],X="",j="";if(x){let be=x.records.filter((me)=>me.entry.seq<=p),se=be.filter((me)=>me.entry.type==="user"&&!me.entry.notices&&me.raw.role==="user");if(se.length){X=[`<chunk-input id="${x.id}" status="partial">`,...se.map((qe,It)=>`<user-message sequence="${It+1}">
79
- ${Ni(qe.entry.seq,$s(qe.raw))}
80
- </user-message>`),"</chunk-input>"].join(`
81
- `);let me=se.flatMap((qe)=>{let It=qe.raw.content;return typeof It==="string"?[]:It.filter((Je)=>Je.type==="image")});q.push(me.length?{role:"user",content:[{type:"text",text:X},...me],timestamp:0}:wl(X))}j=Sl(be,x,i.index,c.cwd),q.push(jh(j,n))}let V=e.flatMap((be)=>{let se=be.raw;if(be.entry.seq>p||se?.role!=="toolResult"||se.toolName!=="skill")return[];return[wl(se.content.filter((me)=>me.type==="text").map((me)=>me.text).join(`
82
- `))]}),J="",ee=()=>{J=$P({runs:y,visible:C.map((se)=>se.run),archived:P,partial:!!x,tokens:L,budget:i});let be=[wl(J)];for(let{content:se}of C){if(se.input)be.push(OP(se));be.push(jh(se.summary,n))}return[...be,...V,...q]},ie=(be)=>be.reduce((se,me)=>se+F(me),0),H=ee(),ce=ie(H)+T,fe=ce,{trim:_e}=c;while(_e&&_e.fixed+ce>_e.limit){let be=x||C.at(-1)?.run.status==="completed"?C:C.slice(0,-1);if(!be.length)break;let se=0,me=0;for(let qe of be)if(me++,se+=qe.content.tokens,se>=_e.fixed+ce-_e.limit)break;P=[...P,...C.slice(0,me).map((qe)=>qe.run)],C=C.slice(me),L-=se,H=ee(),ce=ie(H)+T}return{items:c.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:F(H[0]),detail:J},...C.map(({run:be,content:se})=>({id:be.id,label:`Chunk ${be.id}`,state:"sealed",tokens:(se.input?F(OP(se)):0)+F(jh(se.summary,n)),detail:[se.input,se.summary].filter(Boolean).join(`
83
-
84
- `)})),...P.map((be)=>({id:be.id,label:`Chunk ${be.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:ie(q),detail:[X,j].filter(Boolean).join(`
85
-
86
- `)}]:[],...S]:[],messages:au([...H,...b]),visible:C.length,archived:P.length,open:T,tokens:ce,untrimmed:fe}}function uu(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Uh=0.97,ZU=0.97,_P=0.5,eB=0.05,tB=20000,rB=24000;function Uc(e){return{target:tB,hard:rB,index:Math.floor(uu(e)*eB)}}function Bh(e){let n=e.usage;return n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite}class Bc{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 Uc(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(uu(e)*Uh/this.ratio)}prepare(e,n,i,c){let p=uu(i),g=Uc(i),y=e.reduce((H,ce)=>H+F(ce),0)+Li(n),x=this.records().at(-1)?.entry.seq??0,b=()=>c?[...c,...this.records().filter((H)=>H.entry.seq>x)]:this.records(),S=()=>ke(b(),i,g,{cwd:this.cwd(),trim:{fixed:y,limit:Math.floor(p*Uh/this.ratio)}}),T=b().findLast((H)=>H.raw?.role==="assistant"),A=T?b().filter((H)=>H.entry.seq>T.entry.seq&&H.raw):[],C=T?.raw,P=()=>T!==void 0&&(T.entry.seq===this.reshapedAfter||b().some((H)=>H.entry.type==="compaction"&&H.entry.seq>T.entry.seq)),L=this.dueSeal(i);if(L!==void 0)this.fold(L,!1),this.reshapedAfter=T?.entry.seq??-1;let q=S(),X=A.reduce((H,ce)=>H+F(ce.raw),0);if(this.lastEstimate===0&&T&&C&&!P()){let H=C.usage.input+C.usage.cacheRead+C.usage.cacheWrite,ce=y+q.untrimmed-F(C)-X;if(H>0&&ce>0)this.ratio=Math.min(2,Math.max(0.5,H/ce))}let V=((H)=>{let ce=y+H.untrimmed,fe=y+H.tokens;return((T&&C&&!P()&&Bh(C)>0?Bh(C)+Math.round(this.ratio*X):void 0)??Math.round(ce*this.ratio))-Math.round((ce-fe)*this.ratio)})(q);if(V>p*ZU){let H=V-q.open*this.ratio,ce=Math.max(1000,Math.floor((p*_P-H-g.index)/this.ratio)),fe=T?.entry.seq??-1,_e=b().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,be=Math.max(this.lastFoldSeq,_e),me=(be>0?b().filter((qe)=>qe.entry.seq>be&&qe.raw?.role==="assistant").length:999)<=1;if(!me||this.consecutivePartialFolds<2){let qe=Fc(b(),ce);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=fe,this.lastFoldSeq=fe,this.consecutivePartialFolds=me?this.consecutivePartialFolds+1:1,q=S()}}else this.consecutivePartialFolds=0;this.lastEstimate=y+q.tokens;let J=q.messages,ee=y+q.tokens;if(Math.round(ee*this.ratio)>p)J=nB(J,Math.floor((p-y)/this.ratio)),ee=y+J.reduce((H,ce)=>H+F(ce),0);return this.lastEstimate=ee,{messages:au([...e,...J]),estimate:ee}}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(bl(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)),y=(i?n.filter((x)=>x.entry.seq>i.entry.seq&&x.raw):[]).reduce((x,b)=>x+F(b.raw),0);if(p||!c||Bh(c)+y<Math.floor(uu(e)*Uh))return}return iu(n)}recover(e){let n=uu(e),i=Uc(e),c=ke(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((n*_P-(n-c.open*this.ratio)-i.index)/this.ratio),g=Fc(this.records(),p);if(g===void 0)return!1;return this.fold(g,!0),this.reshapedAfter=this.records().findLast((y)=>y.raw?.role==="assistant")?.entry.seq??-1,!0}}function nB(e,n){let i=e.reduce((p,g)=>p+F(g),0);if(i<=n)return e;let c=[];for(let p of e){let g=p;if(g.role!=="toolResult"||i<=n){c.push(p);continue}let y=F(p);if(y<=1500){c.push(p);continue}let x=Math.max(500,Math.floor(y/2)),b=g.content.map((A)=>{if(A.type!=="text")return A;return{...A,text:So(A.text,x)}}),S={...g,content:b},T=F(S);i-=y-T,c.push(S)}return c}var oB=2000;function cu(e,n){let i=[];for(let c of n.replace(/\r\n/g,`
87
- `).split(`
88
- `))for(let p=0;p<Math.max(c.length,1);){let g=Math.min(c.length,p+oB);if(g<c.length&&/[\uD800-\uDBFF]/.test(c.charAt(g-1)))g--;i.push({source:e,text:c.slice(p,g)}),p=g>p?g:p+1}return i}function mu(e){let n=[],i=ms(e.records),c=new Map(i.map((g)=>[g.call,g])),p=new Set(i.flatMap((g)=>g.result?[g.result]:[]));for(let g of e.records){let y=g.raw;if(y.role==="user")n.push(...cu(g.entry.type==="user"&&g.entry.notices?"NOTICE":"USER",$s(y)));else if(y.role==="assistant"){for(let x of y.content)if(x.type==="text"&&x.text.trim())n.push(...cu("ASSISTANT",x.text));else if(x.type==="toolCall"){let b=c.get(x);if(b)for(let S of yl(b))n.push(...cu(S.source,S.text))}}else if(y.role==="toolResult"&&!p.has(y))n.push(...cu(y.isError?"TOOL_ERROR":"TOOL_OUTPUT",ou(y)))}return n.map((g,y)=>({chunk:e.id,line:y,...g}))}function Gc(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 cu("USER",$s(i.raw)).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Kc(e,n){let i=e.find((c)=>c.entry.seq===n)?.entry;if(i?.type!=="extension"||!i.display)return;return cu("EXTENSION",i.display.text).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Hc(e,n=""){return e.map((i,c)=>{let p=e[c-1],g=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${n}${g?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
89
- `)}import{join as Pg}from"path";import{existsSync as ZP}from"fs";import{realpath as e$}from"fs/promises";import{dirname as t$,isAbsolute as EB,join as r$,relative as SB,resolve as Jh,sep as wB}from"path";import{existsSync as sB,watch as iB}from"fs";import{readdir as aB,stat as uB}from"fs/promises";import{basename as Gh,dirname as cB,join as LP,resolve as mB}from"path";class Kh{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 b;try{b=await aB(x)}catch(S){if(S instanceof Error&&"code"in S&&S.code==="ENOENT")continue;throw S}for(let S of b.sort()){let T=LP(x,S),A=(await uB(T)).isDirectory()?LP(T,"index.ts"):T;if(!A.endsWith(".ts")||A.endsWith(".d.ts"))continue;try{c.push({definition:await this.read(A),path:A})}catch(C){let P=Gh(A)==="index.ts"?Gh(cB(A)):Gh(A,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let L={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};i.push({definition:L,path:A}),this.slots.set(P,{definition:L,path:A,enabled:!0,discoveryFailed:!0,error:C instanceof Error?C.message:String(C)})}}}let p=n.filter((x)=>![...c,...i].some((b)=>b.definition.id===x.definition.id)),g=[...p,...c],y=this.order(g.map(({definition:x})=>x));for(let x of y){let b=g.find((T)=>T.definition===x)?.path,S=p.some((T)=>T.definition===x);try{await this.host.install(x,b,S)}catch(T){this.slots.set(x.id,{definition:x,path:b,builtin:S,enabled:!0,error:T instanceof Error?T.message:String(T)})}}if(this.watching())for(let x of[...g,...i]){if(!sB(x.path))continue;let b=iB(x.path,()=>{let S=x.definition.id,T=this.debounceTimers.get(S);if(T)clearTimeout(T);let A=setTimeout(()=>{this.debounceTimers.delete(S),this.host.reload(S).catch((C)=>{let P=this.slots.get(S);if(P)P.error=C instanceof Error?C.message:String(C)})},this.debounceMs);A.unref?.(),this.debounceTimers.set(S,A)});b.on("error",(S)=>{let T=this.slots.get(x.definition.id);if(T)T.error=S.message,this.host.changed()}),this.watchers.push(b)}}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,g=new Set,y=(x)=>{if(g.has(x.id))return;if(p.has(x.id))throw Error(`Plugin dependency cycle: ${x.id}`);p.add(x.id);for(let b of x.deps??[]){let S=i.get(b);if(S)y(S);else if(!this.slots.has(b))throw Error(`Missing plugin dependency: ${b}`)}p.delete(x.id),g.add(x.id),c.push(x)};for(let x of e)y(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(`${mB(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 NP(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((g,y)=>{p=setTimeout(()=>{c.abort(),y(Error(`Plugin callback timed out after ${n}ms`))},n)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as pB}from"async_hooks";import{isDeepStrictEqual as DP}from"util";var xa=new pB;function vs(){let e=xa.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function pu(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 qP(e,n){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Entry replacement must be a body");for(let b of["seq","time","session_id","raw"])if(b in n)throw Error(`Entry replacement contains protected field: ${b}`);let i=JSON.parse(JSON.stringify(n,(b,S)=>{if(typeof S==="function"||typeof S==="symbol"||typeof S==="number"&&!Number.isFinite(S))throw Error("Entry replacement must contain JSON values");return S}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let c=i,p=[];switch(e.type){case"user":p.push("text","attachments");break;case"assistant":p.push("parts","error");break;case"tool_result":p.push("output","images");break;case"extension":p.push("payload","display");break;case"notice_pending":p.push("notice");break;case"run":if(e.state==="end")p.push("error");break;case"compaction":break}let g={...e};for(let b of new Set([...Object.keys(e),...Object.keys(c)])){if(!p.includes(b)&&!DP(g[b],c[b]))throw Error(`Entry replacement changed protected field: ${b}`);if(["seq","time","session_id","raw"].includes(b))throw Error(`Entry replacement contains protected field: ${b}`)}let y=(b)=>b===void 0||typeof b==="string",x=!0;switch(e.type){case"user":x=typeof c.text==="string"&&(c.attachments===void 0||Array.isArray(c.attachments)&&c.attachments.every((b)=>b&&typeof b.name==="string"&&typeof b.mimeType==="string"&&Zc.includes(b.kind)&&typeof b.data==="string"));break;case"assistant":x=y(c.error)&&Array.isArray(c.parts)&&c.parts.every((b)=>b&&(["text","thinking"].includes(b.type)&&typeof b.text==="string"||b.type==="tool_call"&&typeof b.id==="string"&&typeof b.name==="string"&&("input"in b)));break;case"tool_result":x=typeof c.output==="string"&&(c.images===void 0||Array.isArray(c.images)&&c.images.every((b)=>b&&typeof b.mimeType==="string"&&typeof b.data==="string"));break;case"extension":{let b=c.display;x="payload"in c&&(b===void 0||b!==null&&typeof b==="object"&&("text"in b)&&typeof b.text==="string"&&(!("title"in b)||y(b.title)));break}case"notice_pending":{let S=["text"],T=g.notice,A=c.notice;if(x=!!A&&typeof A==="object"&&!Array.isArray(A),!x)break;let C=A;for(let P of new Set([...Object.keys(T),...Object.keys(C)]))if(S.includes(P)){if(typeof C[P]!=="string")x=!1}else if(!DP(T[P],C[P]))x=!1;break}case"run":x=y(c.error);break;case"compaction":break}if(!x)throw Error("Invalid entry replacement content");return i}function FP(e,n,i,c,p,g){let y=c;for(let x of i.generations)for(let b of x.hooks.get("entry.before_append")??[]){if(x.disabled)break;let S={phase:"before",violated:!1};try{let T=xa.run(S,()=>{let A=pu(y),C=performance.now(),P=b(A,{sessionID:p,seq:g});if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")throw Promise.resolve(P).catch(()=>{}),Error("entry.before_append must be synchronous");let L=P===void 0?void 0:qP(y,P);if(S.violated)throw Error("entry.before_append attempted a database write");if(performance.now()-C>e)throw Error("entry.before_append exceeded budget");return L});if(T&&JSON.stringify(T)!==JSON.stringify(y))y=T;x.beforeFailures=0,x.failures=0}catch(T){x.failures=x.beforeFailures++,n(x,T)}}return y}function lB(e,n){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return n;if(e==="entry.after_append")return pu(n);return structuredClone(n)}async function jP(e,n,i,c,p,g,y,x,b="end"){let S=g;for(let T of c){if(T.disabled)continue;let A=T.hooks.get(p)??[];for(let C of A){if(T.disabled)break;let P=T.hookOptions.get(C);if(p==="prompt.fragments"&&(P?.promptPosition??"end")!==b)continue;let L=p==="prompt.fragments"?JSON.stringify([y?.id,S]):void 0,q=L===void 0?void 0:T.promptCache.get(C)?.get(L);try{let X=lB(p,S),j=P?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:y,connection:x}):j,J=await n((ee)=>C(X,{runtime:e.runtime,session:y,connection:x,signal:ee}),V);if(L!==void 0){let ee=J===void 0?S:J;if(!Array.isArray(ee)||ee.some((H)=>typeof H!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(ee))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let ie=T.promptCache.get(C)??new Map;ie.set(L,[...ee]),T.promptCache.set(C,ie)}if(T.failures=0,J!==void 0&&p!=="entry.after_append")S=J}catch(X){if(q)S=structuredClone(q);if(i(T,X),P?.errorMode==="propagate")throw X}}}return S}class Wc{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 dB}from"fs";import{dirname as fB,resolve as UP}from"path";var Hh=new WeakMap;function BP(e){return[...e].map((n)=>{let i=Boolean(n.path&&(Boolean(n.definition.webEntry)||dB(UP(fB(UP(n.path)),"web.tsx"))));if(n.current&&!Hh.has(n.current))Hh.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?Hh.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 Wh{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 g=[];for(let y of c.generations){if(y.disabled)continue;for(let x of y.hooks.get(e)??[]){let b=y.hookOptions.get(x)?.timeoutMs,S=typeof b==="function"?b({runtime:this.host.runtime,session:n,connection:i}):b;g.push(this.deadline((T)=>x(n,{runtime:this.host.runtime,session:n,connection:i,signal:T}),S,!0).catch((T)=>this.fail(y,T)))}}await Promise.all(g)}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:pu(i),p=(this.entryQueues.get(n)??Promise.resolve()).then(async()=>{try{if(c)await xa.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 g=()=>{if(this.pending.delete(p),this.entryQueues.get(n)===p)this.entryQueues.delete(n)};p.then(g,g)}}function GP(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 hB(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 gB(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=bn(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 g=(await e.models()).models.filter((x)=>x.available===!0),y=p?rt(p):c;if(!g.some((x)=>x.id===y)){let x=g[0];if(x)p=bn(e.options.models,x.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function KP(e,n){hB(n);let i=await gB(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="",g=!1;try{let y=[...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:y},{maxTokens:c,signal:n.signal});for await(let b of x){if(n.signal?.aborted)throw Error("cancelled");if(b.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${GP(b.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(b.type==="text_delta")p+=b.delta;if(b.type==="done"){if(b.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(b.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${b.reason}\uFF09`);g=!0}}}catch(y){if(n.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${GP(y instanceof Error?y.message:String(y))}`)}if(n.signal?.aborted)throw Error("Completion cancelled");if(!g)throw Error("Model completion ended without a stop response; retry");return{text:p,model:rt(i)}}var yB=["active","archived","all"];function HP(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function xB(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&&!yB.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 IB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function WP(e){function n(i,c={}){let{types:p,bodies:g}=c;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let y=HP(c.limit),x=c.after??0;if(!Number.isSafeInteger(x)||x<0)throw Error("sessions after must be a non-negative integer");let b=(e.get(i)?.entries(x)??[]).filter((S)=>p===void 0||p.includes(S.type)).slice(0,y);return structuredClone(g===!1?b.map(IB):b)}return{list(i={}){xB(i);let c=i.limit===void 0?void 0:HP(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((g)=>i.projectID===void 0||g.projectID===i.projectID).filter((g)=>i.since===void 0||g.created>=i.since);return structuredClone(c===void 0?p:p.slice(0,c))},get(i){return structuredClone(e.get(i)?.info())},entries:n}}async function zP(e,n,i,c,p,g){let y={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,b=new Map,S=!1,T=!0,A=()=>{if(!T||y.disposed)throw Error("Plugin registration scope is closed")},C=(j,V)=>{if(A(),!S){b.set(j,V);return}if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,j);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,j,V)},P={get:(j)=>{A();let V=b.has(j)?b.get(j):x.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(n.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");C(j,J)},delete:(j)=>C(j,null)},L=()=>{if(A(),S)throw Error("Register resources during setup only")},q=[...n.migrations??[]].sort((j,V)=>j.version-V.version),X=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||X.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(X.add(j.version),x.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(n.id,j.version))continue;x.transaction(()=>{if(j.sql!==void 0)x.run(j.sql);else j.up({...P,db:x});for(let[V,J]of b)if(J===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,J);x.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(n.id,j.version)})(),b.clear()}return await c(async()=>n.setup({runtime:e.runtime,sessions:WP(e.runtime),complete:(j)=>KP(e.runtime,j),kv:P,database:x,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{L(),y.gates.push(j)},registerNoticeSource:(j,V)=>{if(L(),!j||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");y.noticeSources.set(j,{...V})},provide:(j,V)=>{if(L(),j.pluginID!==n.id)throw Error("Service key must belong to the providing plugin");if(y.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);y.services.set(j.name,V)},on:(j,V,J)=>{if(L(),J?.promptPosition&&j!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let ee=y.hooks.get(j)??[];if(ee.push(V),y.hooks.set(j,ee),J)y.hookOptions.set(V,J)},registerHistoryResolver:(j)=>{L(),y.historyResolvers.push(j)},registerTool:(j,V)=>{if(L(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||bB(e,p,n.id).has(j.name.toLowerCase())||y.tools.some((ee)=>ee.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let J=i?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;y.tools.push({...j,defer:J,source:`plugin:${n.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(L(),!(j.path.startsWith(`/api/plugins/${n.id}/`)||(n.routePrefixes??[]).some((V)=>j.path===V||j.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(j.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(y.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");y.routes.push(j)},registerWebSocket:(j)=>{if(L(),!j.path.startsWith(`/api/plugins/${n.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(y.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");y.websockets.push(j)},registerCommand:(j)=>{L(),y.commands.push(j)},registerWebContribution:(j)=>{L(),y.web.push(j)},registerToolPolicy:(j,V)=>{L(),y.policies.set(j,V)},appendExtension:(j,V)=>{if(vs(),A(),!S)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{L(),y.deactivators.push(j)},onDispose:(j)=>{L(),y.disposers.push(j)}})),x.transaction(()=>{for(let[j,V]of b)if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,j);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,j,V)})(),b.clear(),S=!0,y}catch(j){throw T=!1,await g(y),j}}function bB(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,g]of n){if(p===i)continue;for(let y of g.current?.tools??[])c.add(y.name.toLowerCase())}return c}class zh{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 VP(e,n,i,c){for(let p of n){let g=p.current;if(!g||g.disabled||g.retired)continue;let y=g.websockets.find((x)=>x.path===c);if(!y)continue;return{connect:(x)=>{let b=!1;g.references++,g.connections.add(x);let S={send:(A)=>{if(b||g.retired||g.disabled)return;x.send(A)},close:(A,C)=>x.close(A,C)},T=async(A)=>{if(b||g.retired||g.disabled){x.close(1012,"Plugin unavailable");return}try{await i(A),g.failures=0}catch(C){if(g.failures++,g.error=C instanceof Error?C.message:String(C),x.close(1011,"Plugin callback failed"),g.failures>=e.failureThreshold){g.disabled=!0;for(let P of g.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>T(()=>y.open?.(S)),message:(A)=>T(()=>y.message(S,A)),close:async()=>{if(b)return;b=!0,g.connections.delete(x);try{await i(()=>y.close?.(S))}catch(A){g.error=A instanceof Error?A.message:String(A)}finally{g.references--,await e.collect(g)}}}}}}return}function Vh(e,n){let i=e.split("/"),c=new URL(n.url).pathname.split("/");if(i.length!==c.length)return;let p={};return i.every((y,x)=>{let b=c[x];if(b===void 0)return!1;if(!y.startsWith(":"))return b===y;try{p[y.slice(1)]=decodeURIComponent(b)}catch{return!1}return b.length>0})?p:void 0}async function JP(e,n,i,c,p){let g=e.pin();try{let y=g.generations.find((x)=>x.definition.id===i)?.commands.find((x)=>x.id===c);if(!y)throw new f("Plugin command is unavailable");return await n(()=>y.execute(p))}finally{await g.release()}}function QP(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.method===n.method&&Vh(p.path,n)!==void 0))}finally{i.release()}}function XP(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.public===!0&&p.method===n.method&&Vh(p.path,n)!==void 0))}finally{i.release()}}async function YP(e,n,i){let c=e.pin(),p=!0;try{for(let g of c.generations)for(let y of g.routes){if(y.method!==i.method)continue;let x=Vh(y.path,i);if(x){let b=await n(()=>y.handler(i,x),y.timeoutMs);if(!b)return;if(b.body&&b.body instanceof ReadableStream){p=!1;let S=!1,T=()=>{if(S)return;S=!0,c.release()},A=b.body.getReader(),C=new ReadableStream({async pull(P){try{let{done:L,value:q}=await A.read();if(L)P.close(),T();else P.enqueue(q)}catch(L){P.error(L),T()}},async cancel(P){try{await A.cancel(P)}finally{T()}}});return new Response(C,{status:b.status,statusText:b.statusText,headers:b.headers})}return b}}return}finally{if(p)await c.release()}}class Qh{runtime;options;slots=new Map;retirement=new zh(this.deadline.bind(this));observers=new Wh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new fl;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 Kh(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 f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=n.current.services.get(e.name);if(!e.validate(i))throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((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(Jh(i));return this.catalog.discover(e,n).finally(()=>this.changed())}async pluginPath(e){let n=await e$(e),i=[...this.directories,r$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((c)=>r$(c.directory,".basalt","plugins"))];for(let c of i){if(!ZP(c))continue;let p=SB(await e$(c),n);if(p&&p!==".."&&!p.startsWith(`..${wB}`)&&!EB(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&&!ZP(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),g=n.current;n.definition=i,n.current=p,n.error=void 0,n.discoveryFailed=!1;let y=new Map(this.slots);this.slots.clear();for(let x of c){let b=y.get(x.id);if(b)this.slots.set(x.id,b)}if(g)await this.retirement.retire(g)}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 y of this.slots.values())if(y.enabled&&y.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${y.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 g=i.current;if(i.definition=c,n)i.discoveryFailed=!1;if(i.enabled=n,i.current=p,i.error=void 0,g)await this.retirement.retire(g)})}require(e){if(this.closed)throw Error("Plugin host is closed");let 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 zP(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 Wc(this,e)}async invoke(e,n,i,c,p,g="end"){return jP(this,this.deadline.bind(this),this.fail.bind(this),e,n,i,c,p,g)}pinEntry(e){if(xa.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 Wc(this,n)}beforeEntry(e,n,i,c){return FP(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 NP(e,n,i)}appendExtension(e,n){return vs(),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 BP(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,t$(Jh(n.path)));return{ok:!0}}catch(n){if(n instanceof dl)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,t$(Jh(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 JP(this,this.deadline.bind(this),e,n,i)}hasRoute(e){return QP(this,e)}isPublicRoute(e){return XP(this,e)}route(e){return YP(this,this.deadline.bind(this),e)}websocket(e){return VP(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 n$}from"fs";import{join as TB}from"path";var RB=500,kB=1000,AB=3600000,CB=5000,PB=2000,$B=3,MB=1073741824;class Xh{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,Ho),this.features={...qo(),...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+=n$(this.indexPath+n).size}catch{}return e}budget(){let e=0;try{e=n$(this.options.store.path).size}catch{}return Math.max(MB,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(),Jn(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,He,1),n.postMessage({type:"pause"}),Atomics.wait(this.flags,Tt,0,CB);try{return e()}finally{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=Go(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,He,0),Atomics.store(this.flags,Tt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(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<$B&&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,He,0),Atomics.notify(this.flags,He);let n=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([n,Bun.sleep(PB)]),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)Jn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),AB),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,kB-(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 fu,mkdirSync as DB,readdirSync as p$,readFileSync as a$,realpathSync as Yh,statSync as Cl,writeFileSync as Zh}from"fs";import{dirname as Al,isAbsolute as eg,relative as l$,resolve as qB}from"path";import{existsSync as zc}from"fs";import{dirname as NB,join as du}from"path";import{mkdirSync as vB,writeFileSync as OB}from"fs";import{tmpdir as _B}from"os";import{join as o$}from"path";var Tl=2000,Pe=30000;function u(e){return{content:[{type:"text",text:e}],details:void 0}}function lu(e,n){return e.map((i,c)=>{let p=i.length>Tl?`${i.slice(0,Tl)}\u2026 [line truncated]`:i;return`${String(n+c).padStart(6)} ${p}`}).join(`
90
- `)}function We(e,n){if(e.length<=n)return e;let i=Math.floor(n*0.4),c=n-i,p=e.length-i-c,g=e.slice(i,e.length-c).split(`
91
- `).length-1;return`${e.slice(0,i)}
92
-
93
- \u2026 [${p} characters, ~${g} lines omitted] \u2026
94
-
95
- ${e.slice(-c)}`}var LB=0;function nt(e,n,i){if(e.length<=n)return e;let c=We(e,n);try{let p=i?id(i):o$(_B(),"basalt-output");vB(p,{recursive:!0});let g=o$(p,`${process.pid}-${Date.now().toString(36)}-${LB++}.txt`);return OB(g,e),`${c}
96
- [Full output saved to ${g}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return c}}var s$=120000,i$=600000,Ia;function tr(){if(Ia!==void 0)return Ia||void 0;let n=(process.env.PATH??"").split(";").map((c)=>c.trim()).filter(Boolean);for(let c of n){let p=du(c,"bash.exe");if(zc(p))return Ia=p,p}for(let c of n){let p=du(c,"git.exe");if(zc(p)){let g=NB(c),y=du(g,"bin","bash.exe");if(zc(y))return Ia=y,y;let x=du(g,"usr","bin","bash.exe");if(zc(x))return Ia=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?du(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?du(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let c of i)if(zc(c))return Ia=c,c;Ia="";return}class Rl{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 g=p>=48&&p<=57?4:2;if(i+g>n.length)break;i+=g}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 ba(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:[tr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(c==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=tr();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,n){let i=await je(e,n.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:c,isWindows:p}=ba(e,n.shell),g=Bun.spawn(c,{cwd:n.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,...nm(n.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...n.extraPath?{[Object.keys(process.env).find((ee)=>ee.toLowerCase()==="path")??"PATH"]:n.extraPath}:{}}}),y=!1,x=()=>{try{if(p)g.kill();else process.kill(-g.pid,"SIGKILL")}catch{}},b=setTimeout(()=>{y=!0,x()},n.timeout);n.signal?.addEventListener("abort",x,{once:!0});let S=Pe*2,T="",A="",C=0,P=0,L="",q=(ee=!1)=>{let ie=C-T.length-A.length,H=ie>0?`${T}
97
- \u2026 [${ie} characters omitted] \u2026
98
- ${A}`:T+A;if(!ee)return We(H,Pe);return nt(L.length===C?L:H,Pe,n.cwd)},X=()=>{let ee=new Rl;return async(ie)=>{for await(let ce of ie){let fe=ee.decode(ce);if(C+=fe.length,L.length<4000000)L+=fe;if(T.length<S)T+=fe;else A=(A+fe).slice(-S);if(n.onOutput){let _e=performance.now();if(_e-P>=80)P=_e,n.onOutput(q())}}let H=ee.flush();if(H){if(C+=H.length,L.length<4000000)L+=H;if(T.length<S)T+=H;else A=(A+H).slice(-S)}}},j=Promise.all([X()(g.stdout),X()(g.stderr)]),V=await g.exited;if(clearTimeout(b),n.signal?.removeEventListener("abort",x),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))A+=`
99
- [background processes are still running; their later output is not captured]`;return{output:q(!0),code:y?null:V,timedOut:y}}class tg{seen=new Map;mark(e,n=Cl(e).mtimeMs){this.seen.set(e,n)}check(e){let n=this.seen.get(e);if(n===void 0)return"unread";return Cl(e).mtimeMs!==n?"changed":void 0}}var u$=2000,FB=500,jB=10485760,kl=20,UB=6,BB=40000,GB=80000;function KB(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 d$(e,n,i=[],c){let p=(L)=>eg(L)?L:qB(e,L),g=(L)=>{let q=l$(e,L);return q&&!q.startsWith("..")&&!eg(q)?q:L},y=(L)=>{let q=L;while(!fu(q)&&Al(q)!==q)q=Al(q);let X=Yh(q);if(i.some((j)=>fu(j)&&m$(Yh(j),X))&&!m$(Yh(e),X))throw Error("External directories are read-only")},x=(L,q,X)=>{let j=p(L);if(!fu(j))throw Error(`No such file or directory: ${j}${VB(j)}`);let V=Cl(j);if(V.isDirectory()){let me=p$(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),qe=me.slice(0,FB),It=me.length-qe.length;return u(`${qe.join(`
100
- `)}${It>0?`
101
- \u2026 and ${It} more entries`:""}`||"(empty directory)").content}let J=a$(j),ee=KB(J);if(ee){if(V.size>jB)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return n.mark(j),[{type:"text",text:`Read image ${g(j)} (${ee}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:ee}]}if(J.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);n.mark(j);let ie=J.toString("utf8");if(!ie)return u("(empty file)").content;let H=ie.replace(/\r?\n$/,"").split(/\r?\n/),ce=(q??1)-1;if(ce>=H.length)throw Error(`offset ${q} is past the end of the file (${H.length} lines)`);let fe=Math.min(H.length,ce+(X??u$)),_e=0,be=ce;while(be<fe){let me=H[be]?.length??0;if(be>ce&&_e+me>BB)break;_e+=me,be++}let se=lu(H.slice(ce,be),ce+1);if(be<fe)se+=`
102
-
103
- (Showing lines ${ce+1}-${be} of ${H.length} (truncated at line ${be} due to safety budget). Use offset/limit to read specific windows.)`;else if(ce>0||be<H.length)se+=`
104
-
105
- (Showing lines ${ce+1}-${be} of ${H.length}. Use offset/limit to read other parts.)`;return u(se).content},b=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.
106
- - path may be absolute or relative to the working directory.
107
- - By default reads up to ${u$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
108
- - Lines longer than ${Tl} characters are truncated.
109
- - Reading a directory lists its entries (directories end with /).
110
- - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
111
- - To read several files at once, give paths instead of path (up to ${kl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
112
- - Always read a file before editing or overwriting it.`,parameters: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(B(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:kl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(L,q){let X=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(X.length===0)throw Error("Give path, or paths to read several files");if(X.length===1){let ie=X[0];return{content:x(ie.path,ie.offset,ie.limit),details:void 0}}if(X.length>kl)throw Error(`Read at most ${kl} paths per call`);let j=[],V=[],J=0,ee=(ie)=>{let H=j.at(-1);if(ie.type==="text"&&H?.type==="text")H.text+=`
113
-
114
- ${ie.text}`;else j.push(ie)};for(let ie of X){let H=`==> ${g(p(ie.path))} <==`;if(J>=GB){ee({type:"text",text:`${H}
115
- (Skipped due to total read safety budget; read in separate calls)`});continue}try{let ce=x(ie.path,ie.offset,ie.limit);for(let fe=0;fe<ce.length;fe++){let _e=ce[fe];if(!_e)continue;if(_e.type==="text")J+=_e.text.length,ee(fe===0?{..._e,text:`${H}
116
- ${_e.text}`}:_e);else ee(_e)}}catch(ce){let fe=ce instanceof Error?ce.message:String(ce);V.push(fe),ee({type:"text",text:`${H}
117
- Error: ${fe}`})}}if(V.length===X.length)throw Error(V.join(`
118
- `));return{content:j,details:void 0}}}),S=async(L,q,X,j)=>{let V=j?.update,J=await rr(L,{cwd:e,timeout:120000,signal:X,extraPath:c?.extraPath,shell:typeof c?.shell==="function"?c.shell():c?.shell,onOutput:V?(fe)=>V(u(`${j.prefix}
119
-
120
- $ ${L}
121
- ${fe.trimEnd()}`)):void 0}),ee=J.output.trimEnd()||"(no output)",ie=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,H=J.timedOut||J.code!==0,ce=H?`
122
- ${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
123
-
124
- $ ${L}
125
- ${ee}
126
- [${ie}]${ce}`,failed:H}},T=(L,q=!1)=>{let X=n.check(L);if(X==="changed")return`Note: ${g(L)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(X==="unread"&&q)return`Note: ${g(L)} existed and had not been read; it was replaced whole.`;return},A=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.
127
- - An existing file is replaced whole, including changes made since you last read it.
128
- - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
129
- - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
130
- - Do not create documentation or README files unless asked.`,parameters: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,X,j){let V=p(q.path);y(V);let J=fu(V),ee;if(J){if(Cl(V).isDirectory())throw Error(`${V} is a directory`);ee=T(V,!0)}DB(Al(V),{recursive:!0}),Zh(V,q.content),n.mark(V);let ie=q.content?q.content.split(`
131
- `).length:0,H=`${J?"Overwrote":"Created"} ${g(V)} (${ie} lines)${ee?`
132
- ${ee}`:""}`;if(q.then_run){let ce=await S(q.then_run,`${g(V)} was written as given`,X,{prefix:H,update:j});if(H+=ce.out,ce.failed)return{...u(H),isError:!0}}return u(H)}}),C=(L,q,X,j)=>{let V=p(L);if(!fu(V))throw Error(`File not found: ${V} (use write to create it)`);y(V);let J=T(V),ee=a$(V,"utf8"),ie=ee,H=ie.includes(`\r
133
- `),ce=[],fe=[],_e=0,be=0;return q.forEach((se,me)=>{let qe=j?`edits[${X+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 It=H&&!se.old_string.includes(`\r
134
- `),Je=It?se.old_string.replace(/\n/g,`\r
135
- `):se.old_string,Yt=It?se.new_string.replace(/\n/g,`\r
136
- `):se.new_string,Fe=HB(ie,Je).map((Ct)=>[Ct,Ct+Je.length]);if(Fe.length===0)Fe=WB(ie,Je);if(Fe.length===0)throw Error(`${qe}old_string not found in ${g(V)}; read the relevant lines and copy the exact text.${zB(ie,Je)}`);if(Fe.length>1&&!se.replace_all){let Ct=Fe.map(([it])=>c$(ie,it)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${Ct}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=c$(ie,Fe[0][0]),qt=se.replace_all?Fe:[Fe[0]],lt="",Ot=0;for(let[Ct,it]of qt)lt+=ie.slice(Ot,Ct)+Yt,Ot=it;ie=lt+ie.slice(Ot),_e++,be+=qt.length;let yr=ie.split(/\r?\n/),pr=Ue+Yt.split(/\r?\n/).length-1,Ut=Math.max(1,Ue-1),st=Math.min(yr.length,pr+1);if(st-Ut+1<=UB+2)ce.push(lu(yr.slice(Ut-1,st),Ut));else ce.push(`${lu(yr.slice(Ut-1,Ue+1),Ut)}
137
- \u2026 (${pr-Ue-3} lines as given)
138
- ${lu(yr.slice(pr-2,st),pr-1)}`)}catch(It){fe.push(It instanceof Error?It.message:String(It))}}),{path:V,original:ee,content:ie,echoes:ce,applied:_e,total:be,count:q.length,note:J,failed:fe}},P=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.
139
- - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
140
- - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
141
- - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
142
- - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
143
- - To create a file use write; to delete or move files use bash.
144
- - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
145
- - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters: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(B(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,X,j){let V=q.edits&&q.edits.length>0?q.edits.map((se)=>({path:se.path??q.path,step:se})):q.old_string!==void 0&&q.new_string!==void 0?[{path:q.path,step:{old_string:q.old_string,new_string:q.new_string,replace_all:q.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,ee=new Map;V.forEach((se,me)=>{if(!se.path)throw Error(`${J?`edits[${me}]: `:""}path is required`);let qe=p(se.path),It=ee.get(qe)??{raw:se.path,steps:[],offset:me};It.steps.push(se.step),ee.set(qe,It)});let ie=[],H=[];for(let se of ee.values())try{let me=C(se.raw,se.steps,se.offset,J);if(me.applied>0)ie.push(me);H.push(...me.failed)}catch(me){let qe=me instanceof Error?me.message:String(me);H.push(`${J?`edits[${se.offset}]: `:""}${qe}`)}if(ie.length===0)throw Error(H.join(`
146
- `));let ce=[];try{for(let se of ie)Zh(se.path,se.content),ce.push(se)}catch(se){for(let me of ce)Zh(me.path,me.original);throw se}for(let se of ie)n.mark(se.path);let _e=ie.map((se)=>{let me=se.total===1?"1 occurrence":`${se.total} occurrences`,qe=se.note?`
147
- ${se.note}`:"";if(!J)return`Edited ${g(se.path)} (${me}).${qe}
148
- ${se.echoes[0]}`;let It=se.failed.length>0?`, ${se.failed.length} failed`:"";return`Edited ${g(se.path)} (${se.applied} edits${It}, ${me}). Regions are shown as they were right after each edit; later edits may shift line numbers.${qe}
149
- ${se.echoes.map((Je,Yt)=>`--- edit ${Yt+1}
150
- ${Je}`).join(`
151
- `)}`}).join(`
152
-
153
- `),be=!1;if(q.then_run){let se=await S(q.then_run,"The edits above were applied",X,{prefix:_e,update:j});if(_e+=se.out,se.failed)be=!0}if(H.length>0)_e+=`
154
-
155
- ${H.length===1?"1 edit":`${H.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
156
- - ${H.join(`
157
- - `)}`,be=!0;return be?{...u(_e),isError:!0}:u(_e)}});return[we(b,"cat","view","read_file","view_file","open_file","open"),we(A,"write_file","create_file","new_file","save_file"),we(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function HB(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 c$(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((b)=>b.trimEnd()),c=[],p=e.split(`
158
- `),g=0;for(let b of p)c.push(g),g+=b.length+1;let y=p.map((b)=>b.replace(/\r$/,"").trimEnd()),x=[];for(let b=0;b+i.length<=y.length;b++)if(i.every((S,T)=>y[b+T]===S)){let S=b+i.length-1,T=c[S]+p[S].replace(/\r$/,"").length,A=n.endsWith(`
159
- `)&&T<e.length?e[T]==="\r"?2:1:0;x.push([c[b],T+A]),b+=i.length-1}return x}function zB(e,n){let i=(x)=>x.replace(/\s+/g," ").trim(),c=i(n);if(!c)return"";let p=e.split(/\r?\n/),g=n.split(/\r?\n/).length;for(let x=0;x+g<=p.length;x++)if(i(p.slice(x,x+g).join(`
160
- `))===c)return` A match ignoring whitespace exists at line ${x+1}; copy the exact indentation and line breaks from the read output:
161
- ${We(lu(p.slice(x,x+g),x+1),4000)}`;let y=n.split(/\r?\n/).find((x)=>x.trim())?.trim();if(y){let x=p.findIndex((b)=>b.includes(y));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 VB(e){let n=Al(e);if(!fu(n))return"";let c=e.slice(n.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!c)return"";let p=p$(n).filter((g)=>{let y=g.toLowerCase().replace(/\.[^.]*$/,"");return y&&(y.includes(c)||c.includes(y))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function m$(e,n){let i=l$(e,n);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!eg(i)}var rg=20,ng=80,JB=5,f$=(e)=>e!==void 0&&e>0?e:void 0;function Pl(e,n){let i=(g)=>{if(n)return n(g);if(g.source&&g.source!=="self"||g.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.
162
- - Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
163
- - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters: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(B(l({minLength:1}),{maxItems:JB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:o(l({description:"Only search this chunk"})),seq:o(w({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:o(D({description:"Default false"})),head_limit:o(w({minimum:1,maximum:rg,description:`Hits to return (default ${rg})`})),offset:o(w({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(g,y){let x=i(y),b=f$(y.seq),S=()=>Ms(x.records),T=`session_id=${x.sessionID}`,A=b!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
164
- `:"",C;if(b!==void 0){let H=Gc(x.records,b)??Kc(x.records,b);if(!H)throw Error(`No user message with seq ${b}`);C=[H]}else{let H=S(),ce=y.chunk_id?H.filter((fe)=>fe.id===y.chunk_id):H;if(y.chunk_id&&!ce.length)throw Error(`No chunk ${y.chunk_id}. Chunk IDs look like r12.`);C=ce.map(mu)}let P=(H)=>y.case_sensitive?H:H.toLowerCase(),L=[y.pattern,...(y.also??[]).filter(Boolean)].map(P),q=y.head_limit??rg,X=y.offset??0,j=[],V=new Map,J=0;for(let H of C)H.forEach((ce,fe)=>{let _e=P(ce.text);if(!L.every((se)=>_e.includes(se)))return;if(V.set(ce.chunk,(V.get(ce.chunk)??0)+1),J++,J<=X||j.length>=q)return;let be=H.slice(Math.max(0,fe-2),fe+3);j.push(`${T} chunk ${ce.chunk} line ${ce.line}:
165
- ${Hc(be," ")}`)});if(!J)return u(`${A}No matches`);if(!j.length)return u(`${A}No matches at offset ${X} (total ${J})`);let ee=J-X-j.length,ie=V.size>1?` (all matches by chunk: ${[...V].map(([H,ce])=>`${H} ${ce}`).join(", ")})`:"";return u(`${A}${j.join(`
166
-
167
- `)}${ee>0?`
168
-
169
- \u2026 ${ee} more matches${ie}; continue with offset=${X+j.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=v({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),chunk_id:o(l({description:"Chunk to read"})),seq:o(w({description:"User message to read (from a user-text-reference)"})),offset:o(w({minimum:0,description:"First line (default 0)"})),limit:o(w({minimum:1,maximum:ng,description:`Lines to return (default ${ng})`}))}),async execute(g,y){let x=i(y),b=f$(y.seq),S=()=>Ms(x.records),T=`session_id=${x.sessionID}`,A=b!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
170
- `:"",C;if(b!==void 0){if(C=Gc(x.records,b)??Kc(x.records,b),!C)throw Error(`No user message with seq ${b}`)}else if(y.chunk_id){let X=S().find((j)=>j.id===y.chunk_id);if(!X)throw Error(`No chunk ${y.chunk_id}. Chunk IDs look like r12.`);C=mu(X)}else{let X=S().map((j)=>`${T} ${j.id} (${j.status}, ${mu(j).length} lines)`);return u(X.length?`Pass chunk_id or seq. Chunks in this session:
171
- ${X.join(`
172
- `)}`:"This session has no history yet")}let P=y.offset??0,L=C.slice(P,P+(y.limit??ng));if(!L.length)return u(`No lines at offset ${P} (total ${C.length})`);let q=C.length-P-L.length;return u(`${A}${T} ${b!==void 0?`seq=${b}`:y.chunk_id}
173
- ${Hc(L)}${q>0?`
174
-
175
- \u2026 ${q} more lines; continue with offset=${P+L.length}`:""}`)}});return[c,p]}import{statSync as QB}from"fs";import{isAbsolute as h$,relative as XB,resolve as g$}from"path";var $l=200,YB=30000,Ml=Bun.which("rg");async function og(e,n,i){let c=Bun.spawn(e,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,g,y]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(y>1)throw Error(g.trim()||`${e[0]} exited with ${y}`);return p}function y$(e){let n=(g)=>g?h$(g)?g:g$(e,g):e,i=(g)=>{let y=XB(e,g);return y&&!y.startsWith("..")&&!h$(y)?y:g},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).
176
- - Respects .gitignore and skips .git. Use it instead of find or ls -R.
177
- - 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(g,y,x){let b=n(y.path),S;if(Ml)S=(await og([Ml,"--files","--hidden","--glob","!.git","--glob",y.pattern],b,x)).split(`
178
- `).filter(Boolean);else{S=[];for await(let P of new Bun.Glob(y.pattern).scan({cwd:b,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(P))S.push(P)}if(!S.length)return u("No files found");let T=S.map((P)=>{let L=g$(b,P);try{return{path:L,time:QB(L).mtimeMs}}catch{return{path:L,time:0}}});T.sort((P,L)=>L.time-P.time);let A=T.slice(0,$l).map((P)=>i(P.path)),C=S.length-A.length;return u(`${A.join(`
179
- `)}${C>0?`
180
- \u2026 ${C} 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.
181
- - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
182
- - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
183
- - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
184
- - Use this instead of running grep or rg through bash.`,parameters: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(g,y,x){let b=n(y.path),S=y.output??"files",T;if(Ml){let P=[Ml,"--hidden","--glob","!.git","--max-columns","400","--max-columns-preview"];if(y.ignore_case)P.push("-i");if(y.glob)P.push("--glob",y.glob);if(S==="files")P.push("-l");else if(S==="count")P.push("-c");else if(P.push("-n","--no-heading"),y.context)P.push("-C",String(y.context));P.push("--",y.pattern,b),T=await og(P,e,x)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(y.ignore_case)P.push("-i");if(y.glob)P.push(`--include=${y.glob}`);if(S==="files")P.push("-l");else if(S==="count")P.push("-c");else if(P.push("-n"),y.context)P.push(`-C${y.context}`);P.push("--",y.pattern,b),T=await og(P,e,x)}let A=`${e}/`,C=T.split(`
185
- `).filter(Boolean).map((P)=>P.startsWith(A)?P.slice(A.length):P).filter((P)=>S!=="count"||!P.endsWith(":0"));if(!C.length)return u("No matches");if(S==="files"&&C.length>$l)return u(`${C.slice(0,$l).join(`
186
- `)}
187
- \u2026 ${C.length-$l} more files; narrow the search`);return u(nt(C.join(`
188
- `),YB,e))}});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 x$(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.
189
- Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
190
- - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
191
- - Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
192
- - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:s({todos:B(s({content:l({minLength:1,description:"What to do, in imperative form"}),status:m(Fg.map((n)=>a(n)))}))}),async execute(n,i){let c=i.todos.map((y)=>({content:y.content,status:y.status}));e(c);let p=c.filter((y)=>y.status==="completed").length,g=c.find((y)=>y.status==="in_progress");return u(`Todo list updated (${p}/${c.length} completed${g?`; in progress: ${g.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function $e(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}function I$(e){let n=$e(e);return{target:n,hard:n,index:n}}class vl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,n=()=>{return},i){this.records=e;this.cwd=n;if(i)this.defaultPolicy=new Bc(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)??I$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??$e(e)}prepare(e,n,i,c,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,n,i,c);let g=e.reduce((S,T)=>S+F(T),0)+Li(n),y=Math.max(0,$e(i)*this.recoveryRatio-g),x=ke(c??this.records(),i,I$(i),{cwd:this.cwd()}).messages,b=x.reduce((S,T)=>S+F(T),0);if(p&&b>y)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(b>y&&x.length>1){let S=x.shift();if(S)b-=F(S);while(x[0]?.role==="toolResult"){let T=x.shift();if(T)b-=F(T)}}if(b>y){let S=x.at(-1),T=S&&"content"in S&&typeof S.content==="string"?S.content:"[Context omitted: use history tools to retrieve earlier messages.]";x.length=0;let A=T;while(A&&F({role:"user",content:A,timestamp:0})>y)A=A.slice(Math.ceil(A.length/2));if(A)x.push({role:"user",content:A,timestamp:0});b=x.reduce((C,P)=>C+F(P),0)}return this.lastMessageCount=x.length,{messages:[...e,...x],estimate:g+b}}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 b$,readFileSync as ZB}from"fs";import{homedir as eG}from"os";import{dirname as tG,join as E$}from"path";var rG=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
193
-
194
- # How to work
195
-
196
- - Complete the task end to end. Keep going until the user's request is fully resolved before ending your turn: investigate, make the change, verify it. Do not stop halfway to report a plan or ask "should I continue?" when the next step is clear.
197
- - Ask the user only when you are genuinely blocked: the request is ambiguous in a way that changes the outcome, or the action is destructive or irreversible. Otherwise make a reasonable choice, state the assumption briefly, and proceed.
198
- - If the user only asks a question or asks for a plan or review, answer it; do not start changing files. For a review, lead with findings: bugs, risks, behavior regressions and missing tests, ordered by severity with file:line. Keep any summary short and after the findings.
199
- - Do not use the todo tool for a single deliverable, even a complex one (implementing a feature, fixing a bug, writing a module and its tests): work through it directly with a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later. Never make reading, environment checks or the final summary into items, and update it only together with your next action, never as a turn of its own.
200
-
201
- # Making changes
202
-
203
- - Investigate before changing anything. Find the relevant code with grep/glob, read it, and understand how it is used. Edit from what you have actually seen: a read, or grep output with enough context to copy the text exactly.
204
- - Verify unfamiliar technical entities instead of recalling them. When a task involves a library, API, tool or version you do not confidently recognize, check the project first: package manifests and lockfiles, \`--version\`, or the installed sources. A fluent answer built on an outdated memory looks right and is wrong. Never guess URLs; use only ones the user or the project gave you.
205
- - Follow the conventions of the existing code: style, naming, structure, libraries, error handling, comment density, test layout. Before using a library, confirm the project already depends on it.
206
- - Fix the root cause, not the symptom. Keep changes minimal and focused on the task; do not refactor, rename or "clean up" unrelated code, and do not add features that were not requested. Between two correct approaches, prefer the smaller one. Do not add backward-compatibility code unless something concrete needs it (persisted data, shipped behavior, external consumers, an explicit requirement).
207
- - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
208
- - Do not add comments that narrate the change ("added this", "fixed bug"). Comment only where the code is not self-explanatory, in the style of the surrounding code.
209
-
210
- # Verifying
211
-
212
- - Verify behaviour the way the user would see it. When asked to test a feature, or after a change with user-visible effects, run the real thing first: start the app or server with bash background=true, exercise the changed path (curl an endpoint, run the CLI with real input, or drive a web UI with the browser tools: open, act, then browser_screenshot and look at the image), and confirm the result matches the requirement. Unit tests complement this; they do not replace it, and "the tests pass" is not evidence the feature works.
213
- - For code with no runnable surface (a library, a refactor, types, build config), or when the app cannot be started here, run the most specific tests, type checker, linter or build instead \u2014 find how in the project's README, package scripts, Makefile or CI config \u2014 and say what you could not exercise.
214
- - Once the change is verified, stop: re-verify only after new changes, failures or a concrete unresolved concern. Do not re-run a check that already passed when nothing it covers has changed. Kill servers and close pages you started.
215
- - Do not re-read a file after your own edit or re-check mkdir/delete/move results: an edit result already shows the new content, and a failing call reports an error. Re-read only if someone else changed the file.
216
- - When a step fails, read the error and diagnose why before retrying. Do not loop on the same failing approach; after two failed attempts, step back and reconsider. If a tool call is blocked, do not retry it unchanged; follow the stated reason or ask the user.
217
-
218
- # Tools
219
-
220
- - Tool calls are the only way to act; describing an action does not perform it.
221
- - Use the dedicated tools for files: read to view (paths reads several files in one call), edit for replacements (give edits for several changes, even across files), write to create or rewrite a file, grep to search contents, glob to find files. A quick read-only look (ls, cat, sed -n) may share a bash command with other work, such as listing a directory while checking tool versions; to only view or edit a file, use read and edit.
222
- - Create files you will keep or edit later with write, passing then_run to run them or their tests in the same step. A file written by a bash heredoc has not been read through the tools, so a later edit of it costs an extra step; a heredoc is fine for a throwaway script that the same command runs.
223
- - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
224
- - In bash, search with rg / rg --files when it exists (much faster than grep/find). Do not join commands with echo or printf separators such as an echo '====' line; the output gets noisy. Do not use python or other scripts just to print or edit file contents when read, edit will do. Backticks and $() inside a command still execute, so escape text carefully.
225
- - Put every tool call you already know into one response. Independent reads and searches run in parallel; calls that change things (edit, write, bash) run one after another in the order you give them, so you can edit a file and run its tests in the same response. Put all replacements of one logical change (for example an import, a helper and its call sites, plus the matching test) into one edit call's edits and pass then_run with the test command, instead of one edit per spot followed by a separate test run. Pass then_run to write as well. When probing behaviour, batch the checks into one script instead of one command each.
226
- - Use bash for builds, tests, git, package managers and running programs. Each bash call starts in the project directory; use absolute or project-relative paths and chain dependent steps with &&.
227
- - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished, including dev servers you start to verify a change. Do not busy-wait or poll repeatedly.
228
-
229
- # Honesty
230
-
231
- - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
232
- - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
233
- - When the user asks you to run something, run it, even when you can predict the result.
234
- - If a step failed, was skipped or could not be verified, say which one and why.
235
-
236
- # Safety
237
-
238
- - Do not run destructive or irreversible commands (rm -rf on broad paths, git reset --hard, git push --force, dropping databases, killing unrelated processes) unless the user explicitly asked for exactly that.
239
- - Never commit, push, create branches or rewrite git history unless the user asks. If asked to commit, write a concise message that explains why, matching the repository's existing style.
240
- - Do not revert or overwrite changes you did not make; the user may be editing files at the same time. If a file changed unexpectedly, read it again and work with the new content.
241
- - Never print, log or commit secrets such as API keys, tokens or passwords.
242
-
243
- # Communication
244
-
245
- - Reply in the same language the user writes in.
246
- - Be concise and direct. No filler, no flattery, no restating the request. Do not narrate every tool call: a short sentence before a batch of related actions, and in a long run a brief progress note every few calls, is enough.
247
- - Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
248
- - Do not use emojis unless the user does or asks for them.
249
- - When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
250
- - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,nG=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
251
-
252
- # Tools
253
-
254
- - Use read to view files, edit to change them and write to create them; use grep/glob to search contents and find files in the working directory.
255
- - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
256
- - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
257
- - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
258
- - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
259
-
260
- # Communication
261
-
262
- - Reply in the same language the user writes in.
263
- - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
264
- - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,oG=["AGENTS.md","CLAUDE.md"],sG=20000;function S$(e){let n=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?rG:nG}],i=[];if(e.globalInstructions?.trim())i.push(sg("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let c of iG(e.project.directory))i.push(sg(c.path,c.content));if(e.project.instructions.trim())i.push(sg(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)n.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
265
-
266
- # Instructions from the user and project
267
-
268
- The following instructions were written by the user or the project maintainers. Follow them; they override the defaults above when they conflict. More specific (deeper directory) instructions take precedence over general ones.
269
-
270
- ${i.join(`
271
-
272
- `)}`});return n.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
273
-
274
- ${aG(e)}`}),n}function sg(e,n){return`<instructions source="${e}">
275
- ${We(n.trim(),sG)}
276
- </instructions>`}function iG(e){let n=[],i=e;for(let c=0;c<20;c++){for(let g of oG){let y=E$(i,g);if(b$(y)){try{n.unshift({path:y,content:ZB(y,"utf8")})}catch{}break}}if(b$(E$(i,".git"))||i===eG())break;let p=tG(i);if(p===i)break;i=p}return n}function aG(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:g}=ba("",e.shell),y=[`Working directory: ${p}`,`Shell: ${g}`,`Date: ${i} (${c})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project){let x=uG(e.project.directory);y.push(x??"Git: not a git repository")}return`<environment>
277
- ${y.join(`
278
- `)}
279
- </environment>`}function uG(e){let n=(...x)=>{try{let b=Bun.spawnSync(["git",...x],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0});return b.exitCode===0?b.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(`
280
- `):[],g=p.length>30?[...p.slice(0,30),`\u2026 ${p.length-30} more`]:p,y=n("log","--oneline","-5")??"";return[`Git branch: ${i}`,`Git status at session start:${g.length?`
281
- ${g.join(`
282
- `)}`:" clean"}`,y?`Recent commits:
283
- ${y}`:"Recent commits: none"].join(`
284
- `)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Pl(e.records,e.history):[],c=e.directory??process.cwd();return[...d$(c,new tg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...y$(c),x$(e.onTodos),...i]}class Di{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!Ug.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!jg.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,g=p.source??"core",y=c.name.toLowerCase(),x=p.defer??"always",b="suggestion";if(n.global)x=n.global,b="global";if(Object.hasOwn(n.sources,g))x=n.sources[g]??x,b="source";if(Object.hasOwn(n.tools,y))x=n.tools[y]??x,b="tool";if(g==="core"||p.builtin&&p.defer!=="defer")x="always",b="suggestion";return{name:c.name,source:g,mode:x,origin:b,deferred:x==="defer"}})}}function ig(e){return{name:e.name,description:e.description,parameters:e.parameters}}function ag(e,n){if(!n)return e;let i=Array.isArray(n.type)?n.type:[n.type],c=e;if(i.includes("number")||i.includes("integer")){let p=typeof c==="string"&&c.trim()?Number(c):c;if(typeof p!=="number"||!Number.isFinite(p))return c;let g=p;if(typeof n.maximum==="number"&&g>n.maximum)g=n.maximum;if(typeof n.minimum==="number"&&g<n.minimum)g=n.minimum;return g===p?c:g}if(typeof c==="string"&&(i.includes("object")||i.includes("array")))try{let p=JSON.parse(c),g=Array.isArray(p);if(typeof p==="object"&&p!==null&&!g&&i.includes("object")||g&&i.includes("array"))c=p}catch{}if(Array.isArray(c)){let p=n.items;if(!p||typeof p!=="object"||Array.isArray(p))return c;return c.map((g)=>ag(g,p))}if(typeof c==="object"&&c!==null&&n.properties){let p={...c};for(let[g,y]of Object.entries(n.properties))if(g in p)p[g]=ag(p[g],y);return p}return c}function cG(e){let n=e.prepareArguments;return{...e,prepareArguments:(i)=>{let c=ag(i,e.parameters);return n?n(c):c}}}function mG(e,n,i){let c=e.prepareArguments?e.prepareArguments(i):i;return nu(e,{type:"toolCall",id:n,name:e.name,arguments:c})}class ug{retrieved=new Map;stub(e,n){let i=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${i}
285
- (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:s({},{additionalProperties:!0}),execute:async(c,p,g,y)=>{let x=JSON.stringify(ig(e)),b;try{b=mG(e,c,p??{})}catch(A){return{...u(`Invalid arguments for ${e.name}: ${String(A)}
286
- Schema: ${x}`),isError:!0}}let S=await e.execute(c,b,g,y),T=S.content.map((A)=>A.type==="text"?{...A,text:nt(A.text,Pe,n)}:A);return{...S,content:T}}}}assemble(e,n,i,c){let p=e.map(cG),g=new Set(n.filter((x)=>x.deferred).map((x)=>x.name));if(!g.size)return p;let y=p.filter((x)=>g.has(x.name)&&i(x.name)).sort((x,b)=>x.name<b.name?-1:x.name>b.name?1:0);return[...p.filter((x)=>!g.has(x.name)),...y.map((x)=>this.stub(x,c)),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(x,b)=>{let S=b.query.trim().toLowerCase(),T=S.startsWith("select:")?S.slice(7).split(",").map((C)=>C.trim()):void 0,A=y.filter((C)=>i(C.name)&&(T?T.includes(C.name.toLowerCase()):`${C.name} ${C.description}`.toLowerCase().includes(S))).slice(0,b.max_results??5);return u(JSON.stringify(A.map((C)=>{let P=JSON.stringify(ig(C)),L=this.retrieved.get(C.name);if(L?.schema===P)return{name:C.name,status:"\u5DF2\u53D6\u56DE",callID:L.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(C.name,{schema:P,callID:x}),ig(C)})))}}),"tool_search")]}}async function Ol(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 g=c.systemPrompt,y=c.systemParts?.at(-1);if(y?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let T=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),A=g.length-y.detail.length;g=g.slice(0,A)+T.join("")+y.detail}let x=await i.invoke("prompt.fragments",[],e),b=[...c.tools,...i.tools()],S=i.has("tools.visible")?await i.invoke("tools.visible",b,e):b;return{...c,systemPrompt:g+x.join(""),tools:S}}var pG=3,w$={attempts:1/0,delayMs:2000},lG=/\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 dG(e,n){if(e.stopReason!=="error")return!1;if(ua(e,n))return!1;return!lG.test(e.errorMessage??"")}function T$(e,n,i){if(ua(e,n))return!0;if(i?.preserveHistory!==!0)return!1;return e.errorMessage===(i.overflowError??"Context exceeds the request budget")}function fG(e,n){return new Promise((i,c)=>{if(n.aborted)return c(n.reason);let p=setTimeout(()=>{n.removeEventListener("abort",g),i()},e),g=()=>{clearTimeout(p),c(n.reason)};n.addEventListener("abort",g,{once:!0})})}async function R$(e,n,i,c,p,g,y,x,b=!1){let S=b?void 0:await n?.invoke("run.start",{text:g},e);if(S)g=S.text;if(x.throwIfAborted(),g===void 0)await c.resume();else await c.prompt(g,y);let T=0,A=0;while(T<pG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!T$(q,p.contextWindow,i)){if(!dG(q,p.contextWindow)||A>=w$.attempts)return;A++,await fG(w$.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(),T++,await c.retry()}let P=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&P?.stopReason==="error"&&T$(P,p.contextWindow,i))throw Error(i.overflowError??"Context exceeds the request budget")}async function k$(e,n,i,c,p,g){g.throwIfAborted();let y,x;try{x=await Promise.race([Ol(e,n,i()),new Promise((C,P)=>{y=()=>P(g.reason),g.addEventListener("abort",y,{once:!0})})])}finally{if(y)g.removeEventListener("abort",y)}g.throwIfAborted();let b=i(),S=(C)=>{if(!b)return C;return{...C,execute:async(P,L,q,X)=>{let j=c()??x.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?b.policy(j):void 0;if(j&&!V?.(C.name,e))throw Error(`Tool ${C.name} is unavailable under tool policy ${j}`);let J=await b.invoke("tool.before_call",{name:C.name,callID:P,args:L},e);if(J.block)throw Error(J.block);let ee=await K.run(e,()=>C.execute(P,J.args,q,X));return b.invoke("tool.after_result",ee,e)}}};if(b)x.tools=x.tools.map(S);let T=x.tools,A=()=>{if(!T.some((P)=>P.name==="history_grep")){if(e.records.some((L)=>L.entry.type==="compaction")){let q=Pl(()=>e.records,(X)=>n.runtime?.resolveHistory?.(e.id,X)).map(S);for(let X of q)if(!T.some((j)=>j.name===X.name))T.push(X)}}let C=new Di(n.store).partition(T);return x.tools=p.assemble(T,C,(P)=>e.permitsTool(P),x.cwd),x.tools};return x.tools=A(),{setup:x,executionTools:T,assemble:A}}function A$(e,n,i,c,p,g,y){return{response:async(x)=>{let b=await n()?.invoke("model.after_response",x,e)??x;if(b.role==="assistant")for(let S of b.content){if(S.type!=="toolCall"||S.name.toLowerCase()!=="tool_call")continue;let T=S.arguments.name;if(typeof T==="string"){let A=y.find((C)=>C.name.toLowerCase()===T.toLowerCase());S.arguments.name=A?.name??T}}return b},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 S of x?.notices??[])e.notice(S);await g.work;let b=await g.flushNotices();if(b&&!p())e.agent?.steer(b)},prepare:async(x,b,S)=>{if(c())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let T=await n()?.invoke("model.check",{},e);if(T?.error)throw Error(T.error);let A=await n()?.invoke("step.before",{notices:[]},e);for(let j of A?.notices??[])e.notice(j);await g.work,await g.flushNotices();let C=await n()?.invoke("projection.before",e.records,e),P=await n()?.invoke("projection.prefix",[],e)??[],L=e.context.prepare([...x,...P],b,S,C,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&L.estimate>$e(S))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=L.messages,X=await n()?.invoke("projection.after",q,e)??q;return au(X)}}}async function C$(e,n,i){let c=n.store.pendingNotices(e.id);if(!c.length)return;let p=c,g=n.plugins?.pin();try{if(g){let P=await g.invoke("notice.deliver",c,e);p=c.map((L,q)=>({...L,text:P[q]?.text??L.text}))}}finally{await g?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let y=p.map((P)=>P.text).join(`
287
- `),x=p.map((P)=>n.plugins?.noticeSource(P.sourceKind)),b=Math.max(800,...x.map((P)=>P?.summaryLimit??800)),S=y.length>b?`
288
- [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",A=`${x.find((P)=>P?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
289
- ${y.slice(0,b)}${S}`,C={role:"user",content:A,timestamp:Date.now()};return i({type:"user",text:A,notices:c.map(({text:P,...L})=>L)},C),C}class cg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,n,i,c,p,g,y,x){this.session=e;this.context=n;this.isStopped=i;this.isRunning=c;this.waiting=p;this.start=g;this.invalidateAgent=y;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=C$(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 hG=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 mg(e){let n={};for(let[i,c]of Object.entries(e)){if(!hG.has(i.toLowerCase())){n[i]=c;continue}let p=/^bearer\s+/i.exec(c)?.[0];n[i]=p?`${p}***`:"***"}return n}function P$(e,n,i,c){let g=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((H,ce)=>({id:`system-${ce}`,label:H.label,detail:H.detail,tokens:O(H.detail)+(ce===0?16:0)})),y=i.tools.map((H)=>{let ce=H,fe=ce.defer==="defer"||H.description.includes("(Parameters not inlined: use toolsearch");return{name:H.name,description:H.description,group:ce.group??"\u5185\u7F6E",schema:H.parameters,deferred:fe}});g.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Li(i.tools),detail:JSON.stringify(y,null,2)});let x=g.reduce((H,ce)=>H+ce.tokens,0),b=c!==void 0?e.records.filter((H)=>H.entry.seq<=c):e.records,S=ke(b,n,e.context.budget(n),{inspect:!0,cwd:i.cwd,trim:{fixed:x,limit:e.context.previewLimit(n)}}),T,A=0,C=0;for(let H of b){if(H.raw?.role!=="assistant")continue;let ce=H.raw.usage;T??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},T.input+=ce.input,T.output+=ce.output,T.cacheRead+=ce.cacheRead,T.cacheWrite+=ce.cacheWrite,T.cost+=ce.cost.total;let fe=H.entry.generationMs??H.raw.generationMs;if(typeof fe==="number"&&fe>0&&ce.output>0)A+=fe,C+=ce.output}if(T){let H=T.input+T.cacheRead+T.cacheWrite;if(H>0)T.cacheHitRate=T.cacheRead/H}if(T&&A>0&&C>0)T.generationMs=A,T.tps=Number((C/(A/1000)).toFixed(1));let P=x+S.tokens,L=e.context.calibrationRatio??1,q=Math.round(P*L),X=b.findLast((H)=>H.raw?.role==="assistant"),j=X?.raw,J=(X?b.filter((H)=>H.entry.seq>X.entry.seq&&H.raw):b.filter((H)=>H.raw)).length>0,ee,ie;if(j){let H=j.usage,ce=H.input+H.cacheRead+H.cacheWrite;if(ce>0)ee=ce,ie=H.cacheRead/ce}return{contextWindow:n.contextWindow,usableWindow:$e(n),items:[...g,...S.items],calibratedTokens:q,calibrationRatio:L,lastInputTokens:ee,lastCacheHitRate:ie,hasPendingOutput:J,tools:y,usage:T}}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 pg="medium";class _l{row;ctx;events;notices;lease;policyID;discovery=new ug;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let n=await Ol(this,this.ctx,e);return new Di(this.ctx.store).partition(n.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new oe;this.policyID=e,this.reset()}historyScope(e){if(this.lease)return this.lease.resolveHistory(this,e);return this.ctx.plugins?.resolveHistory(this,e)}permitsTool(e){let n=this.policyID??this.setup?.toolPolicy;if(!n)return this.info().parentID===null;return(this.lease?.policy(n)??this.ctx.plugins?.toolPolicy(n))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,n,i){this.row=e;this.ctx=n;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new cg(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((y)=>y.type==="extension"&&y.namespace==="session"&&y.kind==="stop_requested"),g=this.entries().findLast((y)=>y.type==="run"&&y.state==="start");if(p&&p.seq>(g?.seq??0))this.stopped=!0;if(c?.type==="run"&&c.state==="start"){let y=this.records.some((b)=>b.entry.seq>c.seq&&b.entry.type==="user"),x=n.store.pendingNotices(e.id).some((b)=>b.wake&&b.recovery!=="discard");if(!this.stopped&&(y||x))this.recoveryStart=c.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new vl(()=>this.records,()=>this.cwd,(y,x)=>this.appendCompaction(y,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=bn(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:mg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:mg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??pg}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get 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:g,created:y,updated:x,todos:b}=this.row;return{id:e,title:n,projectID:i,model:c,thinking:p??pg,metadata:g,created:y,updated:x,archivedAt:this.row.archivedAt,status:this.status,todos:b,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=bn(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 Ol(this,this.ctx,c)}finally{await c?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new Di(this.ctx.store).partition(p.tools),(y)=>this.permitsTool(y),p.cwd);let g=P$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:g};return g})();if(e!==void 0)return 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"||!bn(this.ctx.models,e))throw new t(`unknown model ${e}`);let n=this.row.model;if(n===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:n,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let n=e?.trim()?e.trim():null;if(this.row.thinking===n)return;this.save({thinking:n}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,n){this.startRun(e,Yl(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=Yl(n),c=Oh(e,i),p=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},c);if(this.recallableSteers.set(p.seq,c),this.events.changed(),this.agent)this.agent.steer(c);else this.pendingSteers.push(c)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let n=this.records.find((g)=>g.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 g=JSON.stringify(i);c=this.pendingSteers.findIndex((y)=>JSON.stringify(y)===g)}let p=!1;if(c>=0)this.pendingSteers.splice(c,1),p=!0;else p=this.agent?.unsteer(i)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[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=bn(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:gG(e,n)},this.ctx.store.updateSession(this.row);let g=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let y=this.append({type:"user",text:e,...n?.length?{attachments:n}:{}});this.pendingUserSeq=y.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let x=this.records.filter((A)=>A.entry.seq>g),b=x.filter((A)=>A.entry.type==="user"&&!A.raw);if(b.length>1)return{reason:"interrupted"};let S=b[0];if(S?.entry.type==="user"){if(x.some((A)=>A.entry.seq>S.entry.seq&&A.raw?.role==="assistant"))return{reason:"interrupted"};e=S.entry.text,n=S.entry.attachments,this.pendingUserSeq=S.entry.seq}for(let A of ms(x.filter((C)=>C.raw))){if(A.result)continue;let{body:C,raw:P}=gP(A.call);this.append(C,P)}if(!S&&this.waitingForInput())return{reason:"waiting_user"};let T=this.records.findLast((A)=>A.entry.seq>g&&A.raw)?.raw;if(!S&&T?.role==="assistant")return _h(T);if(!S&&!T&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!c)throw Error(`unknown model ${this.row.model}`);let y=await this.prepareAgent(c,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let x=this.pendingSteers.shift();if(x)y.steer(x)}return await R$(this,this.lease,this.setup,y,c,e,n,p.signal,i!==void 0&&e===void 0),_h(this.records.findLast((x)=>x.entry.seq>g&&x.raw?.role==="assistant")?.raw)}).then((y)=>p.signal.aborted?{reason:"aborted"}:y,(y)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(y)}).then(async(y)=>{try{if(!this.suspended&&y.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())y={reason:"waiting_user"};if(y.reason!=="interrupted")y=await this.lease?.invoke("run.end",{reason:y.reason,error:y.error},this)??y}}catch(x){y={reason:"error",error:String(x)}}finally{try{await this.lease?.release()}catch(x){y={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",...y});let x=bn(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 k$(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=hP({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((g)=>!this.pendingSteers.includes(g.raw)).flatMap((g)=>g.raw?[g.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??pg,captureRequest:(g)=>{this.lastRequestSnapshot=g},captureResponse:(g)=>{this.lastResponseSnapshot=g},steerConsumed:(g)=>this.markSteerConsumed(g),hooks:{tools:p,...A$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,c),message:(g,y)=>{if(this.suspended&&y.role==="assistant"&&(y.stopReason==="aborted"||y.stopReason==="error"))return;if(y.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,y);let x=this.loaded?.find((b)=>b.entry.seq===this.pendingUserSeq);if(x)x.raw=y;this.pendingUserSeq=void 0;return}if(y.role==="assistant")this.context.calibrate(y);this.append(g,y)},draft:(g)=>{this.draftParts=g,this.events.draft(g)}}})}return this.agent}notice(e,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=bn(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,g={entry:{type:"compaction",through:e,partial:n,seq:this.seq+1,time:0}},y=ke([...this.records,g],i,c,{cwd:this.cwd}).tokens;return{before:p,after:y}}compact(){this.assertWritable();let e=iu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,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 gG(e,n){let c=(e.trim()||n?.map((p)=>p.name).join(" ")||"").split(`
290
- `)[0]?.trim()??"";return c.length>40?`${c.slice(0,40)}\u2026`:c}var M$=new Set(["user","assistant","tool_result","run","compaction"]),yG=new Set(["user","assistant","toolResult"]);function v$(e,n,i){return{format:Xl,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...i?{project:i}:{},records:n.filter((c)=>M$.has(c.entry.type)).map((c)=>c.raw===void 0?{entry:c.entry}:{entry:c.entry,raw:c.raw})}}function No(e){if(!gr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Xl)return xG(e);if(gr(e.info)&&Array.isArray(e.messages))return bG(e);throw new t("\u65E0\u6CD5\u8BC6\u522B\u7684\u4F1A\u8BDD\u6587\u4EF6\uFF1A\u53EA\u652F\u6301 Basalt \u5BFC\u51FA\u548C OpenCode \u7684 `opencode export` \u6587\u4EF6")}function xG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let n=e.session;if(!gr(n))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let i=0,c=e.records.flatMap((p,g)=>{let y=`records[${g}]`;if(!gr(p)||!gr(p.entry))throw new t(`${y} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let x=p.entry;if(x.type==="notice_pending"||x.type==="extension")return[];if(typeof x.type!=="string"||!M$.has(x.type))throw new t(`${y} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(x.type)}`);let{seq:b,time:S}=x;if(typeof b!=="number"||!Number.isSafeInteger(b)||b<=i)throw new t(`${y} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof S!=="number"||!Number.isFinite(S))throw new t(`${y} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=b,IG(x,y);let T=p.raw;if(T!==void 0&&!(gr(T)&&typeof T.role==="string"&&yG.has(T.role)))throw new t(`${y} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:x,...T===void 0?{}:{raw:T}}]});return{title:Lr(n.title),model:typeof n.model==="string"?n.model:void 0,thinking:typeof n.thinking==="string"?n.thinking:null,todos:Array.isArray(n.todos)?n.todos.flatMap(_$):[],created:zs(n.created)??Date.now(),updated:zs(n.updated)??Date.now(),needsRaw:!1,records:c}}function IG(e,n){let i=(c)=>new t(`${n}\uFF08${String(e.type)}\uFF09${c}`);switch(e.type){case"user":if(typeof e.text!=="string")throw i("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw i("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw i("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&_g.includes(e.reason)))throw i("\u7684 state/reason \u4E0D\u5408\u6CD5");return;case"compaction":if(typeof e.through!=="number"||typeof e.partial!=="boolean")throw i("\u7F3A\u5C11 through \u6216 partial");return}}function bG(e){let n=e.info,i=gr(n.time)?n.time:{},c=gr(n.model)?n.model:void 0,p=e.messages.filter(gr).sort(EG),g=[],y=0,x=0,b=(X,j)=>{x=Math.max(x,j??x),y+=1,g.push({entry:{...X,seq:y,time:x}})},S=!1,T=(X,j)=>{if(!S)return;S=!1,b({type:"run",state:"end",reason:X,...j?{error:j}:{}},void 0)};for(let X of p){let j=gr(X.info)?X.info:{},V=Array.isArray(X.parts)?X.parts.filter(gr):[],J=zs(gr(j.time)?j.time.created:void 0);if(j.role==="user"){T("done");let ee=SG(V);if(!ee)continue;b({type:"run",state:"start"},J),b(ee,J),S=!0}else if(j.role==="assistant"){if(!S)b({type:"run",state:"start"},J),S=!0;RG(j,V,b);let ee=O$(j.error);if(ee)T(ee.aborted?"aborted":"error",ee.aborted?void 0:ee.message)}}T("done");let A=p.findLast((X)=>gr(X.info)&&X.info.role==="assistant"),C=gr(A?.info)?A.info:void 0,P=Lr(c?.providerID)||Lr(C?.providerID),L=Lr(c?.id)||Lr(C?.modelID),q=P&&L?`${P}/${L}`:void 0;return{title:Lr(n.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(_$):[],created:zs(i.created)??g[0]?.entry.time??Date.now(),updated:zs(i.updated)??g.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:g}}function EG(e,n){let i=(p)=>(gr(p.info)&&gr(p.info.time)?zs(p.info.time.created):void 0)??0,c=(p)=>gr(p.info)?Lr(p.info.id):"";return i(e)-i(n)||c(e).localeCompare(c(n))}function SG(e){let n=e.filter((c)=>c.type==="text"&&c.synthetic!==!0&&c.ignored!==!0).map((c)=>Lr(c.text)).join(`
291
-
292
- `),i=e.flatMap((c)=>c.type==="file"?wG(c):[]);if(!n.trim()&&i.length===0)return;return{type:"user",text:n,...i.length?{attachments:i}:{}}}function wG(e){let n=Lr(e.mime)||"application/octet-stream",i=Lr(e.filename)||"file",c=Lr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(c);if(p){let g=p[3]??"";if(n.startsWith("image/"))return[{name:i,mimeType:n,kind:"image",data:p[2]?g:btoa(g)}];if(n.startsWith("text/")||n==="application/json"){let y=p[2]?new TextDecoder().decode(Uint8Array.from(atob(g),(x)=>x.charCodeAt(0))):g;return[{name:i,mimeType:n,kind:"text",data:y}]}return[]}if(c.startsWith("file://"))try{return[{name:i,mimeType:n,kind:"path",data:decodeURIComponent(new URL(c).pathname)}]}catch{return[]}return[]}function TG(e){let n=[[]];for(let i of e){if(i.type==="step-start"){if(n.at(-1)?.length)n.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")n.at(-1)?.push(i)}return n.filter((i)=>i.length>0)}function RG(e,n,i){let c=`${Lr(e.providerID)}/${Lr(e.modelID)}`,p=O$(e.error),g=TG(n);g.forEach((y,x)=>{let b=y.flatMap((A)=>{if(A.type==="reasoning")return Lr(A.text).trim()?[{type:"thinking",text:Lr(A.text)}]:[];if(A.type==="text")return A.ignored!==!0&&Lr(A.text).trim()?[{type:"text",text:Lr(A.text)}]:[];return[{type:"tool_call",id:$$(A.callID),name:Lr(A.tool),input:gr(A.state)&&gr(A.state.input)?A.state.input:{}}]}),S=x===g.length-1,T=kG(y);i({type:"assistant",parts:b,model:c,...S&&p&&!p.aborted?{error:p.message}:{}},T);for(let A of y){if(A.type!=="tool")continue;let C=gr(A.state)?A.state:{},P=C.status==="error",L=C.status==="pending"||C.status==="running",q=P?[Lr(C.output),Lr(C.error)].filter(Boolean).join(`
293
- `):L?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Lr(C.output);i({type:"tool_result",callID:$$(A.callID),name:Lr(A.tool),output:q,isError:P||L},zs(gr(C.time)?C.time.end:void 0))}})}function $$(e){return Lr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function O$(e){if(!gr(e))return;let n=gr(e.data)?e.data:{};return{message:Lr(n.message)||Lr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function kG(e){for(let n of e){let i=gr(n.time)?zs(n.time.start):gr(n.state)?AG(n.state):void 0;if(i!==void 0)return i}return}function AG(e){return gr(e.time)?zs(e.time.start):void 0}function _$(e){if(!gr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function L$(e,n){let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:c})=>{let p=c.time;switch(c.type){case"user":return{entry:c,raw:CG(c,p)};case"assistant":{let g=c.parts.flatMap((x)=>{if(x.type==="text")return[{type:"text",text:x.text}];if(x.type==="thinking")return[];return[{type:"toolCall",id:x.id,name:x.name,arguments:PG(x.input)}]}),y=g.some((x)=>x.type==="toolCall");return{entry:c,raw:{role:"assistant",content:g,api:n.api,provider:n.provider,model:n.id,usage:i,stopReason:c.error?"error":y?"toolUse":"stop",...c.error?{errorMessage:c.error}:{},timestamp:p}}}case"tool_result":return{entry:c,raw:{role:"toolResult",toolCallId:c.callID,toolName:c.name,content:[{type:"text",text:c.output}],isError:c.isError,timestamp:p}};default:return{entry:c}}})}function CG(e,n){let i=(e.attachments??[]).flatMap((g)=>g.kind==="path"?[`<file path=${JSON.stringify(g.data)} />`]:g.kind==="text"?[`<file name=${JSON.stringify(g.name)}>
294
- ${g.data}
295
- </file>`]:[]),c=(e.attachments??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),p=[...i,...e.text.trim()?[e.text]:[]].join(`
296
-
297
- `);return{role:"user",content:c.length?[{type:"text",text:p},...c]:p,timestamp:n}}function gr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e==="string"?e:""}function zs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function PG(e){return gr(e)?e:{}}function or(e,n){let i=e.at(-1)?.entry.seq??0,c,p,g;for(let{entry:S}of e){if(S.type==="run"&&S.state==="start")c=S.seq;if(S.seq===n)if(S.type==="user"&&!S.notices)i=(c??S.seq)-1;else p=c;if(S.type==="run"&&S.state==="end"){if(p!==void 0&&c===p)g=S.seq;c=void 0}}let y=e.find((S)=>S.entry.seq===n)?.entry;if(n!==void 0&&!y)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(y&&!(y.type==="user"&&!y.notices)){if(p!==void 0&&g===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=g??y.seq}else if(n===void 0&&c!==void 0)i=e.findLast(({entry:S})=>S.type==="run"&&S.state==="end")?.entry.seq??0;let x=e.filter(({entry:S})=>S.seq<=i&&(S.type!=="compaction"||S.through<=i)),b=new Map(x.map(({entry:S},T)=>[S.seq,T+1]));return x.map((S,T)=>{let A=structuredClone(S);if(A.entry.seq=T+1,A.entry.type==="compaction"){let C=A.entry.through,P=x.findLast(({entry:L})=>L.seq<=C);A.entry.through=P?b.get(P.entry.seq)??0:0}return A})}function ir(e){let n=new Map,i=[];for(let c of e){if(c.type==="assistant"){for(let y of c.parts)if(y.type==="tool_call"&&y.name==="todo")n.set(y.id,y.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 g=[];for(let y of p.todos){if(!y||typeof y!=="object"||!("content"in y)||typeof y.content!=="string"||!("status"in y)||y.status!=="pending"&&y.status!=="in_progress"&&y.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");g.push({content:y.content,status:y.status})}i=g}return i}import{Buffer as Nl}from"buffer";import{createHash as N$}from"crypto";import{isDeepStrictEqual as Ll}from"util";var qi="@blob:";function hu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Dl(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(qi)){let g=Nl.from(p.data,"base64");if(g.byteLength>0&&g.toString("base64")===p.data){let y=N$("sha256").update(g).digest("hex");return n.put(y,p.mimeType,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),i=!0,{...p,data:`${qi}${y}`}}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(qi)){let g=Nl.from(p.data,"base64");if(g.byteLength>0&&g.toString("base64")===p.data){let y=N$("sha256").update(g).digest("hex");return n.put(y,p.mimeType,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),i=!0,{...p,data:`${qi}${y}`}}}return p});if(!i)return e;return{...e,images:c}}return e}function Ea(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.startsWith(qi)){let g=p.data.slice(qi.length),y=n.get(g);if(y!==void 0)return i=!0,{...p,data:Nl.from(y.buffer,y.byteOffset,y.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.startsWith(qi)){let g=p.data.slice(qi.length),y=n.get(g);if(y!==void 0)return i=!0,{...p,data:Nl.from(y.buffer,y.byteOffset,y.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,images:c}}return e}function Vc(e,n){if(!hu(n))return n;if(e.type==="user"){let{merged:i,images:c}=qc(e.text,e.attachments),p=c.length>0?[{type:"text",text:i},...c]:i,g=Object.keys(n),{role:y,timestamp:x,content:b}=n;if(g.length===3&&y==="user"&&typeof x==="number"&&"content"in n&&Ll(b,p))return{role:"user",timestamp:x};return n}if(e.type==="tool_result"){let{role:i,toolCallId:c,toolName:p,isError:g,timestamp:y,content:x}=n;if(i!=="toolResult"||c!==e.callID||typeof p!=="string"||g!==e.isError||typeof y!=="number")return n;let b=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in n?!Ll(n.details,e.meta):e.meta!==void 0)return n;let{role:T,toolCallId:A,toolName:C,content:P,details:L,isError:q,timestamp:X,...j}=n;if(Ll(x,b))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:y};if(Array.isArray(x)){let V=e.images??[],J=0,ee=!0,ie=x.map((H)=>{if(hu(H)&&H.type==="image"){let ce=V[J++],fe=Object.keys(H);if(ce&&fe.length===3&&H.mimeType===ce.mimeType&&H.data===ce.data)return{type:"image",mimeType:H.mimeType};ee=!1}return H});if(ee&&J===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:ie,...j,timestamp:y}}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,g=c.map((y,x)=>{let b=e.parts[x];if(hu(y)){if(y.type==="text"&&b?.type==="text"&&y.text===b.text){p=!0;let S={...y};return delete S.text,S}if(y.type==="thinking"&&b?.type==="thinking"&&y.thinking===b.text){p=!0;let S={...y};return delete S.thinking,S}if(y.type==="toolCall"&&b?.type==="tool_call"&&y.id===b.id&&y.name===b.name&&"arguments"in y&&Ll(y.arguments,b.input)){p=!0;let S={...y};return delete S.id,delete S.name,delete S.arguments,S}}return y});if(!p)return n;return{...n,content:g}}return n}function lg(e,n){if(!hu(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:g}=qc(e.text,e.attachments);return{role:"user",content:g.length>0?[{type:"text",text:p},...g]: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:g,toolName:y,content:x,timestamp:b,...S}=n,T;if(Array.isArray(x)){let A=e.images??[],C=0;T=x.map((P)=>{if(hu(P)&&P.type==="image"&&!("data"in P)){let L=A[C++];if(L)return{type:"image",mimeType:P.mimeType,data:L.data}}return P})}else T=[{type:"text",text:e.output},...(e.images??[]).map((A)=>({type:"image",mimeType:A.mimeType,data:A.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof y==="string"?y:e.name,content:T,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...S,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,g=c.map((y,x)=>{let b=e.parts[x];if(hu(y)){if(y.type==="text"&&!("text"in y)&&b?.type==="text"){p=!0;let{type:S,...T}=y;return{type:S,text:b.text,...T}}if(y.type==="thinking"&&!("thinking"in y)&&b?.type==="thinking"){p=!0;let{type:S,...T}=y;return{type:S,thinking:b.text,...T}}if(y.type==="toolCall"&&!("arguments"in y)&&b?.type==="tool_call"){p=!0;let{type:S,...T}=y;return{type:S,id:b.id,name:b.name,arguments:structuredClone(b.input),...T}}}return y});if(!p)return n;return{...n,content:g}}return n}function D$(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(b,S,T){n.run(b,S,T)},get(b){return i.get(b)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),g=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),y=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),x=0;return e.transaction(()=>{for(let b of p){let S;try{S=JSON.parse(b.body)}catch{continue}let T=Ea(S,c),A=Dl(T,c),C=A===S?b.body:JSON.stringify(A),P=b.raw;if(b.raw!==null)try{let L=JSON.parse(b.raw),q=lg(T,L),X=Vc(T,q);P=JSON.stringify(X)}catch{P=b.raw}if(C!==b.body)g.run(C,P,b.session_id,b.seq),x++;else if(P!==b.raw)y.run(P,b.session_id,b.seq),x++}})(),x}import{Database as $G}from"bun:sqlite";import{chmodSync as q$,existsSync as MG,mkdirSync as vG}from"fs";import{dirname as OG}from"path";var dg=[`
298
- CREATE TABLE projects (
299
- id TEXT PRIMARY KEY,
300
- name TEXT NOT NULL,
301
- directory TEXT NOT NULL UNIQUE,
302
- instructions TEXT NOT NULL DEFAULT '',
303
- created INTEGER NOT NULL,
304
- updated INTEGER NOT NULL
305
- );
306
- CREATE TABLE automations (
307
- id TEXT PRIMARY KEY,
308
- project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
309
- name TEXT NOT NULL,
310
- prompt TEXT NOT NULL,
311
- schedule TEXT NOT NULL,
312
- model TEXT NOT NULL,
313
- enabled INTEGER NOT NULL,
314
- created INTEGER NOT NULL,
315
- updated INTEGER NOT NULL,
316
- next_run INTEGER,
317
- last_run INTEGER,
318
- last_session_id TEXT
319
- );
320
- CREATE TABLE sessions (
321
- id TEXT PRIMARY KEY,
322
- project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
323
- automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
324
- title TEXT NOT NULL DEFAULT '',
325
- model TEXT NOT NULL,
326
- todos TEXT NOT NULL DEFAULT '[]',
327
- created INTEGER NOT NULL,
328
- updated INTEGER NOT NULL
329
- );
330
- CREATE INDEX sessions_project ON sessions(project_id);
331
- CREATE TABLE entries (
332
- session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
333
- seq INTEGER NOT NULL,
334
- time INTEGER NOT NULL,
335
- body TEXT NOT NULL,
336
- raw TEXT,
337
- PRIMARY KEY (session_id, seq)
338
- ) WITHOUT ROWID;
339
- `,"","","",`
340
- ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
341
- ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
342
- ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
343
- CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
344
- ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
345
- ALTER TABLE sessions ADD COLUMN notice_floor_seq INTEGER NOT NULL DEFAULT 0;`,"ALTER TABLE sessions ADD COLUMN truncation_epoch INTEGER NOT NULL DEFAULT 0;",`CREATE TABLE plugin_kv (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
346
- PRIMARY KEY (namespace, key));
347
- CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
348
- PRIMARY KEY (namespace, version));
349
- CREATE TABLE plugin_settings (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL);`,"ALTER TABLE sessions ADD COLUMN thinking TEXT;","ALTER TABLE sessions ADD COLUMN metadata TEXT;","ALTER TABLE sessions ADD COLUMN archived_at INTEGER;",`CREATE TABLE search_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, seq INTEGER NOT NULL);
350
- CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
351
- INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
352
- END;
353
- CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
354
- INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
355
- END;
356
- CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
357
- INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
358
- END;
359
- CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
360
- INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
361
- END;
362
- CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
363
- INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
364
- END;
365
- CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
366
- INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
367
- END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
368
- WHERE json_extract(body,'$.type')='compaction';
369
- CREATE TABLE IF NOT EXISTS blobs (
370
- hash TEXT PRIMARY KEY,
371
- mime TEXT NOT NULL,
372
- data BLOB NOT NULL
373
- ) WITHOUT ROWID;
374
- CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`,"ALTER TABLE projects ADD COLUMN position INTEGER NOT NULL DEFAULT 0;","ALTER TABLE projects ADD COLUMN closed_at INTEGER;"];var _G=[20,50,100,200,400,800];function LG(e){if(!e||typeof e!=="object")return!1;let n="code"in e&&typeof e.code==="string"?e.code:"";if(n==="SQLITE_BUSY"||n.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let c="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(c)}function fg(e){let n=0;while(!0)try{return e()}catch(i){let c=_G[n];if(c===void 0||!LG(i))throw i;n++,Bun.sleepSync(c)}}function F$(e,n){if(e!==":memory:")vG(OG(e),{recursive:!0});let i=new $G(e,{create:!0,strict:!0}),c=(g,y=!0)=>new Proxy(function(...x){return Reflect.apply(g,this,x)},{apply(x,b,S){vs();let T=n.length===0&&!i.inTransaction,A=y?Reflect.get(g,"immediate"):void 0,C=()=>{let P=[];n.push(P);let L=!1;try{let q=typeof A==="function"?Reflect.apply(A,g,S):Reflect.apply(x,b,S);return L=!0,q}finally{n.pop();let q=n.at(-1);if(L&&q)q.push(...P);else for(let X of P)if(L)X.commit();else X.rollback()}};return T?fg(C):C()},get(x,b){let S=Reflect.get(g,b);if(["deferred","immediate","exclusive"].includes(String(b))&&typeof S==="function")return c(S,!1);return S}}),p=new Proxy(i,{get(g,y){let x=Reflect.get(g,y,g);if(typeof x!=="function")return x;return(...b)=>{vs();let A=(y==="run"||y==="exec")&&n.length===0&&!i.inTransaction?fg(()=>Reflect.apply(x,g,b)):Reflect.apply(x,g,b);if(y==="transaction"&&typeof A==="function")return c(A,!0);if(y!=="query"&&y!=="prepare")return A;if(!A||typeof A!=="object")throw Error("Invalid SQL statement");return new Proxy(A,{get(C,P,L){let q=Reflect.get(C,P,C);if(typeof q!=="function")return q;return(...X)=>{vs();let J=(P==="run"||P==="get"||P==="all"||P==="values")&&n.length===0&&!i.inTransaction?fg(()=>Reflect.apply(q,C,X)):Reflect.apply(q,C,X);return J===C?L:J}}})}}});if(e!==":memory:")q$(e,384);if(p.run("PRAGMA journal_mode = WAL"),p.run("PRAGMA synchronous = FULL"),p.run("PRAGMA foreign_keys = ON"),p.run("PRAGMA busy_timeout = 10000"),NG(p),p.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),p.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let g of["-wal","-shm"]){let y=e+g;if(MG(y))q$(y,384)}return p}function NG(e,n=dg){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]??"",g=Array.isArray(p)?p:c>=4?DG(p):[p];for(let y of g)try{if(y.trim())e.run(y)}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 DG(e){let n=[],i=0,c=0,p=[],g=!1,y=0,x=(b)=>{let S=e.slice(i,b).trim();if(S)n.push(S);i=b+1,p=[],g=!1,y=0};while(c<e.length){let b=e[c];if(b==="'"||b==='"'||b==="`"||b==="["){let S=b==="["?"]":b;c++;while(c<e.length)if(e[c]===S)if(S!=="]"&&e[c+1]===S)c+=2;else break;else c++;c++;continue}if(b==="-"&&e[c+1]==="-"){let S=e.indexOf(`
375
- `,c);c=S===-1?e.length:S+1;continue}if(b==="/"&&e[c+1]==="*"){let S=e.indexOf("*/",c+2);c=S===-1?e.length:S+2;continue}if(/[A-Za-z_]/.test(b)){let S=c+1;while(S<e.length&&/[A-Za-z0-9_$]/.test(e[S]))S++;let T=e.slice(c,S).toUpperCase();if(p.length<3)p.push(T),g=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(g){if(T==="BEGIN"||T==="CASE"&&y>0)y++;else if(T==="END"&&y>0)y--}c=S;continue}if(b===";"&&y===0)x(c);c++}return x(e.length),n}var ql=({position:e,closed_at:n,...i})=>({...i,closedAt:n??null}),Fl=(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 jl{path;plugins;entryTransactions=[];db;blobs;constructor(e){this.path=e;this.db=F$(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 position, updated DESC").all().map(ql)}project(e){let n=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return n?ql(n):void 0}projectByDirectory(e){let n=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return n?ql(n):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let n=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[i,c]of e.entries())n.run(i,c)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){this.db.query("DELETE FROM projects WHERE id = ?").run(e)}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(Fl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(Fl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(Fl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((n)=>n.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,n,i){this.insertSessionWithRecords(n,or(this.records(e),i))}insertSessionWithRecords(e,n){this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(n.at(-1)?.entry.seq??0,e.id);let i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:c,raw:p}of n){let{seq:g,time:y,...x}=c,b=x,S=Dl(b,this.blobs),T=p===void 0?null:JSON.stringify(Vc(b,p));i.run(e.id,g,y,JSON.stringify(S),T)}})()}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){vs();let p=this.plugins,g=p?.pinEntry(i),y;try{return y=this.db.transaction(()=>{let x=Math.max(n??0,this.lastSeq(e)+1),S=(g&&p?p.beforeEntry(g,i,e,x):void 0)??i,T=JSON.stringify(S),A=g?JSON.parse(T):S,C={...A,seq:x,time:Date.now()},P=Dl(A,this.blobs),L=P===A&&!g?T:JSON.stringify(P),q=c===void 0?null:JSON.stringify(Vc(A,c));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,x,C.time,L,q),C.type==="user"&&!(("notices"in C)&&C.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(C.time,e);return C})(),y}finally{if(g&&p){let x={commit:()=>p.finishEntry(g,e,y),rollback:()=>p.finishEntry(g,e)},b=this.entryTransactions.at(-1);if(b)b.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=Ea(JSON.parse(c.body),this.blobs),g=Vc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(g),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)=>({...Ea(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)=>({...Ea(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=(b)=>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,b),p=c(n),g=p?.type==="run"&&p.state==="start"?n+1:n;if(g>=i)return i;let y=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,g,g);if(!y)return i;if(y.end)return y.seq;let x=c(y.seq-1);return x?.type==="run"&&x.state==="start"&&y.seq-1>g?y.seq-2:y.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 g=Math.min(Math.max(1,n),p),y=this.alignToUser(e,Math.max(1,g-i)),x=this.alignToTurnEnd(e,Math.min(p,g+c));return this.window(e,y,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 g=this.alignToTurnEnd(e,Math.min(c,p+i-1));return this.window(e,p,g,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"),g=p?.type==="compaction"?p.through+1:1,y=Math.max(1,c-i+1,Math.min(g,c-n+1));return this.alignToUser(e,y)}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=Ea(JSON.parse(i.body),this.blobs);return{entry:{...c,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:lg(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?{...Ea(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 g=await p.invoke("notice.enqueue",n,this.plugins.runtime.get(e));if(g===null)return!1;n={...g,dedupeKey:c.dedupeKey,wake:c.wake&&g.wake,recovery:c.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==i)return!1;if(this.entries(e).some((x)=>x.type==="notice_pending"&&x.notice.dedupeKey===n.dedupeKey||x.type==="user"&&x.notices?.some((b)=>b.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 g of i)if(g.type==="user"&&g.notices)for(let y of g.notices)c.add(y.dedupeKey);else if(g.type==="extension"&&g.namespace==="basalt.notice"&&g.kind==="discarded"&&g.payload&&typeof g.payload==="object"&&"dedupeKey"in g.payload&&typeof g.payload.dedupeKey==="string")c.add(g.payload.dedupeKey);let p=[];for(let g of i)if(g.type==="notice_pending"&&!c.has(g.notice.dedupeKey))p.push(g.notice);return p}}function ue(e){let n=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(n).toString("base64url")}`}import{existsSync as qG,readdirSync as U$,statSync as B$}from"fs";import{join as G$}from"path";function Jc(e){try{return B$(e).size}catch{return 0}}function K$(e){try{return Math.round(B$(e).mtimeMs)}catch{return}}function H$(e){let n=0,i=0;try{let c=U$(e,{withFileTypes:!0});for(let p of c){let g=G$(e,p.name);if(p.isDirectory()){let y=H$(g);n+=y.bytes,i+=y.files}else if(p.isFile())n+=Jc(g),i+=1}}catch{return{bytes:0,files:0}}return{bytes:n,files:i}}function FG(e){if(!qG(e))return[];try{return U$(e,{withFileTypes:!0}).flatMap((n)=>{let i=G$(jG(e),n.name),c=K$(i);if(n.isDirectory()){let p=H$(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:Jc(i),...c!==void 0?{modified:c}:{}}];return[]}).sort((n,i)=>i.bytes-n.bytes||n.name.localeCompare(i.name))}catch{return[]}}function jG(e){return e}function Vs(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 j$(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 UG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},BG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function GG(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 g of c)i.set(g.name,g.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let g of p){let y=i.get(g.name)??g.name;if(y.startsWith("sqlite_autoindex_")){let b=y.slice(17),S=b.lastIndexOf("_");if(S>0)y=b.slice(0,S)}let x=n.get(y)??{bytes:0,pages:0};n.set(y,{bytes:x.bytes+(Number(g.bytes)||0),pages:x.pages+(Number(g.pages)||0)})}}catch{}return n}function KG(e){let n=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
376
- count(*) AS total,
377
- sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
378
- sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
379
- sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
380
- sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
381
- FROM sessions`).get(),c=e.db.query(`SELECT
382
- count(*) AS total,
383
- coalesce(sum(octet_length(body)), 0) AS body_bytes,
384
- coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
385
- min(time) AS oldest_time,
386
- max(time) AS newest_time
387
- FROM entries`).get(),g=e.db.query(`SELECT
388
- coalesce(json_extract(body, '$.type'), 'unknown') AS type,
389
- count(*) AS count,
390
- coalesce(sum(octet_length(body)), 0) AS body_bytes,
391
- coalesce(sum(octet_length(raw)), 0) AS raw_bytes
392
- FROM entries
393
- GROUP BY type
394
- ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((b)=>({type:String(b.type||"unknown"),count:Number(b.count)||0,bodyBytes:Number(b.body_bytes)||0,rawBytes:Number(b.raw_bytes)||0})),y=g.find((b)=>b.type==="compaction")?.count??0,x=[];try{let b=new Map,S=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let C of S)b.set(C.namespace,Number(C.max_ver)||0);let T=e.db.query(`SELECT
395
- namespace,
396
- count(*) AS keys,
397
- coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
398
- FROM plugin_kv
399
- GROUP BY namespace
400
- ORDER BY bytes DESC, keys DESC`).all(),A=new Set;for(let C of T){A.add(C.namespace);let P=b.get(C.namespace);x.push({namespace:C.namespace,keys:Number(C.keys)||0,bytes:Number(C.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[C,P]of b.entries())if(!A.has(C))x.push({namespace:C,keys:0,bytes:0,migrationVersion:P})}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:y,...c?.oldest_time?{oldestEntryTime:Number(c.oldest_time)}:{},...c?.newest_time?{newestEntryTime:Number(c.newest_time)}:{},entryTypes:g,pluginNamespaces:x}}function Ul(e,n){let i=Vs(e,"page_size"),c=Vs(e,"page_count"),p=Vs(e,"freelist_count"),g=e.db.query("PRAGMA journal_mode").get(),y=e.db.query("SELECT sqlite_version() AS v").get(),x=Vs(e,"synchronous"),b=Vs(e,"auto_vacuum"),S=Vs(e,"cache_size"),T=S<0?Math.abs(S)*1024:S*i,A=Vs(e,"foreign_keys")===1,C=Vs(e,"busy_timeout"),P=j$(e,"encoding")??"UTF-8",L=j$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?K$(e.path):void 0,X=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),j=GG(e),V=FG(n);return{dataDir:n,databasePath:e.path,dataBytes:V.reduce((J,ee)=>J+ee.bytes,0),database:{size:Jc(e.path),walSize:Jc(`${e.path}-wal`),shmSize:Jc(`${e.path}-shm`),sqliteVersion:y?.v??"unknown",journalMode:g?.journal_mode??"unknown",synchronous:UG[x]??String(x),foreignKeys:A,busyTimeout:C,encoding:P,autoVacuum:BG[b]??String(b),cacheSizeBytes:T,pageSize:i,pageCount:c,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Vs(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:L},analytics:KG(e),entries:V,tables:X.map(({name:J,sql:ee})=>{let ie=J.replaceAll('"','""'),H=e.db.query(`SELECT count(*) AS count FROM "${ie}"`).get().count,ce=e.db.query(`PRAGMA table_info("${ie}")`).all().map((se)=>se.name),fe=e.db.query(`PRAGMA index_list("${ie}")`).all().length,_e=Boolean(ee&&/WITHOUT\s+ROWID/i.test(ee)),be=j.get(J);return{name:J,rows:H,...be?{bytes:be.bytes,pages:be.pages}:{},indexes:fe,columns:ce,withoutRowid:_e}})}}function HG(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 g of i)for(let y of g.body.matchAll(/@blob:([0-9a-f]{64})/g)){let x=y[1];if(x)c.add(x)}let p=[];for(let g of n)if(!c.has(g.hash))p.push(g.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let g=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let y of p)g.run(y)})()}catch{return 0}return p.length}function W$(e,n,i){let c=Ul(e,n);if(i.vacuum)D$(e.db),HG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:c,after:Ul(e,n)}}var WG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Bl{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(WG.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 z$(e,n){let i=Qr(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 V$(e,n){let c=(await e.options.models.getAvailable().catch(()=>[])).map((g)=>({...z$(rt(g),g),available:!0})),p=new Set(c.map((g)=>g.id));for(let g of[n,...e.list(!0,{archive:"all"}).map((y)=>y.model)]){if(p.has(g))continue;let y=bn(e.options.models,g);if(!y)continue;p.add(g),c.push({...z$(g,y),available:!1})}return{models:c}}function J$(e,n){if(typeof n!=="string"||!bn(e.options.models,n))throw new t(`unknown model ${n}`);return n}import{existsSync as zG,statSync as VG}from"fs";import{basename as JG,resolve as QG}from"path";class hg{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 f("no such project");return n}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let n=QG(e.directory.trim());if(!zG(n)||!VG(n).isDirectory())throw new t(`${n} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(n);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let c=Date.now(),p={id:ue("p"),name:e.name?.trim()||JG(n)||n,directory:n,instructions:e.instructions??"",created:c,updated:c,closedAt:null};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}:{},...typeof n.closed==="boolean"?{closedAt:n.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(c);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:c}),c}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let n=new Set(this.runtime.store.projects().map((p)=>p.id)),i=new Set(e);if(!(i.size===e.length&&i.size===n.size&&e.every((p)=>n.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let 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 yK,readFileSync as xK}from"fs";import{homedir as IK}from"os";import{join as gu}from"path";var rM=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),XG={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"]},YG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),xg={'"':['"'],"\u201C":["\u201D",'"']},gg=(e)=>e!==void 0&&/\s/.test(e),nM=(e)=>[...new Set(e)],Qc=(e)=>[...e].length;var ZG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function eK(e,n){let i=e.trim().toLowerCase(),c=new Date(n),p=c.getFullYear(),g=c.getMonth(),y=c.getDate();if(i==="today")return{start:new Date(p,g,y).getTime(),end:new Date(p,g,y+1).getTime()};if(i==="yesterday")return{start:new Date(p,g,y-1).getTime(),end:new Date(p,g,y).getTime()};let x=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(x)return{start:n-Number(x[1])*ZG[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 b=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!b)return null;let S=Number(b[1]),T=Number(b[3]);if(T<1||T>12)return null;if(b[4]===void 0){if(b[5]!==void 0)return null;return{start:new Date(S,T-1,1).getTime(),end:new Date(S,T,1).getTime()}}let A=Number(b[4]),C=Number(b[5]??0),P=Number(b[6]??0),L=Number(b[7]??0);if(C>23||P>59||L>59)return null;let q=new Date(S,T-1,A,C,P,L);if(q.getMonth()!==T-1||q.getDate()!==A)return null;if(b[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(S,T-1,A+1).getTime()}}var tK=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Ig=(e,n)=>e===void 0?n:n===void 0?e:Math.max(e,n),bg=(e,n)=>e===void 0?n:n===void 0?e:Math.min(e,n);function yg(e,n,i,c,p,g){let y=i.trim(),x=(S,T)=>e.diagnostics.push({code:S,message:T,filter:n});if(!y)return x("empty_filter",`${n}: \u7F3A\u5C11\u53D6\u503C`);if(c&&n!=="is")return x("unsupported_negation",`-${n}: \u4E0D\u652F\u6301\u53D6\u53CD`);let b=p?[y]:y.split(",").map((S)=>S.trim()).filter(Boolean);switch(n){case"in":case"project":for(let S of b){let T=S.toLowerCase();if(n==="in"&&T==="this")e.currentSession=!0;else if(n==="in"&&T==="title")e.fields.push("title");else e.projectID.push(S)}return;case"session":for(let S of b)if(S.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(S);return;case"from":case"role":for(let S of b){let T=XG[S.toLowerCase()];if(T)e.fields.push(...T);else x("bad_filter_value",`${n}:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...b);return;case"model":e.model.push(...b);return;case"is":for(let S of b){let T=S.toLowerCase();if(T==="error")e.isError=!c;else if(T==="archived")e.archived=!c;else if(T==="compacted")e.compacted=!c;else x("bad_filter_value",`is:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let S=eK(y,g);if(!S)return x("bad_filter_value",`${n}:${y} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(n==="after")e.after=Ig(e.after,S.start);else if(n==="before")e.before=bg(e.before,S.start);else if(e.after=Ig(e.after,S.start),S.end!==void 0)e.before=bg(e.before,S.end)}}}function rK(e,n){let i={},c=(L,q)=>{let X=nM([...L??[],...q]);return X.length?X:void 0},p=c(e?.projectID,n.projectID),g=c(e?.sessionID,n.sessionID),y=c(e?.fields,n.fields),x=c(e?.tools,n.tools),b=c(e?.model,n.model);if(p)i.projectID=p;if(g)i.sessionID=g;if(y)i.fields=y;if(x)i.tools=x;if(b)i.model=b;let S=n.isError??e?.isError,T=n.archived??e?.archived,A=n.compacted??e?.compacted;if(S!==void 0)i.isError=S;if(T!==void 0)i.archived=T;if(A!==void 0)i.compacted=A;let C=Ig(e?.after,n.after),P=bg(e?.before,n.before);if(C!==void 0)i.after=C;if(P!==void 0)i.before=P;if(C!==void 0&&P!==void 0&&C>=P)n.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function Q$(e,n){let i=xg[e[n]]??['"'],c="",p=n+1;while(p<e.length){let g=e[p],y=e[p+1];if(g==="\\"&&y!==void 0&&(y==="\\"||y==='"'||y==="\u201C"||y==="\u201D")){c+=y,p+=2;continue}if(i.includes(g))return{text:c,next:p+1,closed:!0};c+=g,p++}return{text:c,next:p,closed:!1}}function X$(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 rM.has(c)?c:void 0}function Y$(e,n,i){let c=e==="word"&&!i&&Qc(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 nK(e,n){let i=[],c=e.length,p=0;while(p<c){if(gg(e[p])){p++;continue}let g=!1;if(e[p]==="-"){if(p+1>=c||gg(e[p+1])){p++;continue}g=!0,p++}if(xg[e[p]]){let P=Q$(e,p);if(p=P.next,!P.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let L=P.text.trim();if(L)i.push({kind:"term",negated:g,term:Y$("phrase",L,!1)});continue}let y=[],x;while(p<c&&!gg(e[p])){let P=e[p],L=e[p+1];if(P==="\\"&&L!==void 0&&YG.has(L)){y.push({c:L,esc:!0}),p+=2;continue}let q=xg[P]?X$(y):void 0;if(q){let X=Q$(e,p);if(p=X.next,!X.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});x={key:q,value:X.text,quoted:!0};break}y.push({c:P,esc:!1}),p++}if(x){i.push({kind:"filter",negated:g,...x});continue}let b=y.findIndex((P,L)=>L>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),S=b>0?X$(y.slice(0,b+1)):void 0;if(S){i.push({kind:"filter",negated:g,key:S,value:y.slice(b+1).map((P)=>P.c).join(""),quoted:!1});continue}if(!g&&y.length===2&&y.every((P)=>!P.esc)&&y[0]?.c==="O"&&y[1]?.c==="R"){i.push({kind:"or"});continue}let T=y[y.length-1],A=y.length>1&&T!==void 0&&!T.esc&&T.c==="*",C=(A?y.slice(0,-1):y).map((P)=>P.c).join("");if(C)i.push({kind:"term",negated:g,term:Y$("word",C,A)})}return i}var oK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function Z$(e){let n=[];return{rest:e.replace(oK,(c,p,g,y,x)=>{let b=y.toLowerCase();if(!rM.has(b))return c;let S=x.startsWith('"')&&x.length>=2;return n.push({key:b,value:S?x.slice(1,-1).replace(/\\(["\\])/g,"$1"):x,negated:g==="-",quoted:S}),p}).trim(),filters:n}}var eM={n:`
401
- `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function sK(e){let n=[...e],i=0,c=(T)=>{let A=n.slice(i,i+T).join("");if(A.length!==T||!/^[0-9a-fA-F]+$/.test(A))return;return i+=T,String.fromCodePoint(Number.parseInt(A,16))},p=()=>{let T=n[i++];if(T===void 0)return{kind:"lit",ch:"\\"};if(T in eM)return{kind:"lit",ch:eM[T]};if("dDwWsS".includes(T))return{kind:"any"};if(T==="b"||T==="B")return{kind:"zero"};if(T>="1"&&T<="9"){while(n[i]!==void 0&&/\d/.test(n[i]))i++;return{kind:"any"}}if(T==="k"||T==="p"||T==="P"){let A=n[i];if(A==="<"||A==="{"){let C=A==="<"?">":"}",P=n.indexOf(C,i);i=P<0?n.length:P+1}return{kind:"any"}}if(T==="c")return i++,{kind:"any"};if(T==="x"){let A=c(2);return A===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:A}}if(T==="u"){if(n[i]==="{"){let C=n.indexOf("}",i),P=C<0?"":n.slice(i+1,C).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return i=C+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let A=c(4);return A===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:A}}return{kind:"lit",ch:T}},g=()=>{if(n[i]==="^")i++;while(i<n.length&&n[i]!=="]")i+=n[i]==="\\"?2:1;return i++,{kind:"any"}},y=()=>{let T="capture";if(n[i]==="?"){let C=n[i+1],P=n[i+2];if(C===":")T="plain",i+=2;else if(C==="="||C==="!")T="look",i+=2;else if(C==="<"&&(P==="="||P==="!"))T="look",i+=3;else if(C==="<"){let L=n.indexOf(">",i);i=L<0?n.length:L+1}else{T="opaque";while(i<n.length&&n[i]!==":"&&n[i]!==")")i++;if(n[i]===":")i++}}let A=S();if(n[i]===")")i++;if(T==="look")return{kind:"zero"};return{kind:"group",alts:A,opaque:T==="opaque"}},x=()=>{let T=n[i],A=1,C=!0;if(T==="*"||T==="?")A=0,i++;else if(T==="+")i++;else if(T==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(n.slice(i,i+24).join(""));if(!P)return{quantified:!1,min:1};A=Number(P[1]),i+=P[0].length}else return{quantified:!1,min:1};if(n[i]==="?")i++;return{quantified:C,min:A}},b=()=>{let T=[];while(i<n.length){let A=n[i];if(A==="|"||A===")")break;i++;let C;if(A==="(")C=y();else if(A==="[")C=g();else if(A==="\\")C=p();else if(A===".")C={kind:"any"};else if(A==="^"||A==="$")C={kind:"zero"};else if(A==="*"||A==="+"||A==="?")C={kind:"zero"};else C={kind:"lit",ch:A};T.push({atom:C,...x()})}return T};function S(){let T=[b()];while(n[i]==="|")i++,T.push(b());return T}return S()}function tM(e){let n=[],i="",c=()=>{if(i)n.push([i]);i=""},p=(g)=>{for(let y of g){let x=y.atom;if(x.kind==="lit")if(y.min>=1){if(i+=x.ch,y.quantified)c()}else c();else if(x.kind==="group"&&!x.opaque&&y.min>=1)if(x.alts.length===1&&!y.quantified)p(x.alts[0]);else c(),n.push(...oM(x.alts));else c()}};return p(e),c(),n}function oM(e){if(e.length===1)return tM(e[0]);let n=[];for(let i of e){let c=tM(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!c.length)return[];n.push(c.reduce((p,g)=>Qc(g)>Qc(p)?g:p))}return[nM(n)]}var iK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function aK(e){return!/^\s*$/.test(e)&&(Qc(e)>=2||iK.test(e))}function uK(e){let n;try{n=oM(sK(e))}catch{return[]}let i=n.filter((b)=>b.every(aK)),c=i.filter((b)=>b.length===1).map((b)=>b[0]),p=i.filter((b)=>{if(b.length!==1)return!0;let S=b[0];return!c.some((T)=>T!==S&&T.includes(S))}),g=new Set,y=p.filter((b)=>{let S=JSON.stringify(b);if(g.has(S))return!1;return g.add(S),!0}),x=(b)=>Math.min(...b.map(Qc));return y.sort((b,S)=>x(S)-x(b))}function cK(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 mK(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),g="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))g="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))g="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))g="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))g="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${g}`}}}function Gl(e,n={}){let i=n.now??Date.now(),c=e.q??"",p=tK(),g=p.diagnostics,y,x=[];if(e.mode==="regex"){let q=Z$(c);for(let X of q.filters)yg(p,X.key,X.value,X.negated,X.quoted,i);y=q.rest}else{let q=Z$(c),X=/^\/([\s\S]+)\/$/.exec(q.rest);if(X){for(let j of q.filters)yg(p,j.key,j.value,j.negated,j.quoted,i);y=X[1]}else{x=[{include:[],exclude:[]}];for(let j of nK(c,g)){let V=x[x.length-1];if(j.kind==="or")x.push({include:[],exclude:[]});else if(j.kind==="filter")yg(p,j.key,j.value,j.negated,j.quoted,i);else(j.negated?V.exclude:V.include).push(j.term)}x=x.filter((j)=>j.include.length||j.exclude.length)}}let b=x.flatMap((q)=>[...q.include,...q.exclude]),S=y!==void 0?cK(y):b.some((q)=>/\p{Lu}/u.test(q.text)),T=e.caseSensitive??S,A=e.caseSensitive===void 0&&S,C,P;if(y){let q=mK(y,T);if("message"in q)P={code:"bad_regex",message:q.message};else{let X=uK(y);C={source:y,flags:q.flags,literals:X,deepScan:X.length===0}}}let L=rK(e.filters,p);return{mode:y!==void 0?"regex":"text",branches:x,...C?{regex:C}:{},filters:L,currentSession:p.currentSession,caseSensitive:T,smartCase:A,wholeWord:e.wholeWord??!1,fuzzy:x.some((q)=>q.include.some((X)=>X.fuzzy)),hasPositive:C!==void 0||x.some((q)=>q.include.length>0),hasFilters:Object.keys(L).length>0||p.currentSession,...P?{error:P}:{},diagnostics:g}}var Sg={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},sM=new WeakMap;function iM(e){let n=e.query("PRAGMA data_version").get()?.data_version??0,i=sM.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 sM.set(e,{version:n,terms:c}),c}var Eg=32,pK=1024,Xc=(e)=>`"${e.replaceAll('"','""')}"`;function lK(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 g=0;g<n.length;g++)p.push(Math.min((p[g]??0)+1,(i[g+1]??0)+1,(i[g]??0)+Number(e[c]!==n[g])));i=p}return i[n.length]??e.length}function wg(e,n){let i=gt(n.trim());if(!i||i.length>64)return[];let c=iM(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 g=i.length>=8?2:1,y=[];for(let x of c){if(Math.abs(x.t.length-i.length)>g)continue;if(lK(i,x.t)<=g)y.push(x.t);if(y.length>=8)break}return[...new Set([...p,...y])].slice(0,8)}function aM(e,n){let i=!1,c=[],p=[],g=n.filters,y=(X,j)=>{if(!j?.length)return;p.push(`${X} IN (${j.map(()=>"?").join(",")})`),c.push(...j)};if(y("s.project_id",g.projectID),g.sessionID?.length){p.push(`(${g.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let X of g.sessionID)c.push(X,X)}if(g.archived!==void 0)p.push(`s.archived_at IS ${g.archived?"NOT ":""}NULL`);let x=p.length?p.join(" AND "):"1",b=[...c];if(y("r.kind",g.fields?.map((X)=>Oe[X])),y("r.tool",g.tools),g.model?.length){p.push(`(${g.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let X of g.model)c.push(X,X)}if(g.isError!==void 0)p.push("r.err = ?"),c.push(Number(g.isError));if(g.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
402
- SELECT max(json_extract(body,'$.through')) FROM store.entries
403
- WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
404
- ),0)) = ?`),c.push(Number(g.compacted));if(g.after!==void 0)p.push("r.time >= ?"),c.push(g.after);if(g.before!==void 0)p.push("r.time < ?"),c.push(g.before);let S=e.query("SELECT v FROM meta WHERE k='layout'").get(),T=S&&JSON.parse(S.v).msg==="trigram",A=!n.hasPositive||Boolean(n.regex?.deepScan),C=(X)=>{let j=(ee)=>{let ie=gt(ee);if(!X&&T){if([...ie].length<3){let se=[...ie].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ie,`${ie}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ie);if([...ie].length===1&&se.length>Eg)se.length=Eg,i=!0;if(!se.length)return Xc("__basalt_no_short_match__");return`(${se.map((me)=>Xc(me.term)).join(" OR ")})`}return Xc(ie)}let H=/^[\p{Script=Latin}\p{N}]+$/u.test(ee)?[ie]:zo(ee),ce=H.filter((se)=>!/^[a-z0-9]{1,2}$/.test(se)),fe=ce.length?ce:H;if(!fe.length){A=!0;return}let _e=fe.map((se,me)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(se),It=fe.length>2&&me>0&&me<fe.length-1;if(qe||It){let Fe=e.query("SELECT n FROM term WHERE t=?").get(se)?.n??0;return{expression:Xc(se),frequency:Fe}}let Je=[se],Yt=0;for(let Fe of iM(e)){if(!Fe.t.includes(se))continue;if(Yt+=Fe.n,Fe.t!==se)Je.push(Fe.t);if(Je.length>=Eg){i=!0;break}}return{expression:`(${Je.map(Xc).join(" OR ")})`,frequency:Yt}});return _e.sort((se,me)=>se.frequency-me.frequency),`(${_e.slice(0,(_e[0]?.frequency??1/0)<=pK?1:2).map((se)=>se.expression).join(" AND ")})`},V=n.regex?n.regex.literals:n.branches.map((ee)=>ee.include.map((ie)=>ie.text));if(n.regex){let ee=V.map((ie)=>ie.map(j));if(ee.some((ie)=>ie.some((H)=>!H)))return;return ee.map((ie)=>`(${ie.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((ee)=>{let ie=ee.filter((H)=>!/^[a-z0-9]{1,2}$/i.test(H));return(ie.length?ie:ee).map(j)});if(J.some((ee)=>!ee.length||ee.some((ie)=>!ie)))return;return J.map((ee)=>`(${ee.join(" AND ")})`).join(" OR ")||void 0},P=C(!1),L=C(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:L,scan:A,where:p.length?p.join(" AND "):"1",bindings:c,forks:q,sessionWhere:x,sessionBindings:b,partial:i,candidateLimit:n.branches.some((X)=>X.include.length>0&&X.include.every((j)=>[...j.text].length<2))?512:void 0}}function uM(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 Kl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(Sg).map(([i,c])=>`WHEN ${Oe[i]} THEN ${c}`).join(" ")} ELSE 1 END) *
405
- (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function cM(e,n,i,c){let p=Math.max(0,c-i)/86400000;return Math.max(0.000000001,-e)*Sg[n]*(0.3+0.7/(1+p/30))}function Tg(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 kg=512;function mM(e,n,i){let c=performance.now(),p=n.partial;Ag(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[g,y]of[["fts",n.msg],["fts_out",n.out]]){if(!y)continue;let x=n.candidateLimit??2000,b=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
406
- ORDER BY ${n.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(y,n.candidateLimit?x+1:x);if(n.candidateLimit&&b.length>x)b.length=x,p=!0;else if(!n.candidateLimit&&b.length===x){let T=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
407
- AND rowid NOT IN (SELECT value FROM json_each(?))`).all(y,JSON.stringify(b.map((A)=>A.doc)));for(let A of T)b.push(A)}let S=uM(b);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
408
- FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(S))}return i?.("match",performance.now()-c),p}function pM(e,n,i,c,p){let g=performance.now();if(n.candidateLimit){let x=e.query(`
409
- SELECT r.session_id,r.seq,${Kl(c)} AS score
410
- FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
411
- ${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
412
- WHERE ${n.where} LIMIT ${n.candidateLimit+1}
413
- `).all(...n.bindings);if(x.length>n.candidateLimit)x.length=n.candidateLimit,n.partial=!0;let b=new Map;for(let S of x){let T=i?S.seq:0,A=JSON.stringify([S.session_id,T]),C=b.get(A);if(!C||S.score>C.score)b.set(A,{...S,seq:T})}return p?.("filter",performance.now()-g),[...b.values()].sort((S,T)=>T.score-S.score||(S.session_id<T.session_id?-1:Number(S.session_id>T.session_id))||T.seq-S.seq)}let y=e.query(`
414
- SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Kl(c)}) AS score
415
- FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
416
- ${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
417
- WHERE ${n.where}
418
- GROUP BY r.session_id${i?",r.seq":""}
419
- ORDER BY score DESC,r.session_id,seq DESC LIMIT ${n.candidateLimit?n.candidateLimit+1:-1}
420
- `).all(...n.bindings);return p?.("filter",performance.now()-g),y}var lM=new WeakMap,dK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
421
- SELECT id,forked_from_id,forked_from_seq FROM store.sessions
422
- WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
423
- UNION
424
- SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
425
- FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
426
- WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
427
- )`;function Ag(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(`${dK} 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();lM.set(e,new Map(i.map((c)=>[c.ancestor,c.through])))}function Rg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
428
- SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
429
- JOIN store.sessions ps ON ps.id=pr.session_id
430
- WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
431
- AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
432
- AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
433
- SELECT 1 FROM store.entries original JOIN store.entries copied
434
- ON copied.session_id=r.session_id AND copied.seq=r.seq
435
- WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
436
- ))
437
- ))`}function dM(e,n,i,c,p){let g=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let y=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,x=n.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
438
- INSERT INTO temp.search_window SELECT r.* FROM ref r ${y>4000?"INDEXED BY ref_time":""}
439
- ${x} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${n.where} AND ${Rg(n)}
440
- 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 b=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(b===c){let S=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(S)e.query(`
441
- INSERT INTO temp.search_window SELECT r.* FROM ref r ${x}
442
- WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
443
- AND ${n.where} AND ${Rg(n)} AND NOT EXISTS (
444
- SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
445
- )`).run(S.session_id,S.seq,...n.bindings,...n.forks?n.bindings:[]),b=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-g),b}function fM(e,n,i,c,p,g,y){let x=performance.now(),b=n.group==="none",S=n.sort==="recent"?"time DESC":"relevance DESC,time DESC",T=e.query(`
446
- SELECT r.session_id,${b?"r.seq":"0"} AS seq,
447
- max(${Kl(p)}) AS relevance,max(r.time) AS time
448
- FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
449
- WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
450
- GROUP BY r.session_id${b?",r.seq":""}
451
- ORDER BY ${S},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(g),c,i);return y?.("group",performance.now()-x),T}function hM(e,n,i,c,p,g){let y=performance.now(),x=p?n:{...n,forks:!1},b=e.query(`
452
- SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
453
- ${x.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
454
- WHERE r.session_id=? ${c?"AND r.seq=?":""}
455
- AND ${n.where} AND ${Rg(x)}
456
- ${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 g?.("filter",performance.now()-y),b}function Cg(e,n,i,c){if(!n.forks)return[];let p=lM.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
457
- SELECT DISTINCT r.session_id,s.title,e.body
458
- FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
459
- CROSS JOIN ref r ON r.session_id=l.child
460
- JOIN store.sessions s ON s.id=r.session_id
461
- LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
462
- WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${n.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...n.bindings).filter((g)=>{if(i.seq===0)return g.title===c;if(!g.body)return!1;let y=JSON.parse(g.body);return Ke(y,!0).some((x)=>x.part===i.part&&x.kind===Jr[i.kind]&&x.text===c)}).map((g)=>g.session_id)}function fK(e,n){let i=n?e:gt(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let c="",p=[],g=[],y=0;for(let x of e){let b=n?x:gt(x);c+=b;for(let S=0;S<b.length;S++)p.push(y),g.push(y+x.length);y+=x.length}return{normalized:c,starts:p,ends:g}}function Hl(e,n){if(n.regex){let b=new RegExp(n.regex.source,`${n.regex.flags}g`),S=[];for(let T of e.matchAll(b)){if(n.wholeWord&&!gM(e,T.index,T.index+T[0].length))continue;S.push([T.index,T.index+T[0].length])}return S.length?S:void 0}let{normalized:i,starts:c,ends:p}=fK(e,n.caseSensitive),g=(b)=>{let S=n.caseSensitive?b.text:gt(b.text),T=[],A=i.indexOf(S);while(A>=0&&S){let C=c?c[A]:A,P=p?p[A+S.length-1]:A+S.length,L=C===0||C!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(C-1,C))||/[a-z0-9][A-Z]/.test(e.slice(C-1,C+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(b.text));if(C!==void 0&&P!==void 0&&(!b.prefix||L)&&(!n.wholeWord||gM(e,C,P)))T.push([C,P]);A=i.indexOf(S,A+Math.max(1,S.length))}return T};if(!n.branches.length)return[];let y=[],x=!1;for(let b of n.branches){if(b.exclude.some((T)=>g(T).length))continue;let S=b.include.map(g);if(S.some((T)=>!T.length))continue;x=!0,y.push(...S.flat())}return x?y:void 0}function gM(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 Wl(e,n){let i=e.split(`
463
- `),c=new Set,p=0,g=i.map((y,x)=>{let b=p;if(n.some(([S,T])=>S<=b+y.length&&T>=b))for(let S=Math.max(0,x-1);S<=Math.min(i.length-1,x+1);S++)c.add(S);return p+=y.length+1,b});if(!c.size)c.add(0);return[...c].sort((y,x)=>y-x).slice(0,5).map((y)=>{let x=i[y]??"",b=g[y]??0,S=n.filter(([P,L])=>L>b&&P<b+x.length),T=Math.max(0,(S[0]?.[0]??b)-b-100),A=x.slice(T,T+300),C=S.map(([P,L])=>[Math.max(0,P-b-T),Math.min(A.length,L-b-T)]);return{text:A,line:y+1,ranges:C.filter(([P,L])=>P<L)}})}var yM=3;function hK(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 xM(e,n){return n.score-e.score||(e.sessionID<n.sessionID?-1:Number(e.sessionID>n.sessionID))||n.seq-e.seq}function gK(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:[],g="emitted"in i?i.emitted:[],y="after"in i?i.after:void 0;if(y!==void 0&&!hK(y))throw Error("invalid best cursor");let x=(b)=>Array.isArray(b)&&b.every((S)=>typeof S==="string"&&S.length<=1024);if(typeof c==="number"&&Number.isSafeInteger(c)&&c>=0&&x(p)&&x(g))return{offset:i.offset,key:n,now:i.now,window:c,seen:p,emitted:g,after:y}}}catch{}throw Error("invalid search cursor")}function On(e,n){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:n})).toString();return gK(e.cursor,i)}async function Hr(e,n,i){let c="search"in e?e.search:e,p=performance.now(),g=(Fe)=>{if(!i.signal?.aborted)i.onEvent(Fe)};if(i.signal?.aborted)return;let y=On(n,i.sessionID);if(n.filters?.sessionID?.length===1)n={...n,group:"none"};let x=Gl(n,{now:y.now});if(x.error){g({type:"error",...x.error});return}if(x.currentSession){if(!i.sessionID){g({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){g({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let b=performance.now(),S=c.withIndex((Fe)=>aM(Fe,x));if(!S){g({type:"error",code:"unavailable",message:c.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}i.onTiming?.("plan",performance.now()-b);let T=S.partial,A=y.after,C=new Map,P=new Map,L=[],q=!1,X=new Map,j=new WeakMap,V=new Map,J=new Map,{offset:ee,window:ie}=y,H=[...y.seen],ce=[...y.emitted],fe=!1,_e=Math.max(1,Math.min(200,n.limit??30)),be=Math.min(S.candidateLimit??2000,n.group==="none"?kg:Math.min(2000,Math.max(kg,_e*32))),se=(Fe,Ue)=>{let qt=C.get(Ue);if(qt)return qt;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)C.set(Ue,lt);return lt??void 0},me=(Fe,Ue,qt)=>{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 Ot=Jr[Ue.kind];if(!Ot)return;let yr=lt.title;if(Ue.seq!==0){let it=`${Ue.session_id}:${Ue.seq}`,Jt=J.get(it);if(!Jt){let cn=qt?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!qt&&!cn)return;let Kt=qt??JSON.parse(cn?.body??"null");Jt=Ke(Kt,!0),J.set(it,Jt)}let Zt=Jt.find((cn)=>cn.part===Ue.part&&cn.kind===Ot);if(!Zt)return;yr=Zt.text}let pr=Hl(yr,x);if(!pr)return;let Ut=P.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,P.set(lt.id,Ut);let st=Ue.seq>0&&Ue.seq<=Ut;if(x.filters.compacted!==void 0&&st!==x.filters.compacted)return;let Ct={sessionID:lt.id,seq:Ue.seq,time:Ue.time,field:Ot,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:cM(Ue.relevance,Ot,Ue.time,y.now),flags:{archived:lt.archived_at!==null,compacted:st,partial:yr.length>Ai+Ei}};return X.set(Ct,{text:yr,ranges:pr}),L.push(Ct),q=!0,V.set(Ct,{doc:Ue.doc,part:Ue.part}),Ct},qe=(Fe)=>{let Ue=performance.now(),qt=[...Fe].sort((st,Ct)=>st.time-Ct.time||st.sessionID.localeCompare(Ct.sessionID)),lt=[],Ot=new Map;for(let st of qt){let Ct=V.get(st),Jt=C.get(st.sessionID),Zt=new Set;while(Jt?.forked_from_id&&Jt.forked_from_seq!==null&&st.seq<=Jt.forked_from_seq&&!Zt.has(Jt.id))Zt.add(Jt.id),Jt=C.get(Jt.forked_from_id)??c.withIndex((wo)=>se(wo,Jt?.forked_from_id??""));let cn=`${Jt?.id??st.sessionID}:${st.seq}:${Ct?.part}:${Ct?.doc}`,Kt=Ot.get(cn);if(Kt){if(Kt.sessionID!==st.sessionID)Kt.forks=[...new Set([...Kt.forks??[],st.sessionID])]}else Ot.set(cn,st),lt.push(st)}let yr=[],pr=new Map,Ut=new Map;for(let st of lt){let Ct=`${st.sessionID}:${st.seq}`,it=Ut.get(Ct);if(!it){Ut.set(Ct,st),j.set(st,[st]);continue}let Jt=[...j.get(it)??[it],st],Zt=st.score>it.score?st:it;if(Zt.forks=[...new Set([...it.forks??[],...st.forks??[]])],!Zt.forks.length)Zt.forks=void 0;Zt.flags={archived:it.flags.archived||st.flags.archived,compacted:it.flags.compacted||st.flags.compacted,partial:it.flags.partial||st.flags.partial},Ut.set(Ct,Zt),j.set(Zt,Jt)}for(let st of Tg([...Ut.values()],n.sort??"best")){let Ct=C.get(st.sessionID);if(!Ct)continue;let it=n.group==="none"?void 0:pr.get(Ct.id);if(!it)it={session:{id:Ct.id,title:Ct.title,projectID:Ct.project_id,updated:Ct.updated},hits:[],more:0,...T&&n.group!=="none"?{moreIsLowerBound:!0}:{}},yr.push(it),pr.set(Ct.id,it);if(it.hits.length<yM||n.group==="none")it.hits.push(st);else it.more++}return i.onTiming?.("group",performance.now()-Ue),yr},It=(Fe)=>{for(let Ue of Fe)for(let qt of Ue.hits){if(i.allowedSessionIDs&&qt.forks)qt.forks=qt.forks.filter((yr)=>i.allowedSessionIDs?.has(yr));let lt=performance.now(),Ot=new Map;for(let yr of j.get(qt)??[qt]){let pr=X.get(yr);if(!pr)continue;for(let Ut of Wl(pr.text,pr.ranges)){let st=`${Ut.line}:${Ut.text}`,Ct=Ot.get(st);if(!Ct)Ot.set(st,Ut);else Ct.ranges=[...new Map([...Ct.ranges,...Ut.ranges].map((it)=>[it.join(":"),it])).values()]}}qt.snippet=[...Ot.values()],i.onTiming?.("snippet",performance.now()-lt)}},Je=n.deep||S.scan,Yt=(Fe,Ue)=>{let qt=se(Fe,Ue.session_id);if(!qt)return[];let lt=hM(Fe,S,Ue,n.group==="none",qt.forked_from_id!==null,i.onTiming);if(S.candidateLimit&&lt.length>S.candidateLimit)lt.length=S.candidateLimit,T=!0;let Ot=L.length,yr=performance.now();for(let pr of lt){if(i.signal?.aborted)break;let Ut=me(Fe,pr);if(!Ut)continue;let st=Cg(Fe,S,pr,X.get(Ut)?.text??"");if(st.length)Ut.forks=st}return i.onTiming?.("body",performance.now()-yr),L.slice(Ot)};if(Je){T=!1;let Fe=[],Ue=new Set,qt=c.withIndex((it)=>{Ag(it,S);for(let Kt of it.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())C.set(Kt.id,Kt);let Jt=new Set(it.query(`SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}`).all(...S.sessionBindings).map((Kt)=>Kt.id)),Zt=(Kt)=>{if(Ue.has(Kt.id))return;Ue.add(Kt.id);let wo=Kt.forked_from_id?C.get(Kt.forked_from_id):void 0;if(wo)Zt(wo);if(Jt.has(Kt.id))Fe.push(Kt)};for(let Kt of C.values())Zt(Kt);return(it.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
464
- SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}
465
- )`).get(...S.sessionBindings)?.n??0)+Jt.size})??0,lt=0,Ot=0,yr=0;if(x.regex?.deepScan)g({type:"groups",groups:[]});let pr=new Set,Ut=new Set,st=new Map,Ct=()=>{let it=qe(L),Jt=[];for(let Zt of it){let cn=Zt.session.id,Kt=n.group==="none"?void 0:st.get(cn);if(n.group!=="none"&&Ut.has(cn)&&!Kt)continue;if(!Kt){if(Ut.add(cn),Ot<y.offset){Ot++;continue}if(yr>=_e){fe=!0;break}yr++,ee++}if(n.group!=="none"){let wo=(Kt?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,yM-(Kt?.shown??0));let yu=(Kt?.shown??0)+Zt.hits.length;Zt.more=wo-yu,st.set(cn,{shown:yu,count:wo})}Jt.push(Zt)}if(Jt.length)It(Jt),g({type:"groups",groups:Jt});L.length=0,X.clear(),V.clear(),J.clear()};for(let it of Fe){if(i.signal?.aborted||fe)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||fe)break;let cn=c.withIndex((Kt)=>{let wo=Kt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(it.id,Math.max(0,Jt));if(Jt<0)wo.unshift({seq:0,time:it.updated,body:null});for(let Fi of wo){if(i.signal?.aborted)break;let xu=Fi.body?JSON.parse(Fi.body):void 0;if(xu?.type==="assistant")Zt=xu.model;let TM=xu?Ke(xu,!0):[{part:0,kind:"title",text:it.title}];for(let Ko of TM){if(i.signal?.aborted)break;let Os={session_id:it.id,seq:Fi.seq,part:Ko.part,doc:Number(BigInt(Bun.hash(Ko.text))&0x1fffffffffffffn),kind:Oe[Ko.kind],tool:Ko.tool??null,err:Number(Ko.err??!1),model:Ko.model??(Ko.tool?Zt:void 0)??null,time:Fi.time,relevance:-1};if(!Kt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
466
- JOIN store.sessions s ON s.id=r.session_id WHERE ${S.where}`).get(Os.session_id,Os.seq,Os.kind,Os.tool,Os.err,Os.model,Os.time,...S.bindings))continue;let Js=it,$g=new Set;while(Js.forked_from_id&&Js.forked_from_seq!==null&&Fi.seq<=Js.forked_from_seq&&!$g.has(Js.id)){$g.add(Js.id);let Iu=C.get(Js.forked_from_id);if(!Iu)break;Js=Iu}let Mg=`${Js.id}:${Fi.seq}:${Ko.part}:${Bun.hash(Ko.text)}`;if(pr.has(Mg))continue;let vg=me(Kt,Os,xu);if(vg){if(pr.add(Mg),S.forks){let Iu=Kt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(it.id,Fi.seq,Ko.part);if(Iu){let Og=Cg(Kt,S,{...Os,doc:Iu.doc},Ko.text);if(Og.length)vg.forks=Og}}}}}let yu=wo.at(-1);if(yu)Jt=yu.seq;return wo.length});if(cn===void 0){g({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=cn,g({type:"progress",scanned:lt,total:qt}),i.signal?.aborted)return;if(Ct(),!cn||fe)break;await Bun.sleep(0)}}}else c.withIndex((Fe)=>{if(T=mM(Fe,S,i.onTiming)||T,x.regex?x.regex.literals.every((lt)=>lt.some((Ot)=>[...Ot].length<3)):x.branches.some((lt)=>lt.include.length>0&&lt.include.every((Ot)=>[...Ot.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=pM(Fe,S,n.group==="none",y.now,i.onTiming);if(T||=S.partial,S.candidateLimit&&lt.length>S.candidateLimit)lt.length=S.candidateLimit,T=!0;let Ot=[];for(let pr of lt){if(i.signal?.aborted)return;let Ut=Ot[_e]?.key.score;if(Ut!==void 0&&pr.score+0.000000000001<Ut)break;let st=L.length,Ct=Yt(Fe,pr);L.splice(st);let it=Tg([...Ct],"best")[0];if(!it)continue;let Jt={score:it.score,sessionID:it.sessionID,seq:n.group==="none"?it.seq:0};if(y.after&&xM(Jt,y.after)<=0)continue;if(Ot.push({key:Jt,hits:Ct}),Ot.sort((Zt,cn)=>xM(Zt.key,cn.key)),Ot.length>_e+1)Ot.length=_e+1}fe=Ot.length>_e;let yr=Ot.slice(0,_e);for(let pr of yr)L.push(...pr.hits);A=yr.at(-1)?.key;return}let qt=0;for(;;){if(i.signal?.aborted)return;let lt=dM(Fe,S,ie,be,i.onTiming),Ot=S.candidateLimit!==void 0&&ie+lt>=S.candidateLimit;T||=Ot;let yr=fM(Fe,n,ee,_e-qt+1,y.now,H,i.onTiming);fe=yr.length>_e-qt;let pr=yr.slice(0,_e-qt);if(!pr.length){if(lt<be||Ot){fe=!1;break}ie+=lt,ee=0,H=[...new Set([...H,...ce])],ce=[];continue}for(let Ut of pr)if(ee++,Yt(Fe,Ut).length){if(qt++,n.group!=="none")ce.push(Ut.session_id)}if(qt>=_e){fe||=!Ot&&lt>=be;break}if(!fe){if(lt<be||Ot)break;ie+=lt,ee=0,H=[...new Set([...H,...ce])],ce=[]}}});if(i.signal?.aborted)return;if(!Je){let Fe=qe(L);It(Fe),g({type:"groups",groups:Fe})}if(!q){let Fe=x.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)g({type:"suggest",terms:c.withIndex((Ue)=>wg(Ue,Fe))??[]})}g({type:"done",cursor:fe?Buffer.from(JSON.stringify(!Je&&n.sort!=="recent"?{...y,offset:0,window:0,seen:[],emitted:[],after:A}:{...y,offset:ee,window:ie,seen:H,emitted:ce})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:T,index:c.status()})}function Do(e,n){return e.withIndex((i)=>wg(i,n))??[]}function IM(e,n,i){let c=v({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:s({query:o(m([l({maxLength:2000}),Pn()])),scope:o(m([a("session"),a("project"),a("all"),a(""),Pn()])),fields:o(m([B($r({type:"string",enum:[...Mn]})),Pn()])),tool:o(m([l(),Pn()])),isError:o(m([D(),Pn()])),after:o(m([l(),Y(),Pn()])),before:o(m([l(),Y(),Pn()])),limit:o(m([w(),Pn()])),session:o(m([l(),Pn()])),seq:o(m([w(),Pn()])),around:o(m([w(),Pn()]))}),async execute(p,g,y){let x={query:g.query?.trim(),scope:g.scope||void 0,fields:g.fields?.length?g.fields:void 0,tool:g.tool?.trim(),isError:g.isError??void 0,after:g.after??void 0,before:g.before??void 0,limit:g.limit||void 0,session:g.session?.trim(),seq:g.seq??void 0,around:g.around??void 0},b=x.query?.trim(),S=!b&&Boolean(x.session?.trim())&&Number.isSafeInteger(x.seq)&&(x.seq??0)>=1;if(S&&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(y?.aborted)throw Error("History search cancelled");let T=e.sessions().find((se)=>se.id===i);if(!T)throw Error("History session is unavailable");let A=(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},C=S?void 0:A(x.after),P=S?void 0:A(x.before);if(C!==void 0&&P!==void 0&&C>=P)throw Error("after must precede before");let L=[];if(S&&x.session&&x.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===x.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let me=x.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(x.session,Math.max(1,x.seq-me),x.seq+me);if(!qe.some((Je)=>Je.seq===x.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:qe.map((Je)=>{let Yt={...JSON.parse(Je.body),seq:Je.seq,time:Je.time};return`[seq=${Je.seq}]
467
- ${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
468
- `).slice(0,4000)}`}).join(`
469
-
470
- `)||"No history content"}],details:{groups:L,count:qe.length}}}if(!b)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,X=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,j=new Set(e.sessions().filter((se)=>{if(x.scope==="session")return se.id===i;if((x.scope??"project")==="project"&&T.projectID)return se.projectID===T.projectID;return!0}).map((se)=>se.id)),V={q:b,filters:{tools:x.tool?.trim()?[x.tool.trim()]:void 0,isError:x.isError,after:C,before:P},group:"none",limit:q},J=Gl(V);if(J.error)throw Error(J.error.message);if(x.fields?.length){if(J.filters.fields=x.fields.filter((se)=>(se in Oe)),J.filters.fields.length!==x.fields.length)throw Error("Unknown search field")}if((x.scope??"project")==="session")J.filters.sessionID=[i];else if((x.scope??"project")==="project"&&T.projectID)J.filters.projectID=[T.projectID];let ee=n.status().state!=="ready",ie=!1;if(!ee){let se=J.filters.fields??Object.keys(Oe).filter((It)=>(It in Oe)),me=se.filter((It)=>It!=="title"),qe=me.length?[me]:[];if(se.includes("title"))qe.push(["title"]);for(let It of qe){if(L.length>=q&&ie)break;if(await Hr(n,{...V,limit:Math.max(1,q-L.length),filters:{...J.filters,fields:It}},{signal:y,excludeEntry:X===void 0?void 0:{sessionID:i,seq:X},sessionID:i,allowedSessionIDs:j,onEvent(Je){if(Je.type==="groups")L.push(...Je.groups);if(Je.type==="done")ie||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")ee=!0;else throw Error(Je.message)}}),ee)break}}let H=[],ce=0;if(ee){L.length=0;let se=performance.now()+2000;e:for(let me of e.sessions()){if(!j.has(me.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(me.id))continue;if(J.filters.projectID&&(!me.projectID||!J.filters.projectID.includes(me.projectID)))continue;let qe=Number.MAX_SAFE_INTEGER,It=!0;for(;;){let Je=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(me.id,qe);if(It)Je.push({body:"null",seq:0,time:me.updated}),It=!1;if(!Je.length)break;for(let Yt of Je){if(Yt.seq>0)qe=Yt.seq;if(y?.aborted)throw Error("History search cancelled");if(ce>=1e4||performance.now()>se){ie=!0;break e}if(ce++,me.id===i&&Yt.seq===X)continue;if(J.filters.after!==void 0&&Yt.time<J.filters.after||J.filters.before!==void 0&&Yt.time>=J.filters.before)continue;let Fe=Yt.seq===0?[{part:0,kind:"title",text:me.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Ue of Fe){if(J.filters.fields&&!J.filters.fields.includes(Ue.kind))continue;if(J.filters.tools&&(!Ue.tool||!J.filters.tools.includes(Ue.tool)))continue;if(J.filters.isError!==void 0&&Boolean(Ue.err)!==J.filters.isError)continue;let qt=Hl(Ue.text,J);if(!qt)continue;if(L.length>=q&&Ue.kind!=="title"){ie=!0;break e}(Ue.kind==="title"?H: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:Wl(Ue.text,qt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(y?.aborted)throw Error("History search cancelled");if(H.length>Math.max(0,q-L.length))ie=!0;if(L.push(...H.slice(0,q)),L.sort((se,me)=>Number(se.hits[0]?.field==="title")-Number(me.hits[0]?.field==="title")),L.length>q)ie=!0;L.length=Math.min(L.length,q);let fe=new Map;for(let se of L)for(let me of se.hits){let qe=fe.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}`:""}]
471
- ${me.snippet.slice(0,3).map((It)=>{let Je=It.text;for(let[Yt,Fe]of[...It.ranges].sort((Ue,qt)=>qt[0]-Ue[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Fe)}\u3011${Je.slice(Fe)}`;return Je}).join(`
472
- `)}`),fe.set(se.session.id,qe)}let _e="";if(ee){if(_e="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",n.status().state==="disabled")_e="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let be=L.reduce((se,me)=>se+me.hits.length,0);return{content:[{type:"text",text:[_e,ee&&ie?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ce} \u6761`:"",[...fe.values()].map((se)=>se.join(`
473
-
474
- `)).join(`
475
-
476
- `),be===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 ${be} \u6761\uFF1B${ie?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
477
- `)}],details:{groups:L,count:be}}}});return Object.assign(c,{source:"history",builtin:!0,defer:"defer"})}async function bM(e,n){let i=n.projectID?e.store.project(n.projectID):void 0,c=i?.directory??process.cwd(),g=n.info().kind==="sub",y=()=>g||n.records.some((S)=>S.entry.type==="compaction"),x=e.options.tools??nr({directory:i?.directory,records:()=>n.records,history:(S)=>e.resolveHistory(n.id,S),onTodos:(S)=>n.setTodos(S),shell:()=>e.serverShell(),hasCompacted:y});if(e.options.tools===void 0)x.push(IM(e.store,e.search,n.id));let b=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:S$({project:i,globalInstructions:EK(e),shell:e.serverShell()});return{systemPrompt:b.map((S)=>S.detail).join(""),systemParts:b,tools:[...x,...e.tools.snapshot()],cwd:c}}var bK=[gu(".basalt","AGENTS.md"),gu(".agents","AGENTS.md"),gu(".opencode","AGENTS.md"),gu(".claude","CLAUDE.md"),gu(".codex","AGENTS.md")];function EK(e){let n=e.options.homeDir??IK();for(let i of bK){let c=gu(n,i);try{if(yK(c))return xK(c,"utf8")}catch{return}}return}class qr{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 hg(this,this.sessions,(n)=>this.emit(n)),this.defaultModel=e.defaultModel,this.store=new jl(Pg(e.dataDir,"basalt.db")),this.plugins=new Qh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Bl(this.plugins,()=>this.builtinToolNames()),this.search=new Xh({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 qr(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??[Pg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Pg(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 V$(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{...Ul(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>W$(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)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,n={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let c=n.archive??"active";return c==="all"||i.archivedAt!==null===(c==="archived")}).sort((i,c)=>c.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((n)=>n.info().parentID===e).map((n)=>n.info())}resolveHistory(e,n){let i=this.get(e);if(!i)throw new t("History session is unavailable");let c=i.historyScope(n);if(c)return c;if(n.source&&n.source!=="self"||n.session_id&&n.session_id!==i.id)throw new t("History source is unavailable");return{sessionID:i.id,records:i.records}}openStoredSession(e,n="restore"){let i=this.open(e,n);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let n=e.model??this.defaultModel;if(!bn(this.options.models,n))throw new t(`unknown model ${n}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),c={id:ue("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:n,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(c);let p=this.open(c);return this.sessions.set(c.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,n,i){n={...n,archivedAt:null},this.store.copySession(e,n,i);let c=this.open(n);return this.sessions.set(n.id,c),this.plugins.notify("session.fork",c),this.emit({type:"session",session:c.info()}),c}exportSession(e){let n=this.get(e);if(!n)throw new f("no such session");let i=n.info(),c=i.projectID?this.store.project(i.projectID):void 0;return v$(i,this.store.records(e),c?{name:c.name,directory:c.directory}:void 0)}importSession(e,n={}){if(n.model!==void 0)this.checkModel(n.model);if(n.projectID)this.projectOperations.requireProject(n.projectID);let i=[n.model,e.model,this.defaultModel].find((y)=>y!==void 0&&bn(this.options.models,y)!==void 0),c=i?bn(this.options.models,i):void 0;if(!i||!c)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:ue("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:n.projectID??null,model:i,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?L$(e.records,c):e.records);let g=this.open(p);return this.sessions.set(p.id,g),this.emit({type:"session",session:g.info()}),g}truncateHistory(e,n){let i=this.sessions.get(e.id);if(!i)throw new f("no such session");if(i.assertWritable(),i.status==="busy")throw new oe;if(!bn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);i.close();for(let p of this.sessions.values()){if(p.info().parentID!==e.id)continue;if(p.status==="busy")p.abort();p.close()}this.store.truncateSession(e,n);let c=this.open(e,"replay");return this.sessions.set(e.id,c),this.emit({type:"truncated",sessionID:e.id,after:n-1,truncationEpoch:this.store.truncationEpoch(e.id)}),c}setArchived(e,n){let i=this.sessions.get(e);if(!i)throw new f("no such session");if(i.info().parentID)throw new t("\u8BF7\u5F52\u6863\u6216\u6062\u590D\u6240\u5C5E\u4F1A\u8BDD\uFF08\u542B\u5B50\u4F1A\u8BDD\uFF09");let c=this.sessionTree(i);if(c.some((p)=>p.status==="busy"))throw new 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 f("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 _l(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>bM(this,p)},{entry:(p)=>{this.emit({type:"entry",sessionID:i,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:i,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(p)=>this.emit({type:"draft",sessionID:i,parts:p}),changed:()=>{let p=this.sessions.get(i);if(p)this.emit({type:"session",session:p.info()})}});if(n!=="restore")this.plugins.notify(n==="create"?"session.create":"session.open",c);return c}get toolLoading(){return new Di(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!Ql.includes(e))throw new t(`Invalid shell type; must be ${Ql.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 J$(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 EM=1048576,SM=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 X=od(e);if(X.length>0)throw Error(sd(X))}if(this.list().filter((X)=>X.state==="running").length>=SM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${SM}\uFF09`);let y=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:x,isWindows:b}=ba(e,y),S=Bun.spawn(x,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!b,windowsHide:!0,env:{...process.env,...nm(this.cwd)}}),T={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:S,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(T.id,T);let A=()=>{for(let X of T.waiters.splice(0))X()},C=async(X,j)=>{let V=new Rl;for await(let ee of X){let ie=V.decode(ee);T.output+=ie,c?.output(ie,j);let H=Buffer.from(T.output);if(H.length>EM){let ce=H.length-EM;while(ce<H.length&&(H[ce]??0)>>6===2)ce++;let fe=H.subarray(ce).toString(),_e=T.output.length-fe.length;T.unreadDroppedBytes+=Buffer.byteLength(T.output.slice(Math.max(0,T.readAt-T.dropped),_e)),T.output=fe,T.dropped+=_e}A()}let J=V.flush();if(T.output+=J,J)c?.output(J,j)},P,L=Promise.all([C(S.stdout,"stdout"),C(S.stderr,"stderr")]).catch((X)=>{P=X,this.kill(T)}),q=!1;if(T.done=(async()=>{if(T.code=await S.exited,T.timer?.(),this.kill(T),await L,P)throw P;if(T.state==="running")T.state="exited";if(q=!0,c?.end(T.state,T.code),!c&&T.state!=="killed")this.terminal?.(T);A()})().catch((X)=>{if(T.state="exited",T.output+=`
478
- [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(X)}]`,!q)c?.end(T.state,T.code);if(c)throw X;if(!c)this.terminal?.(T,X);A()}),n!==void 0)T.timer=p.after(n,()=>{if(T.state==="running")T.state="timeout",this.kill(T)});return T}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 g=this.find(e),y=n?new RegExp(n):void 0,x=Date.now()+i;p?.throwIfAborted();while(g.state==="running"){p?.throwIfAborted();let C=g.output.slice(Math.max(0,g.readAt-g.dropped));if((y?y.test(C):!c)||Date.now()>=x)break;await new Promise((P,L)=>{let q=()=>{clearTimeout(j);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);L(p?.reason)},X=()=>{clearTimeout(j),p?.removeEventListener("abort",q);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);P()},j=setTimeout(X,Math.max(0,x-Date.now()));g.waiters.push(X),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let b=g.unreadDroppedBytes;g.unreadDroppedBytes=0;let S=g.output.slice(Math.max(0,g.readAt-g.dropped));g.readAt=g.dropped+g.output.length;let T=S.slice(-this.outputLimit),A=b+Buffer.byteLength(S.slice(0,S.length-T.length));return{job:g,output:`${A?`[truncated ${A} bytes]
479
- `:""}${T}`}}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 g=p.proc.stdin;if(!g||typeof g==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(n){let y=await je(n,c);if(y)throw Error(y);g.write(n)}if(i)await g.end();else await g.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 zl=new WeakMap,Vl=new WeakMap;function sr(e,n){let i=zl.get(e);if(!i)i=n(),zl.set(e,i);return i}function ar(e){Vl.set(e,(Vl.get(e)??0)+1)}function lr(e,n){let i=(Vl.get(n)??1)-1;if(Vl.set(n,i),i>0)return!1;if(n.close(),zl.get(e)===n)zl.delete(e);return!0}async function U(e){let n=await e.json();if(!n||typeof n!=="object"||Array.isArray(n))throw new t("expected a JSON object");return n}function E(e,n){let i=e[n];if(!i)throw new t(`${n} is required`);return i}var Nn=100,cr=1e4,SK=60000,wK=200,Rn=()=>l(),wM=()=>o(w({minimum:1,maximum:cr})),Yc=()=>o(l({minLength:1,maxLength:128})),TK=m([s({click:m([Rn(),s({selector:Rn()})])}),s({type:s({label:Rn(),text:Rn()})}),s({waitText:Rn(),timeoutMs:wM()}),s({expectText:Rn(),within:o(Rn())}),s({waitSelector:Rn(),timeoutMs:wM()}),s({expectCount:s({selector:Rn(),n:w({minimum:0})})}),s({snapshot:s({selector:Rn(),depth:o(w({minimum:0,maximum:wK}))})}),s({expectCalls:s({onOpen:o(B(Rn())),onClose:o(w({minimum:0}))})}),s({expectValue:s({label:Rn(),value:Rn()})})]),RK=s({status:w({minimum:100,maximum:599}),body:Rr(),delayMs:o(w({minimum:0,maximum:cr}))}),kK=m([a("paths"),a("request"),a("verify"),a("ui_test"),a("list"),a("docs"),a("check"),a("load"),a("reload"),a("enable"),a("disable")]),AK=m([a("page"),a("tab"),a("card"),a("sidebar")]),xi=s({action:kK,path:o(l({minLength:1,maxLength:4096})),method:o(Rn()),body:o(Ss(Rn(),Rr())),importTimeoutMs:o(w({minimum:1,maximum:cr})),timeoutMs:o(w({minimum:1,maximum:SK})),sessionID:Yc(),scope:o(m([a("user"),a("all")])),id:Yc(),slot:Yc(),view:Yc(),codeBlock:Yc(),kind:o(AK),props:o(Ss(Rn(),Rr())),context:o(Ss(Rn(),Rr())),steps:o(B(TK,{maxItems:Nn})),mockRoutes:o(Ss(Rn(),RK)),topic:o(l({maxLength:100})),grep:o(l({minLength:1,maxLength:200}))});
480
- export{t,f,pi,di,mi,Fr,er,ko,Mn,hi,fi,gi,Ft,yi,bi,Wr,Ro,Ee,Si,et,Pt,K,Co,je,tt,B,o,s,$r,D,w,a,Y,l,m,h,ae,Ln,Io,Mo,Lo,Oo,we,v,rt,pt,k,O,F,ke,Pe,u,We,nt,tr,rr,$e,nr,dt,oe,No,or,ir,ue,On,Hr,Do,qr,Re,Wt,sr,ar,lr,U,E,Uo,Nn,cr,xi};