@bkm016/basalt 0.1.8 → 0.1.10

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 (258) hide show
  1. package/{chunk-0039s4jt.js → chunk-02d3x4mj.js} +3 -3
  2. package/{chunk-ky55taar.js → chunk-0mjb3sm3.js} +327 -316
  3. package/{chunk-ckjw3b61.js → chunk-13gvs0ax.js} +2 -2
  4. package/{chunk-0d51ggzj.js → chunk-1n7dat03.js} +4 -4
  5. package/{chunk-ppxv5q7y.js → chunk-1zj3zvw5.js} +3 -3
  6. package/{chunk-2ek3wq4b.js → chunk-29qrxygd.js} +1 -1
  7. package/{chunk-7p6e2f5s.js → chunk-30rjf7my.js} +3 -3
  8. package/{chunk-v2srrqcv.js → chunk-38g3gctw.js} +2 -2
  9. package/chunk-3mqf9ped.js +479 -0
  10. package/{chunk-3j2kkgsc.js → chunk-4dw43syb.js} +1 -1
  11. package/{chunk-t66jqz12.js → chunk-4gtgqcct.js} +2 -2
  12. package/{chunk-qmdpgbg3.js → chunk-755sy11p.js} +1 -1
  13. package/{chunk-n015c8nx.js → chunk-7zkswxvk.js} +1 -1
  14. package/{chunk-91r5nvth.js → chunk-82v8jh1h.js} +2 -2
  15. package/{chunk-12trygzx.js → chunk-95964592.js} +16 -16
  16. package/{chunk-nmtk9xra.js → chunk-9as0p561.js} +2 -2
  17. package/{chunk-pn413hjw.js → chunk-a1352w87.js} +1 -1
  18. package/{chunk-rnt1ckk9.js → chunk-a1rb1a48.js} +5 -5
  19. package/{chunk-fzcmzbsq.js → chunk-a98wma9j.js} +1 -1
  20. package/{chunk-kgkrccr1.js → chunk-asyr3gnq.js} +2 -2
  21. package/{chunk-5gxj9560.js → chunk-ax04trym.js} +1 -1
  22. package/chunk-b2bxqeb4.js +2 -0
  23. package/{chunk-xjw78yey.js → chunk-bdjr0kfr.js} +4 -4
  24. package/{chunk-7kjr9gdx.js → chunk-bk4rpnm8.js} +2 -2
  25. package/{chunk-47vf66t6.js → chunk-c0zfefq8.js} +1 -1
  26. package/{chunk-kpvaqb7c.js → chunk-c6q04xrd.js} +2 -2
  27. package/chunk-c71173py.js +25 -0
  28. package/{chunk-adys4qq4.js → chunk-cmwdjes8.js} +5 -5
  29. package/{chunk-dcwdmpw2.js → chunk-d0a1jxk5.js} +1 -1
  30. package/{chunk-2nrkqq45.js → chunk-d5j74pcp.js} +7 -7
  31. package/{chunk-pkpj7s2k.js → chunk-dfh9m9n7.js} +1 -1
  32. package/{chunk-26cz8et8.js → chunk-dq01v5eq.js} +1 -1
  33. package/{chunk-fpxc6qjr.js → chunk-e1x629v0.js} +2 -2
  34. package/{chunk-86xhmz7k.js → chunk-en218k4y.js} +1 -1
  35. package/{chunk-3hg7yn1t.js → chunk-fgwda4m0.js} +1 -1
  36. package/chunk-gbjn6d81.js +2 -0
  37. package/{chunk-x496kg3v.js → chunk-gkf5jwvj.js} +1 -1
  38. package/{chunk-k3q5jqjj.js → chunk-hb4f2v34.js} +2 -2
  39. package/{chunk-mr807v9n.js → chunk-hbnmymaq.js} +1 -1
  40. package/{chunk-818nd6s1.js → chunk-jj4hqbrx.js} +2 -2
  41. package/{chunk-jyv9cae6.js → chunk-jn5pqy5v.js} +1 -1
  42. package/{chunk-yyy2yp6f.js → chunk-jtsve11b.js} +9 -9
  43. package/chunk-m1eam0s5.js +2 -0
  44. package/{chunk-6vnjg5x9.js → chunk-mbpb5c7w.js} +1 -1
  45. package/{chunk-t40fag3z.js → chunk-msm9hmk9.js} +1 -1
  46. package/{chunk-j781n7ca.js → chunk-n0ybj4h9.js} +2 -2
  47. package/{chunk-jp5afrwm.js → chunk-n2jcx65v.js} +2 -2
  48. package/{chunk-2ks2tnac.js → chunk-nrsd810j.js} +2 -2
  49. package/chunk-pnspvnyd.js +2 -0
  50. package/chunk-pz2afna8.js +2 -0
  51. package/{chunk-d37gemt2.js → chunk-q9f4xb0w.js} +3 -3
  52. package/{chunk-hd3x1w46.js → chunk-qaeyhe65.js} +1 -1
  53. package/chunk-qnkrrwmg.js +2 -0
  54. package/{chunk-e6c2mzxc.js → chunk-r4ttdkrz.js} +2 -2
  55. package/{chunk-r9aatvwm.js → chunk-stj493dn.js} +2 -2
  56. package/{chunk-g3ed130w.js → chunk-tevejprz.js} +4 -4
  57. package/{chunk-k3rmjrf1.js → chunk-v3ee9z3f.js} +1 -1
  58. package/{chunk-4n49ptbz.js → chunk-vtqr7dm8.js} +2 -2
  59. package/{chunk-z3ch1wg6.js → chunk-xh444pfn.js} +14 -14
  60. package/{chunk-pehyqj8k.js → chunk-zc9ar0r4.js} +1 -1
  61. package/{chunk-ef9yhnk3.js → chunk-zyyzk5ha.js} +1 -1
  62. package/compiled.js +9 -9
  63. package/package.json +1 -1
  64. package/ui-test-worker.js +8 -8
  65. package/web/chunk-045d3b5d.js +1 -0
  66. package/web/{chunk-r4ffr96e.js → chunk-0770q5e1.js} +1 -1
  67. package/web/chunk-12qf1r6m.js +1 -0
  68. package/web/{chunk-s7e93552.js → chunk-18neka5g.js} +4 -4
  69. package/web/{chunk-et8q775x.js → chunk-1ev0n3n4.js} +5 -5
  70. package/web/chunk-1ex3wgms.js +2 -0
  71. package/web/{chunk-svh2gkx8.js → chunk-1qh7f5kr.js} +1 -1
  72. package/web/{chunk-s38s9ff9.js → chunk-26ecc2xh.js} +30 -30
  73. package/web/chunk-2cz7tx8q.js +1 -0
  74. package/web/chunk-32ty2xfn.js +1 -0
  75. package/web/{chunk-q1xxs319.js → chunk-3eexx7y5.js} +4 -4
  76. package/web/{chunk-v14s4vgc.js → chunk-46jnkghq.js} +1 -1
  77. package/web/chunk-4am8j3k3.js +1 -0
  78. package/web/{chunk-85gdsmt4.js → chunk-5qvmefq2.js} +1 -1
  79. package/web/chunk-5svqfj4g.js +3 -0
  80. package/web/{chunk-f93pe4kb.js → chunk-5v5q13hz.js} +4 -4
  81. package/web/chunk-5z2n4z9x.css +1 -0
  82. package/web/{chunk-qcge7d6s.js → chunk-6e87m0nm.js} +2 -2
  83. package/web/chunk-6y55gk1n.js +1 -0
  84. package/web/chunk-7np1jp3x.js +8 -0
  85. package/web/chunk-87e8d1hv.js +1 -0
  86. package/web/{chunk-33w36n91.js → chunk-88wd49xe.js} +2 -2
  87. package/web/chunk-8h2x89tw.js +2 -0
  88. package/web/chunk-8y2526ve.js +1 -0
  89. package/web/chunk-905vw286.js +2 -0
  90. package/web/chunk-918e5t4x.js +2 -0
  91. package/web/chunk-96m2m3e8.js +1 -0
  92. package/web/chunk-9f4zzqbx.js +1 -0
  93. package/web/{chunk-fe31sv6t.js → chunk-9yfftz38.js} +1 -1
  94. package/web/{chunk-z0zrp8n8.js → chunk-a1n4468c.js} +1 -1
  95. package/web/chunk-arnzrqnm.js +1 -0
  96. package/web/{chunk-c01176kn.js → chunk-awkdw9rw.js} +2 -2
  97. package/web/{chunk-m5y2d4zv.js → chunk-b46ws7rf.js} +1 -1
  98. package/web/chunk-bc3ajvfg.js +24 -0
  99. package/web/chunk-bwy3e58v.js +1 -0
  100. package/web/{chunk-ja7w629n.js → chunk-c57f714b.js} +2 -2
  101. package/web/chunk-d5gshd1a.js +1 -0
  102. package/web/chunk-de40q05r.js +30 -0
  103. package/web/chunk-dp0k5vhd.js +1 -0
  104. package/web/{chunk-qq2v8h6d.js → chunk-dv1berk6.js} +5 -5
  105. package/web/{chunk-jzte2phh.js → chunk-eh7wp62z.js} +1 -1
  106. package/web/{chunk-823b7866.js → chunk-ehtmb6sn.js} +18 -18
  107. package/web/{chunk-d9wdsjkk.js → chunk-eqndhs21.js} +2 -2
  108. package/web/chunk-et1hytyv.js +1 -0
  109. package/web/chunk-f7jpakwh.js +1 -0
  110. package/web/chunk-f9m9seam.js +1 -0
  111. package/web/{chunk-7a4xk6j9.js → chunk-fmmrthpa.js} +5 -5
  112. package/web/{chunk-fv6vm14n.js → chunk-frnh4zqf.js} +2 -2
  113. package/web/chunk-g2erm7k0.js +1 -0
  114. package/web/chunk-g3kbn0t2.js +1 -0
  115. package/web/{chunk-h5cfg3vv.js → chunk-g7dc4hrd.js} +2 -2
  116. package/web/{chunk-dgwkqcz6.js → chunk-g7kz8f7q.js} +2 -2
  117. package/web/chunk-ght0t49g.js +1 -0
  118. package/web/{chunk-jjjtv2r1.js → chunk-ghwm7bdj.js} +2 -2
  119. package/web/{chunk-sda7cyrt.js → chunk-grm2208k.js} +21 -21
  120. package/web/{chunk-0zwc2rvh.js → chunk-gsw1tv96.js} +1 -1
  121. package/web/chunk-gw8x1g61.js +24 -0
  122. package/web/chunk-gx340asc.js +1 -0
  123. package/web/chunk-h2txs73e.js +39 -0
  124. package/web/chunk-h3tkacc7.js +1 -0
  125. package/web/{chunk-cyjnert7.js → chunk-h5ckjk48.js} +16 -16
  126. package/web/{chunk-1s8zg6fb.js → chunk-j37p0b13.js} +5 -5
  127. package/web/chunk-j89s11x8.js +78 -0
  128. package/web/{chunk-jam45rqg.js → chunk-jccz14ye.js} +2 -2
  129. package/web/chunk-je78j3vr.js +1 -0
  130. package/web/chunk-jke2ev6m.js +2 -0
  131. package/web/{chunk-1gx0zpmp.js → chunk-js6kb05s.js} +9 -9
  132. package/web/{chunk-30b33r2w.js → chunk-k0cg4n2k.js} +2 -2
  133. package/web/{chunk-tkp72r9b.js → chunk-knm82fw9.js} +1 -1
  134. package/web/{chunk-xb9m0092.js → chunk-kxdtg9dt.js} +1 -1
  135. package/web/{chunk-w37n09px.js → chunk-m4fxd5d9.js} +10 -10
  136. package/web/chunk-m9xzt9p7.js +1 -0
  137. package/web/{chunk-8773nwdc.js → chunk-myd6sc76.js} +1 -1
  138. package/web/{chunk-sf101c23.js → chunk-mykrm8ba.js} +2 -2
  139. package/web/chunk-mzzaet63.js +1 -0
  140. package/web/{chunk-2axwda8c.js → chunk-n4yzs2q0.js} +7 -7
  141. package/web/{chunk-wj3ymejj.js → chunk-nawxgz87.js} +4 -4
  142. package/web/chunk-ngt1j8py.js +1139 -0
  143. package/web/{chunk-hstbgb83.js → chunk-p55vhns6.js} +5 -5
  144. package/web/{chunk-xabcx3ry.js → chunk-pgwf37s2.js} +3 -3
  145. package/web/chunk-q34as3v6.js +1 -0
  146. package/web/{chunk-dtg5yhhs.js → chunk-q4bst4an.js} +1 -1
  147. package/web/chunk-qdzy124b.js +4 -0
  148. package/web/chunk-qe0bgeda.js +1 -0
  149. package/web/{chunk-sd3cdqcm.js → chunk-qh62nkem.js} +2 -2
  150. package/web/{chunk-j1bw5v1g.js → chunk-qq6m2my8.js} +2 -2
  151. package/web/{chunk-8dp7h6w8.js → chunk-qy1zx2yw.js} +16 -16
  152. package/web/chunk-rag65pfs.js +4 -0
  153. package/web/chunk-rbqnre6q.js +36 -0
  154. package/web/{chunk-hbkasy6c.js → chunk-rh3xb76f.js} +22 -22
  155. package/web/{chunk-fx4mackk.js → chunk-rwfmccmh.js} +4 -4
  156. package/web/{chunk-mf6xng5b.js → chunk-rxvm70w5.js} +2 -2
  157. package/web/chunk-sat7zyva.js +1 -0
  158. package/web/{chunk-cn0tmwjs.js → chunk-sc63488q.js} +2 -2
  159. package/web/{chunk-xsz1dfm2.js → chunk-sd3xat3r.js} +20 -20
  160. package/web/{chunk-nky3bqfg.js → chunk-se4h6wx0.js} +1 -1
  161. package/web/chunk-sjkg40ay.js +7 -0
  162. package/web/chunk-sk0hpa80.js +1 -0
  163. package/web/{chunk-xqyazzm7.js → chunk-t5nvgz7z.js} +5 -5
  164. package/web/{chunk-3q0v8w45.js → chunk-tfqarvdx.js} +80 -80
  165. package/web/{chunk-d0m0h0eb.js → chunk-tqze6d6b.js} +1 -1
  166. package/web/{chunk-rbdvc8x7.js → chunk-tt93zbn4.js} +7 -7
  167. package/web/chunk-tvcxrx6h.js +1 -0
  168. package/web/chunk-tzpnh70q.js +1 -0
  169. package/web/{chunk-8wg44w91.js → chunk-vasppf6b.js} +2 -2
  170. package/web/chunk-vb7g4xg6.js +1 -0
  171. package/web/chunk-w3zgfhjb.js +2 -0
  172. package/web/{chunk-0j9a7811.js → chunk-wrevb4ew.js} +6 -6
  173. package/web/chunk-wtvch4ad.js +106 -0
  174. package/web/chunk-wzfe6jtq.js +1 -0
  175. package/web/{chunk-cez1k71m.js → chunk-x5g1yy12.js} +1 -1
  176. package/web/chunk-x850q01z.js +1 -0
  177. package/web/chunk-xh4xn1az.js +1 -0
  178. package/web/chunk-xk904wqv.js +1 -0
  179. package/web/chunk-xtn305fd.js +1 -0
  180. package/web/chunk-xzwxcxb4.js +1 -0
  181. package/web/{chunk-4anjs6yp.js → chunk-y2rzeb4v.js} +2 -2
  182. package/web/chunk-yekaz74b.js +1 -0
  183. package/web/{chunk-8nv7q5ac.js → chunk-yppgejg7.js} +15 -15
  184. package/web/chunk-ys2tns0p.js +1 -0
  185. package/web/chunk-z4bp6p32.js +62 -0
  186. package/web/{chunk-p0cjvjdx.js → chunk-z5qn0xev.js} +1 -1
  187. package/web/{chunk-rkjkynm3.js → chunk-zms6mrqk.js} +12 -12
  188. package/web/{chunk-6e38yf3a.js → chunk-zse05v6j.js} +4 -4
  189. package/web/{chunk-cn1xpg3q.js → chunk-zz1qkaar.js} +2 -2
  190. package/web/index.html +1 -1
  191. package/worker.js +1 -1
  192. package/chunk-2gcp3xdc.js +0 -2
  193. package/chunk-320174qe.js +0 -2
  194. package/chunk-dvb5nd2x.js +0 -2
  195. package/chunk-frt9k18g.js +0 -480
  196. package/chunk-ndt6rjt9.js +0 -2
  197. package/chunk-xy2bxwq8.js +0 -2
  198. package/chunk-yzevjkms.js +0 -25
  199. package/chunk-zdyd8hbn.js +0 -2
  200. package/web/chunk-0jfda4jw.js +0 -2
  201. package/web/chunk-2p3fkhy8.js +0 -1
  202. package/web/chunk-3sz5qcwj.js +0 -1
  203. package/web/chunk-433c80pc.js +0 -1
  204. package/web/chunk-48cnmhvd.js +0 -106
  205. package/web/chunk-5r37rwq1.js +0 -4
  206. package/web/chunk-6bwgdvf6.js +0 -1
  207. package/web/chunk-7f1t7z72.js +0 -2
  208. package/web/chunk-7x35g67d.js +0 -78
  209. package/web/chunk-8pzg8qw4.js +0 -1
  210. package/web/chunk-8r0s8tx7.js +0 -1
  211. package/web/chunk-9p5dfvav.js +0 -1
  212. package/web/chunk-9q9w9pay.js +0 -1
  213. package/web/chunk-a3teqvz2.js +0 -39
  214. package/web/chunk-ahztazsg.js +0 -1
  215. package/web/chunk-bd8ftfxn.js +0 -3
  216. package/web/chunk-c03bt2pz.js +0 -1
  217. package/web/chunk-c1ha2xg6.js +0 -8
  218. package/web/chunk-cgng31df.js +0 -1
  219. package/web/chunk-cvd4f51j.js +0 -1
  220. package/web/chunk-cybvxssy.js +0 -1
  221. package/web/chunk-d22wq71s.js +0 -1
  222. package/web/chunk-dynajx8x.js +0 -2
  223. package/web/chunk-f3vv7n52.js +0 -1
  224. package/web/chunk-fmthkpff.js +0 -1
  225. package/web/chunk-fpa81dv7.js +0 -62
  226. package/web/chunk-g17n6asp.js +0 -1
  227. package/web/chunk-g9dzaw9e.js +0 -30
  228. package/web/chunk-gcwhx3av.js +0 -1139
  229. package/web/chunk-gf8vm6b5.js +0 -1
  230. package/web/chunk-gnmeyy4h.js +0 -1
  231. package/web/chunk-hn7mhsbg.js +0 -1
  232. package/web/chunk-jfvxxp5c.js +0 -1
  233. package/web/chunk-k8h8zx6r.js +0 -24
  234. package/web/chunk-m3ajw575.js +0 -1
  235. package/web/chunk-mbwwj216.js +0 -1
  236. package/web/chunk-mz9b5bsa.js +0 -1
  237. package/web/chunk-np33kmn4.js +0 -1
  238. package/web/chunk-nvk8mazs.js +0 -1
  239. package/web/chunk-nyw5ewgv.js +0 -1
  240. package/web/chunk-p56dcqpr.js +0 -1
  241. package/web/chunk-pdn4r8x4.js +0 -1
  242. package/web/chunk-qpt34d8d.js +0 -1
  243. package/web/chunk-qskt3tqa.js +0 -1
  244. package/web/chunk-qt3n897m.js +0 -4
  245. package/web/chunk-r1rt48h9.js +0 -1
  246. package/web/chunk-r7tgd2fm.js +0 -7
  247. package/web/chunk-rznszqmy.js +0 -1
  248. package/web/chunk-s1pefd34.js +0 -1
  249. package/web/chunk-sc29azev.js +0 -1
  250. package/web/chunk-t4jc4nac.js +0 -1
  251. package/web/chunk-t7g366a5.js +0 -24
  252. package/web/chunk-thbqwq6b.js +0 -1
  253. package/web/chunk-v94v68xg.js +0 -36
  254. package/web/chunk-wcphswcx.js +0 -2
  255. package/web/chunk-wwcnvyjh.css +0 -1
  256. package/web/chunk-xce8n339.js +0 -1
  257. package/web/chunk-xfd3b01q.js +0 -1
  258. package/web/chunk-xtss82z2.js +0 -1
@@ -0,0 +1,479 @@
1
+ // @bun
2
+ import{$o,Qr,W}from"./chunk-4gtgqcct.js";import{Si,He,Et,wi,Yn,vi,_i,Ai,Pt,Ti,Ne,eo,Ke}from"./chunk-c71173py.js";import{Gn,Ci,Kr}from"./chunk-n0ybj4h9.js";import{Ie,te,Ho,zn,I,jn,ht,Me,dr,U,Le,Vn,ft,me,$t,oe,Xr,qo,Oe,re,nt,Kn,Go,be,Ii,yi,Se,Qn,d,Mi,Q,Jr,G,Li}from"./chunk-1n7dat03.js";import{Xn,M,Jn,Ve,bi,Ht,ke}from"./chunk-n2jcx65v.js";import{r,Xe}from"./chunk-bwawt15q.js";var Gg=r(function(aH,Bg){var Mv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Yl=/[\n\r\u2028\u2029]/,Ov=/[\s#!"$&'():;<=>@\\^`|~]/g;Bg.exports=function(o){var i=!1;return o.map(function(u){if(i&&typeof u==="string"&&Yl.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Yl.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(Ov,"\\$&")}if("op"in u&&typeof u.op==="string"){if(Mv.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(Yl.test(u.comment))throw TypeError("`comment` must not contain line terminators");return i=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var Xg=r(function(uH,Qg){var Vg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Kg=new RegExp("^"+Vg+"$"),Hg="|&;()<> \\t",_v="'([^']*?)'",Jg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Wg="\\$'"+Jg+"'",Yc=new RegExp("\\$'"+Jg+"(?:(')|\\\\?$)","g"),Lv="abeEfnrtv",Nv=`\x07\b\x1B\x1B\f
3
+ \r \v`,Dv=/^#$/,Zl="'",zg='"',bu="$",Ui="",qv=4294967296;for(Xc=0;Xc<4;Xc++)Ui+=(qv*Math.random()).toString(16);var Xc,Fv=new RegExp("^"+Ui);function jv(e,o){var i=o.lastIndex,u=[],p;while(p=o.exec(e))if(u[u.length]=p,o.lastIndex===p.index)o.lastIndex+=1;return o.lastIndex=i,u}function Uv(e,o,i){var u=typeof e==="function"?e(i):e[i];if(typeof u>"u"&&i!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+Ui+JSON.stringify(u)+Ui;return o+u}var Bv=/\\([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 Gv(e,o){var i=o.charAt(0);if(i==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var p=parseInt(o.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(i>="0"&&i<="7")return String.fromCharCode(parseInt(o,8)&255);var g=Lv.indexOf(o);return g<0?o:Nv.charAt(g)}function Kv(e){return e.replace(Bv,Gv).split("\x00")[0]}function Hv(e,o){return Yc.lastIndex=o,!!Yc.exec(e)[1]}function Wv(e,o,i){if(!i)i={};var u=i.escape||"\\",p=i.splitUnquoted===!0?`
4
+ `:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",g="(\\"+u+`['"$\\`+u+Hg+"]|\\$\\$|\\$(?!"+Wg.slice(2)+`)|[^\\s'"$`+Hg+"])+",y='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',b=new RegExp(["("+Vg+")","("+Wg+"|"+g+"|"+y+"|"+_v+")+"].join("|"),"g"),E=jv(e,b);if(E.length===0)return[];if(!o)o={};var S=!1;return E.map(function(w){var R=w[0];if(!R||S)return;if(Kg.test(R))return{op:R};var A=!1,P=!1,C="",q=[],X=!1,j=null,V=!1,J;function ee(){J+=1;var pe,qe,xt=R.charAt(J);if(xt==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var Je=1;pe=J;while(Je>0&&pe<R.length){if(R.charAt(pe)==="{"&&R.charAt(pe-1)==="$")Je+=1;else if(R.charAt(pe)==="}")Je-=1;pe+=1}if(Je!==0)throw Error("Bad substitution: "+R.slice(J));pe-=1,qe=R.slice(J,pe),J=pe}else if(/[*@#?$!-]/.test(xt))qe=xt;else{var Yt=R.slice(J);if(pe=Yt.match(/[^\w\d_]/),!pe)qe=Yt,J=R.length;else qe=Yt.slice(0,pe.index),J+=pe.index-1}return Uv(o,"",qe)}function ae(){if(j===null)return;if(j===0){if(C!=="")q[q.length]=C,C=""}else{q[q.length]=C,C="";for(var pe=1;pe<j;pe+=1)q[q.length]=""}j=null}for(J=0;J<R.length;J++){var H=R.charAt(J);if(p&&H!==bu)ae();if(V=V||!A&&(H==="*"||H==="?"),P)C+=H,P=!1;else if(A)if(H===A)A=!1;else if(A==Zl)C+=H;else if(H===u)if(J+=1,H=R.charAt(J),H===zg||H===u||H===bu)C+=H;else C+=u+H;else if(H===bu)C+=ee();else C+=H;else if(H===zg||H===Zl)A=H,X=!0;else if(Kg.test(H))return{op:R};else if(Dv.test(H)){S=!0;var ue={comment:e.slice(w.index+J+1)};if(C.length)return[C,ue];return[ue]}else if(H===u)P=!0;else if(H===bu&&R.charAt(J+1)===Zl&&Hv(R,J))ae(),X=!0,C+=Kv(R.slice(J+2,Yc.lastIndex-1)),J=Yc.lastIndex-1;else if(H===bu){var he=ee();if(!p)C+=he;else for(var $e=0;$e<he.length;$e+=1){var Ee=he.charAt($e);if(p.indexOf(Ee)<0)ae(),C+=Ee;else if(j===null)j=Ee===" "||Ee==="\t"||Ee===`
5
+ `?0:1;else if(Ee!==" "&&Ee!=="\t"&&Ee!==`
6
+ `)j+=1}}else C+=H}if(V)return{op:"glob",pattern:C};if(p){if(j!==null&&j>0){q[q.length]=C,C="";for(var se=1;se<j;se+=1)q[q.length]=""}if(C!==""||X&&q.length===0)q[q.length]=C;return q}return C}).reduce(function(w,R){if(typeof R>"u")return w;return[].concat(R).forEach(function(A){w[w.length]=A}),w},[])}Qg.exports=function(o,i,u){var p=Wv(o,i,u);if(typeof i!=="function")return p;return p.reduce(function(g,y){if(typeof y==="object")return g[g.length]=y,g;var b=y.split(RegExp("("+Ui+".*?"+Ui+")","g"));if(b.length===1)return g[g.length]=b[0],g;return b.filter(Boolean).forEach(function(E){g[g.length]=Fv.test(E)?JSON.parse(E.split(Ui)[1]):E}),g},[])}});var Wo={};Xe(Wo,{ArchivedError:()=>dt,BadRequestError:()=>t,BusyError:()=>ie,DEFAULT_TIMEOUT:()=>s$,FoldingPolicy:()=>Uc,MAX_ATTACHMENTS:()=>ut,MAX_TIMEOUT:()=>i$,MAX_TOOL_OUTPUT:()=>Te,NotFoundError:()=>f,PluginCheckError:()=>pt,ProcessRegistry:()=>Wt,Type:()=>io,aliased:()=>_e,budget:()=>jc,calls:()=>us,clip:()=>de,clipSaved:()=>rt,dataDir:()=>et,definePlugin:()=>k,estimateMessage:()=>F,estimateTokens:()=>D,estimateTools:()=>Ni,extensionTranscript:()=>Sl,findWindowsBash:()=>tr,foldPoint:()=>qc,foldedThrough:()=>xa,formatLines:()=>Bc,gateShellCommand:()=>je,groupRuns:()=>Ks,historyTodos:()=>ir,newID:()=>ne,normalizeRunRecords:()=>Nh,processRegistry:()=>sr,project:()=>Re,projectUserText:()=>Di,releaseProcesses:()=>lr,requestBody:()=>N,resolveShellCommand:()=>Ea,retainProcesses:()=>ar,routeParam:()=>v,runShell:()=>rr,sealPoint:()=>iu,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>yl,text:()=>c,timerClock:()=>Ce,tool:()=>x,toolSession:()=>z,transcript:()=>cu,usable:()=>ce,userTranscript:()=>El,validAttachment:()=>Ft,workState:()=>Il});var Uo={};Xe(Uo,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>ER,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>TR,EventStream:()=>Xn,InMemoryCredentialStore:()=>zn,InMemoryModelsStore:()=>jn,ModelsError:()=>I,StringEnum:()=>jq,Type:()=>io,appendAssistantMessageDiagnostic:()=>ke,calculateCost:()=>Q,clampThinkingLevel:()=>G,cleanupSessionResources:()=>Ci,collapseSystemMessages:()=>Oe,contentText:()=>dr,createAssistantMessageDiagnostic:()=>Ht,createAssistantMessageEventStream:()=>Jn,createFauxCore:()=>bR,createInitialSystemMessage:()=>Vn,createModels:()=>Qn,createProvider:()=>d,declarationsEqual:()=>Kn,defaultProviderAuthContext:()=>Ho,envApiKeyAuth:()=>h,extractDiagnosticError:()=>bi,fauxAssistantMessage:()=>No,fauxProvider:()=>Do,fauxText:()=>On,fauxThinking:()=>Oo,fauxToolCall:()=>Iq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>Xr,getCurrentSystemPrompt:()=>qo,getCurrentTools:()=>oe,getDeclaredTools:()=>be,getInitialSystemMessage:()=>me,getModelType:()=>ht,getOverflowPatterns:()=>Lq,getSupportedThinkingLevels:()=>Jr,getSystemMessageText:()=>U,getToolStateChanges:()=>Go,hasApi:()=>Mi,hasNonAdditiveToolChanges:()=>yi,hasToolRedefinitions:()=>Ii,isContextOverflow:()=>ca,isModelType:()=>Me,isRecoverableLength:()=>_q,isRetryableAssistantError:()=>kR,lazyApi:()=>te,lazyOAuth:()=>le,lazyStream:()=>Ie,modelsAreEqual:()=>Li,normalizeContext:()=>ft,parseJsonWithRepair:()=>Qr,parseStreamingJson:()=>W,reduceAssistantMessageFrames:()=>vq,registerSessionResourceCleanup:()=>Gn,renderSystemMessageUpdate:()=>Le,repairJson:()=>$o,resolveTranscript:()=>re,resolveTranscriptTools:()=>Se,retryAssistantCall:()=>Fq,retryDelayMs:()=>RR,toToolDeclaration:()=>nt,uuidv7:()=>Kr,validateToolArguments:()=>nu,validateToolCall:()=>RU,withoutInitialSystemMessage:()=>$t});var K={};Xe(K,{Counted:()=>cd,Entries:()=>ln,EntriesRegExp:()=>md,Every:()=>an,EveryAll:()=>An,GraphemeCount:()=>SM,HasPropertyKey:()=>fe,IsArray:()=>Ge,IsBigInt:()=>Nr,IsBoolean:()=>pn,IsClassInstance:()=>fy,IsConstructor:()=>ad,IsDeepEqual:()=>Ta,IsEqual:()=>L,IsFunction:()=>ms,IsGreaterEqualThan:()=>Sa,IsGreaterThan:()=>Ki,IsInteger:()=>rm,IsLessEqualThan:()=>ps,IsLessThan:()=>Su,IsMaxLength:()=>hy,IsMinLength:()=>gy,IsMultipleOf:()=>dy,IsNull:()=>ho,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>zo,IsString:()=>gt,IsSymbol:()=>ud,IsUndefined:()=>Ut,IsUnsafePropertyKey:()=>wu,IsValueLike:()=>Hi,Keys:()=>we,ShiftLeft:()=>It,Some:()=>wa,SomeAll:()=>yy,Symbols:()=>xy,Values:()=>pd});var Yi={};Xe(Yi,{Hash:()=>xd,HashCode:()=>Yy});var _t={};Xe(_t,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Ae,ExtendsUnion:()=>jd,IsExtendsFalse:()=>Gd,IsExtendsTrue:()=>Bd,IsExtendsTrueLike:()=>so,IsExtendsUnion:()=>Ud,Match:()=>br});var io={};Xe(io,{Any:()=>Pa,Array:()=>B,BigInt:()=>Cu,Boolean:()=>O,Call:()=>pw,Capitalize:()=>xw,Codec:()=>lm,Conditional:()=>kw,Constructor:()=>ds,ConstructorParameters:()=>Pw,Cyclic:()=>gs,Decode:()=>rx,DecodeBuilder:()=>pm,Dependent:()=>Xi,Encode:()=>nx,EncodeBuilder:()=>mm,Enum:()=>By,Evaluate:()=>Rn,Exclude:()=>$w,Extends:()=>Tn,ExtendsResult:()=>_t,Extract:()=>Mw,Function:()=>fs,Generic:()=>Xs,Identifier:()=>$u,Immutable:()=>ox,Index:()=>Nw,Infer:()=>Pu,InstanceType:()=>aT,Instantiate:()=>Ao,Integer:()=>_,Interface:()=>WS,Intersect:()=>Cn,IsAny:()=>vr,IsArray:()=>wt,IsBigInt:()=>mo,IsBoolean:()=>Wn,IsCall:()=>ja,IsCodec:()=>Hn,IsConstructor:()=>en,IsCyclic:()=>Qt,IsDependent:()=>Dr,IsEnum:()=>on,IsEnumValue:()=>Uy,IsFunction:()=>tn,IsGeneric:()=>Aa,IsIdentifier:()=>ux,IsImmutable:()=>Zi,IsInfer:()=>nn,IsInteger:()=>fn,IsIntersect:()=>ze,IsKind:()=>Pe,IsLiteral:()=>yt,IsNever:()=>co,IsNull:()=>xs,IsNumber:()=>kr,IsObject:()=>Qe,IsOptional:()=>cn,IsParameter:()=>lx,IsReadonly:()=>ta,IsRecord:()=>Gt,IsRef:()=>qt,IsRefine:()=>dm,IsRest:()=>ni,IsSchema:()=>Cr,IsString:()=>sn,IsSymbol:()=>Is,IsTemplateLiteral:()=>ur,IsThis:()=>Am,IsTuple:()=>mt,IsUndefined:()=>Yo,IsUnion:()=>xe,IsUnknown:()=>rn,IsUnsafe:()=>cm,IsVoid:()=>po,KeyOf:()=>cT,Literal:()=>s,Lowercase:()=>Iw,Mapped:()=>yT,Module:()=>sR,Never:()=>zt,NonNullable:()=>ET,Null:()=>$n,Number:()=>Y,Object:()=>l,Omit:()=>wT,Optional:()=>n,Parameter:()=>ra,Parameters:()=>kT,Partial:()=>PT,Pick:()=>LT,Readonly:()=>sx,ReadonlyObject:()=>If,ReadonlyType:()=>qT,Record:()=>bs,RecordKey:()=>ri,RecordPattern:()=>hn,RecordValue:()=>fr,Ref:()=>un,Refine:()=>ix,Required:()=>ZT,Rest:()=>oa,ReturnType:()=>tR,Script:()=>cR,String:()=>a,Symbol:()=>va,TemplateLiteral:()=>dS,This:()=>km,Tuple:()=>Ur,Uncapitalize:()=>bw,Undefined:()=>_a,Union:()=>m,Unknown:()=>Rr,Unsafe:()=>qr,Uppercase:()=>Ew,Void:()=>Pm,With:()=>lp});var eu={};Xe(eu,{Clear:()=>Bk,Entries:()=>zF,Get:()=>QF,Has:()=>JF,IsDate:()=>Xa,IsDateTime:()=>Ep,IsDuration:()=>Sp,IsEmail:()=>wp,IsHostname:()=>vp,IsIPv4:()=>_p,IsIPv6:()=>Lp,IsIdnEmail:()=>Mp,IsIdnHostname:()=>Op,IsIri:()=>Dp,IsIriReference:()=>Np,IsJsonPointer:()=>Fp,IsJsonPointerUriFragment:()=>qp,IsRegex:()=>jp,IsRelativeJsonPointer:()=>Up,IsTime:()=>Ya,IsUri:()=>Kp,IsUriReference:()=>Bp,IsUriTemplate:()=>Gp,IsUrl:()=>Hp,IsUuid:()=>Wp,Reset:()=>Kk,Set:()=>VF,Test:()=>Gk});var Iu="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 Pv(e,o){if(e===o)return 0;let i=Array.from({length:o.length+1},(u,p)=>p);for(let u=1;u<=e.length;u++){let p=i[0]??0;i[0]=u;for(let g=1;g<=o.length;g++){let y=i[g]??0;i[g]=Math.min((i[g]??0)+1,(i[g-1]??0)+1,p+(e[u-1]===o[g-1]?0:1)),p=y}}return i[o.length]??0}function Dg(e,o){let i=Lg(e);if(!i)return[];let u=Ng(e),p=[];for(let g of o){let y=g.id.indexOf("/"),b=y>=0?g.id.slice(y+1):"",S=[g.id,g.name,b].filter(Boolean).map((R)=>({compact:Lg(R),tokens:Ng(R)})).filter((R)=>R.compact.length>0),w=Number.POSITIVE_INFINITY;for(let R of S)if(R.compact===i)w=Math.min(w,0);else if(R.compact.includes(i)||i.includes(R.compact)){let A=Math.abs(R.compact.length-i.length);w=Math.min(w,1+A/Math.max(R.compact.length,i.length))}else{let A=0;for(let P of u)if(R.tokens.has(P))A++;if(A>0){let P=A/Math.max(u.size,R.tokens.size);w=Math.min(w,10+(1-P)*10)}}if(!Number.isFinite(w)&&i.length>=4){let R=Math.max(2,Math.floor(i.length*0.34));for(let A of S){if(Math.abs(A.compact.length-i.length)>R)continue;let P=Pv(i,A.compact);if(P<=R)w=Math.min(w,100+P)}}if(Number.isFinite(w))p.push({model:g,score:w})}return p.sort((g,y)=>g.score-y.score||g.model.id.localeCompare(y.model.id))}function Cv(e,o,i=5){return Dg(e,o).slice(0,Math.max(1,i)).map((u)=>u.model)}function Fr(e,o){let i=Dg(e,o);if(i.length===0)return;let u=i.filter((g)=>g.score===0);if(u.length===1&&u[0])return u[0].model;if(u.length>1)return;let p=i.filter((g)=>g.score<10);if(p.length===1&&p[0])return p[0].model;return}function Wr(e,o){let i=[...o].sort((y,b)=>y.id.localeCompare(b.id)),u=(y)=>y.name===y.id?y.id:`${y.id} (${y.name})`,p=Cv(e,i).map(u),g=i.map(u);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 li=["openai-completions","openai-responses","anthropic-messages"];function $r(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let o=e.trim().toLowerCase();if(!o)return;let i=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let u=Number.parseFloat(i[1]??"");if(!Number.isFinite(u)||u<=0)return;let p=i[2];if(p==="k")return Math.round(u*1000);if(p==="m")return Math.round(u*1e6);return Math.round(u)}function Vl(e){if(e>=1e6&&e%1e5===0)return`${e/1e6}m`;if(e>=1000&&e%1000===0)return`${e/1000}k`;return String(e)}function $v(e){let o=e.trim();if(!o)return;let i,u,p=o,g=p.match(/\s*\[(.*?)\]\s*$/);if(g&&g.index!==void 0){p=p.slice(0,g.index).trim();let w=g[1]?.split(",").map((A)=>A.trim()).filter(Boolean)??[],R=0;for(let A of w){let P=A.indexOf("=");if(P>=0){let C=A.slice(0,P).trim().toLowerCase(),q=$r(A.slice(P+1).trim());if(C==="context"||C==="ctx"||C==="window"||C==="contextwindow")i=q;else if(C==="max"||C==="output"||C==="maxtokens")u=q}else{let C=$r(A);if(R===0)i=C;else if(R===1)u=C;R++}}}else{let w=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(w?.[1]&&w[2])p=w[1].trim(),i=$r(w[2])}let y=p.indexOf("="),b,E;if(y<0)b=p.trim(),E=b;else b=p.slice(0,y).trim(),E=p.slice(y+1).trim()||b;if(!b)return;let S={id:b,name:E};if(i!==void 0)S.contextWindow=i;if(u!==void 0)S.maxTokens=u;return S}function er(e){return e.split(/\r?\n/).map($v).filter((o)=>o!==void 0)}function Io(e){return e.map((o)=>{let i=o.name===o.id?o.id:`${o.id}=${o.name}`,u=[];if(o.contextWindow!==void 0)u.push(Vl(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)u.push(Vl(o.maxTokens));else u.push(`max=${Vl(o.maxTokens)}`);return u.length>0?`${i} [${u.join(", ")}]`:i}).join(`
8
+ `)}var qg=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var Ln=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],ci=["text","regex"],ui=["best","recent"],pi=["session","none"];var Bt=4,di="https://basalt.work",mi=["https://basalt.work","https://www.basalt.work"],Hr=7420;var Jl=["auto","bash","powershell","cmd"];var Mo=["active","archived","all"],hi="session.group";var Fg=["pending","in_progress","completed"],Ql="basalt-session",Qc=["image","text","path"];var jg=["defer","always"],Ug=["global","tool","source"];function Be(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let i=o;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:o};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:o}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:o};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:o}}}function fi(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var ut=10,vv=15000000;function Ft(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&Qc.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=vv}function Xl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}var zv=Gg(),ed=Xg();import{AsyncLocalStorage as Vv}from"async_hooks";var z=new Vv;var Jv=3,Yg=160,Qv=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),Xv=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),ty=/^[A-Za-z_][A-Za-z0-9_]*=/,Yv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),Zv=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),eM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,tM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),rM=new Set(["command","builtin","nohup","time","exec"]),nM=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 Zc(e){return{out:e.out,depth:e.depth+1}}function Zg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function td(e,o,i,u){let p=e.length,g=0,y=o;while(y<p){let b=e.charAt(y);if(b==="\\"){y+=2;continue}if(b==="'"||b==='"'||b==="`"){let E=y+1;while(E<p){let S=e.charAt(E);if(S==="\\"){E+=2;continue}if(S===b)break;E++}y=E+1;continue}if(b===i)g++;else if(b===u){if(g--,g===0)return y+1}y++}return p}function oM(e){let o={text:"",subs:[],heredocs:[]},i=[],u=[],p=e.length,g=0,y=0,b=null,E=(S)=>{if(e.charAt(S)==="`"){let P=S+1;while(P<p){let C=e.charAt(P);if(C==="\\"){P+=2;continue}if(C==="`")break;P++}return o.subs.push(e.slice(S+1,P)),P<p?P+1:p}if(e.charAt(S+1)==="("){let P=td(e,S+1,"(",")");if(e.charAt(S+2)==="(")return i.push(e.slice(S,P)),P;return o.subs.push(e.slice(S+2,P-1)),P}let R=td(e,S+1,"{","}"),A=e.slice(S+2,R-1);for(let P=0;P<A.length;P++){let C=A.charAt(P);if(C==="\\"){P++;continue}if(C==="`"){let q=A.indexOf("`",P+1);o.subs.push(q<0?A.slice(P+1):A.slice(P+1,q)),P=q<0?A.length:q;continue}if(C==="$"&&A.charAt(P+1)==="("){let q=td(A,P+1,"(",")");o.subs.push(A.slice(P+2,q-1)),P=q-1}}return R};while(g<p){let S=e.charAt(g);if(b==="'"){if(S==="'")b=null;i.push(S),g++;continue}if(b==='"'){if(S==="\\"){if(!'$`"\\\n'.includes(e.charAt(g+1)))i.push("\\");i.push(S,e.charAt(g+1)),g+=2;continue}if(S==='"'){b=null,i.push(S),g++;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}i.push(S),g++;continue}if(S==="'"||S==='"'){b=S,i.push(S),g++;continue}if(S==="\\"){i.push(S,e.charAt(g+1)),g+=2;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}if(S==="#"){let w=i.at(-1);if(w===void 0||`
9
+ ;&|()`.includes(w)){while(g<p&&e.charAt(g)!==`
10
+ `)g++;continue}i.push(S),g++;continue}if(S==="<"&&e.charAt(g+1)==="<"&&e.charAt(g+2)!=="<"){let w=g+2;if(e.charAt(w)==="-")w++;i.push(e.slice(g,w));let R=w;while(R<p&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let A="";while(R<p){let P=e.charAt(R);if(P==="'"||P==='"'){let C=e.indexOf(P,R+1);if(C<0)break;A+=e.slice(R+1,C),R=C+1;continue}if(P==="\\"){A+=e.charAt(R+1),R+=2;continue}if(` \r
11
+ ;&|()<>`.includes(P))break;A+=P,R++}if(A)u.push(A);g=w;continue}if(S===`
12
+ `){if(u.length>0){let w=eM.test(i.slice(y).join(""));g++;for(let R of u.splice(0)){let A=g,P=p;while(g<p){let C=e.indexOf(`
13
+ `,g),q=C<0?p:C;if(e.slice(g,q).trim()===R){P=g,g=C<0?p:C+1;break}g=C<0?p:C+1}if(w&&P>A)o.heredocs.push(e.slice(A,P))}}else g++;i.push(";",`
14
+ `),y=i.length;continue}i.push(S),g++}return o.text=i.join(""),o}function Eu(e,o){if(o.depth>Jv)return;let i=oM(e),u;try{u=ed(i.text)}catch{return}let p=[];for(let g of u){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})}sM(p,o);for(let g of i.subs)Eu(g,Zc(o));for(let g of i.heredocs)Eu(g,Zc(o))}function sM(e,o){let i=[],u=()=>{if(i.length>0)iM(i,o);i=[]};for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;if(g.kind==="op"){if(Yv.has(g.text)){u();continue}if(Zv.has(g.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(g.text)}u()}function iM(e,o){let i=0;for(;;){let y=e[i];if(y===void 0)return;if(Xv.has(y)||ty.test(y)){i++;continue}let b=uM(Zg(y),e,i);if(b===i)break;i=b}let u=e[i];if(u===void 0)return;let p=Zg(u),g=e.slice(i+1);if(p==="git"){mM(u,g,o);return}if(Qv.has(p)){aM(g,o);return}if(p==="powershell"||p==="pwsh")ey(g,/^-(command|c)$/i,o);if(p==="cmd")ey(g,/^\/[ck]$/i,o)}function ey(e,o,i){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let p=e.slice(u+1).join(" ");if(p.trim())Eu(p,Zc(i));return}}function aM(e,o){for(let i=0;i<e.length;i++){let u=e[i]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){i++;continue}if(u.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(u);if(p){let g=p[1]||e[i+1];if(g)Eu(g,Zc(o));return}if(u.startsWith("-")||u==="")continue;return}}function uM(e,o,i){if(rM.has(e)){let g=i+1;while(o[g]?.startsWith("-"))g++;return g}let u=nM.get(e);if(!u)return i;let p=i+1;for(;;){let g=o[p];if(g===void 0)return p;if(u.includes(g)){p+=2;continue}if(ty.test(g)||g.startsWith("-")){p++;continue}return p}}function Ko(e,o){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(o))}function ro(e,o){return e.some((i)=>i===`--${o}`||i.startsWith(`--${o}=`))}var cM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Ko(e,"f")||Ko(e,"i")||ro(e,"force")||ro(e,"interactive"))&&!(Ko(e,"n")||ro(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Ko(e,"f")||ro(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Ko(e,"f")||ro(e,"force")||Ko(e,"C")||ro(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>Ko(e,"f")||ro(e,"force")||ro(e,"force-with-lease")||ro(e,"force-if-includes")||ro(e,"delete")||ro(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>ro(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Ko(e,"D")||Ko(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>ro(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>Ko(e,"f")||ro(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(Ko(e,"f")||ro(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function mM(e,o,i){let u=0;for(;;){let E=o[u];if(E===void 0)break;if(tM.has(E)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(E)||/^-[Cc].+/.test(E)||E.startsWith("-")){u++;continue}break}let p=o[u]?.toLowerCase();if(!p)return;let g=cM[p];if(!g)return;let y=g(o.slice(u+1));if(!y)return;let b=[e,...o.slice(u)].join(" ");i.out.push({rule:p,fragment:b.length>Yg?`${b.slice(0,Yg)}\u2026`:b,reason:y})}function nd(e){let o={out:[],depth:0};return Eu(e,o),o.out}function ry(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),i=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${i}`}var rd=new Map;function pM(e,o,i,u,p){let g=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((y)=>{let b=(S)=>{if(!rd.delete(g))return;p?.removeEventListener("abort",E),y(S)},E=()=>{ny(e,g),b("aborted")};if(rd.set(g,{session:e,finish:b}),e.appendExtension({namespace:Iu,kind:"requested",schemaVersion:1,payload:{id:g,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:S,reason:w})=>({fragment:S,reason:w})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)E();else p?.addEventListener("abort",E,{once:!0})})}function ny(e,o){try{e.appendExtension({namespace:Iu,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Lo(e,o,i){let u=rd.get(o);if(!u||u.session!==e){if(!lM(e,o))return"unknown";return ny(e,o),"expired"}return e.appendExtension({namespace:Iu,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(i?"approved":"denied"),"answered"}function lM(e,o){let i=!1;for(let u of e.entries()){if(u.type!=="extension"||u.namespace!==Iu)continue;let p=u.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==o)continue;if(u.kind==="requested")i=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return i}function od(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,o){let i=nd(e);if(!i.at(0))return;let p=ry(i),g=z.getStore();if(g?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${od(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let y=await pM(g,e,p,i,o);if(y==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${y==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{existsSync as dM,mkdirSync as fM,writeFileSync as hM}from"fs";import{homedir as gM}from"os";import{join as Bi}from"path";function et(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=gM();if(process.platform==="win32")return Bi(e.LOCALAPPDATA??Bi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Bi(o,"Library","Application Support","basalt");return Bi(e.XDG_DATA_HOME??Bi(o,".local","share"),"basalt")}function yM(e){return Bi(e,".basalt","tmp")}function sd(e){let o=yM(e);fM(o,{recursive:!0});let i=Bi(o,".gitignore");if(!dM(i))hM(i,`*
15
+ !.gitignore
16
+ `);return o}function em(e){try{let o=sd(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var cs={assign:0,create:0,clone:0,discard:0,update:0};function Gi(e,o,i){return e>=o&&e<=i}function iy(e){return e===8205}function xM(e){return Gi(e,55296,56319)}function oy(e){return Gi(e,127462,127487)}function ay(e){return Gi(e,65024,65039)}function uy(e){return Gi(e,768,879)||Gi(e,6832,6911)||Gi(e,7616,7679)||Gi(e,65056,65071)}function tm(e){return e>65535?2:1}function sy(e,o){while(o<e.length){let i=e.codePointAt(o);if(uy(i)||ay(i))o+=tm(i);else break}return o}function id(e,o){let i=e.codePointAt(o),u=o+tm(i);u=sy(e,u);while(u<e.length-1&&iy(e.codePointAt(u))){let p=e.codePointAt(u+1);u+=1+tm(p),u=sy(e,u)}if(oy(i)&&u<e.length&&oy(e.codePointAt(u)))u+=tm(e.codePointAt(u));return u}function cy(e){return e>=768&&(xM(e)||uy(e)||ay(e)||iy(e))}function my(e){let o=0,i=0;while(i<e.length)i=id(e,i),o++;return o}function IM(e,o){let i=0,u=0;while(u<e.length)if(u=id(e,u),++i>=o)return!0;return!1}function bM(e,o){let i=0,u=0;while(u<e.length)if(u=id(e,u),++i>o)return!1;return!0}function py(e,o){if(o===0)return!0;if(e.length<o)return!1;let i=0;while(!0){if(cy(e.charCodeAt(i)))return IM(e,o);if(++i>=o)return!0}}function ly(e,o){if(e.length<=o)return!0;let i=0;while(!0){if(cy(e.charCodeAt(i)))return bM(e,o);if(++i>o)return!1}}function Ge(e){return Array.isArray(e)}function Nr(e){return L(typeof e,"bigint")}function pn(e){return L(typeof e,"boolean")}function ad(e){if(Ut(e)||!ms(e))return!1;let o=Function.prototype.toString.call(e);if(/^class\s/.test(o))return!0;if(/\[native code\]/.test(o))return!0;return!1}function ms(e){return L(typeof e,"function")}function rm(e){return Number.isInteger(e)}function ho(e){return L(e,null)}function Ot(e){return Number.isFinite(e)}function zo(e){return at(e)&&!Ge(e)}function at(e){return L(typeof e,"object")&&!ho(e)}function gt(e){return L(typeof e,"string")}function ud(e){return L(typeof e,"symbol")}function Ut(e){return L(e,void 0)}function L(e,o){return e===o}function Ki(e,o){return e>o}function Su(e,o){return e<o}function ps(e,o){return e<=o}function Sa(e,o){return e>=o}function dy(e,o){if(Nr(e)||Nr(o))return BigInt(e)%BigInt(o)===0n;let i=0.0000000001;if(!Ot(e))return!0;if(rm(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<i}function fy(e){if(!at(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(ho(o))return!1;return L(typeof o.constructor,"function")&&!(L(o.constructor,globalThis.Object)||L(o.constructor.name,"Object"))}function Hi(e){return Nr(e)||pn(e)||ho(e)||Ot(e)||gt(e)||Ut(e)}function SM(e){return my(e)}function hy(e,o){return ly(e,o)}function gy(e,o){return py(e,o)}function an(e,o,i){return e.every((u,p)=>p<o||i(u,p))}function An(e,o,i){let u=!0;return e.forEach((p,g)=>{if(g>=o&&!i(p,g))u=!1}),u}function wa(e,o){return e.some((i,u)=>o(i,u))}function yy(e,o){let i=!1;return e.forEach((u,p)=>{if(o(u,p))i=!0}),i}function cd(e,o){return e.reduce((i,u,p)=>o(u,p)?++i:i,0)}function It(e,o,i){return L(e.length,0)?i():o(e[0],e.slice(1))}function wu(e){return L(e,"__proto__")||L(e,"constructor")||L(e,"prototype")}function fe(e,o){return wu(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function md(e){return we(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function ln(e){return Object.entries(e)}function we(e){return Object.getOwnPropertyNames(e)}function xy(e){return Object.getOwnPropertySymbols(e)}function pd(e){return Object.values(e)}function wM(e,o){if(!at(o))return!1;let i=we(e);return L(i.length,we(o).length)&&i.every((u)=>Ta(e[u],o[u]))}function TM(e,o){return Ge(o)&&L(e.length,o.length)&&e.every((i,u)=>Ta(e[u],o[u]))}function Ta(e,o){return Ge(e)?TM(e,o):at(e)?wM(e,o):L(e,o)}var RM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function kM(e){return RM.test(e)}function Sn(e,o){return`(${e} && ${o})`}function xr(e,o){return`(${e} || ${o})`}function Un(e){return`!(${e})`}function nm(e){return`Array.isArray(${e})`}function Iy(e){return`typeof ${e} === "bigint"`}function AM(e){return`typeof ${e} === "boolean"`}function PM(e){return`Number.isInteger(${e})`}function CM(e){return`${e} === null`}function by(e){return`Number.isFinite(${e})`}function Ey(e){return Sn(Sy(e),Un(nm(e)))}function Sy(e){return`typeof ${e} === "object" && ${e} !== null`}function wy(e){return`typeof ${e} === "string"`}function $M(e){return`typeof ${e} === "symbol"`}function ld(e){return`${e} === undefined`}function vM(e){return`typeof ${e} === "function"`}function MM(e){return`Guard.IsConstructor(${e})`}function uo(e,o){return`${e} === ${o}`}function Ty(e,o){return`${e} > ${o}`}function dd(e,o){return`${e} < ${o}`}function Wi(e,o){return`${e} <= ${o}`}function Tu(e,o){return`${e} >= ${o}`}function OM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function _M(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function ls(e,o,i,u){return L(o,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${u}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${o}) || (${u}))`}function LM(e,o,i){return`${e}.some((${o[0]}, ${o[1]}) => ${i})`}function NM(e,o,i){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${i}) result = true }); return result })(${e})`}function om(e,o,i){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${i}) ? ++result : result, 0)`}function Ry(e){return`Object.entries(${e})`}function zi(e){return`Object.getOwnPropertyNames(${e})`}function Vi(e,o){return L(o,'"__proto__"')||L(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function ky(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function DM(e){return`[${e.join(", ")}]`}function Vs(e,o){return`((${e.join(", ")}) => ${o})`}function Ir(e,o){return`${e}(${o.join(", ")})`}function fd(e,o){return`new ${e}(${o.join(", ")})`}function bt(e,o){return`${e}${kM(o)?`.${o}`:`[${De(o)}]`}`}function De(e){if(!Hi(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function qM(e,o,i){return`(${e} ? ${o} : ${i})`}function sm(e){return`{ ${e.join("; ")}; }`}function vs(e,o){return`const ${e} = ${o}`}function Ay(e,o){return`if(${e}) { ${o} }`}function im(e){return`return ${e}`}function Pn(e){return L(e.length,0)?"true":e.reduce((o,i)=>Sn(o,i))}function hd(e){return L(e.length,0)?"false":e.reduce((o,i)=>xr(o,i))}function FM(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function jM(e){return e instanceof Boolean}function UM(e){return e instanceof Number}function BM(e){return e instanceof String}function Py(e){return globalThis.ArrayBuffer.isView(e)}function Cy(e){return e instanceof globalThis.RegExp}function GM(e){return e instanceof globalThis.Date}function KM(e){return e instanceof globalThis.Set}function HM(e){return e instanceof globalThis.Map}var zM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Vo(){return zM}function Js(e){return Vo().immutableTypes?Object.freeze(e):e}function dn(e,o){return cs.assign+=1,Js({...e,...o})}function VM(e){return e}function JM(e){return fe(e,"~kind")||fe(e,"~unsafe")}function QM(e){let o={};for(let i of we(e)){if(wu(i))continue;let u=Object.getOwnPropertyDescriptor(e,i);if(u.value=Ji(u.value),L(u.enumerable,!0))o[i]=u.value;else Object.defineProperty(o,i,u)}return o}function XM(e){let o={};for(let i of we(e)){if(wu(i))continue;o[i]=Ji(e[i])}for(let i of xy(e))o[i]=Ji(e[i]);return o}function YM(e){return fy(e)?VM(e):JM(e)?QM(e):XM(e)}function ZM(e){return e.map((o)=>Ji(o))}function eO(e){return e.slice()}function tO(e){return new RegExp(e.source,e.flags)}function rO(e){return new Map(Ji([...e.entries()]))}function nO(e){return new Set(Ji([...e.values()]))}function Ji(e){return Py(e)?eO(e):Cy(e)?tO(e):HM(e)?rO(e):KM(e)?nO(e):Ge(e)?ZM(e):at(e)?YM(e):e}function Ra(e){return cs.clone+=1,Ji(e)}function oO(e,o){for(let i of Object.keys(o))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:o[i]});return e}function $y(e,o){return{...e,...o}}function Ct(e,o,i={}){cs.create+=1;let u=$y(o,i),p=Vo().enumerableKind?$y(u,e):oO(u,e);return Js(p)}function Jo(e,o){cs.discard+=1;let i={};for(let u of we(e)){if(o.includes(u))continue;let p=Object.getOwnPropertyDescriptor(e,u);p.value=Ra(p.value),Object.defineProperty(i,u,p)}return Js(i)}function St(e,o,i){cs.update+=1;let u=Vo(),p=Ra(e);for(let g of Object.keys(o))Object.defineProperty(p,g,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[g]});for(let g of Object.keys(i))Object.defineProperty(p,g,{configurable:!0,enumerable:!0,writable:!0,value:i[g]});return Js(p)}function Pe(e,o){return at(e)&&fe(e,"~kind")&&L(e["~kind"],o)}function Cr(e){return at(e)}function ve(e,o,i){return Ct({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:i},{})}function Qs(e){return Pe(e,"Deferred")}function sO(e){return St(e,{"~readonly":!0},{})}function ku(e,o){return St(sO(e),{},o)}function vy(e,o,i,u){let p=ge(e,o,i);return ku(p,u)}function iO(e){return St(e,{"~optional":!0},{})}function Au(e,o){return St(iO(e),{},o)}function My(e,o,i,u){let p=ge(e,o,i);return Au(p,u)}function B(e,o){return Ct({"~kind":"Array"},{type:"array",items:e},o)}function wt(e){return Pe(e,"Array")}function ka(e){return Jo(e,["~kind","type","items"])}function ds(e,o,i={}){return Ct({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},i)}function en(e){return Pe(e,"Constructor")}function Oy(e){return Jo(e,["~kind","type","parameters","instanceType"])}function fs(e,o,i={}){return Ct({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},i)}function tn(e){return Pe(e,"Function")}function _y(e){return Jo(e,["~kind","type","parameters","returnType"])}function un(e,o){return Ct({["~kind"]:"Ref"},{$ref:e},o)}function qt(e){return Pe(e,"Ref")}function Xs(e,o){return Ct({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Aa(e){return Pe(e,"Generic")}function Pa(e){return Ct({["~kind"]:"Any"},{},e)}function vr(e){return Pe(e,"Any")}var Ly="(?!)";function zt(e){return Ct({"~kind":"Never"},{not:{}},e)}function co(e){return Pe(e,"Never")}function hs(e,o={}){return ve("AddOptional",[e],o)}function Qi(e,o={}){return Au(e,o)}function n(e){return Qi(e)}function cn(e){return Cr(e)&&fe(e,"~optional")}function Ny(e){return we(e).filter((o)=>!cn(e[o]))}function am(e){return we(e)}function um(e){return pd(e)}function l(e,o={}){let i=Ny(e),u=i.length>0?{required:i}:{};return Ct({"~kind":"Object"},{type:"object",...u,properties:e},o)}function Qe(e){return Pe(e,"Object")}function Dy(e){return Jo(e,["~kind","type","properties","required"])}function Rr(e){return Ct({["~kind"]:"Unknown"},{},e)}function rn(e){return Pe(e,"Unknown")}function gs(e,o,i){let u=we(e).reduce((p,g)=>({...p,[g]:St(e[g],{},{$id:g})}),{});return Ct({["~kind"]:"Cyclic"},{$defs:u,$ref:o},i)}function Qt(e){return Pe(e,"Cyclic")}function qr(e){return St(e,{["~unsafe"]:null},{})}function cm(e){return zo(e)&&fe(e,"~unsafe")&&ho(e["~unsafe"])}function wn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Pu(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p,p],1:(u)=>[u,Rr(),Rr()]});return Ct({["~kind"]:"Infer"},{type:"infer",name:o,extends:i},{})}function nn(e){return Pe(e,"Infer")}function Xi(e,o,i,u={}){return Ct({"~kind":"Dependent"},{if:e,then:o,else:i},u)}function Dr(e){return Pe(e,"Dependent")}function qy(e){return Jo(e,["~kind","if","then","else"])}function Fy(e){return zo(e)}function jy(e){return we(e).filter((i)=>isNaN(i)).reduce((i,u)=>[...i,e[u]],[])}function Uy(e){return gt(e)||Ot(e)}function By(e,o){let i=Fy(e)?jy(e):e;return Ct({"~kind":"Enum"},{enum:i},o)}function on(e){return Pe(e,"Enum")}function Cn(e,o={}){return Ct({"~kind":"Intersect"},{allOf:e},o)}function ze(e){return Pe(e,"Intersect")}function Gy(e){return Jo(e,["~kind","allOf"])}var gd=void 0;function aO(){try{return Hy("null")(),!0}catch{return!1}}function Ky(){if(Ut(gd))gd=aO();return gd&&Vo().useAcceleration}function Hy(...e){return new globalThis.Function(...e)}function jr(){throw Error("Unreachable")}function uO(e){let o=new Set,i=e;while(i&&i!==Object.prototype){for(let u of Reflect.ownKeys(i))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);i=Object.getPrototypeOf(i)}return[...o]}function cO(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 Ca=BigInt("14695981039346656037"),[mO,pO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],lO=Array.from({length:256}).map((e,o)=>BigInt(o)),Jy=new Float64Array(1),Qy=new DataView(Jy.buffer),Xy=new Uint8Array(Jy.buffer);function In(e){Ca=Ca^lO[e],Ca=Ca*mO%pO}function dO(e){In(Bn.Array);for(let o of e)Ys(o)}function fO(e){In(Bn.BigInt),Qy.setBigInt64(0,e);for(let o of Xy)In(o)}function zy(e){In(Bn.Boolean),In(e?1:0)}function hO(e){In(Bn.Constructor),Ys(e.toString())}function gO(e){In(Bn.Date),Ys(e.getTime())}function yO(e){In(Bn.Function),Ys(e.toString())}function xO(e){In(Bn.Null)}function Vy(e){In(Bn.Number),Qy.setFloat64(0,e,!0);for(let o of Xy)In(o)}function IO(e){In(Bn.Object);for(let o of uO(e).sort())Ys(o),Ys(e[o])}function bO(e){In(Bn.RegExp),yd(e.toString())}var EO=new TextEncoder;function yd(e){In(Bn.String);for(let o of EO.encode(e))In(o)}function SO(e){In(Bn.Symbol),Ys(e.toString())}function wO(e){In(Bn.TypeArray);let o=new Uint8Array(e.buffer);for(let i=0;i<o.length;i++)In(o[i])}function TO(e){return In(Bn.Undefined)}function Ys(e){return Py(e)?wO(e):GM(e)?gO(e):Cy(e)?bO(e):jM(e)?zy(e.valueOf()):BM(e)?yd(e.valueOf()):UM(e)?Vy(e.valueOf()):cO(e)?Vy(e):Ge(e)?dO(e):pn(e)?zy(e):Nr(e)?fO(e):ad(e)?hO(e):ho(e)?xO(e):at(e)?IO(e):gt(e)?yd(e):ud(e)?SO(e):Ut(e)?TO(e):ms(e)?yO(e):jr()}function Yy(e){return Ca=BigInt("14695981039346656037"),Ys(e),Ca}function xd(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 RO=Zy;function ex(){return RO}class mm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,i=Hn(o)?(g)=>this.decode(o["~codec"].decode(g)):this.decode,u=Hn(o)?(g)=>o["~codec"].encode(e(g)):e,p={decode:i,encode:u};return St(this.type,{"~codec":p},{})}}class pm{constructor(e){this.type=e}Decode(e){return new mm(this.type,e)}}function lm(e){return new pm(e)}function rx(e,o){return lm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function nx(e,o){return lm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Hn(e){return Cr(e)&&fe(e,"~codec")&&at(e["~codec"])&&fe(e["~codec"],"encode")&&fe(e["~codec"],"decode")}function ox(e){return $a(e)}function Zi(e){return Cr(e)&&fe(e,"~immutable")}function ys(e,o={}){return ve("AddReadonly",[e],o)}function ea(e,o={}){return ku(e,o)}function sx(e){return ea(e)}function ta(e){return Cr(e)&&fe(e,"~readonly")}function AO(e,o){let i=dm(e)?[...e["~refine"],o]:[o];return St(e,{"~refine":i},{})}function ix(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,()=>"Refine Error"]});return AO(o,{check:i,error:u})}function PO(e){return zo(e)&&fe(e,"check")&&fe(e,"error")&&ms(e.check)&&ms(e.error)}function dm(e){return Cr(e)&&fe(e,"~refine")&&Ge(e["~refine"])&&an(e["~refine"],0,(o)=>PO(o))}var ax="-?(?:0|[1-9][0-9]*)n";function Cu(e){return Ct({"~kind":"BigInt"},{type:"bigint"},e)}function mo(e){return Pe(e,"BigInt")}function O(e){return Ct({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return Pe(e,"Boolean")}function $u(e){return Ct({"~kind":"Identifier"},{name:e})}function ux(e){return Pe(e,"Identifier")}var fm="-?(?:0|[1-9][0-9]*)";function _(e){return Ct({"~kind":"Integer"},{type:"integer"},e)}function fn(e){return Pe(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 CO(e){return Nr(e)?"bigint":pn(e)?"boolean":Ot(e)?"number":gt(e)?"string":(()=>{throw new cx(e)})()}function s(e,o){return Ct({"~kind":"Literal"},{type:CO(e),const:e},o)}function hm(e){return Nr(e)||pn(e)||Ot(e)||gt(e)}function mx(e){return yt(e)&&Nr(e.const)}function px(e){return yt(e)&&pn(e.const)}function gm(e){return yt(e)&&Ot(e.const)}function ym(e){return yt(e)&&gt(e.const)}function yt(e){return Pe(e,"Literal")}function $n(e){return Ct({"~kind":"Null"},{type:"null"},e)}function xs(e){return Pe(e,"Null")}var xm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Y(e){return Ct({"~kind":"Number"},{type:"number"},e)}function kr(e){return Pe(e,"Number")}function va(e){return Ct({"~kind":"Symbol"},{type:"symbol"},e)}function Is(e){return Pe(e,"Symbol")}function ra(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,g],1:(p)=>[p,Rr(),Rr()]});return Ct({"~kind":"Parameter"},{name:o,extends:i,equals:u},{})}function lx(e){return Pe(e,"Parameter")}var Im=".*";function a(e){return Ct({"~kind":"String"},{type:"string"},e)}function sn(e){return Pe(e,"String")}function m(e,o={}){return Ct({"~kind":"Union"},{anyOf:e},o)}function xe(e){return Pe(e,"Union")}function dx(e){return Jo(e,["~kind","anyOf"])}function vu(e){let o=fx(e);return L(o.length,2)?o[0]:[]}function $O(e){return!0}function hx(e){return It(e,(o,i)=>vO(o)?hx(i):!1,()=>!0)}function gx(e){return L(e.length,0)?!1:hx(e)}function vO(e){return xe(e)?gx(e.anyOf):yt(e)?$O(e.const):!1}function bm(e){return gx(e)}function Em(e){return Ct({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function yx(e,o,i=[]){return It(e,(u,p)=>yx(p,o,[...i,`${u}${o}`]),()=>i)}function MO(e,o){return L(e.length,0)?[`${o}`]:yx(e,o)}function xx(e,o,i=[]){return It(o,(u,p)=>xx(e,p,[...i,...Ix(e,u)]),()=>i)}function Ix(e,o){return xe(o)?xx(e,o.anyOf):yt(o)?MO(e,o.const):jr()}function bx(e,o){return It(o,(i,u)=>bx(Ix(e,i),u),()=>e)}function OO(e){return e.map((o)=>s(o))}function _O(e){let o=bx([],e),i=OO(o);return m(i)}function LO(e){return L(e.length,0)?jr():L(e.length,1)&&yt(e[0])?e[0]:_O(e)}function Id(e){let o=vu(e);return L(o.length,0)?a():bm(o)?LO(o):Em(e)}function Mu(e){let o=Id(e);return ur(o)?a():o}function no(e,o){let u={[e]:o};return Ct({["~kind"]:"Record"},{type:"object",patternProperties:u})}function Ex(e){return no(Qo,e)}function Sx(e){return l({true:e,false:e})}function Ur(e,o={}){let[i,u,p]=[e,e.length,!1];return Ct({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:u},o)}function mt(e){return Pe(e,"Tuple")}function wx(e){return Jo(e,["~kind","type","items","minItems","additionalItems"])}function NO(e){return Jo(e,["~readonly"])}function bd(e,o){return St(NO(e),{},o)}function Tx(e,o,i,u){let p=ge(e,o,i);return bd(p,u)}function Rx(e,o={}){return ve("RemoveReadonly",[e],o)}function kx(e,o={}){return bd(e,o)}function DO(e){return Jo(e,["~optional"])}function Ed(e,o){return St(DO(e),{},o)}function Ax(e,o,i,u){let p=ge(e,o,i);return Ed(p,u)}function Px(e,o={}){return ve("RemoveOptional",[e],o)}function Sm(e,o={}){return Ed(e,o)}function Sd(e){return e.reduceRight((i,u,p)=>({[p]:u,...i}),{})}function Cx(e){let o=Sd(e.items);return l(o)}function wd(e){return Qe(e)||mt(e)}function qO(e,o){return ta(e)?ta(o)?!0:!1:!1}function FO(e,o){return cn(e)?cn(o)?!0:!1:!1}function jO(e,o){let i=qO(e,o),u=FO(e,o),p=Ar([e,o]),g=kx(Sm(p));return i&&u?ea(Qi(g)):i&&!u?ea(g):!i&&u?Qi(g):g}function UO(e,o,i){return i in e?i in o?jO(e[i],o[i]):e[i]:(i in o)?o[i]:zt()}function BO(e,o){return[...new Set([...we(e),...we(o)])].reduce((p,g)=>({...p,[g]:UO(e,o,g)}),{})}function $x(e){return Qe(e)?e.properties:mt(e)?Sd(e.items):{}}function vx(e,o){let i=$x(e),u=$x(o),p=BO(i,u);return l(p)}function GO(e,o){let i=Ma(e,o);return L(i,_u)?e:L(i,Lu)?o:L(i,Ou)?o:zt()}function KO(e,o){let i=wd(e),u=wd(o);return i&&u?vx(e,o):i&&!u?e:!i&&u?o:GO(e,o)}function Mx(e,o){return co(e)?e:vr(e)?e:rn(e)?o:co(o)?o:vr(o)?o:rn(o)?e:KO(e,o)}function HO(e,o){return xe(e)||xe(o)}function WO(e,o){let i=ko(e),u=ko(o);return HO(i,u)?Ar([i,u]):Mx(i,u)}function Ox(e,o,i=[]){return It(o,(u,p)=>Ox(e,p,[...i,WO(u,e)]),()=>L(i.length,0)?[e]:i)}function _x(e,o,i=[]){return It(e,(u,p)=>_x(p,o,[...i,...Nu([u],o)]),()=>i)}function Nu(e,o=[]){return It(e,(i,u)=>xe(i)?Nu(u,_x(i.anyOf,o)):Nu(u,Ox(i,o)),()=>o)}function zO(e,o){let i=Tn({},e,o);return so(i)?[]:[e]}function Lx(e,o,i=[]){return It(e,(u,p)=>Lx(p,o,[...i,...zO(u,o)]),()=>i)}function wm(e,o){let i=ko(e),u=xe(i)?i.anyOf:[i],p=Lx(u,o);return oo(p)}function Xo(e,o,i){let u=Ar([e,o]),p=wm(i,e);return oo([u,p])}function Zn(e,o=[]){return It(e,(i,u)=>Zn(u,[...o,s(i)]),()=>oo(o))}function Ar(e){let o=Nu(e),i=Td(o);return oo(i)}function vn(e){let o=Mu(e);return ko(o)}function oo(e){let o=Td(e);return Zs(o)}function ko(e){return Dr(e)?Xo(e.if,e.then,e.else):on(e)?Zn(e.enum):ze(e)?Ar(e.allOf):ur(e)?vn(e.pattern):xe(e)?oo(e.anyOf):e}function Zs(e){return L(e.length,1)?e[0]:L(e.length,0)?zt():m(e)}function Nx(e,o){let i=Zn(e);return ei(i,o)}function Dx(e,o){return no(ti,o)}function qx(e,o){let i=Ar(e);return ei(i,o)}function Fx(e,o){return gt(e)||Ot(e)?l({[e]:o}):L(e,!1)?l({false:o}):L(e,!0)?l({true:o}):l({})}function jx(e,o){return no(Oa,o)}function Ux(e,o){return fe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?no(e.pattern.toString(),o):no(Qo,o)}function Bx(e,o){let i=vu(e);return bm(i)?ei(vn(e),o):no(e,o)}function VO(e){return xe(e)?na(e.anyOf):[e]}function na(e,o=[]){return It(e,(i,u)=>na(u,[...o,...VO(i)]),()=>o)}function JO(e){return e.some((o)=>sn(o)||kr(o)||fn(o))}function QO(e,o){return L(JO(e),!0)?no(Qo,o):void 0}function XO(e,o){return e.reduce((i,u)=>yt(u)&&(gt(u.const)||Ot(u.const))?{...i,[u.const]:o}:i,{})}function YO(e,o){let i=XO(e,o);return l(i)}function Gx(e,o){let i=na(e),u=QO(i,o);return Cr(u)?u:YO(i,o)}function ei(e,o){return vr(e)?Ex(o):Wn(e)?Sx(o):on(e)?Nx(e.enum,o):fn(e)?Dx(e,o):ze(e)?qx(e.allOf,o):yt(e)?Fx(e.const,o):kr(e)?jx(e,o):xe(e)?Gx(e.anyOf,o):sn(e)?Ux(e,o):ur(e)?Bx(e.pattern,o):l({})}function Rd(e,o,i){return ct([e])?St(ei(e,o),{},i):Tm(e,o,i)}function Kx(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return Rd(g,y,p)}var ti=`^${fm}$`,Oa=`^${xm}$`,Qo=`^${Im}$`;function Tm(e,o,i={}){return ve("Record",[e,o],i)}function bs(e,o,i={}){return Rd(e,o,i)}function Hx(e,o){return no(e,o)}function Rm(e){return L(e,Qo)?a():L(e,ti)?_():L(e,Oa)?Y():Id(e)}function hn(e){return we(e.patternProperties)[0]}function ri(e){let o=hn(e);return Rm(o)}function fr(e){return e.patternProperties[hn(e)]}function Gt(e){return Pe(e,"Record")}function oa(e){return Ct({"~kind":"Rest"},{type:"rest",items:e},{})}function ni(e){return Pe(e,"Rest")}function km(e){return Ct({["~kind"]:"This"},{$ref:"#"},e)}function Am(e){return Pe(e,"This")}function _a(e){return Ct({"~kind":"Undefined"},{type:"undefined"},e)}function Yo(e){return Pe(e,"Undefined")}function Pm(e){return Ct({"~kind":"Void"},{type:"void"},e)}function po(e){return Pe(e,"Void")}function e_(e,o){return L(e,"Array")?B(o[0]):L(e,"Capitalize")?$m(o[0]):L(e,"ConstructorParameters")?Lm(o[0]):L(e,"Evaluate")?uE(o[0]):L(e,"Exclude")?Nm(o[0],o[1]):L(e,"Extract")?Dm(o[0],o[1]):L(e,"Index")?ju(o[0],o[1]):L(e,"InstanceType")?qm(o[0]):L(e,"Lowercase")?vm(o[0]):L(e,"NonNullable")?Fm(o[0]):L(e,"Omit")?jm(o[0],o[1]):L(e,"Parameters")?Um(o[0]):L(e,"Partial")?Bm(o[0]):L(e,"Pick")?Gm(o[0],o[1]):L(e,"Readonly")?Km(o[0]):L(e,"KeyOf")?Uu(o[0]):L(e,"Record")?Tm(o[0],o[1]):L(e,"Required")?Hm(o[0]):L(e,"ReturnType")?Wm(o[0]):L(e,"Uncapitalize")?Mm(o[0]):L(e,"Uppercase")?Om(o[0]):Fu(un(e),o)}function sa(){throw Error("Unreachable")}function Qx(e,o=[]){return It(e,(i,u)=>Qx(u,[...o,i[1]]),()=>o)}function Ms(e){return L(e.length,3)?[e[0],...Qx(e[1])]:[]}function Xx(e){return ra(e[0],e[2],e[4])}function Yx(e){return ra(e[0],e[2],e[2])}function Zx(e){return ra(e[0],Rr(),e[2])}function eI(e){return ra(e,Rr(),Rr())}function tI(e){return e}function rI(e){return Ms(e)}function nI(e){return e[1]}function oI(e){return Ms(e)}function sI(e){return e[1]}function iI(e){return e_(e[0],e[1])}function aI(e){return null}function uI(e){return a()}function cI(e){return Y()}function mI(e){return O()}function pI(e){return _a()}function lI(e){return $n()}function dI(e){return _()}function fI(e){return Cu()}function hI(e){return Rr()}function gI(e){return Pa()}function yI(e){return l({})}function xI(e){return zt()}function II(e){return va()}function bI(e){return Pm()}function EI(e){return km()}function SI(e){return s(BigInt(e))}function wI(e){return s(L(e,"true"))}function TI(e){return s(parseFloat(e))}function RI(e){return s(e)}function kI(e){return e[1]}function AI(e){return s(e)}function PI(e){return L(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function CI(e){return e[1]}function $I(e){return Cm(e)}function vI(e){return L(e.length,6)?Xi(e[1],e[3],e[5]):Xi(e[1],e[3],Rr())}function MI(e){return e.length>0}function OI(e){return e.reduce((o,i)=>L(i.length,3)?[...o,[i[1]]]:[...o,[]],[])}function _I(e){return L(e.length,6)?[e[1],e[3],e[5]]:[]}function LI(e){return Ge(e)&&L(e.length,3)?e[1]:e}function NI(e){return L(e.length,2)?e[1]:[]}function Wx(e,o){return o.reduce((i,u)=>{let p=u;return L(p.length,1)?ju(i,p[0]):L(p.length,0)?B(i):sa()},e)}function zx(e,o){return L(o.length,3)?_m(e,o[0],o[1],o[2]):e}function t_(e,o){return Ge(o)&&L(o.length,0)?e:zm(e,o)}function DI(e){let[o,i,u,p,g]=e;return t_(o?zx(Uu(Wx(i,u)),p):zx(Wx(i,u),p),g)}function kd(e,o){return L(o.length,3)?(()=>{let[i,u,p]=o,g=kd(u,p);if(L(i,"&"))return ze(g)?Cn([e,...g.allOf]):Cn([e,g]);if(L(i,"|"))return xe(g)?m([e,...g.anyOf]):m([e,g]);sa()})():e}function qI(e){return e}function FI(e){let[o,i]=e;return kd(o,i)}function jI(e){return e}function UI(e){let[o,i]=e;return kd(o,i)}function BI(e){return aE(e[1])}function GI(e){return e[1]}function KI(e){return Xs(e[0],e[2])}function HI(e){return L(e.length,4)?Pu(e[1],e[3]):L(e.length,2)?Pu(e[1],Rr()):sa()}function WI(e){return e}function zI(e){return`${e}`}function VI(e){return e}function JI(e){return e}function QI(e){return fn(e[3])?ti:kr(e[3])?Oa:Is(e[3])?Qo:sn(e[3])?Qo:sa()}function XI(e){return e}function YI(e){return e.length>0}function ZI(e){return e.length>0}function eb(e){let[o,i,u,p,g]=e;return{[i]:o&&u?ys(hs(g)):o&&!u?ys(g):!o&&u?hs(g):g}}function tb(e){return e}function rb(e){return Ms(e)}function nb(e){return e.reduce((o,i)=>fe(i,ti)||fe(i,Oa)||fe(i,Qo)?[o[0],dn(o[1],i)]:[dn(o[0],i),o[1]],[{},{}])}function ob(e){return nb(e[1])}function sb(e){let[o,i]=e,u=L(we(i).length,0)?{}:{patternProperties:i};return l(o,u)}function ib(e){return L(e.length,5)?ys(hs(e[4])):L(e.length,3)?e[2]:L(e.length,4)?L(e[2],"readonly")?ys(e[3]):hs(e[3]):sa()}function ab(e){if(!Ge(e)||!L(e.length,3))return e;let[o,i,u]=e;return o&&u?ys(hs(i)):o&&!u?ys(i):!o&&u?hs(i):i}function ub(e){return L(e.length,2)?oa(e[1]):L(e.length,1)?e[0]:sa()}function cb(e){return Ms(e)}function mb(e){return Ur(e[1])}function pb(e){return ys(hs(e[4]))}function lb(e){return ys(e[3])}function db(e){return hs(e[3])}function fb(e){return e[2]}function hb(e){return e}function gb(e){return L(e.length,2)?oa(e[1]):L(e.length,1)?e[0]:sa()}function yb(e){return Ms(e)}function xb(e){return fs(e[1],e[4])}function Ib(e){return ds(e[2],e[5])}function Vx(e,o){return L(e,"remove")?Rx(o):L(e,"add")?ys(o):o}function bb(e){return L(e.length,2)&&L(e[0],"-")?"remove":L(e.length,2)&&L(e[0],"+")?"add":L(e.length,1)?"add":"none"}function Jx(e,o){return L(e,"remove")?Px(o):L(e,"add")?hs(o):o}function Eb(e){return L(e.length,2)&&L(e[0],"-")?"remove":L(e.length,2)&&L(e[0],"+")?"add":L(e.length,1)?"add":"none"}function Sb(e){return L(e.length,2)?[e[1]]:[]}function wb(e){return Ge(e[6])&&L(e[6].length,1)?Du($u(e[3]),e[5],e[6][0],Vx(e[1],Jx(e[8],e[10]))):Du($u(e[3]),e[5],un(e[3]),Vx(e[1],Jx(e[8],e[10])))}function Tb(e){return un(e)}function Rb(e){return BigInt(e)}function kb(e){return parseFloat(e)}function Ab(e){return L(e,"true")}function Pb(e){return e}function Cb(e){return null}function $b(e){return}function vb(e){return{[e[0]]:e[2]}}function Mb(e){return Ms(e)}function r_(e){return e.reduce((o,i)=>dn(o,i),{})}function Ob(e){return r_(e[1])}function _b(e){return Ms(e)}function Lb(e){return e[1]}function Nb(e){return e}function Db(e){return Cu()}function qb(e){return a()}function Fb(e){return Y()}function jb(e){return _()}function Ub(e){return zt()}function Bb(e){return s(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 Ms(e)}function Qb(e){return L(e.length,2)?e[1]:[]}function Xb(e){let o=e[2],i=e[3],[u,p]=e[4],g=L(we(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Xs(o,qu(i,u,g))}}function Yb(e){let o=e[2],[i,u]=e[3],p=L(we(u).length,0)?{}:{patternProperties:u};return{[e[1]]:qu(o,i,p)}}function Zb(e){return{[e[1]]:Xs(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 Ms(e)}function oE(e){return e[1]}function sE(e){let[o,i]=[e[0],e[1]];return cE(dn(o,nb(i)[0]))}function iE(e){return e}function Bu(e){return L(e.length,2)}function Tt(e,o,i){return Bu(e)?o(e[0],e[1]):i()}function s_(e,o){return L(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Or(e,o){for(let i=0;i<e.length;i++){let u=s_(e[i],o);if(Bu(u))return u}return[]}function Ad(e,o){return Array.from({length:o-e+1},(i,u)=>String.fromCharCode(e+u))}var mE=[...Ad(97,122),...Ad(65,90)],Pd="0",Cd=Ad(49,57),La=[Pd,...Cd],pE=" ",Na=`
17
+ `;var oi="_",Vm=".",lE="$",Jm="-";var dE="//",fE="/*",a_="*/";function hE(e){let o=e.indexOf(a_);return L(o,-1)?"":e.slice(o+2)}function gE(e){let o=e.indexOf(Na);return L(o,-1)?"":e.slice(o)}function u_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Qm(e){let o=u_(e);return o.startsWith(fE)?Qm(hE(o.slice(2))):o.startsWith(dE)?Qm(gE(o.slice(2))):o}function bn(e){let o=e.trimStart();return o.startsWith(fE)?bn(hE(o.slice(2))):o.startsWith(dE)?bn(gE(o.slice(2))):o}function Xm(e,o){return Tt(Or([e],o),(i,u)=>[i,u],()=>["",o])}function c_(e,o){return e.includes(o)}function Da(e,o,i,u=""){return Tt(Or(e,i),(p,g)=>c_(o,p)?Da(e,o,g,u):Da(e,o,g,`${u}${p}`),()=>[u,i])}function m_(e){return Or(Cd,e)}var p_=[...La,oi];function l_(e){return Da(p_,[oi],e)}function d_(e){return Tt(Or([Pd],e),(o,i)=>[o,i],()=>Tt(m_(e),(o,i)=>Tt(l_(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[]))}function Ym(e){return d_(bn(e))}function f_(e){return Xm(Jm,e)}function h_(e){return Tt(f_(e),(o,i)=>Tt(Ym(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function yE(e){return h_(bn(e))}function g_(e){return Tt(yE(e),(o,i)=>Tt(Or(["n"],i),(u,p)=>[`${o}`,p],()=>[]),()=>[])}function $d(e){return g_(e)}function vd(e,o){return Or([e],o)}function Z(e,o){return L(e,"")?["",o]:e.startsWith(Na)?vd(e,Qm(o)):e.startsWith(pE)?vd(e,o):vd(e,bn(o))}var xE=[...mE,oi,lE];function y_(e){return Or(xE,e)}var x_=[...xE,...La];function IE(e,o=""){return Tt(Or(x_,e),(i,u)=>IE(u,`${o}${i}`),()=>[o,e])}function I_(e){return Tt(y_(e),(o,i)=>Tt(IE(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Br(e){return I_(bn(e))}var b_=[...La,oi];function E_(e){return Bu(Or([Vm],e))}function bE(e){return Tt(Da(b_,[oi],e),(o,i)=>L(o,"")?[]:[o,i],()=>[])}function S_(e){return Tt(Or([Vm],e),(o,i)=>Tt(bE(i),(u,p)=>[`0${o}${u}`,p],()=>[]),()=>[])}function w_(e){return Tt(Ym(e),(o,i)=>Tt(Or([Vm],i),(u,p)=>Tt(bE(p),(g,y)=>[`${o}${u}${g}`,y],()=>[`${o}`,p]),()=>[`${o}`,i]),()=>[])}function T_(e){return E_(e)?S_(e):w_(e)}function EE(e){return T_(bn(e))}function R_(e){return Xm(Jm,e)}function k_(e){return Tt(R_(e),(o,i)=>Tt(EE(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Zm(e){return k_(bn(e))}function A_(e){return L(e,"")?[]:[e.slice(0,1),e.slice(1)]}function SE(e,o){return It(e,(i,u)=>o.startsWith(i)?!0:SE(u,o),()=>!1)}function si(e,o,i=""){return Tt(A_(o),(u,p)=>SE(e,o)?[i,o]:si(e,p,`${i}${u}`),()=>[])}function P_(e,o,i){return Tt(Or([e],i),(u,p)=>Tt(si([o],p),(g,y)=>Tt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function C_(e,o,i){return Tt(Or([e],i),(u,p)=>Tt(si([Na,o],p),(g,y)=>Tt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function wE(e,o,i,u){return i?P_(e,o,bn(u)):C_(e,o,bn(u))}function $_(e,o){return Or(e,o)}function v_(e,o){return wE(e,e,!1,o)}function M_(e,o){return Tt($_(e,o),(i,u)=>v_(i,`${i}${u}`),()=>[])}function ep(e,o){return M_(e,bn(o))}function TE(e,o){return Tt(si(e,o),(i,u)=>L(i,"")?[]:[i,u],()=>[])}var T=(e,o,i=()=>[])=>e.length===2?o(e):i(),__=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([u,p])=>T(vt(p),([g,y])=>T(Z("=",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Xx(o),i]),L_=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Yx(o),i]),N_=(e)=>T(T(Br(e),([o,i])=>T(Z("=",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Zx(o),i]),D_=(e)=>T(Br(e),([o,i])=>[eI(o),i]),AE=(e)=>T(T(__(e),([o,i])=>[o,i],()=>T(L_(e),([o,i])=>[o,i],()=>T(N_(e),([o,i])=>[o,i],()=>T(D_(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[tI(o),i]),PE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(AE(u),([p,g])=>[[i,p],g])),([i,u])=>PE(u,[...o,i]),()=>[o,e]),q_=(e)=>T(T(T(AE(e),([o,i])=>T(PE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[rI(o),i]),_d=(e)=>T(T(Z("<",e),([o,i])=>T(q_(i),([u,p])=>T(Z(">",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[nI(o),i]),CE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vt(u),([p,g])=>[[i,p],g])),([i,u])=>CE(u,[...o,i]),()=>[o,e]),F_=(e)=>T(T(T(vt(e),([o,i])=>T(CE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[oI(o),i]),j_=(e)=>T(T(Z("<",e),([o,i])=>T(F_(i),([u,p])=>T(Z(">",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[sI(o),i]),U_=(e)=>T(T(Br(e),([o,i])=>T(j_(i),([u,p])=>[[o,u],p])),([o,i])=>[iI(o),i]),$E=(e)=>T(T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[aI(o),i]),vE=(e)=>T(Z("string",e),([o,i])=>[uI(o),i]),ME=(e)=>T(Z("number",e),([o,i])=>[cI(o),i]),B_=(e)=>T(Z("boolean",e),([o,i])=>[mI(o),i]),G_=(e)=>T(Z("undefined",e),([o,i])=>[pI(o),i]),K_=(e)=>T(Z("null",e),([o,i])=>[lI(o),i]),OE=(e)=>T(Z("integer",e),([o,i])=>[dI(o),i]),H_=(e)=>T(Z("bigint",e),([o,i])=>[fI(o),i]),W_=(e)=>T(Z("unknown",e),([o,i])=>[hI(o),i]),z_=(e)=>T(Z("any",e),([o,i])=>[gI(o),i]),V_=(e)=>T(Z("object",e),([o,i])=>[yI(o),i]),J_=(e)=>T(Z("never",e),([o,i])=>[xI(o),i]),_E=(e)=>T(Z("symbol",e),([o,i])=>[II(o),i]),Q_=(e)=>T(Z("void",e),([o,i])=>[bI(o),i]),X_=(e)=>T(Z("this",e),([o,i])=>[EI(o),i]),Y_=(e)=>T(T(Z("${",e),([o,i])=>T(vt(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[kI(o),i]),Md=(e)=>T(si(["${","`"],e),([o,i])=>[AI(o),i]),LE=(e)=>T(T(T(Md(e),([o,i])=>T(Y_(i),([u,p])=>T(LE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(T(Md(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Md(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[PI(o),i]),Ld=(e)=>T(T(Z("`",e),([o,i])=>T(LE(i),([u,p])=>T(Z("`",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[CI(o),i]),Z_=(e)=>T(Ld(e),([o,i])=>[$I(o),i]),eL=(e)=>T(T(T(Z("if",e),([o,i])=>T(vt(i),([u,p])=>T(Z("then",p),([g,y])=>T(vt(y),([b,E])=>T(Z("else",E),([S,w])=>T(vt(w),([R,A])=>[[o,u,g,b,S,R],A])))))),([o,i])=>[o,i],()=>T(T(Z("if",e),([o,i])=>T(vt(i),([u,p])=>T(Z("then",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>[])),([o,i])=>[vI(o),i]),tL=(e)=>T($d(e),([o,i])=>[SI(o),i]),rL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[wI(o),i]),nL=(e)=>T(Zm(e),([o,i])=>[TI(o),i]),oL=(e)=>T(ep(["'",'"'],e),([o,i])=>[RI(o),i]),sL=(e)=>T(T(T(Z("keyof",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[MI(o),i]),NE=(e,o=[])=>T(T(T(Z("[",e),([i,u])=>T(vt(u),([p,g])=>T(Z("]",g),([y,b])=>[[i,p,y],b]))),([i,u])=>[i,u],()=>T(T(Z("[",e),([i,u])=>T(Z("]",u),([p,g])=>[[i,p],g])),([i,u])=>[i,u],()=>[])),([i,u])=>NE(u,[...o,i]),()=>[o,e]),iL=(e)=>T(NE(e),([o,i])=>[OI(o),i]),aL=(e)=>T(T(T(Z("extends",e),([o,i])=>T(vt(i),([u,p])=>T(Z("?",p),([g,y])=>T(vt(y),([b,E])=>T(Z(":",E),([S,w])=>T(vt(w),([R,A])=>[[o,u,g,b,S,R],A])))))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[_I(o),i]),uL=(e)=>T(T(T(Z("(",e),([o,i])=>T(vt(i),([u,p])=>T(Z(")",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(vE(e),([o,i])=>[o,i],()=>T(ME(e),([o,i])=>[o,i],()=>T(B_(e),([o,i])=>[o,i],()=>T(G_(e),([o,i])=>[o,i],()=>T(K_(e),([o,i])=>[o,i],()=>T(OE(e),([o,i])=>[o,i],()=>T(H_(e),([o,i])=>[o,i],()=>T(W_(e),([o,i])=>[o,i],()=>T(z_(e),([o,i])=>[o,i],()=>T(V_(e),([o,i])=>[o,i],()=>T(J_(e),([o,i])=>[o,i],()=>T(_E(e),([o,i])=>[o,i],()=>T(Q_(e),([o,i])=>[o,i],()=>T(X_(e),([o,i])=>[o,i],()=>T(tL(e),([o,i])=>[o,i],()=>T(rL(e),([o,i])=>[o,i],()=>T(nL(e),([o,i])=>[o,i],()=>T(oL(e),([o,i])=>[o,i],()=>T(Z_(e),([o,i])=>[o,i],()=>T(eL(e),([o,i])=>[o,i],()=>T(IL(e),([o,i])=>[o,i],()=>T(SL(e),([o,i])=>[o,i],()=>T(PL(e),([o,i])=>[o,i],()=>T(AL(e),([o,i])=>[o,i],()=>T(ML(e),([o,i])=>[o,i],()=>T(U_(e),([o,i])=>[o,i],()=>T(OL(e),([o,i])=>[o,i],()=>[])))))))))))))))))))))))))))),([o,i])=>[LI(o),i]),cL=(e)=>T(T(T(Z("with",e),([o,i])=>T(ZE(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[NI(o),i]),DE=(e)=>T(T(sL(e),([o,i])=>T(uL(i),([u,p])=>T(iL(p),([g,y])=>T(aL(y),([b,E])=>T(cL(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[DI(o),i]),qE=(e)=>T(T(T(Z("&",e),([o,i])=>T(DE(i),([u,p])=>T(qE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[qI(o),i]),FE=(e)=>T(T(DE(e),([o,i])=>T(qE(i),([u,p])=>[[o,u],p])),([o,i])=>[FI(o),i]),jE=(e)=>T(T(T(Z("|",e),([o,i])=>T(FE(i),([u,p])=>T(jE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[jI(o),i]),tp=(e)=>T(T(FE(e),([o,i])=>T(jE(i),([u,p])=>[[o,u],p])),([o,i])=>[UI(o),i]),mL=(e)=>T(T(Z("readonly",e),([o,i])=>T(tp(i),([u,p])=>[[o,u],p])),([o,i])=>[BI(o),i]),pL=(e)=>T(T(Z("|",e),([o,i])=>T(tp(i),([u,p])=>[[o,u],p])),([o,i])=>[GI(o),i]),lL=(e)=>T(T(_d(e),([o,i])=>T(Z("=",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[KI(o),i]),dL=(e)=>T(T(T(Z("infer",e),([o,i])=>T(Br(i),([u,p])=>T(Z("extends",p),([g,y])=>T(tp(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Z("infer",e),([o,i])=>T(Br(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>[])),([o,i])=>[HI(o),i]),vt=(e)=>T(T(dL(e),([o,i])=>[o,i],()=>T(pL(e),([o,i])=>[o,i],()=>T(mL(e),([o,i])=>[o,i],()=>T(tp(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[WI(o),i]),fL=(e)=>T(Zm(e),([o,i])=>[zI(o),i]),hL=(e)=>T(Br(e),([o,i])=>[VI(o),i]),gL=(e)=>T(ep(["'",'"'],e),([o,i])=>[JI(o),i]),yL=(e)=>T(T(Z("[",e),([o,i])=>T(Br(i),([u,p])=>T(Z(":",p),([g,y])=>T(T(OE(y),([b,E])=>[b,E],()=>T(ME(y),([b,E])=>[b,E],()=>T(vE(y),([b,E])=>[b,E],()=>T(_E(y),([b,E])=>[b,E],()=>[])))),([b,E])=>T(Z("]",E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[QI(o),i]),UE=(e)=>T(T(fL(e),([o,i])=>[o,i],()=>T(hL(e),([o,i])=>[o,i],()=>T(gL(e),([o,i])=>[o,i],()=>T(yL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[XI(o),i]),BE=(e)=>T(T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[YI(o),i]),GE=(e)=>T(T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[ZI(o),i]),KE=(e)=>T(T(BE(e),([o,i])=>T(UE(i),([u,p])=>T(GE(p),([g,y])=>T(Z(":",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[eb(o),i]),rp=(e)=>T(T(T(Z(",",e),([o,i])=>T(Z(`
18
+ `,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>T(Z(`
19
+ `,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(",",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
20
+ `,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))))),([o,i])=>[tb(o),i]),HE=(e,o=[])=>T(T(rp(e),([i,u])=>T(KE(u),([p,g])=>[[i,p],g])),([i,u])=>HE(u,[...o,i]),()=>[o,e]),xL=(e)=>T(T(T(KE(e),([o,i])=>T(HE(i),([u,p])=>T(T(rp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[rb(o),i]),Nd=(e)=>T(T(Z("{",e),([o,i])=>T(xL(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[ob(o),i]),IL=(e)=>T(Nd(e),([o,i])=>[sb(o),i]),bL=(e)=>T(T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(Z("readonly",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>[])))),([o,i])=>[ib(o),i]),RE=(e)=>T(T(bL(e),([o,i])=>[o,i],()=>T(T(BE(e),([o,i])=>T(vt(i),([u,p])=>T(GE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>[])),([o,i])=>[ab(o),i]),WE=(e)=>T(T(T(Z("...",e),([o,i])=>T(RE(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(RE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[ub(o),i]),zE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(WE(u),([p,g])=>[[i,p],g])),([i,u])=>zE(u,[...o,i]),()=>[o,e]),EL=(e)=>T(T(T(WE(e),([o,i])=>T(zE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[cb(o),i]),SL=(e)=>T(T(Z("[",e),([o,i])=>T(EL(i),([u,p])=>T(Z("]",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[mb(o),i]),wL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[pb(o),i]),TL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(Z("readonly",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[lb(o),i]),RL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[db(o),i]),kL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[fb(o),i]),kE=(e)=>T(T(wL(e),([o,i])=>[o,i],()=>T(TL(e),([o,i])=>[o,i],()=>T(RL(e),([o,i])=>[o,i],()=>T(kL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[hb(o),i]),VE=(e)=>T(T(T(Z("...",e),([o,i])=>T(kE(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(kE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[gb(o),i]),JE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(VE(u),([p,g])=>[[i,p],g])),([i,u])=>JE(u,[...o,i]),()=>[o,e]),QE=(e)=>T(T(T(VE(e),([o,i])=>T(JE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[yb(o),i]),AL=(e)=>T(T(Z("(",e),([o,i])=>T(QE(i),([u,p])=>T(Z(")",p),([g,y])=>T(Z("=>",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[xb(o),i]),PL=(e)=>T(T(Z("new",e),([o,i])=>T(Z("(",i),([u,p])=>T(QE(p),([g,y])=>T(Z(")",y),([b,E])=>T(Z("=>",E),([S,w])=>T(vt(w),([R,A])=>[[o,u,g,b,S,R],A])))))),([o,i])=>[Ib(o),i]),CL=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("readonly",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("readonly",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[bb(o),i]),$L=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("?",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("?",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Eb(o),i]),vL=(e)=>T(T(T(Z("as",e),([o,i])=>T(vt(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Sb(o),i]),ML=(e)=>T(T(Z("{",e),([o,i])=>T(CL(i),([u,p])=>T(Z("[",p),([g,y])=>T(Br(y),([b,E])=>T(Z("in",E),([S,w])=>T(vt(w),([R,A])=>T(vL(A),([P,C])=>T(Z("]",C),([q,X])=>T($L(X),([j,V])=>T(Z(":",V),([J,ee])=>T(vt(ee),([ae,H])=>T($E(H),([ue,he])=>T(Z("}",he),([$e,Ee])=>[[o,u,g,b,S,R,P,q,j,J,ae,ue,$e],Ee]))))))))))))),([o,i])=>[wb(o),i]),OL=(e)=>T(Br(e),([o,i])=>[Tb(o),i]),_L=(e)=>T($d(e),([o,i])=>[Rb(o),i]),LL=(e)=>T(Zm(e),([o,i])=>[kb(o),i]),NL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[Ab(o),i]),DL=(e)=>T(ep(['"',"'"],e),([o,i])=>[Pb(o),i]),qL=(e)=>T(Z("null",e),([o,i])=>[Cb(o),i]),FL=(e)=>T(Z("undefined",e),([o,i])=>[$b(o),i]),XE=(e)=>T(T(UE(e),([o,i])=>T(Z(":",i),([u,p])=>T(Dd(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[vb(o),i]),YE=(e,o=[])=>T(T(rp(e),([i,u])=>T(XE(u),([p,g])=>[[i,p],g])),([i,u])=>YE(u,[...o,i]),()=>[o,e]),jL=(e)=>T(T(T(XE(e),([o,i])=>T(YE(i),([u,p])=>T(T(rp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Mb(o),i]),ZE=(e)=>T(T(Z("{",e),([o,i])=>T(jL(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Ob(o),i]),eS=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(Dd(u),([p,g])=>[[i,p],g])),([i,u])=>eS(u,[...o,i]),()=>[o,e]),UL=(e)=>T(T(T(Dd(e),([o,i])=>T(eS(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[_b(o),i]),BL=(e)=>T(T(Z("[",e),([o,i])=>T(UL(i),([u,p])=>T(Z("]",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Lb(o),i]),Dd=(e)=>T(T(_L(e),([o,i])=>[o,i],()=>T(LL(e),([o,i])=>[o,i],()=>T(NL(e),([o,i])=>[o,i],()=>T(DL(e),([o,i])=>[o,i],()=>T(qL(e),([o,i])=>[o,i],()=>T(FL(e),([o,i])=>[o,i],()=>T(ZE(e),([o,i])=>[o,i],()=>T(BL(e),([o,i])=>[o,i],()=>[])))))))),([o,i])=>[Nb(o),i]),GL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)n",e),([o,i])=>[Db(o),i]),KL=(e)=>T(Z(".*",e),([o,i])=>[qb(o),i]),HL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,i])=>[Fb(o),i]),WL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)",e),([o,i])=>[jb(o),i]),zL=(e)=>T(Z("(?!)",e),([o,i])=>[Ub(o),i]),VL=(e)=>T(TE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,i])=>[Bb(o),i]),JL=(e)=>T(T(GL(e),([o,i])=>[o,i],()=>T(KL(e),([o,i])=>[o,i],()=>T(HL(e),([o,i])=>[o,i],()=>T(WL(e),([o,i])=>[o,i],()=>T(zL(e),([o,i])=>[o,i],()=>T(QL(e),([o,i])=>[o,i],()=>T(VL(e),([o,i])=>[o,i],()=>[]))))))),([o,i])=>[Gb(o),i]),QL=(e)=>T(T(Z("(",e),([o,i])=>T(qd(i),([u,p])=>T(Z(")",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Kb(o),i]),tS=(e)=>T(T(T(Od(e),([o,i])=>T(Z("|",i),([u,p])=>T(tS(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(T(Od(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[]))),([o,i])=>[Hb(o),i]),Od=(e)=>T(T(JL(e),([o,i])=>T(qd(i),([u,p])=>[[o,u],p])),([o,i])=>[Wb(o),i]),qd=(e)=>T(T(tS(e),([o,i])=>[o,i],()=>T(Od(e),([o,i])=>[o,i],()=>[])),([o,i])=>[zb(o),i]),fx=(e)=>T(T(Z("^",e),([o,i])=>T(qd(i),([u,p])=>T(Z("$",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Vb(o),i]),rS=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vt(u),([p,g])=>[[i,p],g])),([i,u])=>rS(u,[...o,i]),()=>[o,e]),XL=(e)=>T(T(T(vt(e),([o,i])=>T(rS(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Jb(o),i]),nS=(e)=>T(T(T(Z("extends",e),([o,i])=>T(XL(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Qb(o),i]),YL=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([u,p])=>T(_d(p),([g,y])=>T(nS(y),([b,E])=>T(Nd(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Xb(o),i]),ZL=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([u,p])=>T(nS(p),([g,y])=>T(Nd(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[Yb(o),i]),eN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([u,p])=>T(_d(p),([g,y])=>T(Z("=",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Zb(o),i]),tN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([u,p])=>T(Z("=",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[eE(o),i]),rN=(e)=>T(T(T(Z("export",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[tE(o),i]),oS=(e)=>T(T(T(Z(";",e),([o,i])=>T(Z(`
21
+ `,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
22
+ `,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[rE(o),i]),sS=(e,o=[])=>T(T(oS(e),([i,u])=>T(Fd(u),([p,g])=>[[i,p],g])),([i,u])=>sS(u,[...o,i]),()=>[o,e]),nN=(e)=>T(T(T(Fd(e),([o,i])=>T(sS(i),([u,p])=>T(T(oS(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[nE(o),i]),Fd=(e)=>T(T(rN(e),([o,i])=>T(T(YL(i),([u,p])=>[u,p],()=>T(ZL(i),([u,p])=>[u,p],()=>T(eN(i),([u,p])=>[u,p],()=>T(tN(i),([u,p])=>[u,p],()=>[])))),([u,p])=>T($E(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[oE(o),i]),oN=(e)=>T(T(Fd(e),([o,i])=>T(nN(i),([u,p])=>[[o,u],p])),([o,i])=>[sE(o),i]),iS=(e)=>T(T(oN(e),([o,i])=>[o,i],()=>T(lL(e),([o,i])=>[o,i],()=>T(vt(e),([o,i])=>[o,i],()=>[]))),([o,i])=>[iE(o),i]);function aS(e){let o=Ld(`\`${e}\``);return L(o.length,2)?o[0]:jr()}function iN(e){return e.join("|")}function aN(e){return e.slice(1,e.length-1)}function uN(e,o,i){return ii(o,`${i}${e}`)}function cN(e,o){return ii(e,`${o}${ax}`)}function mN(e,o){return ii(e,`${o}${fm}`)}function pN(e,o){return ii(e,`${o}${xm}`)}function lN(e,o){return Gu(m([s("false"),s("true")]),e,o)}function dN(e,o){return ii(e,`${o}${Im}`)}function fN(e,o,i){return ii(o,`${i}${aN(e)}`)}function hN(e,o,i){let u=Ku(e,{});return Gu(u,o,i)}function gN(e,o,i){let u=Zn(e);return Gu(u,o,i)}function uS(e,o,i,u=[]){return It(e,(p,g)=>uS(g,o,i,[...u,Gu(p,[],"")]),()=>ii(o,`${i}(${iN(u)})`))}function Gu(e,o,i){return on(e)?gN(e.enum,o,i):fn(e)?mN(o,i):yt(e)?uN(e.const,o,i):mo(e)?cN(o,i):Wn(e)?lN(o,i):kr(e)?pN(o,i):sn(e)?dN(o,i):ur(e)?fN(e.pattern,o,i):mS(e)?hN(e.parameters[0],o,i):xe(e)?uS(e.anyOf,o,i):Ly}function ii(e,o){return It(e,(i,u)=>Gu(i,u,o),()=>o)}function yN(e){return`^${ii(e,"")}$`}function cS(e){let o=yN(e);return Em(o)}function Ku(e,o){return ct(e)?St(cS(e),{},o):Cm(e,o)}function pS(e,o,i,u){let p=yo(e,o,i);return Ku(p,u)}function Cm(e,o={}){return ve("TemplateLiteral",[e],o)}function mS(e){return Cr(e)&&fe(e,"action")&&L(e.action,"TemplateLiteral")}function lS(e){return Ku(e,{})}function xN(e){let o=aS(e);return lS(o)}function dS(e,o={}){let i=gt(e)?xN(e):lS(e);return St(i,{},o)}function ur(e){return Pe(e,"TemplateLiteral")}function jd(e){return Ct({["~kind"]:"ExtendsUnion"},{inferred:e})}function Ud(e){return at(e)&&fe(e,"~kind")&&fe(e,"inferred")&&L(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function Ae(e){return Ct({["~kind"]:"ExtendsTrue"},{inferred:e})}function Bd(e){return at(e)&&fe(e,"~kind")&&fe(e,"inferred")&&L(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ze(){return Ct({["~kind"]:"ExtendsFalse"},{})}function Gd(e){return at(e)&&fe(e,"~kind")&&L(e["~kind"],"ExtendsFalse")}function so(e){return Ud(e)||Bd(e)}function br(e,o,i){return so(e)?o(e.inferred):i()}function IN(e,o,i,u){return br(Rt(e,i,u),(p)=>Ae(dn(dn(e,p),{[o]:i})),()=>Ze())}function bN(e,o){return Ae(e)}function EN(e,o,i,u,p){return br(Rt(e,o,i),(g)=>br(Rt(g,o,u),(y)=>Ae(y),()=>Ze()),()=>br(Rt(e,o,p),(g)=>Ae(g),()=>Ze()))}function SN(e,o,i){let u=Zn(i);return Rt(e,o,u)}function fS(e,o,i){return It(i,(u,p)=>br(Rt(e,o,u),(g)=>fS(g,o,p),()=>Ze()),()=>Ae(e))}function wN(e,o,i){let u=vn(i);return Rt(e,o,u)}function hS(e,o,i){return It(i,(u,p)=>br(Rt(e,o,u),(g)=>Ae(g),()=>hS(e,o,p)),()=>Ze())}function Nt(e,o,i){return vr(i)?bN(e,o):Dr(i)?EN(e,o,i.if,i.then,i.else):on(i)?SN(e,o,i.enum):nn(i)?IN(e,i.name,o,i.extends):ze(i)?fS(e,o,i.allOf):ur(i)?wN(e,o,i.pattern):xe(i)?hS(e,o,i.anyOf):rn(i)?Ae(e):Ze()}function gS(e,o,i){return nn(i)?Nt(e,o,i):vr(i)?Ae(e):rn(i)?Ae(e):jd(e)}function TN(e,o){let i=Zi(e),u=Zi(o);return i&&u?!0:!i&&u?!0:i&&!u?!1:!0}function yS(e,o,i,u){return wt(u)?TN(o,u)?Rt(e,i,u.items):Ze():Nt(e,o,u)}function xS(e,o,i){return mo(i)?Ae(e):Nt(e,o,i)}function IS(e,o,i){return Wn(i)?Ae(e):Nt(e,o,i)}function RN(e,o,i,u,p){let g=nn(u)?o:u,y=nn(u)?u:o,b=cn(o),E=cn(u);return!b&&E?Ze():br(Rt(e,g,y),(S)=>Hu(S,i,p),()=>Ze())}function kN(e,o,i,u){return It(u,(p,g)=>RN(e,o,i,p,g),()=>cn(o)?Ae(e):Ze())}function AN(e,o,i){return It(o,(u,p)=>kN(e,u,p,i),()=>Ae(e))}function Hu(e,o,i){return AN(e,o,i)}function np(e,o,i){return po(i)?Ae(e):Rt(e,o,i)}function bS(e,o,i,u){return vr(u)?Ae(e):rn(u)?Ae(e):en(u)?br(Hu(e,o,u.parameters),(p)=>np(p,i,u.instanceType),()=>Ze()):Ze()}function ES(e,o,i,u,p){return br(Rt(e,o,p),()=>Rt(e,i,p),()=>Rt(e,u,p))}function SS(e,o,i){let u=Zn(o);return Rt(e,u,i)}function wS(e,o,i,u){return vr(u)?Ae(e):rn(u)?Ae(e):tn(u)?br(Hu(e,o,u.parameters),(p)=>np(p,i,u.returnType),()=>Ze()):Ze()}function TS(e,o,i){return fn(i)?Ae(e):kr(i)?Ae(e):Nt(e,o,i)}function RS(e,o,i){let u=Ar(o);return Rt(e,u,i)}function op(e,o,i){return o===i?Ae(e):Ze()}function PN(e,o,i){return yt(i)?op(e,o,i.const):mo(i)?Ae(e):Nt(e,s(o),i)}function CN(e,o,i){return yt(i)?op(e,o,i.const):Wn(i)?Ae(e):Nt(e,s(o),i)}function $N(e,o,i){return yt(i)?op(e,o,i.const):kr(i)?Ae(e):Nt(e,s(o),i)}function vN(e,o,i){return yt(i)?op(e,o,i.const):sn(i)?Ae(e):Nt(e,s(o),i)}function kS(e,o,i){return Nr(o.const)?PN(e,o.const,i):pn(o.const)?CN(e,o.const,i):Ot(o.const)?$N(e,o.const,i):gt(o.const)?vN(e,o.const,i):jr()}function AS(e,o,i){return nn(i)?Nt(e,o,i):Ae(e)}function PS(e,o,i){return xs(i)?Ae(e):Nt(e,o,i)}function CS(e,o,i){return kr(i)?Ae(e):Nt(e,o,i)}function MN(e,o,i){return cn(o)?cn(i)?Ae(e):Ze():Ae(e)}function ON(e,o,i){return nn(i)&&co(i.extends)?Ze():br(Rt(e,o,i),(u)=>MN(u,o,i),()=>Ze())}function _N(e,o){return e.reduce((i,u)=>(u in o)?so(o[u])?{...i,...o[u].inferred}:jr():jr(),{})}function LN(e,o,i){let u={};for(let y of we(i))u[y]=y in o?ON({},o[y],i[y]):cn(i[y])?nn(i[y])?Ae(dn(e,{[i[y].name]:i[y].extends})):Ae(e):Ze();let p=pd(u).every((y)=>so(y)),g=p?_N(we(u),u):{};return p?Ae(g):Ze()}function NN(e,o,i){let u=LN(e,o,i);return so(u)?Ae(dn(e,u.inferred)):Ze()}function DN(e,o,i){return NN(e,o,i)}function qN(e,o){return we(o).reduce((i,u)=>({...i,[u]:fe(e,u)?xe(i[u])?m([...i[u].anyOf,o[u]]):m([e[u],o[u]]):o[u]}),e)}function $S(e,o,i,u){return It(o,(p,g)=>br(Rt({},e[p],i),(y)=>$S(e,g,i,qN(u,y)),()=>Ze()),()=>Ae(u))}function FN(e,o,i,u){let p=we(o);return $S(o,p,u,e)}function vS(e,o,i){return Gt(i)?FN(e,o,hn(i),fr(i)):Qe(i)?DN(e,o,i.properties):Nt(e,l(o),i)}function jN(e,o){return L(we(o).length,0)?Ae(e):Ze()}function UN(e,o,i,u,p){return Rt(e,i,p)}function MS(e,o,i,u){return Gt(u)?UN(e,Rm(o),i,Rm(hn(u)),fr(u)):Qe(u)?jN(e,u.properties):vr(u)?Ae(e):rn(u)?Ae(e):Ze()}function OS(e,o,i){return sn(i)?Ae(e):Nt(e,o,i)}function _S(e,o,i){return Is(i)?Ae(e):Nt(e,o,i)}function LS(e,o,i){let u=vn(o);return Rt(e,u,i)}function Kd(e,o){return Ct({"~kind":"Inferrable"},{name:e,type:o},{})}function Wu(e){return at(e)&&fe(e,"~kind")&&fe(e,"name")&&fe(e,"type")&&L(e["~kind"],"Inferrable")&&gt(e.name)&&at(e.type)}function Hd(e){return ni(e)?nn(e.items)?wt(e.items.extends)?Kd(e.items.name,e.items.extends.items):rn(e.items.extends)?Kd(e.items.name,e.items.extends):void 0:jr():void 0}function sp(e){return nn(e)?Kd(e.name,e.extends):void 0}function Wd(e,o,i=[]){return It(e,(u,p)=>br(Rt({},u,o),()=>Wd(p,o,[...i,u]),()=>{return}),()=>i)}function NS(e,o,i,u){let p=Wd(i,u);return Ge(p)?Ae(dn(e,{[o]:Ur(p)})):Ze()}function ip(e,o,i,u){let p=Wd(i,u);return Ge(p)?Ae(dn(e,{[o]:m(p)})):Ze()}function BN(e){return[...e].reverse()}function zd(e,o){return o?BN(e):e}function GN(e){let o=e.length>0?e[0]:void 0,i=Cr(o)?Hd(o):void 0;return Cr(i)}function KN(e,o,i,u,p,g){return br(Rt(e,i,p),(y)=>DS(y,o,u,g),()=>Ze())}function HN(e,o,i,u,p){let g=Hd(u);return Wu(g)?NS(e,g.name,zd(i,o),g.type):It(i,(y,b)=>KN(e,o,y,b,u,p),()=>Ze())}function WN(e,o,i,u){return It(u,(p,g)=>HN(e,o,i,p,g),()=>L(i.length,0)?Ae(e):Ze())}function DS(e,o,i,u){return WN(e,o,i,u)}function zN(e,o,i){let u=ai(e,hr([],[]),i),p=GN(u);return DS(e,p,zd(o,p),zd(u,p))}function qS(e,o,i){let u=sp(i);return Wu(u)?ip(e,u.name,o,u.type):It(o,(p,g)=>br(Rt(e,p,i),(y)=>qS(y,g,i),()=>Ze()),()=>Ae(e))}function FS(e,o,i){let u=ai(e,hr([],[]),o);return mt(i)?zN(e,u,i.items):wt(i)?qS(e,u,i.items):Nt(e,Ur(u),i)}function jS(e,o,i){return po(i)?Ae(e):Yo(i)?Ae(e):Nt(e,o,i)}function US(e,o,i){return It(i,(u,p)=>br(Rt(e,o,u),(g)=>Ae(g),()=>US(e,o,p)),()=>Ze())}function Vd(e,o,i){return It(o,(u,p)=>br(US(e,u,i),(g)=>Vd(g,p,i),()=>Ze()),()=>Ae(e))}function BS(e,o,i){let u=sp(i);return Wu(u)?ip(e,u.name,o,u.type):xe(i)?Vd(e,o,i.anyOf):Vd(e,o,[i])}function GS(e,o,i){return nn(i)?Nt(e,o,i):vr(i)?Ae(e):rn(i)?Ae(e):Ze()}function KS(e,o,i){return po(i)?Ae(e):Nt(e,o,i)}function Rt(e,o,i){return vr(o)?gS(e,o,i):wt(o)?yS(e,o,o.items,i):mo(o)?xS(e,o,i):Wn(o)?IS(e,o,i):en(o)?bS(e,o.parameters,o.instanceType,i):Dr(o)?ES(e,o.if,o.then,o.else,i):on(o)?SS(e,o.enum,i):tn(o)?wS(e,o.parameters,o.returnType,i):fn(o)?TS(e,o,i):ze(o)?RS(e,o.allOf,i):yt(o)?kS(e,o,i):co(o)?AS(e,o,i):xs(o)?PS(e,o,i):kr(o)?CS(e,o,i):Qe(o)?vS(e,o.properties,i):Gt(o)?MS(e,hn(o),fr(o),i):sn(o)?OS(e,o,i):Is(o)?_S(e,o,i):ur(o)?LS(e,o.pattern,i):mt(o)?FS(e,o.items,i):Yo(o)?jS(e,o,i):xe(o)?BS(e,o.anyOf,i):rn(o)?GS(e,o,i):po(o)?KS(e,o,i):Ze()}function VN(e,o){return Ar([...e,l(o)])}function Jd(e,o,i){return ct(e)?St(VN(e,o),{},i):qu(e,o,i)}function HS(e,o,i,u,p){let g=yo(e,o,i),y=zu(e,o,u);return Jd(g,y,p)}function qu(e,o,i={}){return ve("Interface",[e,o],i)}function qa(e){return Cr(e)&&fe(e,"action")&&L(e.action,"Interface")}function WS(e,o,i={}){return Jd(e,o,i)}function JN(e,o,i){return e.includes(i)?!0:Vu([...e,i],o,o[i])}function zS(e,o,i){let u=um(i);return ia(e,o,u)}function ia(e,o,i){return It(i,(u,p)=>Vu(e,o,u)?!0:ia(e,o,p),()=>!1)}function Vu(e,o,i){return qt(i)?JN(e,o,i.$ref):wt(i)?Vu(e,o,i.items):en(i)?ia(e,o,[...i.parameters,i.instanceType]):tn(i)?ia(e,o,[...i.parameters,i.returnType]):qa(i)?zS(e,o,i.parameters[1]):ze(i)?ia(e,o,i.allOf):Qe(i)?zS(e,o,i.properties):xe(i)?ia(e,o,i.anyOf):mt(i)?ia(e,o,i.items):Gt(i)?Vu(e,o,fr(i)):!1}function VS(e,o,i){return Vu(e,o,i)}function QN(e,o){return o.reduce((i,u)=>VS([u],e,e[u])?[...i,u]:i,[])}function JS(e){let o=am(e);return QN(e,o)}function XN(e,o,i){return i.includes(o)?i:(o in e)?Ju(e,e[o],[...i,o]):jr()}function QS(e,o,i){let u=um(o);return Fa(e,u,i)}function Fa(e,o,i){return o.reduce((u,p)=>Ju(e,p,u),i)}function Ju(e,o,i){return qt(o)?XN(e,o.$ref,i):wt(o)?Ju(e,o.items,i):en(o)?Fa(e,[...o.parameters,o.instanceType],i):tn(o)?Fa(e,[...o.parameters,o.returnType],i):qa(o)?QS(e,o.parameters[1],i):ze(o)?Fa(e,o.allOf,i):Qe(o)?QS(e,o.properties,i):xe(o)?Fa(e,o.anyOf,i):mt(o)?Fa(e,o.items,i):Gt(o)?Ju(e,fr(o),i):i}function XS(e,o,i){return Ju(e,i,[o])}function YN(e){return Pa()}function ZN(e){return we(e).reduce((o,i)=>({...o,[i]:aa(e[i])}),{})}function Qu(e){return e.reduce((o,i)=>[...o,aa(i)],[])}function aa(e){return qt(e)?YN(e.$ref):wt(e)?B(aa(e.items),ka(e)):en(e)?ds(Qu(e.parameters),aa(e.instanceType)):tn(e)?fs(Qu(e.parameters),aa(e.returnType)):ze(e)?Cn(Qu(e.allOf)):Qe(e)?l(ZN(e.properties)):Gt(e)?bs(ri(e),aa(fr(e))):xe(e)?m(Qu(e.anyOf)):mt(e)?Ur(Qu(e.items)):e}function eD(e,o){return o in e?aa(e[o]):Rr()}function YS(e){return eD(e.$defs,e.$ref)}function tD(e,o,i){let u=yo(e,hr([],[]),o),p=zu({},hr([],[]),i);return Ar([...u,l(p)])}function rD(e,o){return we(e).filter((u)=>o.includes(u)).reduce((u,p)=>{let g=e[p],y=qa(g)?tD(e,g.parameters[0],g.parameters[1]):g;return{...u,[p]:y}},{})}function ZS(e,o,i){let u=XS(e,o,i),p=rD(e,u);return gs(p,o)}function ew(e,o){return o in e?qt(e[o])?ew(e,e[o].$ref):e[o]:zt()}function Es(e,o){return ew(e,o)}function tw(e){return Qt(e)?YS(e):cm(e)?Rr():e}function Tn(e,o,i){let u=tw(o),p=tw(i);return Rt(e,u,p)}var Ou=0,Xu=1,_u=2,Lu=3;function Ma(e,o){let i=[Tn({},e,o),Tn({},o,e)];return so(i[0])&&so(i[1])?Ou:so(i[0])&&Gd(i[1])?_u:Gd(i[0])&&so(i[1])?Lu:Xu}function Qd(e,o,i=[],u=o){return It(o,(p,g)=>{let y=Ma(e,p);return L(y,_u)||L(y,Ou)?u:L(y,Xu)?Qd(e,g,[...i,p],u):Qd(e,g,i,u)},()=>[...i,e])}function nD(e,o,i){let u=ko(e);return vr(u)?[u]:rn(u)?[u]:co(u)?ap(o,i):Qe(u)?ap(o,[...i,u]):ap(o,Qd(u,i))}function ap(e,o=[]){return It(e,(i,u)=>nD(i,u,o),()=>o)}function Td(e){let o=ap(e);return na(o)}function Xd(e,o){return St(ko(e),{},o)}function rw(e,o,i,u){let p=ge(e,o,i);return Xd(p,u)}function Yu(e,o=[]){return Qs(e)&&L(e.action,"Conditional")?qt(e.parameters[0])?Yu(e.parameters[2],Yu(e.parameters[3],[...o,e.parameters[0].$ref])):Yu(e.parameters[2],Yu(e.parameters[3],o)):Qs(e)&&L(e.action,"Mapped")?Qs(e.parameters[1])&&L(e.parameters[1].action,"KeyOf")&&qt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function oD(e,o){return e.reduce((i,u)=>[...i,o.includes(u.name)],[])}function sw(e,o,i=[]){return It(e,(u,p)=>It(o,(g,y)=>sw(p,y,[...i,[g,u]]),()=>i),()=>i)}function sD(e){return ur(e)?vn(e.pattern):on(e)?Zn(e.enum):e}function iD(e){let o=sD(e);return xe(o)?[...o.anyOf]:[o]}function aD(e,o){return e.reduce((i,u)=>[...i,[...u,o]],[])}function nw(e,o){return o.reduce((i,u)=>[...i,...aD(e,u)],[])}function ow(e){return e.reduce((o,i)=>L(i[0],!0)?nw(o,iD(i[1])):nw(o,[i[1]]),[[]])}function iw(e,o,i){let u=Yu(i),p=oD(e,u),g=sw(o,p);return Qs(i)&&L(i.action,"Conditional")?ow(g):Qs(i)&&L(i.action,"Mapped")?ow(g):[o]}function uD(){return["(not-resolvable)",zt()]}function cD(){return["(not-generic)",zt()]}function mD(e,o,i){return[e,Xs(o,i)]}function pD(e,o,i){return o in e?aw(e,o,e[o],i):uD()}function aw(e,o,i,u){return Aa(i)?mD(o,i.parameters,i.expression):qt(i)?pD(e,i.$ref,u):cD()}function uw(e,o,i){return aw(e,"(anonymous)",o,i)}function lD(e,o,i){if(nn(o)||ja(o)||so(Tn({},o,i)))return;let u={parameter:e,expect:i,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function cw(e,o,i,u,p){let g=ge(e,o,p);return lD(i,g,u),dn(e,{[i]:g})}function dD(e,o,i,u,p){let g=ge(e,o,i.extends),y=ge(e,o,i.equals);return It(p,(b,E)=>Yd(cw(e,o,i.name,g,b),o,u,E),()=>Yd(cw(e,o,i.name,g,y),o,u,[]))}function Yd(e,o,i,u){return It(i,(p,g)=>dD(e,o,p,g,u),()=>e)}function mw(e,o,i,u){return Yd(e,o,i,u)}var Zd=0,ef=0;function fD(){if(Su(ef,Vo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function hD(){fD(),ef++,Zd++}function gD(){if(Zd--,L(Zd,0))ef=0}function yD(e){return Ki(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function xD(e,o){return L(yD(e),o)}function ID(e,o,i,u,p,g){hD();try{let y=mw(e,o,u,g),b=ge(y,hr([...o.callstack,i.$ref],o.visited),p);return ge(y,hr([],[]),b)}finally{gD()}}function bD(e,o,i,u,p,g){return g.reduce((y,b)=>{let E=ID(e,o,i,u,p,b);return[...y,E]},[])}function ED(e,o,i,u,p,g){let y=iw(u,g,p),b=bD(e,o,i,u,p,y);return L(b.length,1)?b[0]:oo(b)}function up(e,o,i,u){let p=yo(e,o,u),g=uw(e,i,u),y=g[0],b=g[1];return Aa(b)?xD(o,y)?Fu(un(y),p):ED(e,o,un(y),b.parameters,b.expression,p):Fu(i,p)}function Fu(e,o){return Ct({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function pw(e,o){return up({},hr([],[]),e,o)}function ja(e){return Pe(e,"Call")}function SD(e){return Jo(e,["~immutable"])}function lw(e,o){return St(SD(e),{},o)}function dw(e,o,i,u){let p=ge(e,o,i);return lw(p,u)}function fw(e,o){return e(o)}function hw(e,o){return gt(o)?s(fw(e,o)):s(o)}function gw(e,o){let i=vn(o);return Os(e,i)}function yw(e,o){let i=o.map((u)=>Os(e,u));return m(i)}function Os(e,o){return yt(o)?hw(e,o.const):ur(o)?gw(e,o.pattern):xe(o)?yw(e,o.anyOf):o}function $m(e,o={}){return ve("Capitalize",[e],o)}function xw(e,o={}){return tf(e,o)}function vm(e,o={}){return ve("Lowercase",[e],o)}function Iw(e,o={}){return rf(e,o)}function Mm(e,o={}){return ve("Uncapitalize",[e],o)}function bw(e,o={}){return nf(e,o)}function Om(e,o={}){return ve("Uppercase",[e],o)}function Ew(e,o={}){return of(e,o)}var wD=(e)=>e[0].toUpperCase()+e.slice(1),TD=(e)=>e.toLowerCase(),RD=(e)=>e[0].toLowerCase()+e.slice(1),kD=(e)=>e.toUpperCase();function tf(e,o){return ct([e])?St(Os(wD,e),{},o):$m(e,o)}function rf(e,o){return ct([e])?St(Os(TD,e),{},o):vm(e,o)}function nf(e,o){return ct([e])?St(Os(RD,e),{},o):Mm(e,o)}function of(e,o){return ct([e])?St(Os(kD,e),{},o):Om(e,o)}function Sw(e,o,i,u){let p=ge(e,o,i);return tf(p,u)}function ww(e,o,i,u){let p=ge(e,o,i);return rf(p,u)}function Tw(e,o,i,u){let p=ge(e,o,i);return nf(p,u)}function Rw(e,o,i,u){let p=ge(e,o,i);return of(p,u)}function _m(e,o,i,u,p={}){return ve("Conditional",[e,o,i,u],p)}function kw(e,o,i,u,p={}){return sf({},hr([],[]),e,o,i,u,p)}function AD(e,o,i,u,p,g){let y=Tn(e,i,u);return Ud(y)?m([ge(y.inferred,o,p),ge(e,o,g)]):Bd(y)?ge(y.inferred,o,p):ge(e,o,g)}function sf(e,o,i,u,p,g,y){return ct([i,u])?St(AD(e,o,i,u,p,g),{},y):_m(i,u,p,g,y)}function Aw(e,o,i,u,p,g,y){let b=ge(e,o,i),E=ge(e,o,u);return sf(e,o,b,E,p,g,y)}function Lm(e,o={}){return ve("ConstructorParameters",[e],o)}function Pw(e,o={}){return af(e,o)}function PD(e){let o=en(e)?e.parameters:[],i=ai({},hr([],[]),o);return Ur(i)}function af(e,o){return ct([e])?St(PD(e),{},o):Lm(e,o)}function Cw(e,o,i,u){let p=ge(e,o,i);return af(p,u)}function Nm(e,o,i={}){return ve("Exclude",[e,o],i)}function $w(e,o,i={}){return Zu(e,o,i)}function Zu(e,o,i){return ct([e,o])?St(wm(e,o),{},i):Nm(e,o,i)}function vw(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return Zu(g,y,p)}function Dm(e,o,i={}){return ve("Extract",[e,o],i)}function Mw(e,o,i={}){return uf(e,o,i)}function CD(e,o){let i=Tn({},e,o);return so(i)?[e]:[]}function Ow(e,o,i=[]){return It(e,(u,p)=>Ow(p,o,[...i,...CD(u,o)]),()=>i)}function _w(e,o){let i=ko(e),u=xe(i)?i.anyOf:[i],p=Ow(u,o);return oo(p)}function uf(e,o,i){return ct([e,o])?St(_w(e,o),{},i):Dm(e,o,i)}function Lw(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return uf(g,y,p)}function $D(e){return e.reduce((o,i)=>hm(i)?[...o,s(i)]:o,[])}function Ua(e){let o=$D(e);return m(o)}function ju(e,o,i={}){return ve("Index",[e,o],i)}function Nw(e,o,i={}){let u=Ge(o)?Ua(o):o;return cf(e,u,i)}function Dw(e,o){let i=Es(e,o);return xo(i)}function qw(e,o,i){let u=Xo(e,o,i);return xo(u)}function vD(e,o){let i=we(e).filter((w)=>!fe(o,w)),u=we(o).filter((w)=>!fe(e,w)),p=we(e).filter((w)=>fe(o,w)),g=i.reduce((w,R)=>({...w,[R]:e[R]}),{}),y=u.reduce((w,R)=>({...w,[R]:o[R]}),{}),b=p.reduce((w,R)=>({...w,[R]:Ar([e[R],o[R]])}),{}),E=dn(g,y);return dn(E,b)}function Fw(e){return e.reduce((o,i)=>vD(o,xo(i)),{})}function jw(e){return e}function Uw(e){let o=Cx(Ur(e));return xo(o)}function MD(e,o){return we(e).filter((p)=>(p in o)).reduce((p,g)=>({...p,[g]:oo([e[g],o[g]])}),{})}function Bw(e,o){return It(e,(i,u)=>Bw(u,MD(o,xo(i))),()=>o)}function Gw(e){return It(e,(o,i)=>Bw(i,xo(o)),()=>jr())}function xo(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 o=xo(e);return l(o)}var OD=new RegExp("^(?:0|[1-9][0-9]*)$");function Ga(e){let o=`${e}`;return OD.test(o)?parseInt(o):e}function _D(e){return s(Ga(e))}function Kw(e){return e.map((o)=>Hw(o))}function Hw(e){return ze(e)?Cn(Kw(e.allOf)):xe(e)?m(Kw(e.anyOf)):yt(e)?_D(e.const):e}function Ww(e,o){let i=Hw(o),u=Tn({},i,Y());return so(u)?e:yt(o)&&L(o.const,"length")?Y():zt()}function zw(e,o){let i=Es(e,o);return lo(i)}function Vw(e,o,i){let u=Xo(e,o,i);return lo(u)}function Jw(e){let o=Zn(e);return lo(o)}function Qw(e){let o=Ar(e);return lo(o)}function Xw(e){return[`${e}`]}function Yw(e){let o=vn(e);return lo(o)}function Zw(e){return e.reduce((o,i)=>[...o,...lo(i)],[])}function lo(e){return Qt(e)?zw(e.$defs,e.$ref):Dr(e)?Vw(e.if,e.then,e.else):on(e)?Jw(e.enum):ze(e)?Qw(e.allOf):yt(e)?Xw(e.const):ur(e)?Yw(e.pattern):xe(e)?Zw(e.anyOf):[]}function Ka(e){return lo(e)}function ec(e,o){return o.map((i)=>tc(e,i))}function tc(e,o){return wt(o)?B(tc(e,o.items)):en(o)?ds(ec(e,o.parameters),tc(e,o.instanceType)):tn(o)?fs(ec(e,o.parameters),tc(e,o.returnType)):mt(o)?Ur(ec(e,o.items)):xe(o)?m(ec(e,o.anyOf)):ze(o)?Cn(ec(e,o.allOf)):Am(o)?l(e):o}function eT(e,o){return tc(e,o)}function LD(e,o){let i=o in e?e[o]:zt();return eT(e,i)}function tT(e,o){return o.reduce((i,u)=>[...i,LD(e,u)],[])}function ND(e,o){let i=Ka(o),u=tT(e,i);return oo(u)}var DD=new RegExp(ti);function qD(e){return e.filter((i)=>DD.test(i))}function FD(e){let o=am(e),i=qD(o),u=tT(e,i);return oo(u)}function rT(e,o){return kr(o)?FD(e):ND(e,o)}function jD(e){return s(Ga(e))}function nT(e){return e.map((o)=>mf(o))}function mf(e){return ze(e)?Cn(nT(e.allOf)):xe(e)?m(nT(e.anyOf)):yt(e)?jD(e.const):e}function UD(e,o){return e.reduceRight((i,u,p)=>{let g=Tn({},s(p),o);return so(g)?[u,...i]:i},[])}function BD(e,o){let i=mf(o),u=UD(e,i);return Zs(u)}function GD(e){return Zs(e)}function oT(e,o){return yt(o)&&L(o.const,"length")?s(e.length):kr(o)||fn(o)?GD(e):BD(e,o)}function sT(e,o){return wt(e)?Ww(e.items,o):Qe(e)?rT(e.properties,o):mt(e)?oT(e.items,o):zt()}function KD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function cf(e,o,i){return ct([e,o])?St(sT(KD(e),o),{},i):ju(e,o,i)}function iT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return cf(g,y,p)}function qm(e,o={}){return ve("InstanceType",[e],o)}function aT(e,o={}){return pf(e,o)}function HD(e){return en(e)?e.instanceType:zt()}function pf(e,o){return ct([e])?St(HD(e),{},o):qm(e,o)}function uT(e,o,i,u={}){let p=ge(e,o,i);return pf(p,u)}function Uu(e,o={}){return ve("KeyOf",[e],o)}function cT(e,o={}){return lf(e,o)}function mT(){return m([Y(),a(),va()])}function pT(e){return Y()}function WD(e){return e.reduce((i,u)=>hm(u)?[...i,s(Ga(u))]:jr(),[])}function lT(e){let o=we(e),i=WD(o);return Zs(i)}function dT(e){return ri(e)}function fT(e){let o=e.map((i,u)=>s(u));return Zs(o)}function hT(e){return vr(e)?mT():wt(e)?pT(e.items):Qe(e)?lT(e.properties):Gt(e)?dT(e):mt(e)?fT(e.items):zt()}function zD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function lf(e,o){return ct([e])?St(hT(zD(e)),{},o):Uu(e,o)}function gT(e,o,i,u){let p=ge(e,o,i);return lf(p,u)}function Du(e,o,i,u,p={}){return ve("Mapped",[e,o,i,u],p)}function yT(e,o,i,u,p={}){return df({},hr([],[]),e,o,i,u,p)}function VD(e){let o=vn(e);return cp(o)}function JD(e){return e.reduce((o,i)=>[...o,...cp(i)],[])}function QD(e){let o=Zn(e);return cp(o)}function XD(e){return Ot(e)?[s(`${e}`)]:[s(e)]}function cp(e){return on(e)?QD(e.enum):yt(e)?XD(e.const):ur(e)?VD(e.pattern):xe(e)?JD(e.anyOf):[e]}function xT(e){return cp(e)}function YD(e){return ur(e)?vn(e.pattern):e}function ZD(e,o,i,u,p,g){let y=dn(e,{[i.name]:u}),b=ge(y,o,p),E=YD(b),S=ge(y,o,g);return gm(E)||ym(E)?{[E.const]:S}:{}}function eq(e,o,i,u,p,g){return u.reduce((y,b)=>[...y,ZD(e,o,i,b,p,g)],[])}function tq(e){return e.reduce((o,i)=>[...o,l(i)],[])}function IT(e,o,i,u,p,g){let y=xT(u),b=eq(e,o,i,y,p,g),E=tq(b);return Ar(E)}function df(e,o,i,u,p,g,y){return ct([u])?St(IT(e,o,i,u,p,g),{},y):Du(i,u,p,g,y)}function bT(e,o,i,u,p,g,y){let b=ge(e,o,u);return df(e,o,i,b,p,g,y)}function rq(e,o,i){let u=dn(e,o);return we(o).filter((g)=>i.includes(g)).reduce((g,y)=>({...g,[y]:ZS(u,y,o[y])}),{})}function nq(e,o,i){let u=dn(e,o);return we(o).filter((g)=>!i.includes(g)).reduce((g,y)=>({...g,[y]:ge(u,hr([],[]),o[y])}),{})}function oq(e,o,i){let u=JS(o),p=rq(e,o,u),g=nq(e,o,u),y={...p,...g};return St(y,{},i)}function mp(e,o,i,u){return oq(e,i,u)}function Fm(e,o={}){return ve("NonNullable",[e],o)}function ET(e,o={}){return ff(e,o)}function sq(e){let o=m([$n(),_a()]);return Zu(e,o,{})}function ff(e,o){return ct([e])?St(sq(e),{},o):Fm(e,o)}function ST(e,o,i,u){let p=ge(e,o,i);return ff(p,u)}function jm(e,o,i={}){return ve("Omit",[e,o],i)}function wT(e,o,i={}){let u=Ge(o)?Ua(o):o;return hf(e,u,i)}function pp(e){let o=Ba(e);return Qe(o)?o.properties:jr()}function iq(e,o){return we(e).reduce((u,p)=>o.includes(p)?u:{...u,[p]:e[p]},{})}function TT(e,o){let i=pp(e),u=Ka(o),p=iq(i,u);return l(p)}function hf(e,o,i){return ct([e,o])?St(TT(e,o),{},i):jm(e,o,i)}function RT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return hf(g,y,p)}function Um(e,o={}){return ve("Parameters",[e],o)}function kT(e,o={}){return gf(e,o)}function aq(e){let o=tn(e)?e.parameters:[],i=ai({},hr([],[]),o);return Ur(i)}function gf(e,o){return ct([e])?St(aq(e),{},o):Um(e,o)}function AT(e,o,i,u){let p=ge(e,o,i);return gf(p,u)}function Bm(e,o={}){return ve("Partial",[e],o)}function PT(e,o={}){return yf(e,o)}function CT(e,o){let i=Es(e,o),u=Ss(i);return gs(dn(e,{[o]:u}),o)}function $T(e,o,i){let u=Xo(e,o,i);return Ss(u)}function vT(e){let o=Ar(e);return Ss(o)}function MT(e){let o=e.map((i)=>Ss(i));return m(o)}function OT(e){let o=we(e).reduce((u,p)=>({...u,[p]:Qi(e[p])}),{});return l(o)}function Ss(e){return Qt(e)?CT(e.$defs,e.$ref):Dr(e)?$T(e.if,e.then,e.else):ze(e)?vT(e.allOf):xe(e)?MT(e.anyOf):Qe(e)?OT(e.properties):l({})}function yf(e,o){return ct([e])?St(Ss(e),{},o):Bm(e,o)}function _T(e,o,i,u){let p=ge(e,o,i);return yf(p,u)}function Gm(e,o,i={}){return ve("Pick",[e,o],i)}function LT(e,o,i={}){let u=Ge(o)?Ua(o):o;return xf(e,u,i)}function uq(e,o){return we(e).reduce((u,p)=>o.includes(p)?dn(u,{[p]:e[p]}):u,{})}function NT(e,o){let i=pp(e),u=Ka(o),p=uq(i,u);return l(p)}function xf(e,o,i){return ct([e,o])?St(NT(e,o),{},i):Gm(e,o,i)}function DT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return xf(g,y,p)}function Km(e,o={}){return ve("ReadonlyObject",[e],o)}function If(e,o={}){return bf(e,o)}var qT=If;function FT(e){return $a(B(e))}function jT(e,o){let i=Es(e,o),u=ws(i);return gs(dn(e,{[o]:u}),o)}function UT(e,o,i){let u=Xo(e,o,i);return ws(u)}function BT(e){let o=Ar(e);return ws(o)}function GT(e){let o=we(e).reduce((u,p)=>({...u,[p]:ea(e[p])}),{});return l(o)}function KT(e){return $a(Ur(e))}function HT(e){let o=e.map((i)=>ws(i));return m(o)}function ws(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 bf(e,o){return ct([e])?St(ws(e),{},o):Km(e)}function WT(e,o,i,u){let p=ge(e,o,i);return bf(p,u)}function zT(e,o,i,u){return o.visited.includes(u)?i:(u in e)?ge(e,hr(o.callstack,[...o.visited,u]),e[u]):i}function VT(e,o){let i=Es(e,o),u=Ts(i);return gs(dn(e,{[o]:u}),o)}function JT(e,o,i){let u=Xo(e,o,i);return Ts(u)}function QT(e){let o=Ar(e);return Ts(o)}function XT(e){let o=e.map((i)=>Ts(i));return m(o)}function YT(e){let o=we(e).reduce((u,p)=>({...u,[p]:Sm(e[p])}),{});return l(o)}function Ts(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):l({})}function Hm(e,o={}){return ve("Required",[e],o)}function ZT(e,o={}){return Ef(e,o)}function Ef(e,o){return ct([e])?St(Ts(e),{},o):Hm(e,o)}function eR(e,o,i,u){let p=ge(e,o,i);return Ef(p,u)}function Wm(e,o={}){return ve("ReturnType",[e],o)}function tR(e,o={}){return Sf(e,o)}function cq(e){return tn(e)?e.returnType:zt()}function Sf(e,o){return ct([e])?St(cq(e),{},o):Wm(e,o)}function rR(e,o,i,u={}){let p=ge(e,o,i);return Sf(p,u)}function zm(e,o){return ve("With",[e,o],{})}function lp(e,o){return wf(e,o)}function wf(e,o){return ct([e])?St(e,{},o):zm(e,o)}function nR(e,o,i,u){let p=ge(e,o,i);return wf(p,u)}function mq(e){return ni(e)?mt(e.items)?Tf(e.items.items):nn(e.items)?[e]:qt(e.items)?[e]:[zt()]:[e]}function Tf(e){return e.reduce((i,u)=>[...i,...mq(u)],[])}function hr(e,o){return{callstack:e,visited:o}}function ct(e){return It(e,(o,i)=>qt(o)?!1:ct(i),()=>!0)}function zu(e,o,i){return we(i).reduce((u,p)=>({...u,[p]:ge(e,o,i[p])}),{})}function ai(e,o,i){let u=yo(e,o,i);return Tf(u)}function yo(e,o,i){return i.map((u)=>ge(e,o,u))}function pq(e,o){let i=cn(e)?Au(o,{}):o,u=ta(e)?ku(i,{}):i;return Zi(e)?rc(u,{}):u}function lq(e,o,i,u,p){return L(i,"AddImmutable")?oR(e,o,u[0],p):L(i,"RemoveImmutable")?dw(e,o,u[0],p):L(i,"AddReadonly")?vy(e,o,u[0],p):L(i,"RemoveReadonly")?Tx(e,o,u[0],p):L(i,"AddOptional")?My(e,o,u[0],p):L(i,"RemoveOptional")?Ax(e,o,u[0],p):L(i,"Capitalize")?Sw(e,o,u[0],p):L(i,"Conditional")?Aw(e,o,u[0],u[1],u[2],u[3],p):L(i,"ConstructorParameters")?Cw(e,o,u[0],p):L(i,"Evaluate")?rw(e,o,u[0],p):L(i,"Exclude")?vw(e,o,u[0],u[1],p):L(i,"Extract")?Lw(e,o,u[0],u[1],p):L(i,"Index")?iT(e,o,u[0],u[1],p):L(i,"InstanceType")?uT(e,o,u[0],p):L(i,"Interface")?HS(e,o,u[0],u[1],p):L(i,"KeyOf")?gT(e,o,u[0],p):L(i,"Lowercase")?ww(e,o,u[0],p):L(i,"Mapped")?bT(e,o,u[0],u[1],u[2],u[3],p):L(i,"Module")?mp(e,o,u[0],p):L(i,"NonNullable")?ST(e,o,u[0],p):L(i,"Pick")?DT(e,o,u[0],u[1],p):L(i,"Parameters")?AT(e,o,u[0],p):L(i,"Partial")?_T(e,o,u[0],p):L(i,"Omit")?RT(e,o,u[0],u[1],p):L(i,"ReadonlyObject")?WT(e,o,u[0],p):L(i,"Record")?Kx(e,o,u[0],u[1],p):L(i,"Required")?eR(e,o,u[0],p):L(i,"ReturnType")?rR(e,o,u[0],p):L(i,"TemplateLiteral")?pS(e,o,u[0],p):L(i,"Uncapitalize")?Tw(e,o,u[0],p):L(i,"Uppercase")?Rw(e,o,u[0],p):L(i,"With")?nR(e,o,u[0],u[1]):ve(i,u,p)}function dq(e,o,i){let u=qt(i)?zT(e,o,i,i.$ref):wt(i)?B(ge(e,o,i.items),ka(i)):ja(i)?up(e,o,i.target,i.arguments):en(i)?ds(yo(e,o,i.parameters),ge(e,o,i.instanceType),Oy(i)):tn(i)?fs(yo(e,o,i.parameters),ge(e,o,i.returnType),_y(i)):Dr(i)?Xi(ge(e,o,i.if),ge(e,o,i.then),ge(e,o,i.else),qy(i)):ze(i)?Cn(yo(e,o,i.allOf),Gy(i)):Qe(i)?l(zu(e,o,i.properties),Dy(i)):Gt(i)?Hx(hn(i),ge(e,o,fr(i))):ni(i)?oa(ge(e,o,i.items)):mt(i)?Ur(ai(e,o,i.items),wx(i)):xe(i)?m(yo(e,o,i.anyOf),dx(i)):i;return pq(i,u)}function ge(e,o,i){return Qs(i)?lq(e,o,i.action,i.parameters,i.options):dq(e,o,i)}function Ao(e,o){return ge(e,hr([],[]),o)}function fq(e){return St(e,{"~immutable":!0},{})}function rc(e,o){return St(fq(e),{},o)}function oR(e,o,i,u){let p=ge(e,o,i);return rc(p,u)}function aE(e,o={}){return ve("AddImmutable",[e],o)}function $a(e,o={}){return rc(e,o)}function uE(e,o={}){return ve("Evaluate",[e],o)}function Rn(e,o={}){return Xd(e,o)}function cE(e,o={}){return ve("Module",[e],o)}function sR(e,o={}){return mp({},hr([],[]),e,o)}function hq(e,o){let i=Ma(e,o);return L(i,Lu)?1:L(i,Xu)?1:0}function iR(e,o,i=[]){return It(o,(u,p)=>L(hq(e,u),1)?iR(e,p,[...i,u]):[...i,e,...o],()=>[...i,e])}function aR(e,o=[]){return It(e,(i,u)=>aR(u,iR(i,o)),()=>o)}function uR(e){return aR(e)}function cR(...e){let[o,i,u]=wn(e,{2:(y,b)=>gt(y)?[{},y,b]:[y,b,{}],3:(y,b,E)=>[y,b,E],1:(y)=>[{},y,{}]}),p=iS(i),g=Ge(p)&&L(p.length,2)?ge(o,hr([],[]),p[0]):zt();return St(g,{},u)}function h(e,o){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let u=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:u}},resolve:async({ctx:i,credential:u,signal:p})=>{if(p.throwIfAborted(),u?.key)return{auth:{apiKey:u.key},env:u.env,source:"stored credential"};for(let g of o){let y=await i.env(g);if(p.throwIfAborted(),y)return{auth:{apiKey:y},source:g}}return}}}function le(e){let o,i=()=>(o??=e.load(),o);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(u,p)=>(await i()).login(u,p),refresh:async(u,p)=>(await i()).refresh(u,p),toAuth:async(u)=>(await i()).toAuth(u)}}var dR="faux",fR="faux",hR="faux-1",gq="Faux Model",yq="http://localhost:0",xq=3,mR=5,hp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function On(e){return{type:"text",text:e}}function Oo(e){return{type:"thinking",thinking:e}}function Iq(e,o,i={}){return{type:"toolCall",id:i.id??Af("tool"),name:e,arguments:o}}function bq(e){if(typeof e==="string")return[On(e)];return Array.isArray(e)?e:[e]}function No(e,o={}){return{role:"assistant",content:bq(e),api:dR,provider:fR,model:hR,usage:hp,stopReason:o.stopReason??"stop",...o.deferred===void 0?{}:{deferred:o.deferred},...o.errorMessage===void 0?{}:{errorMessage:o.errorMessage},...o.responseId===void 0?{}:{responseId:o.responseId},timestamp:o.timestamp??Date.now()}}function gR(e){return Math.ceil(e.length/4)}function Af(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function yR(e){if(typeof e==="string")return e;return e.map((o)=>{if(o.type==="text")return o.text;return`[image:${o.mimeType}:${o.data.length}]`}).join(`
23
+ `)}function xR(e){return e.map((o)=>{if(o.type==="text")return o.text;if(o.type==="thinking")return o.thinking;return`${o.name}:${JSON.stringify(o.arguments)}`}).join(`
24
+ `)}function Eq(e){return[e.toolName,...e.content.map((o)=>yR([o]))].join(`
25
+ `)}function Sq(e){if(e.role==="system")return[U(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
26
+ `);if(e.role==="user")return yR(e.content);if(e.role==="assistant")return xR(e.content);return Eq(e)}function IR(e,o=e.length){let i=o>0?(o-1)*2:0;for(let u=0;u<o;u++)i+=e[u].length;return i}function wq(e,o){let i=0;while(i<e.length&&i<o.length&&e[i]===o[i])i++;let u=(p)=>i===p.length?"":(i>0?`
27
+
28
+ `:"")+p.slice(i).join(`
29
+
30
+ `);return IR(e,i)+Tq(u(e),u(o))}function Tq(e,o){let i=Math.min(e.length,o.length),u=0;while(u<i&&e[u]===o[u])u++;return u}function pR(e,o,i,u){let p=o.messages.map((A)=>`${A.role}:${Sq(A)}`),g=IR(p),y=Math.ceil(g/4),b=gR(xR(e.content)),E=y,S=0,w=0,R=i?.sessionId;if(R&&i?.cacheRetention!=="none"){let A=u.get(R);if(A){let P=wq(A,p);S=Math.ceil(P/4),w=Math.ceil((g-P)/4),E=Math.max(0,y-S)}else w=y;u.set(R,p)}return{...e,usage:{input:E,output:b,cacheRead:S,cacheWrite:w,totalTokens:E+b+S+w,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function Rf(e,o,i){let u=[],p=0;while(p<e.length){let g=o+Math.floor(Math.random()*(i-o+1)),y=Math.max(1,g*4);u.push(e.slice(p,p+y)),p+=y}return u.length>0?u:[""]}function Rq(e,o,i,u){let p=structuredClone(e);return{...p,api:o,provider:i,model:u,timestamp:p.timestamp??Date.now(),usage:p.usage??hp}}function lR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:hp,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function dp(e,o,i,u){return{role:"assistant",content:[],api:o,provider:i,model:u,usage:hp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function nc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function kf(e,o){if(!o||o<=0)return new Promise((u)=>queueMicrotask(u));let i=gR(e)/o*1000;return new Promise((u)=>setTimeout(u,i))}async function fp(e,o,i,u,p,g){let y={...o,content:[],stopReason:"pending"};if(g?.aborted){let b=nc(y);e.push({type:"error",reason:"aborted",error:b}),e.end(b);return}e.push({type:"start",partial:{...y}});for(let b=0;b<o.content.length;b++){if(g?.aborted){let S=nc(y);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}let E=o.content[b];if(E.type==="thinking"){y.content=[...y.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:b,partial:{...y}});for(let S of Rf(E.thinking,i,u)){if(await kf(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].thinking+=S,e.push({type:"thinking_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"thinking_end",contentIndex:b,content:E.thinking,partial:{...y}});continue}if(E.type==="text"){y.content=[...y.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:b,partial:{...y}});for(let S of Rf(E.text,i,u)){if(await kf(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].text+=S,e.push({type:"text_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"text_end",contentIndex:b,content:E.text,partial:{...y}});continue}y.content=[...y.content,{type:"toolCall",id:E.id,name:E.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:b,partial:{...y}});for(let S of Rf(JSON.stringify(E.arguments),i,u)){if(await kf(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}e.push({type:"toolcall_delta",contentIndex:b,delta:S,partial:{...y}})}y.content[b].arguments=E.arguments,e.push({type:"toolcall_end",contentIndex:b,toolCall:E,partial:{...y}})}if(o.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(o.stopReason==="error"||o.stopReason==="aborted"){e.push({type:"error",reason:o.stopReason,error:o}),e.end(o);return}e.push({type:"done",reason:o.stopReason,message:o}),e.end(o)}function bR(e){let o=e.api??Af(dR),i=e.provider??fR,u=Math.max(1,Math.min(e.tokenSize?.min??xq,e.tokenSize?.max??mR)),p=Math.max(u,e.tokenSize?.max??mR),g=[],y=e.tokensPerSecond,b={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},E=new Map,S=new Map,R=((e.models?.length)?e.models:[{id:hR,name:gq,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((V)=>({id:V.id,name:V.name??V.id,api:o,provider:i,baseUrl:yq,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),A=async(V,J,ee,ae)=>{let H=typeof V==="function"?await V(J,ee,b,ae):V;return pR(Rq(H,o,i,ae.id),J,ee,E)},P=(V,J,ee)=>{let ae=Jn(),H=g.shift();return b.callCount++,queueMicrotask(async()=>{try{if(await ee?.onResponse?.({status:200,headers:{}},V),!H){let he=dp(Error("No more faux responses queued"),o,i,V.id);he=pR(he,J,ee,E),ae.push({type:"error",reason:"error",error:he}),ae.end(he);return}if(ee?.deferred){let he={provider:V.provider,modelId:V.id,api:V.api,id:Af("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};S.set(he.id,{handle:he,step:H,context:J,options:ee,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await fp(ae,lR(V,he),u,p,y,ee.signal);return}let ue=await A(H,J,ee,V);await fp(ae,ue,u,p,y,ee?.signal)}catch(ue){let he=dp(ue,o,i,V.id);ae.push({type:"error",reason:"error",error:he}),ae.end(he)}}),ae},C=(V,J,ee)=>P(V,J,ee),q=(V,J,ee)=>{let ae=Jn();return b.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 fp(ae,lR(V,H.handle),u,p,y,ee?.signal);return}if(!H.final){let{deferred:ue,signal:he,onResponse:$e,...Ee}=H.options??{};try{H.final=await A(H.step,H.context,Ee,H.model)}catch(se){H.final=dp(se,o,i,H.model.id)}}await fp(ae,H.final,u,p,y,ee?.signal)}catch(H){let ue=dp(H,o,i,V.id);ae.push({type:"error",reason:"error",error:ue}),ae.end(ue)}}),ae},X=async(V,J,ee)=>{b.cancelledDeferred.push(structuredClone(J));let ae=S.get(J.id);if(ae)ae.cancelled=!0;await ee?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return R[0];return R.find((J)=>J.id===V)}return{api:o,provider:i,models:R,stream:P,streamSimple:C,fetchDeferred:q,cancelDeferred:X,getModel:j,state:b,setResponses(V){g=[...V]},appendResponses(V){g.push(...V)},getPendingResponseCount(){return g.length}}}function Do(e={}){let o=bR(e);return{provider:d({id:o.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:o.models,api:{stream:o.stream,streamSimple:o.streamSimple,fetchDeferred:o.fetchDeferred,cancelDeferred:o.cancelDeferred}}),api:o.api,models:o.models,getModel:o.getModel,state:o.state,setResponses:o.setResponses,appendResponses:o.appendResponses,getPendingResponseCount:o.getPendingResponseCount}}function kq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function Aq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Pq(e){return{type:"toolCall",id:e.id,name:e.name,arguments:structuredClone(e.arguments),...e.thoughtSignature===void 0?{}:{thoughtSignature:e.thoughtSignature},...e.namespace===void 0?{}:{namespace:e.namespace}}}function Cq(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function oc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Ha(e){oc(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function Cf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var $q=Cf(W(""));function $f(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,p)=>$f(u,o[p]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let i=o;return Object.entries(e).every(([u,p])=>Object.hasOwn(i,u)&&$f(p,i[u]))}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:Cq(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=Ha(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:kq(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Ha(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=Ha(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:Aq(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Ha(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=Ha(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let i=Cf(o.arguments),u=i===$q;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Pq(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let i=W(o.catchupJson);if(Cf(i)!==o.snapshotArguments){let p=W(o.snapshotArguments);if(!$f(p,i))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=Ha(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(oc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){oc(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(i.kind!==o)throw Error(`Assistant message block ${e} is ${i.kind}, not ${o}`);return i}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,i){let u=this.block(e,i);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let p=u.deltaChars;u.deltaChars+=o.length;let g=Math.max(0,u.coveredChars-p);if(g>=o.length)return;let y=g===0?o:o.slice(g);return i==="text"?{type:"text_delta",contentIndex:e,delta:y}:{type:"thinking_delta",contentIndex:e,delta:y}}}function Pf(e,o,i,u,p){if(oc(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(u)),o.set(i,p)}function ua(e,o,i,u,p){oc(i);let g=o.get(i),y=e.content[i];if(!g||!y)throw Error(`${p} frame has no started block at index ${i}`);if(g.kind!==u||y.type!==u)throw Error(`${p} frame expected ${u} 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 vq(e){let o,i,u=new Map;for(let p of e){if(p.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(i!==void 0)throw Error(`${i} frame appears before the start frame`);o=structuredClone(p.partial);continue}if(!o){i??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);Pf(o,u,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:g}=ua(o,u,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}=ua(o,u,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(o,u,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:g}=ua(o,u,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}=ua(o,u,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(o,u,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:g,state:y}=ua(o,u,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}=ua(o,u,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}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(g.id=p.id,g.name=p.name,g.arguments=structuredClone(p.arguments),delete g.thoughtSignature,delete g.namespace,p.thoughtSignature!==void 0)g.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)g.namespace=p.namespace;y.ended=!0;break}}}if(!o)return;for(let[p,g]of u){if(g.kind!=="toolCall"||g.ended||g.json.length===0)continue;let y=o.content[p];if(y?.type!=="toolCall")throw Error("Unreachable tool-call frame state");y.arguments=W(g.json)}return o}var 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],Mq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Oq=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ca(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!Oq.some((u)=>u.test(e.errorMessage))){if(SR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&Mq.test(e.errorMessage))return!0}}if(o&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>o)return!0}if(o&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=o*0.99)return!0}return!1}function _q(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function Lq(){return[...SR]}function wR(e){return new RegExp(e.join("|"),"i")}var Nq=wR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),Dq=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,o){let i=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??TR)}class gp extends Error{constructor(){super("Aborted")}}function qq(e,o){return new Promise((i,u)=>{if(o?.aborted){u(new gp);return}let p=setTimeout(i,e);o?.addEventListener("abort",()=>{clearTimeout(p),u(new gp)},{once:!0})})}async function Fq(e,o,i,u){let p=o?.enabled?o.maxRetries:0,g=0,y;for(;;){let b=await e();if(b.stopReason==="aborted"){if(y)await u?.onRetryFinished?.(!1,y.attempt);return b}if(b.stopReason!=="error"){if(y)await u?.onRetryFinished?.(!0,y.attempt);return b}if(g>=p||!kR(b)){if(y)await u?.onRetryFinished?.(!1,y.attempt,b.errorMessage);return b}g++,y={attempt:g,errorMessage:b.errorMessage||"Unknown error"};let E=RR(o,g);await u?.onRetryScheduled?.(g,p,E,y.errorMessage);try{await qq(E,i)}catch(S){if(await u?.onRetryFinished?.(!1,g,y.errorMessage),S instanceof gp){let{errorMessage:w,...R}=b;return{...R,stopReason:"aborted"}}throw S}await u?.onRetryAttemptStart?.()}}function kR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(Nq.test(o))return!1;return Dq.test(o)}function jq(e,o){return qr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function sc(e){return fe(e,"~refine")&&Ge(e["~refine"])&&an(e["~refine"],0,(o)=>at(o)&&fe(o,"check")&&fe(o,"error")&&ms(o.check)&&ms(o.error))}function gn(e){return at(e)&&!Ge(e)}function _s(e){return pn(e)}function Ye(e){return gn(e)||_s(e)}function Wa(e){return fe(e,"additionalItems")&&Ye(e.additionalItems)}function Po(e){return fe(e,"additionalProperties")&&Ye(e.additionalProperties)}function ic(e){return fe(e,"allOf")&&Ge(e.allOf)&&e.allOf.every((o)=>Ye(o))}function ac(e){return fe(e,"$anchor")&&gt(e.$anchor)}function uc(e){return fe(e,"anyOf")&&Ge(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function yp(e){return fe(e,"const")}function Rs(e){return fe(e,"contains")&&Ye(e.contains)}function bo(e){return fe(e,"default")}function cc(e){return fe(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||Ge(o)&&o.every((i)=>gt(i)))}function mc(e){return fe(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Ge(o)&&o.every((i)=>gt(i)))}function za(e){return fe(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function Ls(e){return fe(e,"$dynamicAnchor")&&gt(e.$dynamicAnchor)}function pc(e){return fe(e,"$dynamicRef")&&gt(e.$dynamicRef)}function lc(e){return fe(e,"else")&&Ye(e.else)}function xp(e){return fe(e,"enum")&&Ge(e.enum)}function dc(e){return fe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||Nr(e.exclusiveMaximum))}function Zo(e){return fe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||Nr(e.exclusiveMinimum))}function ma(e){return fe(e,"format")&&gt(e.format)}function Eo(e){return fe(e,"$id")&&gt(e.$id)}function fc(e){return fe(e,"if")&&Ye(e.if)}function Ns(e){return fe(e,"items")&&(Ye(e.items)||Ge(e.items)&&e.items.every((o)=>Ye(o)))}function hc(e){return Ns(e)&&Ge(e.items)}function gc(e){return fe(e,"maximum")&&(Ot(e.maximum)||Nr(e.maximum))}function yc(e){return fe(e,"maxContains")&&Ot(e.maxContains)}function Va(e){return fe(e,"maxItems")&&Ot(e.maxItems)}function xc(e){return fe(e,"maxLength")&&Ot(e.maxLength)}function Ic(e){return fe(e,"maxProperties")&&Ot(e.maxProperties)}function es(e){return fe(e,"minimum")&&(Ot(e.minimum)||Nr(e.minimum))}function Ds(e){return fe(e,"minContains")&&Ot(e.minContains)}function xi(e){return fe(e,"minItems")&&Ot(e.minItems)}function pa(e){return fe(e,"minLength")&&Ot(e.minLength)}function la(e){return fe(e,"minProperties")&&Ot(e.minProperties)}function bc(e){return fe(e,"multipleOf")&&(Ot(e.multipleOf)||Nr(e.multipleOf))}function Ec(e){return fe(e,"not")&&Ye(e.not)}function Sc(e){return fe(e,"oneOf")&&Ge(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function da(e){return fe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function qs(e){return fe(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function ts(e){return fe(e,"prefixItems")&&Ge(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function Fs(e){return fe(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function Ja(e){return fe(e,"propertyNames")&&(at(e.propertyNames)||Ye(e.propertyNames))}function Uq(e){return fe(e,"$recursiveAnchor")&&pn(e.$recursiveAnchor)}function wc(e){return Uq(e)&&L(e.$recursiveAnchor,!0)}function Tc(e){return fe(e,"$recursiveRef")&&gt(e.$recursiveRef)}function Rc(e){return fe(e,"$ref")&&gt(e.$ref)}function rs(e){return fe(e,"required")&&Ge(e.required)&&e.required.every((o)=>gt(o))}function kc(e){return fe(e,"then")&&Ye(e.then)}function Ac(e){return fe(e,"type")&&(gt(e.type)||Ge(e.type)&&e.type.every((o)=>gt(o)))}function Ei(e){return fe(e,"uniqueItems")&&pn(e.uniqueItems)}function Ri(e){return fe(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function ki(e){return fe(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function Bq(e){return Ri(e)||ki(e)||wa(we(e),(o)=>Ip(e[o]))}function Gq(e){return wa(e,(o)=>Ip(o))}function Ip(e){return Ge(e)?Gq(e):at(e)?Bq(e):!1}function AR(e,o){return Ip(o)||wa(we(e),(i)=>Ip(e[i]))}class vf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ir(bt("context","Push"),[])}Pop(){return Ir(bt("context","Pop"),[])}AddIndex(e){return Ir(bt("context","AddIndex"),[e])}AddKey(e){return Ir(bt("context","AddKey"),[e])}Merge(e){return Ir(bt("context","Merge"),[e])}}class _n{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((i)=>this.GetIndices().add(i)),o.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class qn extends _n{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Vo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var bp={identifier:"External",variables:[]};function Co(e){let o=`External[${bp.variables.length}]`;return bp.variables.push(e),o}function PR(){bp.variables=[]}function CR(){return{...bp}}function $R(e,o,i,u){let p=Co(i["~refine"].map((g)=>g));return ls(p,De(0),["refinement","_"],Ir(bt("refinement","check"),[u]))}function vR(e,o,i,u){return an(i["~refine"],0,(p,g)=>p.check(u))}function MR(e,o,i,u,p,g){return An(p["~refine"],0,(y,b)=>y.check(g)||o.AddError({keyword:"~refine",schemaPath:i,instancePath:u,params:{index:b,message:y.error(g)}}))}var Kq=0;function Vt(){return`var_${Kq++}`}function Mf(e){return Ns(e)&&Ge(e.items)}function Hq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=dd(g,De(i.items.length)),E=o.AddIndex(g);return ls(u,De(0),[p,g],xr(b,Sn(y,E)))}function Wq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=dd(g,De(i.items.length));return ls(u,De(0),[p,g],xr(b,y))}function OR(e,o,i,u){if(!Mf(i))return De(!0);return o.UseUnevaluated()?Hq(e,o,i,u):Wq(e,o,i,u)}function _R(e,o,i,u){if(!Mf(i))return!0;return an(u,0,(g,y)=>Su(y,i.items.length)||So(e,o,i.additionalItems,g)&&o.AddIndex(y))}function LR(e,o,i,u,p,g){if(!Mf(p))return!0;return an(g,0,(b,E)=>{let S=`${i}/additionalItems`,w=`${u}/${E}`;return Su(E,p.items.length)||wo(e,o,S,w,p.additionalItems,b)&&o.AddIndex(E)})}function ns(e){return new RegExp(e,"u")}function zq(e,o){return!e.UseUnevaluated()&&(L(o,!0)||at(o)&&L(we(o).length,0))}function Vq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Of(e){let o=[];if(qs(e))o.push(...we(e.patternProperties));if(Fs(e))o.push(...we(e.properties).map(Vq));return L(o.length,0)?"(?!)":`(${o.join("|")})`}function Jq(e,o,i){return rs(o)&&Fs(o)&&!qs(o)&&L(o.additionalProperties,!1)&&L(we(o.properties).length,o.required.length)}function Qq(e,o,i){return uo(bt(Ir(bt("Object","getOwnPropertyNames"),[i]),"length"),De(o.required.length))}function Xq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Co(ns(Of(i))),b=to(e,o,i.additionalProperties,`${u}[${p}]`),E=Ir(bt(y,"test"),[p]),S=o.AddKey(p),w=o.UseUnevaluated()?xr(E,Sn(b,S)):xr(E,b);return ls(zi(u),De(0),[p,g],w)}function NR(e,o,i,u){if(zq(o,i.additionalProperties))return De(!0);return Jq(o,i,u)?Qq(o,i,u):Xq(e,o,i,u)}function DR(e,o,i,u){let p=ns(Of(i));return an(we(u),0,(y,b)=>p.test(y)||So(e,o,i.additionalProperties,u[y])&&o.AddKey(y))}function qR(e,o,i,u,p,g){let y=ns(Of(p)),b=[];return An(we(g),0,(S,w)=>{let R=`${i}/additionalProperties`,A=`${u}/${S}`,P=y.test(S)||wo(e,o,R,A,p.additionalProperties,g[S])&&o.AddKey(S);if(!P)b.push(S);return P})||o.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:u,params:{additionalProperties:b}})}function Pi(e,o,i,u,p){let g=vs("results","[]"),y=i.map((w,R)=>vs(`context_${R}`,fd("CheckContext",[]))),b=i.map((w,R)=>vs(`condition_${R}`,Ir(Vs(["context"],Lt(e,o,w,u)),[`context_${R}`]))),E=i.map((w,R)=>Ay(`condition_${R}`,Ir(bt("results","push"),[`context_${R}`]))),S=im(Sn(p,o.Merge("results")));return Ir(Vs([],sm([g,...y,...b,...E,S])),[])}function Yq(e,o,i,u){return Pi(e,o,i.allOf,u,uo(bt("results","length"),De(i.allOf.length)))}function Zq(e,o,i,u){return Pn(i.allOf.map((p)=>Lt(e,o,p,u)))}function FR(e,o,i,u){return o.UseUnevaluated()?Yq(e,o,i,u):Zq(e,o,i,u)}function jR(e,o,i,u){let p=i.allOf.reduce((g,y)=>{let b=new _n;return kt(e,b,y,u)?[...g,b]:g},[]);return L(p.length,i.allOf.length)&&o.Merge(p)}function UR(e,o,i,u,p,g){let y=[],b=p.allOf.reduce((S,w,R)=>{let A=`${i}/allOf/${R}`,P=new qn,C=mr(e,P,A,u,w,g);if(!C)y.push(P);return C?[...S,P]:S},[]),E=L(b.length,p.allOf.length)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E}function eF(e,o,i,u){return Pi(e,o,i.anyOf,u,Ty(bt("results","length"),De(0)))}function tF(e,o,i,u){return hd(i.anyOf.map((p)=>Lt(e,o,p,u)))}function BR(e,o,i,u){return o.UseUnevaluated()?eF(e,o,i,u):tF(e,o,i,u)}function GR(e,o,i,u){let p=i.anyOf.reduce((g,y)=>{let b=new _n;return kt(e,b,y,u)?[...g,b]:g},[]);return Ki(p.length,0)&&o.Merge(p)}function KR(e,o,i,u,p,g){let y=[],b=p.anyOf.reduce((S,w,R)=>{let A=new qn,P=`${i}/anyOf/${R}`,C=mr(e,A,P,u,w,g);if(!C)y.push(A);return C?[...S,A]:S},[]),E=Ki(b.length,0)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E||o.AddError({keyword:"anyOf",schemaPath:i,instancePath:u,params:{}})}function HR(e,o,i,u){return i?De(!0):De(!1)}function _f(e,o,i,u){return i}function WR(e,o,i,u,p,g){return _f(e,o,p,g)||o.AddError({keyword:"boolean",schemaPath:i,instancePath:u,params:{}})}function zR(e,o,i,u){return Hi(i.const)?uo(u,De(i.const)):ky(u,Co(i.const))}function Lf(e,o,i,u){return Hi(i.const)?L(u,i.const):Ta(u,i.const)}function VR(e,o,i,u,p,g){return Lf(e,o,p,g)||o.AddError({keyword:"const",schemaPath:i,instancePath:u,params:{allowedValue:p.const}})}function JR(e){return!(Ds(e)&&L(e.minContains,0))}function rF(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Un(uo(bt(u,"length"),De(0))),b=NM(u,[p,g],Sn(Lt(e,o,i.contains,p),o.AddIndex(g)));return Sn(y,b)}function nF(e,o,i,u){let[p]=[Vt()],g=Un(uo(bt(u,"length"),De(0))),y=LM(u,[p,"_"],Lt(e,o,i.contains,p));return Sn(g,y)}function QR(e,o,i,u){if(!JR(i))return De(!0);return o.UseUnevaluated()?rF(e,o,i,u):nF(e,o,i,u)}function Nf(e,o,i,u){if(!JR(i))return!0;return!L(u.length,0)&&yy(u,(p,g)=>kt(e,o,i.contains,p)&&o.AddIndex(g))}function XR(e,o,i,u,p,g){return Nf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:1}})}function YR(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Pn(ln(i.dependencies).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Lt(e,o,b,u),w=(R)=>Pn(R.map((A)=>Vi(u,De(A))));return xr(E,Ge(b)?w(b):S)}));return xr(p,g)}function ZR(e,o,i,u){let p=L(we(u).length,0),g=an(ln(i.dependencies),0,([y,b])=>!fe(u,y)||(Ge(b)?b.every((E)=>fe(u,E)):kt(e,o,b,u)));return p||g}function ek(e,o,i,u,p,g){let y=L(we(g).length,0),b=An(ln(p.dependencies),0,([E,S])=>{let w=`${i}/dependencies/${E}`;return!fe(g,E)||(Ge(S)?S.every((R)=>fe(g,R)||o.AddError({keyword:"dependencies",schemaPath:i,instancePath:u,params:{property:E,dependencies:S}})):mr(e,o,w,u,S,g))});return y||b}function tk(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Pn(ln(i.dependentRequired).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Pn(b.map((w)=>Vi(u,De(w))));return xr(E,S)}));return xr(p,g)}function rk(e,o,i,u){let p=L(we(u).length,0),g=an(ln(i.dependentRequired),0,([y,b])=>!fe(u,y)||b.every((E)=>fe(u,E)));return p||g}function nk(e,o,i,u,p,g){let y=L(we(g).length,0),b=An(ln(p.dependentRequired),0,([E,S])=>!fe(g,E)||An(S,0,(w)=>fe(g,w)||o.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:u,params:{property:E,dependencies:S}})));return y||b}function ok(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Pn(ln(i.dependentSchemas).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Lt(e,o,b,u);return xr(E,S)}));return xr(p,g)}function sk(e,o,i,u){let p=L(we(u).length,0),g=an(ln(i.dependentSchemas),0,([y,b])=>!fe(u,y)||kt(e,o,b,u));return p||g}function ik(e,o,i,u,p,g){let y=L(we(g).length,0),b=An(ln(p.dependentSchemas),0,([E,S])=>{let w=`${i}/dependentSchemas/${E}`;return!fe(g,E)||mr(e,o,w,u,S,g)});return y||b}function ak(e,o,i,u){let p=e.DynamicRef(i)??!1;return js(e,o,p,u)}function uk(e,o,i,u){let p=e.DynamicRef(i)??!1;return Ye(p)&&kt(e,o,p,u)}function ck(e,o,i,u,p,g){let y=e.DynamicRef(p)??!1;return Ye(y)&&mr(e,o,"#",u,y,g)}function mk(e,o,i,u){return hd(i.enum.map((p)=>{if(Hi(p))return uo(u,De(p));let g=Co(p);return ky(u,g)}))}function qf(e,o,i,u){return wa(i.enum,(p)=>Hi(p)?L(u,p):Ta(u,p))}function pk(e,o,i,u,p,g){return qf(e,o,p,g)||o.AddError({keyword:"enum",schemaPath:i,instancePath:u,params:{allowedValues:p.enum}})}function lk(e,o,i,u){return dd(u,De(i.exclusiveMaximum))}function Ff(e,o,i,u){return Su(u,i.exclusiveMaximum)}function dk(e,o,i,u,p,g){return Ff(e,o,p,g)||o.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:u,params:{comparison:"<",limit:p.exclusiveMaximum}})}function fk(e,o,i,u){return Ty(u,De(i.exclusiveMinimum))}function jf(e,o,i,u){return Ki(u,i.exclusiveMinimum)}function hk(e,o,i,u,p,g){return jf(e,o,p,g)||o.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:u,params:{comparison:">",limit:p.exclusiveMinimum}})}var oF=[0,31,28,31,30,31,30,31,31,30,31,30,31],sF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function iF(e){return e%4===0&&(e%100!==0||e%400===0)}function Xa(e){let o=sF.exec(e);if(!o)return!1;let i=+o[1],u=+o[2],p=+o[3];return u>=1&&u<=12&&p>=1&&p<=(u===2&&iF(i)?29:oF[u])}var aF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Ya(e,o=!0){let i=aF.exec(e);if(!i)return!1;if(o&&!i[4]&&!i[5])return!1;let u=+i[1],p=+i[2],g=+i[3];if(u>23||p>59||g>60)return!1;if(i[5]){let w=+i[6],R=+i[7];if(w>23||R>59)return!1}if(g<60)return!0;let y=i[5]==="-"?-1:1,b=+(i[6]||0),E=+(i[7]||0);return((u*60+p-y*(b*60+E))%1440+1440)%1440===1439}function Ep(e){let o=e.split(/T/i);return o.length===2&&Xa(o[0])&&Ya(o[1])}var uF=/^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 Sp(e){return uF.test(e)}var cF=/^(?:[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 wp(e){return cF.test(e)}var gk=/^(?!-).*(?<!-)$/,yk=/^(?!..--)/,xk=/^[a-zA-Z0-9-]*$/;var Za=/[^\p{ASCII}]/u;var mF=/[0-9]/,Ik=/[\u{0660}-\u{0669}]/u,pF=/[\u{06f0}-\u{06f9}]/u,lF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,dF=/[\u{002d}\u{002b}]/u,Uf=/\p{Mn}/u,fF=/\p{Mc}/u;var bk=/[\p{Mn}\p{Mc}\p{Me}]/u,Bf=/\p{L}/u,hF=/\p{Nd}/u,Ek=/\p{Script=Greek}/u,Tp=/\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,Gf=/[\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,gF=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,yF=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Rk=new RegExp([mF,pF].map((e)=>e.source).join("|"),"u"),kk=new RegExp([Bf,dF,lF,hF,Uf,fF,gF,yF].map((e)=>e.source).join("|"),"u");function Ak(e){return gk.test(e)&&yk.test(e)&&xk.test(e)}var os=36,Cc=1,$c=26,IF=38,bF=700,Ck=72,$k=128;function Kf(){throw null}function Rp(e){return e.toLowerCase().startsWith("xn--")}function vk(e,o,i){e=i?Math.floor(e/bF):e>>1,e+=Math.floor(e/o);let u=0;while(e>(os-Cc)*$c>>1)e=Math.floor(e/(os-Cc)),u+=os;return u+Math.floor((os-Cc+1)*e/(e+IF))}function kp(e){let o=[],i=$k,u=0,p=Ck,g=e.lastIndexOf("-");if(g>0)for(let b=0;b<g;b++){let E=e.charCodeAt(b);if(E>=128)Kf();o.push(E)}let y=g<0?0:g+1;while(y<e.length){let b=u,E=1,S=os;while(!0){if(y>=e.length)Kf();let R=e.charCodeAt(y++),A;if(R>=97&&R<=122)A=R-97;else if(R>=48&&R<=57)A=R-48+26;else Kf();u+=A*E;let P=S<=p?Cc:S>=p+$c?$c:S-p;if(A<P)break;E*=os-P,S+=os}let w=o.length+1;p=vk(u-b,w,b===0),i+=Math.floor(u/w),u%=w,o.splice(u,0,i),u++}return String.fromCodePoint(...o)}function Pk(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var EF=new RegExp(Za.source,"gu");function Mk(e){let o=e.replace(EF,""),i=o.length,u=i>0?[o,"-"]:[],p=Array.from(e,(S)=>S.codePointAt(0)),g=$k,y=0,b=Ck,E=i;while(E<p.length){let S=1/0;for(let w of p)if(w>=g&&w<S)S=w;y+=(S-g)*(E+1),g=S;for(let w of p){if(w<g)y++;if(w===g){let R=y;for(let A=os;;A+=os){let P=A<=b?Cc:A>=b+$c?$c:A-b;if(R<P)break;let C=P+(R-P)%(os-P);u.push(Pk(C)),R=Math.floor((R-P)/(os-P))}u.push(Pk(R)),b=vk(y,E+1,E===i),y=0,E++}}y++,g++}return u.join("")}var SF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,Ok=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,wF=/^(?:R|AL|AN)$/;function _k(e){if(Rp(e))try{return Ap(kp(e.slice(4).toLowerCase()))}catch{return!1}return Ap(e)}function Lk(e){let o=String.fromCodePoint(e);return Rk.test(o)?"EN":Ik.test(o)?"AN":Uf.test(o)?"NSM":Tp.test(o)?"R":wk.test(o)?"AL":Bf.test(o)?"L":"ON"}function Ap(e){for(let o of e)if(wF.test(Lk(o.codePointAt(0))))return!0;return!1}function Pp(e){let o=!1,i=Ok,u=!1,p=!1,g=!0;for(let y of e){let b=Lk(y.codePointAt(0));if(g){if(b!=="L"&&b!=="R"&&b!=="AL")return!1;o=b==="R"||b==="AL",i=o?SF:Ok,g=!1}if(!i.test(b))return!1;if(b==="EN")u=!0;else if(b==="AN")p=!0}if(o&&u&&p)return!1;return!0}function TF(e){return Za.test(e)&&Mk(e).length+4>63}function RF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Cp(e){if(TF(e))return!1;if(Ap(e)&&!Pp(e))return!1;let o=[...e],i=o.map((g)=>g.codePointAt(0)),u=i.length;if(RF(o))return!1;if(bk.test(o[0]))return!1;let p=!1;for(let g=0;g<u;g++){let y=i[g],b=o[g];if(Tk.test(b))return!1;if(!kk.test(b))return!1;if(Sk.test(b))p=!0;let E=i[g-1],S=i[g+1];switch(y){case 183:if(E!==108||S!==108)return!1;break;case 885:if(!S||!Ek.test(o[g+1]))return!1;break;case 1523:case 1524:if(!E||!Tp.test(o[g-1]))return!1;break;case 8204:if(!E||E<128&&!Gf.test(o[g-1]))return!1;break;case 8205:if(!E||!Gf.test(o[g-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function $p(e){if(!Rp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let i=kp(o);if(!Za.test(i))return!1;return Cp(i)}catch{return!1}}function kF(e){return e.length>0&&e.length<=63}function AF(e){return kF(e)&&($p(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((o)=>AF(o))}function PF(e){return e.length>0&&e.length<=63}function CF(e){return PF(e)&&($p(e)||Cp(e))}function $F(e){return e.replace(/[\uff01-\uff5e]/g,(o)=>String.fromCharCode(o.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function jk(e){if(e.length===0||e.includes(" "))return!1;let o=$F(e);if(o.length>253)return!1;let i=o.split("."),u=i.some((p)=>_k(p));return i.every((p)=>CF(p)&&(!u||Pp(p)))}function vp(e){return Fk(e)}var vF=/^(?:[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 Mp(e){return vF.test(e.normalize("NFC"))}function Op(e){return jk(e)}var MF=/^(?:(?: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 _p(e){return MF.test(e)}var OF=/^(?:(?:(?:[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 Lp(e){return OF.test(e)}var _F=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,LF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Np(e){return!_F.test(e)&&!LF.test(e)&&URL.canParse(e,"http://example.com")}var NF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,DF=/[\x00-\x20<>\^`{|}\\]/,qF=/%(?![0-9a-fA-F]{2})/;function FF(e){return e.length<2048?e.replace(NF,"[::1]"):e}function Dp(e){if(DF.test(e))return!1;if(qF.test(e))return!1;return URL.canParse(FF(e))}var jF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function qp(e){return jF.test(e)}var UF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Fp(e){return UF.test(e)}function jp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var BF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Up(e){return BF.test(e)}var GF=/^(?:[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 Bp(e){return GF.test(e)}var KF=/^(?:(?:[^\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 Gp(e){return KF.test(e)}var HF=/^[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 Kp(e){return HF.test(e)}function Hp(e){return URL.canParse(e)}var WF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Wp(e){return WF.test(e)}var Er=new Map;function Bk(){Er.clear()}function zF(){return[...Er.entries()]}function VF(e,o){Er.set(e,o)}function JF(e){return Er.has(e)}function QF(e){return Er.get(e)}function Gk(e,o){return Er.get(e)?.(o)??!0}function Kk(){Bk(),Er.set("date-time",Ep),Er.set("date",Xa),Er.set("duration",Sp),Er.set("email",wp),Er.set("hostname",vp),Er.set("idn-email",Mp),Er.set("idn-hostname",Op),Er.set("ipv4",_p),Er.set("ipv6",Lp),Er.set("iri-reference",Np),Er.set("iri",Dp),Er.set("json-pointer-uri-fragment",qp),Er.set("json-pointer",Fp),Er.set("regex",jp),Er.set("relative-json-pointer",Up),Er.set("time",Ya),Er.set("uri-reference",Bp),Er.set("uri-template",Gp),Er.set("uri",Kp),Er.set("url",Hp),Er.set("uuid",Wp)}Kk();function Hk(e,o,i,u){return Ir(bt("Format","Test"),[De(i.format),u])}function Wf(e,o,i,u){return Gk(i.format,u)}function Wk(e,o,i,u,p,g){return Wf(e,o,p,g)||o.AddError({keyword:"format",schemaPath:i,instancePath:u,params:{format:p.format}})}function zk(e,o,i,u){let p=kc(i)?i.then:!0,g=lc(i)?i.else:!0;return qM(Lt(e,o,i.if,u),Lt(e,o,p,u),Lt(e,o,g,u))}function Vk(e,o,i,u){let p=kc(i)?i.then:!0,g=lc(i)?i.else:!0;return kt(e,o,i.if,u)?kt(e,o,p,u):kt(e,o,g,u)}function Jk(e,o,i,u,p,g){let y=kc(p)?p.then:!0,b=lc(p)?p.else:!0,E=new qn,S=mr(e,E,`${i}/if`,u,p.if,g)?mr(e,E,`${i}/then`,u,y,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"then"}}):mr(e,o,`${i}/else`,u,b,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"else"}});if(S)o.Merge([E]);return S}function XF(e,o,i,u){return Pn(i.items.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`),E=o.AddIndex(De(g));return xr(y,Sn(b,E))}))}function YF(e,o,i,u){return Pn(i.items.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`);return xr(y,b)}))}function ZF(e,o,i,u){return o.UseUnevaluated()?XF(e,o,i,u):YF(e,o,i,u)}function e1(e,o,i,u){return an(i.items,0,(p,g)=>ps(u.length,g)||So(e,o,p,u[g])&&o.AddIndex(g))}function t1(e,o,i,u,p,g){return An(p.items,0,(y,b)=>{let E=`${i}/items/${b}`,S=`${u}/${b}`;return ps(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function r1(e,o,i,u){let p=ts(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element"),y=o.AddIndex("index");return ls(u,De(p),["element","index"],Sn(g,y))}function n1(e,o,i,u){let p=ts(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element");return ls(u,De(p),["element","index"],g)}function o1(e,o,i,u){return o.UseUnevaluated()?r1(e,o,i,u):n1(e,o,i,u)}function s1(e,o,i,u){let p=ts(i)?i.prefixItems.length:0;return an(u,p,(g,y)=>So(e,o,i.items,g)&&o.AddIndex(y))}function i1(e,o,i,u,p,g){let y=ts(p)?p.prefixItems.length:0;return An(g,y,(b,E)=>{let S=`${i}/items`,w=`${u}/${E}`;return wo(e,o,S,w,p.items,b)&&o.AddIndex(E)})}function Qk(e,o,i,u){return hc(i)?ZF(e,o,i,u):o1(e,o,i,u)}function Xk(e,o,i,u){return hc(i)?e1(e,o,i,u):s1(e,o,i,u)}function Yk(e,o,i,u,p,g){return hc(p)?t1(e,o,i,u,p,g):i1(e,o,i,u,p,g)}function Zk(e){return Rs(e)}function eA(e,o,i,u){if(!Zk(i))return De(!0);let[p]=[Vt()],g=om(u,[p,"_"],Lt(e,o,i.contains,p));return Wi(g,De(i.maxContains))}function zf(e,o,i,u){if(!Zk(i))return!0;let p=cd(u,(g)=>kt(e,o,i.contains,g));return ps(p,i.maxContains)}function tA(e,o,i,u,p,g){let y=Ds(p)?p.minContains:1;return zf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:y,maxContains:p.maxContains}})}function rA(e,o,i,u){return Wi(u,De(i.maximum))}function Vf(e,o,i,u){return ps(u,i.maximum)}function nA(e,o,i,u,p,g){return Vf(e,o,p,g)||o.AddError({keyword:"maximum",schemaPath:i,instancePath:u,params:{comparison:"<=",limit:p.maximum}})}function oA(e,o,i,u){return Wi(bt(u,"length"),De(i.maxItems))}function Jf(e,o,i,u){return ps(u.length,i.maxItems)}function sA(e,o,i,u,p,g){return Jf(e,o,p,g)||o.AddError({keyword:"maxItems",schemaPath:i,instancePath:u,params:{limit:p.maxItems}})}function iA(e,o,i,u){return _M(u,De(i.maxLength))}function Qf(e,o,i,u){return hy(u,i.maxLength)}function aA(e,o,i,u,p,g){return Qf(e,o,p,g)||o.AddError({keyword:"maxLength",schemaPath:i,instancePath:u,params:{limit:p.maxLength}})}function uA(e,o,i,u){return Wi(bt(zi(u),"length"),De(i.maxProperties))}function Xf(e,o,i,u){return ps(we(u).length,i.maxProperties)}function cA(e,o,i,u,p,g){return Xf(e,o,p,g)||o.AddError({keyword:"maxProperties",schemaPath:i,instancePath:u,params:{limit:p.maxProperties}})}function mA(e){return Rs(e)}function a1(e,o,i,u){let[p,g]=[Vt(),Vt()],y=om(u,[p,g],Sn(Lt(e,o,i.contains,p),o.AddIndex(g)));return Tu(y,De(i.minContains))}function u1(e,o,i,u){let[p]=[Vt()],g=om(u,[p,"_"],Lt(e,o,i.contains,p));return Tu(g,De(i.minContains))}function pA(e,o,i,u){if(!mA(i))return De(!0);return o.UseUnevaluated()?a1(e,o,i,u):u1(e,o,i,u)}function Yf(e,o,i,u){if(!mA(i))return!0;let p=cd(u,(g,y)=>kt(e,o,i.contains,g)&&o.AddIndex(y));return Sa(p,i.minContains)}function lA(e,o,i,u,p,g){return Yf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:p.minContains}})}function dA(e,o,i,u){return Tu(u,De(i.minimum))}function Zf(e,o,i,u){return Sa(u,i.minimum)}function fA(e,o,i,u,p,g){return Zf(e,o,p,g)||o.AddError({keyword:"minimum",schemaPath:i,instancePath:u,params:{comparison:">=",limit:p.minimum}})}function hA(e,o,i,u){return Tu(bt(u,"length"),De(i.minItems))}function eh(e,o,i,u){return Sa(u.length,i.minItems)}function gA(e,o,i,u,p,g){return eh(e,o,p,g)||o.AddError({keyword:"minItems",schemaPath:i,instancePath:u,params:{limit:p.minItems}})}function yA(e,o,i,u){return OM(u,De(i.minLength))}function th(e,o,i,u){return gy(u,i.minLength)}function xA(e,o,i,u,p,g){return th(e,o,p,g)||o.AddError({keyword:"minLength",schemaPath:i,instancePath:u,params:{limit:p.minLength}})}function IA(e,o,i,u){return Tu(bt(zi(u),"length"),De(i.minProperties))}function rh(e,o,i,u){return Sa(we(u).length,i.minProperties)}function bA(e,o,i,u,p,g){return rh(e,o,p,g)||o.AddError({keyword:"minProperties",schemaPath:i,instancePath:u,params:{limit:p.minProperties}})}function EA(e,o,i,u){return FM(u,De(i.multipleOf))}function nh(e,o,i,u){return dy(u,i.multipleOf)}function SA(e,o,i,u,p,g){return nh(e,o,p,g)||o.AddError({keyword:"multipleOf",schemaPath:i,instancePath:u,params:{multipleOf:p.multipleOf}})}function c1(e,o,i,u){return Pi(e,o,[i.not],u,Un(uo(bt("results","length"),De(1))))}function m1(e,o,i,u){return Un(Lt(e,o,i.not,u))}function wA(e,o,i,u){return o.UseUnevaluated()?c1(e,o,i,u):m1(e,o,i,u)}function oh(e,o,i,u){let p=new _n;return!kt(e,p,i.not,u)&&o.Merge([p])}function TA(e,o,i,u,p,g){return oh(e,o,p,g)||o.AddError({keyword:"not",schemaPath:i,instancePath:u,params:{}})}function p1(e,o,i,u){return Pi(e,o,i.oneOf,u,uo(bt("results","length"),De(1)))}function l1(e,o,i,u){let[p]=[Vt()],g=DM(i.oneOf.map((b)=>Lt(e,o,b,u))),y=om(g,[p,"_"],uo(p,De(!0)));return uo(y,De(1))}function RA(e,o,i,u){return o.UseUnevaluated()?p1(e,o,i,u):l1(e,o,i,u)}function kA(e,o,i,u){let p=i.oneOf.reduce((g,y)=>{let b=new _n;return kt(e,b,y,u)?[...g,b]:g},[]);return L(p.length,1)&&o.Merge(p)}function AA(e,o,i,u,p,g){let y=[],b=[],E=p.oneOf.reduce((w,R,A)=>{let P=new qn,C=`${i}/oneOf/${A}`,q=mr(e,P,C,u,R,g);if(q)b.push(A);if(!q)y.push(P);return q?[...w,P]:w},[]),S=L(E.length,1)&&o.Merge(E);if(!S&&L(b.length,0))y.forEach((w)=>w.GetErrors().forEach((R)=>o.AddError(R)));return S||o.AddError({keyword:"oneOf",schemaPath:i,instancePath:u,params:{passingSchemas:b}})}function PA(e,o,i,u){let p=Co(gt(i.pattern)?ns(i.pattern):i.pattern);return Ir(bt(p,"test"),[u])}function sh(e,o,i,u){return(gt(i.pattern)?ns(i.pattern):i.pattern).test(u)}function CA(e,o,i,u,p,g){return sh(e,o,p,g)||o.AddError({keyword:"pattern",schemaPath:i,instancePath:u,params:{pattern:p.pattern}})}function $A(e,o,i,u){return Pn(ln(i.patternProperties).map(([p,g])=>{let[y,b]=[Vt(),Vt()],E=Co(ns(p)),S=Un(Ir(bt(E,"test"),[y])),w=to(e,o,g,b),R=o.AddKey(y),A=o.UseUnevaluated()?xr(S,Sn(w,R)):xr(S,w);return ls(Ry(u),De(0),[`[${y}, ${b}]`,"_"],A)}))}function vA(e,o,i,u){return an(ln(i.patternProperties),0,([p,g])=>{let y=ns(p);return an(ln(u),0,([b,E])=>!y.test(b)||So(e,o,g,E)&&o.AddKey(b))})}function MA(e,o,i,u,p,g){return An(ln(p.patternProperties),0,([y,b])=>{let E=`${i}/patternProperties/${y}`,S=ns(y);return An(ln(g),0,([w,R])=>{let A=`${u}/${w}`;return!S.test(w)||wo(e,o,E,A,b,R)&&o.AddKey(w)})})}function OA(e,o,i,u){return Pn(i.prefixItems.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`),E=o.AddIndex(De(g)),S=o.UseUnevaluated()?Sn(b,E):b;return xr(y,S)}))}function _A(e,o,i,u){return L(u.length,0)||an(i.prefixItems,0,(p,g)=>ps(u.length,g)||So(e,o,p,u[g])&&o.AddIndex(g))}function LA(e,o,i,u,p,g){return L(g.length,0)||An(p.prefixItems,0,(y,b)=>{let E=`${i}/prefixItems/${b}`,S=`${u}/${b}`;return ps(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function zp(e,o){return e.includes(o)||Vo().exactOptionalPropertyTypes}function NA(e,o){return ld(bt(e,o))}function ih(e,o){return Ut(e[o])}function DA(e,o,i,u){let p=rs(i)?i.required:[],g=ln(i.properties).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=to(e,o,b,bt(u,y)),w=o.AddKey(De(y)),R=o.UseUnevaluated()?Sn(S,w):S,A=p.includes(y)?R:xr(E,R);return zp(p,y)?A:xr(NA(u,y),A)});return Pn(g)}function qA(e,o,i,u){let p=rs(i)?i.required:[];return an(ln(i.properties),0,([y,b])=>{let E=!fe(u,y)||So(e,o,b,u[y])&&o.AddKey(y);return zp(p,y)?E:ih(u,y)||E})}function FA(e,o,i,u,p,g){let y=rs(p)?p.required:[];return An(ln(p.properties),0,([E,S])=>{let w=`${i}/properties/${E}`,R=`${u}/${E}`,A=()=>!fe(g,E)||wo(e,o,w,R,S,g[E])&&o.AddKey(E);return zp(y,E)?A():ih(g,E)||A()})}function jA(e,o,i,u){let[p,g]=[Vt(),Vt()];return ls(zi(u),De(0),[p,g],Lt(e,o,i.propertyNames,p))}function UA(e,o,i,u){return an(we(u),0,(p,g)=>kt(e,o,i.propertyNames,p))}function BA(e,o,i,u,p,g){let y=[];return An(we(g),0,(E,S)=>{let w=`${u}/${E}`,R=`${i}/propertyNames`,A=mr(e,o,R,w,p.propertyNames,E);if(!A)y.push(E);return A})||o.AddError({keyword:"propertyNames",schemaPath:i,instancePath:u,params:{propertyNames:y}})}function GA(e,o,i,u){let p=e.RecursiveRef(i)??!1;return js(e,o,p,u)}function KA(e,o,i,u){let p=e.RecursiveRef(i)??!1;return Ye(p)&&kt(e,o,p,u)}function HA(e,o,i,u,p,g){let y=e.RecursiveRef(p)??!1;return Ye(y)&&mr(e,o,"#",u,y,g)}function d1(e,o,i,u){let p=Vs(["context","value"],js(e,o,i,"value")),g=Vs(["context","value"],sm([vs("nextContext",fd("CheckContext",[])),vs("result",Ir(p,["nextContext","value"])),Ay("result",o.Merge("[nextContext]")),im("result")]));return Ir(g,["context",u])}function f1(e,o,i,u){return js(e,o,i,u)}function WA(e,o,i,u){let p=e.Ref(i)??!1;return o.UseUnevaluated()?d1(e,o,p,u):f1(e,o,p,u)}function zA(e,o,i,u){let p=e.Ref(i)??!1,g=new _n,y=Ye(p)&&kt(e,g,p,u);if(y)o.Merge([g]);return y}function VA(e,o,i,u,p,g){let y=e.Ref(p)??!1,b=new qn,E=Ye(y)&&mr(e,b,"#",u,y,g);if(E)o.Merge([b]);if(!E)b.GetErrors().forEach((S)=>o.AddError(S));return E}function JA(e,o,i,u){return Pn(i.required.map((p)=>Vi(u,De(p))))}function QA(e,o,i,u){return an(i.required,0,(p)=>fe(u,p))}function XA(e,o,i,u,p,g){let y=[];return An(p.required,0,(E)=>{let S=fe(g,E);if(!S)y.push(E);return S})||o.AddError({keyword:"required",schemaPath:i,instancePath:u,params:{requiredProperties:y}})}function YA(e,o,i,u){return L(i,"object")?Ey(u):L(i,"array")?nm(u):L(i,"boolean")?AM(u):L(i,"integer")?PM(u):L(i,"number")?by(u):L(i,"null")?CM(u):L(i,"string")?wy(u):L(i,"bigint")?Iy(u):L(i,"constructor")?MM(u):L(i,"function")?vM(u):L(i,"symbol")?$M(u):L(i,"undefined")?ld(u):L(i,"void")?ld(u):De(!0)}function ah(e,o,i,u,p){return L(i,"object")?zo(p):L(i,"array")?Ge(p):L(i,"boolean")?pn(p):L(i,"integer")?rm(p):L(i,"number")?Ot(p):L(i,"null")?ho(p):L(i,"string")?gt(p):L(i,"bigint")?Nr(p):L(i,"constructor")?ad(p):L(i,"function")?ms(p):L(i,"symbol")?ud(p):L(i,"undefined")?Ut(p):L(i,"void")?Ut(p):!0}function h1(e,o,i,u){return hd(i.map((p)=>YA(e,o,p,u)))}function ZA(e,o,i,u,p){return wa(i,(g)=>ah(e,o,g,u,p))}function e0(e,o,i,u){return Ge(i.type)?h1(e,o,i.type,u):YA(e,o,i.type,u)}function t0(e,o,i,u){return Ge(i.type)?ZA(e,o,i.type,i,u):ah(e,o,i.type,i,u)}function r0(e,o,i,u,p,g){return(Ge(p.type)?ZA(e,o,p.type,p,g):ah(e,o,p.type,p,g))||o.AddError({keyword:"type",schemaPath:i,instancePath:u,params:{type:p.type}})}function n0(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetIndices"),[]),b=Ir(bt("indices","has"),[p]),E=Lt(e,o,i.unevaluatedItems,g),S=Ir(bt("context","AddIndex"),[p]),w=ls(u,De(0),[g,p],Sn(xr(b,E),S));return Ir(Vs(["context"],sm([vs("indices",y),im(w)])),["context"])}function o0(e,o,i,u){let p=o.GetIndices();return an(u,0,(g,y)=>(p.has(y)||kt(e,o,i.unevaluatedItems,g))&&o.AddIndex(y))}function s0(e,o,i,u,p,g){let y=o.GetIndices(),b=[];return An(g,0,(S,w)=>{let R=new qn,A=(y.has(w)||mr(e,R,i,u,p.unevaluatedItems,S))&&o.AddIndex(w);if(!A)b.push(w);return A})||o.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:u,params:{unevaluatedItems:b}})}function i0(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetKeys"),[]),b=Ir(bt("keys","has"),[p]),E=Ir(bt("context","AddKey"),[p]),S=Lt(e,o,i.unevaluatedProperties,g),w=ls(Ry(u),De(0),[`[${p}, ${g}]`,"_"],xr(b,Sn(S,E)));return Ir(Vs(["context"],sm([vs("keys",y),im(w)])),["context"])}function a0(e,o,i,u){let p=o.GetKeys();return an(ln(u),0,([g,y])=>p.has(g)||kt(e,o,i.unevaluatedProperties,y)&&o.AddKey(g))}function u0(e,o,i,u,p,g){let y=o.GetKeys(),b=[];return An(ln(g),0,([S,w])=>{let R=new qn,A=y.has(S)||mr(e,R,i,u,p.unevaluatedProperties,w)&&o.AddKey(S);if(!A)b.push(S);return A})||o.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:u,params:{unevaluatedProperties:b}})}function uh(e){return!L(e.uniqueItems,!1)}function c0(e,o,i,u){if(!uh(i))return De(!0);let p=bt(fd("Set",[Ir(bt(u,"map"),[bt("Hashing","Hash")])]),"size"),g=bt(u,"length");return uo(p,g)}function m0(e,o,i,u){if(!uh(i))return!0;let p=new Set(u.map(xd)).size,g=u.length;return L(p,g)}function p0(e,o,i,u,p,g){if(!uh(p))return!0;let y=new Set,b=g.reduce((S,w,R)=>{let A=xd(w);if(y.has(A))return[...S,R];return y.add(A),S},[]);return L(b.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:u,params:{duplicateItems:b}})}function vc(e,o){return Ac(e)&&(Ge(e.type)&&Ki(e.type.length,0)&&an(e.type,0,(i)=>L(i,o))||L(e.type,o))}function g1(e){return vc(e,"object")}function y1(e){return gn(e)&&(Po(e)||cc(e)||mc(e)||za(e)||Fs(e)||qs(e)||Ja(e)||la(e)||Ic(e)||rs(e)||ki(e))}function x1(e){return vc(e,"array")}function I1(e){return gn(e)&&(Wa(e)||Ns(e)||Rs(e)||yc(e)||Va(e)||Ds(e)||xi(e)||ts(e)||Ri(e)||Ei(e))}function b1(e){return vc(e,"string")}function E1(e){return gn(e)&&(pa(e)||xc(e)||ma(e)||da(e))}function S1(e){return vc(e,"number")||vc(e,"bigint")}function w1(e){return gn(e)&&(es(e)||gc(e)||dc(e)||Zo(e)||bc(e))}function to(e,o,i,u){return o.UseUnevaluated()?Sn(Sn(o.Push(),Lt(e,o,i,u)),o.Pop()):Lt(e,o,i,u)}function Lt(e,o,i,u){e.Push(i);let p=[];if(_s(i))return HR(e,o,i,u);if(Ac(i))p.push(e0(e,o,i,u));if(y1(i)){let y=[];if(rs(i))y.push(JA(e,o,i,u));if(Po(i))y.push(NR(e,o,i,u));if(cc(i))y.push(YR(e,o,i,u));if(mc(i))y.push(tk(e,o,i,u));if(za(i))y.push(ok(e,o,i,u));if(qs(i))y.push($A(e,o,i,u));if(Fs(i))y.push(DA(e,o,i,u));if(Ja(i))y.push(jA(e,o,i,u));if(la(i))y.push(IA(e,o,i,u));if(Ic(i))y.push(uA(e,o,i,u));let b=Pn(y),E=xr(Un(Ey(u)),b);p.push(g1(i)?b:E)}if(I1(i)){let y=[];if(Wa(i))y.push(OR(e,o,i,u));if(Rs(i))y.push(QR(e,o,i,u));if(Ns(i))y.push(Qk(e,o,i,u));if(yc(i))y.push(eA(e,o,i,u));if(Va(i))y.push(oA(e,o,i,u));if(Ds(i))y.push(pA(e,o,i,u));if(xi(i))y.push(hA(e,o,i,u));if(ts(i))y.push(OA(e,o,i,u));if(Ei(i))y.push(c0(e,o,i,u));let b=Pn(y),E=xr(Un(nm(u)),b);p.push(x1(i)?b:E)}if(E1(i)){let y=[];if(xc(i))y.push(iA(e,o,i,u));if(pa(i))y.push(yA(e,o,i,u));if(ma(i))y.push(Hk(e,o,i,u));if(da(i))y.push(PA(e,o,i,u));let b=Pn(y),E=xr(Un(wy(u)),b);p.push(b1(i)?b:E)}if(w1(i)){let y=[];if(dc(i))y.push(lk(e,o,i,u));if(Zo(i))y.push(fk(e,o,i,u));if(gc(i))y.push(rA(e,o,i,u));if(es(i))y.push(dA(e,o,i,u));if(bc(i))y.push(EA(e,o,i,u));let b=Pn(y),E=xr(Un(xr(by(u),Iy(u))),b);p.push(S1(i)?b:E)}if(Rc(i))p.push(WA(e,o,i,u));if(Tc(i))p.push(GA(e,o,i,u));if(pc(i))p.push(ak(e,o,i,u));if(yp(i))p.push(zR(e,o,i,u));if(xp(i))p.push(mk(e,o,i,u));if(fc(i))p.push(zk(e,o,i,u));if(Ec(i))p.push(wA(e,o,i,u));if(ic(i))p.push(FR(e,o,i,u));if(uc(i))p.push(BR(e,o,i,u));if(Sc(i))p.push(RA(e,o,i,u));if(Ri(i))p.push(xr(Un(nm(u)),n0(e,o,i,u)));if(ki(i))p.push(xr(Un(Sy(u)),i0(e,o,i,u)));if(sc(i))p.push($R(e,o,i,u));let g=Pn(p);return e.Pop(i),g}function So(e,o,i,u){return o.Push()&&kt(e,o,i,u)&&o.Pop()}function kt(e,o,i,u){e.Push(i);let p=_s(i)?_f(e,o,i,u):(!Ac(i)||t0(e,o,i,u))&&(!(at(u)&&!Ge(u))||(!rs(i)||QA(e,o,i,u))&&(!Po(i)||DR(e,o,i,u))&&(!cc(i)||ZR(e,o,i,u))&&(!mc(i)||rk(e,o,i,u))&&(!za(i)||sk(e,o,i,u))&&(!qs(i)||vA(e,o,i,u))&&(!Fs(i)||qA(e,o,i,u))&&(!Ja(i)||UA(e,o,i,u))&&(!la(i)||rh(e,o,i,u))&&(!Ic(i)||Xf(e,o,i,u)))&&(!Ge(u)||(!Wa(i)||_R(e,o,i,u))&&(!Rs(i)||Nf(e,o,i,u))&&(!Ns(i)||Xk(e,o,i,u))&&(!yc(i)||zf(e,o,i,u))&&(!Va(i)||Jf(e,o,i,u))&&(!Ds(i)||Yf(e,o,i,u))&&(!xi(i)||eh(e,o,i,u))&&(!ts(i)||_A(e,o,i,u))&&(!Ei(i)||m0(e,o,i,u)))&&(!gt(u)||(!xc(i)||Qf(e,o,i,u))&&(!pa(i)||th(e,o,i,u))&&(!ma(i)||Wf(e,o,i,u))&&(!da(i)||sh(e,o,i,u)))&&(!(Ot(u)||Nr(u))||(!dc(i)||Ff(e,o,i,u))&&(!Zo(i)||jf(e,o,i,u))&&(!gc(i)||Vf(e,o,i,u))&&(!es(i)||Zf(e,o,i,u))&&(!bc(i)||nh(e,o,i,u)))&&(!Rc(i)||zA(e,o,i,u))&&(!Tc(i)||KA(e,o,i,u))&&(!pc(i)||uk(e,o,i,u))&&(!yp(i)||Lf(e,o,i,u))&&(!xp(i)||qf(e,o,i,u))&&(!fc(i)||Vk(e,o,i,u))&&(!Ec(i)||oh(e,o,i,u))&&(!ic(i)||jR(e,o,i,u))&&(!uc(i)||GR(e,o,i,u))&&(!Sc(i)||kA(e,o,i,u))&&(!Ri(i)||(!Ge(u)||o0(e,o,i,u)))&&(!ki(i)||(!at(u)||a0(e,o,i,u)))&&(!sc(i)||vR(e,o,i,u));return e.Pop(i),p}function wo(e,o,i,u,p,g){return o.Push()&&mr(e,o,i,u,p,g)&&o.Pop()}function mr(e,o,i,u,p,g){if(o.AtCapacity())return!1;e.Push(p);let y=_s(p)?WR(e,o,i,u,p,g):!!(+(!Ac(p)||r0(e,o,i,u,p,g))&+(!(at(g)&&!Ge(g))||!!(+(!rs(p)||XA(e,o,i,u,p,g))&+(!Po(p)||qR(e,o,i,u,p,g))&+(!cc(p)||ek(e,o,i,u,p,g))&+(!mc(p)||nk(e,o,i,u,p,g))&+(!za(p)||ik(e,o,i,u,p,g))&+(!qs(p)||MA(e,o,i,u,p,g))&+(!Fs(p)||FA(e,o,i,u,p,g))&+(!Ja(p)||BA(e,o,i,u,p,g))&+(!la(p)||bA(e,o,i,u,p,g))&+(!Ic(p)||cA(e,o,i,u,p,g))))&+(!Ge(g)||!!(+(!Wa(p)||LR(e,o,i,u,p,g))&+(!Rs(p)||XR(e,o,i,u,p,g))&+(!Ns(p)||Yk(e,o,i,u,p,g))&+(!yc(p)||tA(e,o,i,u,p,g))&+(!Va(p)||sA(e,o,i,u,p,g))&+(!Ds(p)||lA(e,o,i,u,p,g))&+(!xi(p)||gA(e,o,i,u,p,g))&+(!ts(p)||LA(e,o,i,u,p,g))&+(!Ei(p)||p0(e,o,i,u,p,g))))&+(!gt(g)||!!(+(!xc(p)||aA(e,o,i,u,p,g))&+(!pa(p)||xA(e,o,i,u,p,g))&+(!ma(p)||Wk(e,o,i,u,p,g))&+(!da(p)||CA(e,o,i,u,p,g))))&+(!(Ot(g)||Nr(g))||!!(+(!dc(p)||dk(e,o,i,u,p,g))&+(!Zo(p)||hk(e,o,i,u,p,g))&+(!gc(p)||nA(e,o,i,u,p,g))&+(!es(p)||fA(e,o,i,u,p,g))&+(!bc(p)||SA(e,o,i,u,p,g))))&+(!Rc(p)||VA(e,o,i,u,p,g))&+(!Tc(p)||HA(e,o,i,u,p,g))&+(!pc(p)||ck(e,o,i,u,p,g))&+(!yp(p)||VR(e,o,i,u,p,g))&+(!xp(p)||pk(e,o,i,u,p,g))&+(!fc(p)||Jk(e,o,i,u,p,g))&+(!Ec(p)||TA(e,o,i,u,p,g))&+(!ic(p)||UR(e,o,i,u,p,g))&+(!uc(p)||KR(e,o,i,u,p,g))&+(!Sc(p)||AA(e,o,i,u,p,g))&+(!Ri(p)||(!Ge(g)||s0(e,o,i,u,p,g)))&+(!ki(p)||(!at(g)||u0(e,o,i,u,p,g))))&&(!sc(p)||MR(e,o,i,u,p,g));return e.Pop(p),y}var l0=[0],Vp=new Map,Mc=new Map;function T1(){return`${l0[0]++}`}function R1(e,o){if(!Vp.has(e))Vp.set(e,new Map);let i=Vp.get(e);if(i.has(o))return i.get(o);let u=T1();return i.set(o,u),u}function k1(e,o,i,u){return e.UseUnevaluated()?Ir(`check_${i}`,["context",u]):Ir(`check_${i}`,[u])}function A1(e,o,i,u){let p=Lt(e,o,i,"value");return o.UseUnevaluated()?vs(`check_${u}`,Vs(["context","value"],p)):vs(`check_${u}`,Vs(["value"],p))}function d0(){l0[0]=0,Vp.clear(),Mc.clear()}function f0(){return[...Mc.values()]}function js(e,o,i,u){let p=R1(i,e.LexicalBaseURL()),g=k1(o,i,p,u);if(Mc.has(p))return g;return Mc.set(p,""),Mc.set(p,A1(e,o,i,p)),g}function P1(e,o){return at(o)&&!wu(e)?o[e]:void 0}function C1(e,o){return e.reduce((i,u)=>P1(u,i),o)}function $1(e){if(L(e.length,0))return[];let o=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function v1(e,o){let i=$1(o);return C1(i,e)}var Qp="https://json-schema.org";function g0(e,o){if(at(e)&&Ls(e)&&L(e.$dynamicAnchor,o))return e;if(at(e))for(let i of we(e)){let u=g0(e[i],o);if(u)return u}return}function ch(e,o,i){if(L(e,i))return o.href;let u=gn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(Ge(e))for(let p of e){let g=ch(p,u,i);if(!Ut(g))return g}else if(at(e))for(let p of we(e)){let g=ch(e[p],u,i);if(!Ut(g))return g}return}function M1(e,o,i){if(L(e.$id,i.hash))return e;let u=new URL(i.href,o.href);if(L(o.pathname,u.pathname))return i.hash.startsWith("#")?y0(e,i):e;return}function O1(e,o,i){let u=new URL(`#${e.$anchor}`,o.href),p=new URL(i.href,o.href);return L(u.href,p.href)?e:void 0}function _1(e,o,i){let u=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(i.href,o.href);return L(u.href,p.href)?e:void 0}function y0(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let i=decodeURIComponent(o.hash.slice(1));if(!i.startsWith("/"))return;return v1(e,i)}function L1(e,o,i){if(Eo(e)){let u=M1(e,o,i);if(!Ut(u))return u}if(ac(e)){let u=O1(e,o,i);if(!Ut(u))return u}if(Ls(e)){let u=_1(e,o,i);if(!Ut(u))return u}return y0(e,i)}function N1(e,o,i){return e.reduce((u,p)=>{let g=Xp(p,o,i);return!Ut(g)?g:u},void 0)}function D1(e){return L(e,"const")||L(e,"enum")}function q1(e,o,i){return we(e).reduce((u,p)=>{if(D1(p))return u;let g=Xp(e[p],o,i);return!Ut(g)?g:u},void 0)}function Xp(e,o,i){let u=gn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(gn(e)){let p=L1(e,u,i);if(!Ut(p))return p}if(Ge(e))return N1(e,u,i);if(at(e))return q1(e,u,i);return}function F1(e,o,i){return ch(e,new URL(o||".",Qp),i)}function j1(e,o,i,u){let p=Yp(e,o,i,u,!1);return gn(p)&&Eo(p)?p:void 0}function h0(e){return e.href.split("#")[0]}function U1(e,o){return fe(e,o)?e[o]:void 0}function B1(e,o,i){return Xp(e,o,i)}function G1(e,o,i){let u=h0(i);if(L(u,h0(o)))return;if(!fe(e,u))return;let p=e[u],g=gn(p)&&Eo(p)?new URL(p.$id,u):new URL(u);return L(i.hash,"")?p:Xp(p,g,i)}function K1(e,o,i,u,p){if(!u.$ref.startsWith("#"))return;if(fe(e,"$schema"))return;let g=F1(o,i,p);if(Ut(g)||L(g,i))return;return{target:p,base:g,root:o}}function H1(e,o,i){let u=e[o];if(!gn(u))return;return{target:i,base:o,root:u}}function W1(e,o,i,u,p){let g=p?H1(e.context,u,i):void 0;if(!Ut(g))return g;return K1(e.root,e.lexicalSchema,e.referenceBase,o,i)}function z1(e,o,i,u,p,g){if(Eo(p))return;let y=j1(e,o,i,u);if(!y||g.includes(y))return;return{target:p,resource:y}}function Yp(e,o,i,u,p=!0){let g=new URL(i||".",Qp),y=p&&Eo(o)?new URL(o.$id,g):g,b=new URL(u,y.href);return U1(e,u)??B1(o,y,b)??G1(e,y,b)}function V1(e,o,i,u,p,g){let y=new URL(i||".",Qp),b=p.$dynamicRef.startsWith("#")?u:o,E=Yp(e,b,i,p.$dynamicRef,!1);if(Ut(E)){let R=new URL(p.$dynamicRef,y).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let A=decodeURIComponent(R.slice(1));return g.find((C)=>L(C.$dynamicAnchor,A))??g0(o,A)}return}if(!gn(E)||!Ls(E))return E;if(new URL(p.$dynamicRef,y).hash.startsWith("#/"))return E;return g.find((R)=>L(R.$dynamicAnchor,E.$dynamicAnchor))??E}function J1(e,o){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:i,p=Yp(e.context,u,e.referenceBase,o.$ref,!1);if(!p||!gn(p))return{schema:p};let g=new URL(o.$ref,e.referenceBase).href.split("#")[0],y=!L(g,e.resourceBase),b=W1(e,o,p,g,y),E=y?z1(e.context,e.root,e.referenceBase,g,p,e.ids):void 0;return{schema:p,retrievedResource:b,resolvedResource:E}}function Q1(e,o){let i=wc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Yp(e.context,i,e.lexicalBase,o.$recursiveRef,!1)}function X1(e,o){return V1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var _r=function(e,o,i,u){if(i==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?u:i==="a"?u.call(e):u?u.value:o.get(e)},Sr,el,w0,dh,Zp,x0,I0,b0,E0,ph,lh,fh,hh,S0,T0;class $i{constructor(e,o){Sr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return _r(this,Sr,"m",dh).call(this,this.ids)}Push(e){if(!gn(e))return;if(Eo(e))_r(this,Sr,"m",fh).call(this,e);if(ac(e))this.anchors.push(e);if(wc(e))this.recursiveAnchors.push(e);if(Ls(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!gn(e))return;if(Eo(e))_r(this,Sr,"m",hh).call(this,e);if(ac(e))this.anchors.pop();if(wc(e))this.recursiveAnchors.pop();if(Ls(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();_r(this,Sr,"m",T0).call(this,e)}Ref(e){let o=J1(_r(this,Sr,"m",el).call(this),e);return _r(this,Sr,"m",w0).call(this,o),o.schema}RecursiveRef(e){let o=Q1(_r(this,Sr,"m",el).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=X1(_r(this,Sr,"m",el).call(this),e);if(o)this.pendingResource=!0;return o}}Sr=new WeakSet,el=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",Zp).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},w0=function(o){if(!Ut(o.schema))this.pendingResource=!0;if(!Ut(o.resolvedResource))_r(this,Sr,"m",S0).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!Ut(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},dh=function(o){let i=this.retrievedFrames[this.retrievedFrames.length-1],u=i?new URL(i.base):new URL(Qp);return(i?o.slice(i.idDepth):o).reduce((g,y)=>new URL(y.$id,g),u).href},Zp=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return _r(this,Sr,"m",dh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((i,u)=>new URL(u.$id,i),new URL(o.base)).href},x0=function(){if(this.retrievedFrames.length>0)return _r(this,Sr,"m",Zp).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return _r(this,Sr,"m",Zp).call(this)},I0=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(o)return this.ids.length>o.idDepth?this.ids[this.ids.length-1]:o.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},b0=function(o){o.forEach((i)=>_r(this,Sr,"m",ph).call(this,i,!1))},E0=function(o){o.forEach((i)=>_r(this,Sr,"m",lh).call(this,i,!1))},ph=function e(o,i=!0){if(_s(o))return;if(Ge(o))return _r(this,Sr,"m",b0).call(this,o);if(!gn(o))return;let u=o;if(!i&&Eo(u))return;if(!i&&Ls(u))this.dynamicAnchors.push(u);for(let p of we(u))_r(this,Sr,"m",e).call(this,u[p],!1)},lh=function e(o,i=!0){if(_s(o))return;if(Ge(o))return _r(this,Sr,"m",E0).call(this,o);if(!gn(o))return;let u=o;if(!i&&Eo(u))return;if(!i&&Ls(u))this.dynamicAnchors.pop();for(let p of we(u))_r(this,Sr,"m",e).call(this,u[p],!1)},fh=function(o){this.ids.push(o);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(o);_r(this,Sr,"m",ph).call(this,o,!0)},hh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&L(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();_r(this,Sr,"m",lh).call(this,o,!0)},S0=function(o,i){_r(this,Sr,"m",fh).call(this,i),this.resolvedResources.set(o,i)},T0=function(o){if(!this.resolvedResources.has(o))return;let i=this.resolvedResources.get(o);_r(this,Sr,"m",hh).call(this,i),this.resolvedResources.delete(o)};function Y1(e){let o=e.Functions().join(`;
31
+ `),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${i.join("; ")} }`}function Z1(e,o){return Hy("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(_n,K,eu,Yi,e.External().variables)}function ej(e){let o=new $i(e.Context(),e.Schema()),i=new _n;return(u)=>kt(o,i,e.Schema(),u)}function tj(e,o){return Ky()?Z1(e,o):ej(e)}class R0{constructor(e,o,i){this.isAccelerated=e,this.code=o,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class k0{constructor(e,o,i,u,p,g){this.context=e,this.schema=o,this.external=i,this.functions=u,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=Y1(this),o=tj(this,e);return new R0(Ky(),e,o)}}function tl(...e){let[o,i]=wn(e,{2:(E,S)=>[E,S],1:(E)=>[{},E]});PR(),d0();let u=new $i(o,i),p=new vf(AR(o,i)),g=js(u,p,i,"value"),y=f0(),b=CR();return new k0(o,i,b,y,g,p.UseUnevaluated())}function rl(...e){let[o,i,u]=wn(e,{3:(w,R,A)=>[w,R,A],2:(w,R)=>[{},w,R]}),p=new $i(o,i),g=new qn,y=mr(p,g,"#","",i,u),b=g.GetErrors(),E=ex(),S=b.map((w)=>({...w,message:E(w)}));return[y,S]}function yh(...e){let[o,i,u]=wn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),p=new $i(o,i),g=new _n;return kt(p,g,i,u)}function Xt(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return yh(o,i,u)}function ks(...e){let[o,i,u]=wn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),[p,g]=rl(o,i,u);return g}class fa extends Error{constructor(e,o,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:o},writable:!1,configurable:!1,enumerable:!1})}}function A0(e,o,i){if(!Ge(i))return i;return i.map((u)=>yn(e,o.items,u))}function P0(e,o,i){return yn({...e,...o.$defs},un(o.$ref),i)}function oj(e,o){let i=fe(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Ao(e,o),p=Rn(u);return Qe(p)?lp(p,i):p}function C0(e,o,i){let u=oj(e,o);return yn(e,u,i)}function nl(e){return fe(e,"additionalProperties")?e.additionalProperties:void 0}function $0(e,o,i){if(!at(i)||Ge(i))return i;let u=nl(o);for(let p of we(i)){if(fe(o.properties,p)){i[p]=yn(e,o.properties[p],i[p]);continue}if(pn(u)&&L(u,!0)||Cr(u)&&Xt(e,u,i[p])){i[p]=yn(e,u,i[p]);continue}delete i[p]}return i}function v0(e,o,i){if(!at(i))return i;let u=nl(o),[p,g]=[new RegExp(hn(o)),fr(o)];for(let y of we(i)){if(p.test(y)){i[y]=yn(e,g,i[y]);continue}if(pn(u)&&L(u,!0)||Cr(u)&&Xt(e,u,i[y])){i[y]=yn(e,u,i[y]);continue}delete i[y]}return i}function M0(e,o,i){return fe(e,o.$ref)?yn(e,e[o.$ref],i):i}function O0(e,o,i){if(!Ge(i))return i;let u=Math.min(i.length,o.items.length);for(let p=0;p<u;p++)i[p]=yn(e,o.items[p],i[p]);return Ki(i.length,u)?i.slice(0,u):i}function Vr(e){return Ra(e)}function _0(e,o,i){for(let u of o.anyOf){let p=yn(e,u,Vr(i));if(Xt(e,u,p))return p}return i}function yn(e,o,i){return wt(o)?A0(e,o,i):Qt(o)?P0(e,o,i):ze(o)?C0(e,o,i):Qe(o)?$0(e,o,i):Gt(o)?v0(e,o,i):qt(o)?M0(e,o,i):mt(o)?O0(e,o,i):xe(o)?_0(e,o,i):i}function sj(e,o){for(let i of we(e)){if(fe(o,i))continue;o[i]=e[i]}return o}function ij(e){let o={};for(let i of we(e))o[i]=Oc(e[i]);return o}function aj(e){return xh(uR(e))}function xh(e){return e.map((o)=>Oc(o))}function Oc(e){let o=wt(e)?B(Oc(e.items),ka(e)):ze(e)?Cn(xh(e.allOf)):xe(e)?m(aj(e.anyOf)):Qe(e)?l(ij(e.properties)):Gt(e)?bs(ri(e),Oc(fr(e))):mt(e)?Ur(xh(e.items)):e;return sj(e,o)}function tu(e){return Oc(e)}function vo(...e){let[o,i,u]=wn(e,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]}),p=Vo().unionPrioritySort?tu(i):i;return yn(o,p,u)}function fo(e){return at(e)&&fe(e,"value")}function We(e){return{value:e}}function wr(){return}function uj(e){return Ge(e)?We(e):We([e])}function cj(e){return L(e,!0)?We(BigInt(1)):We(BigInt(0))}var mj=/^-?(0|[1-9]\d*)n$/,pj=/^-?(0|[1-9]\d*)\.\d+$/,lj=/^-?(0|[1-9]\d*)$/;function dj(e){return mj.test(e)}function fj(e){return pj.test(e)}function hj(e){return lj.test(e)}function gj(e){let o=e.toLowerCase();return dj(e)?We(BigInt(e.slice(0,e.length-1))):fj(e)?We(BigInt(e.split(".")[0])):hj(e)?We(BigInt(e)):L(o,"false")?We(BigInt(0)):L(o,"true")?We(BigInt(1)):wr()}function ol(e){return Nr(e)?We(e):pn(e)?cj(e):Ot(e)?We(BigInt(Math.trunc(e))):ho(e)?We(BigInt(0)):gt(e)?gj(e):Ut(e)?We(BigInt(0)):wr()}function yj(e){return L(e,BigInt(0))?We(!1):L(e,BigInt(1))?We(!0):wr()}function xj(e){return L(e,0)?We(!1):L(e,1)?We(!0):wr()}function Ij(e){return L(e.toLowerCase(),"false")?We(!1):L(e.toLowerCase(),"true")?We(!0):L(e,"0")?We(!1):L(e,"1")?We(!0):wr()}function L0(e){return Nr(e)?yj(e):pn(e)?We(e):Ot(e)?xj(e):ho(e)?We(!1):gt(e)?Ij(e):Ut(e)?We(!1):wr()}function bj(e){return L(e,BigInt(0))?We(null):wr()}function Ej(e){return L(e,!1)?We(null):wr()}function Sj(e){return L(e,0)?We(null):wr()}function wj(e){let o=e.toLowerCase();return L(o,"undefined")||L(o,"null")||L(e,"")||L(e,"0")?We(null):wr()}function Tj(e){return Nr(e)?bj(e):pn(e)?Ej(e):Ot(e)?Sj(e):ho(e)?We(null):gt(e)?wj(e):Ut(e)?We(null):wr()}var N0=BigInt(Number.MAX_SAFE_INTEGER),D0=BigInt(Number.MIN_SAFE_INTEGER);function Rj(e){return e<=N0&&e>=D0?We(Number(e)):wr()}function kj(e){return We(e?1:0)}function Aj(e){let o=+e;if(Ot(o))return We(o);let i=e.toLowerCase();if(L(i,"false"))return We(0);if(L(i,"true"))return We(1);let u=ol(e);if(fo(u))return u.value<=N0&&u.value>=D0?We(Number(u.value)):wr();return wr()}function Ih(e){return Nr(e)?Rj(e):pn(e)?kj(e):Ot(e)?We(e):ho(e)?We(0):gt(e)?Aj(e):Ut(e)?We(0):wr()}function q0(e){return Nr(e)?We(e.toString()):pn(e)?We(e.toString()):Ot(e)?We(e.toString()):ho(e)?We("null"):gt(e)?We(e):Ut(e)?We(""):wr()}function Pj(e){return L(e,BigInt(0))?We(void 0):wr()}function Cj(e){return L(e,!1)?We(void 0):wr()}function $j(e){return L(e,0)?We(void 0):wr()}function vj(e){let o=e.toLowerCase();return L(o,"undefined")||L(o,"null")||L(e,"")||L(e,"0")?We(void 0):wr()}function F0(e){return Nr(e)?Pj(e):pn(e)?Cj(e):Ot(e)?$j(e):ho(e)?We(void 0):gt(e)?vj(e):Ut(e)?We(e):wr()}function j0(e,o,i){return uj(i).value.map((p)=>Yr(e,o.items,p))}function U0(e,o,i){let u=ol(i);return fo(u)?u.value:i}function B0(e,o,i){let u=L0(i);return fo(u)?u.value:i}function G0(e,o,i){return Yr({...e,...o.$defs},un(o.$ref),i)}function K0(e,o,i){return Yr(e,Rn(o),i)}function H0(e,o,i){let u=Ih(i);return fo(u)?Math.trunc(u.value):i}function W0(e,o,i){let u=Ao(e,o),p=Rn(u);return Yr(e,p,i)}function Mj(e,o,i){let u=ol(i);return fo(u)&&L(o.const,u.value)?u.value:i}function Oj(e,o,i){let u=L0(i);return fo(u)&&L(o.const,u.value)?u.value:i}function _j(e,o,i){let u=Ih(i);return fo(u)&&L(o.const,u.value)?u.value:i}function Lj(e,o,i){let u=q0(i);return fo(u)&&L(o.const,u.value)?u.value:i}function z0(e,o,i){if(L(o.const,i))return i;return mx(o)?Mj(e,o,i):px(o)?Oj(e,o,i):gm(o)?_j(e,o,i):ym(o)?Lj(e,o,i):jr()}function V0(e,o,i){let u=Tj(i);return fo(u)?u.value:i}function J0(e,o,i){let u=Ih(i);return fo(u)?u.value:i}function sl(e,o,i,u){let p=we(u);for(let[g,y]of o)for(let b of p)if(!g.test(b))u[b]=Yr(e,i,u[b]);return u}function _c(e,o,i){return cn(e)&&Ut(i[o])}function Nj(e,o,i){let u=md(o.properties),p=we(i);for(let[g,y]of u)for(let b of p){if(!g.test(b)||_c(y,b,i))continue;i[b]=Yr(e,y,i[b])}return fe(o,"additionalProperties")&&at(o.additionalProperties)?sl(e,u,o.additionalProperties,i):i}function Q0(e,o,i){return zo(i)?Nj(e,o,i):i}function Dj(e,o,i){let u=md(o.patternProperties),p=we(i);for(let[g,y]of u)for(let b of p)if(g.test(b))i[b]=Yr(e,y,i[b]);return fe(o,"additionalProperties")&&at(o.additionalProperties)?sl(e,u,o.additionalProperties,i):i}function X0(e,o,i){return zo(i)?Dj(e,o,i):i}function Y0(e,o,i){return fe(e,o.$ref)?Yr(e,e[o.$ref],i):i}function Z0(e,o,i){let u=q0(i);return fo(u)?u.value:i}function eP(e,o,i){return Yr(e,Rn(o),i)}function tP(e,o,i){if(!Ge(i))return i;for(let u=0;u<Math.min(o.items.length,i.length);u++)i[u]=Yr(e,o.items[u],i[u]);return i}function rP(e,o,i){let u=F0(i);return fo(u)?u.value:i}function nP(e,o,i){if(o.anyOf.some((y)=>Xt(e,y,i)))return i;let g=o.anyOf.map((y)=>Yr(e,y,Vr(i))).find((y)=>Xt(e,o,y));return Ut(g)?i:g}function oP(e,o,i){let u=F0(i);return fo(u)?void 0:i}function Yr(e,o,i){return wt(o)?j0(e,o,i):mo(o)?U0(e,o,i):Wn(o)?B0(e,o,i):Qt(o)?G0(e,o,i):on(o)?K0(e,o,i):fn(o)?H0(e,o,i):ze(o)?W0(e,o,i):yt(o)?z0(e,o,i):xs(o)?V0(e,o,i):kr(o)?J0(e,o,i):Qe(o)?Q0(e,o,i):Gt(o)?X0(e,o,i):qt(o)?Y0(e,o,i):sn(o)?Z0(e,o,i):ur(o)?eP(e,o,i):mt(o)?tP(e,o,i):Yo(o)?rP(e,o,i):xe(o)?nP(e,o,i):po(o)?oP(e,o,i):i}function is(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Yr(o,i,u)}function sP(e,o,i){if(!Ge(i))return i;for(let u=0;u<i.length;u++)i[u]=xn(e,o.items,i[u]);return i}function iP(e,o,i){return xn({...e,...o.$defs},un(o.$ref),i)}function aP(e,o){if(!Ut(o))return o;return ms(e.default)?e.default():Vr(e.default)}function uP(e,o,i){let u=Ao(e,o),p=Rn(u);return xn(e,p,i)}function cP(e,o,i){if(!at(i))return i;let u=we(o.properties);for(let p of u){let g=xn(e,o.properties[p],i[p]);if(Ut(g)&&(cn(o.properties[p])||!fe(o.properties[p],"default")))continue;i[p]=g}if(!Po(o)||pn(o.additionalProperties))return i;for(let p of we(i)){if(u.includes(p))continue;i[p]=xn(e,o.additionalProperties,i[p])}return i}function mP(e,o,i){if(!at(i))return i;let[u,p]=[new RegExp(hn(o)),fr(o)];for(let g of we(i)){if(!(u.test(g)&&bo(p)))continue;i[g]=xn(e,p,i[g])}if(!Po(o))return i;for(let g of we(i)){if(u.test(g))continue;i[g]=xn(e,o.additionalProperties,i[g])}return i}function pP(e,o,i){return fe(e,o.$ref)?xn(e,e[o.$ref],i):i}function lP(e,o,i){if(!Ge(i))return i;let[u,p]=[o.items,Math.max(o.items.length,i.length)];for(let g=0;g<p;g++)if(g<u.length)i[g]=xn(e,u[g],i[g]);return i}function dP(e,o,i){for(let u of o.anyOf){let p=xn(e,u,Vr(i));if(Xt(e,u,p))return p}return i}function xn(e,o,i){let u=bo(o)?aP(o,i):i;return wt(o)?sP(e,o,u):Qt(o)?iP(e,o,u):ze(o)?uP(e,o,u):Qe(o)?cP(e,o,u):Gt(o)?mP(e,o,u):qt(o)?pP(e,o,u):mt(o)?lP(e,o,u):xe(o)?dP(e,o,u):u}function Us(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return xn(o,i,u)}function ru(e){return(...o)=>{let[i,u,p]=wn(o,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]});return e.reduce((g,y)=>y(i,u,g),p)}}function qj(e,o,i){return o["~codec"].decode(i)}function Fj(e,o,i){return o["~codec"].encode(i)}function Tr(e,o,i,u){if(!Hn(i))return u;return L(e,"Decode")?qj(o,i,u):Fj(o,i,u)}function jj(e,o,i,u){if(!Ge(u))return u;for(let p=0;p<u.length;p++)u[p]=Pr(e,o,i.items,u[p]);return Tr(e,o,i,u)}function Uj(e,o,i,u){let p=Tr(e,o,i,u);if(!Ge(p))return p;for(let g=0;g<p.length;g++)p[g]=Pr(e,o,i.items,p[g]);return p}function fP(e,o,i,u){return L(e,"Decode")?jj(e,o,i,u):Uj(e,o,i,u)}function hP(e,o,i,u){return u=Pr(e,{...o,...i.$defs},un(i.$ref),u),Tr(e,o,i,u)}function gP(e){return e.reduce((o,i)=>({...o,...i}),{})}function yP(e,o){for(let i of o)if(!Ta(e,i))return i;return e}function Bj(e,o,i,u){if(L(i.allOf.length,0))return Tr(e,o,i,u);let p=i.allOf.map((b)=>Pr(e,o,b,vo(b,Vr(u)))),y=p.every((b)=>at(b))?gP(p):yP(u,p);return Tr(e,o,i,y)}function Gj(e,o,i,u){if(L(i.allOf.length,0))return Tr(e,o,i,u);let p=Tr(e,o,i,u),g=i.allOf.map((b)=>Pr(e,o,b,vo(b,Vr(p))));if(g.every((b)=>at(b)))return gP(g);return yP(p,g)}function xP(e,o,i,u){return L(e,"Decode")?Bj(e,o,i,u):Gj(e,o,i,u)}function Kj(e,o,i,u){if(!zo(u))return u;for(let p of we(i.properties)){if(!fe(u,p)||_c(i.properties[p],p,u))continue;u[p]=Pr(e,o,i.properties[p],u[p])}return Tr(e,o,i,u)}function Hj(e,o,i,u){let p=Tr(e,o,i,u);if(!zo(p))return p;for(let g of we(i.properties)){if(!fe(p,g)||_c(i.properties[g],g,p))continue;p[g]=Pr(e,o,i.properties[g],p[g])}return p}function IP(e,o,i,u){return L(e,"Decode")?Kj(e,o,i,u):Hj(e,o,i,u)}function Wj(e,o,i,u){if(!zo(u))return u;let p=new RegExp(hn(i));for(let g of we(u)){if(!p.test(g))continue;u[g]=Pr(e,o,fr(i),u[g])}return Tr(e,o,i,u)}function zj(e,o,i,u){let p=Tr(e,o,i,u);if(!zo(p))return p;let g=new RegExp(hn(i));for(let y of we(p)){if(!g.test(y))continue;p[y]=Pr(e,o,fr(i),p[y])}return p}function bP(e,o,i,u){return L(e,"Decode")?Wj(e,o,i,u):zj(e,o,i,u)}function EP(e,o,i,u){return fe(o,i.$ref)?Pr(e,o,o[i.$ref],u):u}function SP(e,o,i,u){return L(e,"Decode")?Tr(e,o,i,EP(e,o,i,u)):EP(e,o,i,Tr(e,o,i,u))}function Vj(e,o,i,u){if(!Ge(u))return u;for(let p=0;p<Math.min(i.items.length,u.length);p++)u[p]=Pr(e,o,i.items[p],u[p]);return Tr(e,o,i,u)}function Jj(e,o,i,u){let p=Tr(e,o,i,u);if(!Ge(p))return u;for(let g=0;g<Math.min(i.items.length,p.length);g++)p[g]=Pr(e,o,i.items[g],p[g]);return p}function wP(e,o,i,u){return L(e,"Decode")?Vj(e,o,i,u):Jj(e,o,i,u)}function Qj(e,o,i,u){for(let p of i.anyOf){if(!Xt(o,p,u))continue;let g=Pr(e,o,p,u);return Tr(e,o,i,g)}return u}function Xj(e,o,i,u){let p=Tr(e,o,i,u);for(let g of i.anyOf){let y=Pr(e,o,g,Vr(p));if(!Xt(o,g,y))continue;return y}return p}function TP(e,o,i,u){return L(e,"Decode")?Qj(e,o,i,u):Xj(e,o,i,u)}function Pr(e,o,i,u){return wt(i)?fP(e,o,i,u):Qt(i)?hP(e,o,i,u):ze(i)?xP(e,o,i,u):Qe(i)?IP(e,o,i,u):Gt(i)?bP(e,o,i,u):qt(i)?SP(e,o,i,u):mt(i)?wP(e,o,i,u):xe(i)?TP(e,o,i,u):Tr(e,o,i,u)}class RP extends fa{constructor(e,o){super("Decode",e,o)}}function Yj(e,o,i){if(!Xt(e,o,i))throw new RP(i,ks(e,o,i));return i}function Zj(e,o,i){let u=Vo().unionPrioritySort?tu(o):o;return Pr("Decode",e,u,i)}var eU=ru([(e,o,i)=>Vr(i),(e,o,i)=>Us(e,o,i),(e,o,i)=>is(e,o,i),(e,o,i)=>vo(e,o,i),(e,o,i)=>Yj(e,o,i),(e,o,i)=>Zj(e,o,i)]);function bh(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return eU(o,i,u)}class kP extends fa{constructor(e,o){super("Encode",e,o)}}function tU(e,o,i){if(!Xt(e,o,i))throw new kP(i,ks(e,o,i));return i}function rU(e,o,i){let u=Vo().unionPrioritySort?tu(o):o;return Pr("Encode",e,u,i)}var nU=ru([(e,o,i)=>Vr(i),(e,o,i)=>rU(e,o,i),(e,o,i)=>Us(e,o,i),(e,o,i)=>is(e,o,i),(e,o,i)=>vo(e,o,i),(e,o,i)=>tU(e,o,i)]);function Eh(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return nU(o,i,u)}function oU(e,o){return Hn(o)||Oi(e,o.items)}function sU(e,o){return Hn(o)||AP({...e,...o.$defs},un(o.$ref))}function iU(e,o){return Hn(o)||o.allOf.some((i)=>Oi(e,i))}function aU(e,o){return Hn(o)||we(o.properties).some((i)=>Oi(e,o.properties[i]))}function uU(e,o){return Hn(o)||Oi(e,fr(o))}function AP(e,o){if(Sh.has(o.$ref))return!1;return Sh.add(o.$ref),Hn(o)||fe(e,o.$ref)&&Oi(e,e[o.$ref])}function cU(e,o){return Hn(o)||o.items.some((i)=>Oi(e,i))}function mU(e,o){return Hn(o)||o.anyOf.some((i)=>Oi(e,i))}function Oi(e,o){return wt(o)?oU(e,o):Qt(o)?sU(e,o):ze(o)?iU(e,o):Qe(o)?aU(e,o):Gt(o)?uU(e,o):qt(o)?AP(e,o):mt(o)?cU(e,o):xe(o)?mU(e,o):Hn(o)}var Sh=new Set;function wh(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Sh.clear(),Oi(o,i)}class as extends Error{constructor(e,o){super(o);this.type=e}}function PP(e,o){return ms(o.default)?o.default(o):at(o.default)?Vr(o.default):o.default}function CP(e,o){if(Ei(o)&&!bo(o))throw new as(o,"Arrays with uniqueItems constraints must specify a default annotation");let i=xi(o)?o.minItems:0;return Array.from({length:i},()=>Zr(e,o.items))}function $P(e,o){return Zo(o)?BigInt(o.exclusiveMinimum)+BigInt(1):es(o)?BigInt(o.minimum):BigInt(0)}function vP(e,o){return!1}function MP(e,o){let i=Zr(e,o.instanceType);return class{constructor(){Object.assign(this,i)}}}function OP(e,o){return Zr({...e,...o.$defs},un(o.$ref))}function _P(e,o){return Zr(e,Rn(o))}function LP(e,o){let i=Zr(e,o.returnType);return()=>i}function NP(e,o){return Zo(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:es(o)?o.minimum:0}function DP(e,o){let i=Ao(e,o),u=Rn(i);return Zr(e,u)}function qP(e,o){return o.const}function FP(e,o){throw new as(o,"Cannot create TNever types")}function jP(e,o){return null}function UP(e,o){return Zo(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:es(o)?o.minimum:0}function BP(e,o){return(Ut(o.required)?[]:o.required).reduce((u,p)=>({...u,[p]:Zr(e,o.properties[p])}),{})}function GP(e,o){if(la(o)&&!bo(o))throw new as(o,"Record with the minProperties constraint must have a default annotation");return{}}function KP(e,o){return fe(e,o.$ref)?Zr(e,e[o.$ref]):(()=>{throw new as(o,"Unable to deref Ref")})()}function HP(e,o){if((da(o)||ma(o))&&!bo(o))throw Error("Strings with format or pattern constraints must specify default");let u=pa(o)?o.minLength:0;return"".padEnd(u)}function WP(e,o){return Symbol()}function zP(e,o){let i=Mu(o.pattern);if(sn(i))throw new as(o,"Unable to create TemplateLiteral due to infinite type expansion");return Zr(e,i)}function VP(e,o){return Array.from({length:o.minItems},(i,u)=>Zr(e,o.items[u]))}function JP(e,o){return}function QP(e,o){if(L(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Zr(e,o.anyOf[0])}function XP(e,o){return}function Zr(e,o){return bo(o)?PP(e,o):wt(o)?CP(e,o):mo(o)?$P(e,o):Wn(o)?vP(e,o):en(o)?MP(e,o):Qt(o)?OP(e,o):on(o)?_P(e,o):tn(o)?LP(e,o):fn(o)?NP(e,o):ze(o)?DP(e,o):yt(o)?qP(e,o):co(o)?FP(e,o):xs(o)?jP(e,o):kr(o)?UP(e,o):Qe(o)?BP(e,o):Gt(o)?GP(e,o):qt(o)?KP(e,o):sn(o)?HP(e,o):Is(o)?WP(e,o):ur(o)?zP(e,o):mt(o)?VP(e,o):Yo(o)?JP(e,o):xe(o)?QP(e,o):po(o)?XP(e,o):void 0}function As(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Zr(o,i)}class il extends fa{constructor(e,o){super("Parse",e,o)}}function pU(e,o,i){if(!Xt(e,o,i))throw new il(i,ks(e,o,i));return i}var YP=ru([(e,o,i)=>Vr(i),(e,o,i)=>Us(e,o,i),(e,o,i)=>is(e,o,i),(e,o,i)=>vo(e,o,i),(e,o,i)=>pU(e,o,i)]);var dU=l({type:s("insert"),path:a(),value:Rr()}),fU=Object({type:s("update"),path:a(),value:Rr()}),hU=l({type:s("delete"),path:a()}),vOe=m([dU,fU,hU]);class al{constructor(e,o){this.hasCodec=wh(e,o),this.buildResult=tl(e,o),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(Vo().correctiveParse)return YP(this.Context(),this.Type(),e);throw new il(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return ks(this.Context(),this.Type(),e)}Clean(e){return vo(this.Context(),this.Type(),e)}Convert(e){return is(this.Context(),this.Type(),e)}Create(){return As(this.Context(),this.Type())}Default(e){return Us(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?bh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Eh(this.Context(),this.Type(),e):this.Parse(e)}}function Rh(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return new al(o,i)}var eC=new WeakMap,xU=Symbol.for("TypeBox.Kind");function IU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function bU(e,o){switch(o){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function kh(e){try{return rC(e)}catch{return}}function EU(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isFinite(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isInteger(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function SU(e,o){let i=o.properties,u=new Set(i?Object.keys(i):[]);if(i)for(let[p,g]of Object.entries(i)){if(!(p in e))continue;e[p]=ga(e[p],g)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[p,g]of Object.entries(e)){if(u.has(p))continue;e[p]=ga(g,o.additionalProperties)}}function wU(e,o){if(Array.isArray(o.items)){for(let i=0;i<e.length;i++){let u=o.items[i];if(!u)continue;e[i]=ga(e[i],u)}return}if(o.items&&typeof o.items==="object")for(let i=0;i<e.length;i++)e[i]=ga(e[i],o.items)}function tC(e,o){for(let i of o)if(kh(i)?.Check(e))return e;for(let i of o){let u=structuredClone(e),p=ga(u,i);if(kh(i)?.Check(p))return p}return e}function ga(e,o){let i=e;if(Array.isArray(o.allOf))for(let g of o.allOf)i=ga(i,g);if(Array.isArray(o.anyOf))i=tC(i,o.anyOf);if(Array.isArray(o.oneOf))i=tC(i,o.oneOf);let u=IU(o),p=u.length>1&&u.some((g)=>bU(i,g));if(u.length>0&&!p)for(let g of u){let y=EU(i,g);if(y!==i){i=y;break}}if(u.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))SU(i,o);if(u.includes("array")&&Array.isArray(i))wU(i,o);return i}function ul(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let p=0;p<e.length;p++){let g=o.items[p];if(g)ul(e[p],g)}else if(o.items)for(let p of e)ul(p,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let i=e,u=new Set(o.required??[]);for(let[p,g]of Object.entries(o.properties)){if(!(p in i))continue;if(i[p]===null&&!u.has(p)&&typeof g.$ref!=="string"&&kh(g)?.Check(null)===!1)delete i[p];else ul(i[p],g)}}function rC(e){let o=e,i=eC.get(o);if(i)return i;let u=Rh(e);return eC.set(o,u),u}function TU(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function RU(e,o){let i=e.find((u)=>u.name===o.name);if(!i)throw Error(`Tool "${o.name}" not found`);return nu(i,o)}function nu(e,o){let i=structuredClone(o.arguments);ul(i,e.parameters),is(e.parameters,i);let u=rC(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(xU)){let y=ga(i,e.parameters);if(y!==i)if(typeof i==="object"&&i!==null&&typeof y==="object"&&y!==null){for(let b of Object.keys(i))delete i[b];Object.assign(i,y)}else return u.Check(y)?y:i}if(u.Check(i))return i;let p=u.Errors(i).map((y)=>` - ${TU(y)}: ${y.message}`).join(`
32
+ `)||"Unknown validation error",g=`Validation failed for tool "${o.name}":
33
+ ${p}
34
+
35
+ Received arguments:
36
+ ${JSON.stringify(o.arguments,null,2)}`;throw Error(g)}var nC;function Lc(){if(!nC)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return nC}async function oC(e,o,i,u,p,g){let y=aC(o,e),b=[...y],E={...o,messages:[...o.messages,...y]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let S of y)await u({type:"message_start",message:S}),await u({type:"message_end",message:S});return await iC(E,b,i,p,u,g??Lc()),b}async function sC(e,o,i,u,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 iC(y,g,o,u,i,p??Lc()),g}async function iC(e,o,i,u,p,g){let y=e,b=i,E,S=!1,w=await b.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||w.length>0){let P=[];if(E){let J=await b.prepareNextTurn?.(E);if(J)y=J.context??y,P=J.messages??[],b={...b,model:J.model??b.model,reasoning:J.thinkingLevel===void 0?b.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(w.length===0)w=await b.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let J of aC(y,[...P,...w]))await p({type:"message_start",message:J}),await p({type:"message_end",message:J}),y.messages.push(J),o.push(J);w=[];let C=await b.prepareRequest?.({context:y,model:b.model,thinkingLevel:b.reasoning??"off"},u);if(C)y=C.context??y,b={...b,model:C.model??b.model,reasoning:C.thinkingLevel===void 0?b.reasoning:C.thinkingLevel==="off"?void 0:C.thinkingLevel};let q=await AU(y,b,u,p,g);if(o.push(q),q.stopReason==="error"||q.stopReason==="aborted"){E={message:q,toolResults:[],context:y,newMessages:o},await b.finishTurn?.(E,u),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:o});return}let X=q.content.filter((J)=>J.type==="toolCall"),j=[];if(R=!1,X.length>0){let J=q.stopReason==="length"?await PU(X,p):await CU(y,q,b,u,p);j.push(...J.messages),R=!J.terminate;for(let ee of j)y.messages.push(ee),o.push(ee)}E={message:q,toolResults:j,context:y,newMessages:o};let V=await b.finishTurn?.(E,u);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:o});return}if(S=V?.action==="continue",w=await b.getSteeringMessages?.()||[],R||w.length>0)S=!1}let A=await b.getFollowUpMessages?.()||[];if(A.length>0){S=!1,w=A;continue}if(S){S=!1;continue}break}await p({type:"agent_end",messages:o})}function aC(e,o){let i=-1;for(let w=o.length-1;w>=0;w--)if(o[w].role==="system"){i=w;break}let u=o[i],p=u?o.map((w,R)=>R===i?Ah(u,kU):w):o,g=Go(oe([...e.messages,...p]),(e.tools??[]).map(nt)),y=g.toolsAdded.length===0&&g.toolsRemoved.length===0;if(u){if(y&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return p.map((w,R)=>R===i?Ah(u,g):w)}if(y)return o;let b=Ah({role:"system",content:"",timestamp:Date.now()},g),E=o.findIndex((w)=>w.role!=="system"),S=E===-1?o.length:E;return[...o.slice(0,S),b,...o.slice(S)]}var kU={toolsAdded:[],toolsRemoved:[]};function Ah(e,{toolsAdded:o,toolsRemoved:i}){let{toolsAdded:u,toolsRemoved:p,...g}=e;return{...g,...o.length>0?{toolsAdded:o}:{},...i.length>0?{toolsRemoved:i}:{}}}async function AU(e,o,i,u,p){let g=e.messages;if(o.transformContext)g=await o.transformContext(g,i);let y=await o.convertToLlm(g),b=ft({messages:y}),E=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,S=await p(o.model,b,{...o,apiKey:E,signal:i}),w=async()=>Object.assign(await S.result(),{thinkingLevel:o.reasoning??"off"}),R=null,A=!1;for await(let C of S)switch(C.type){case"start":R=C.partial,e.messages.push(R),A=!0,await u({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=C.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:C,message:{...R}});break;case"done":case"error":{let q=await w();if(A)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!A)await u({type:"message_start",message:{...q}});return await u({type:"message_end",message:q}),q}}let P=await w();if(A)e.messages[e.messages.length-1]=P;else e.messages.push(P),await u({type:"message_start",message:{...P}});return await u({type:"message_end",message:P}),P}async function PU(e,o){let i=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let p={toolCall:u,result:Gs(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Nc(p,o);let g=Ph(p);await Ch(g,o),i.push(g)}return{messages:i,terminate:!1}}async function CU(e,o,i,u,p){let g=o.content.filter((b)=>b.type==="toolCall"),y=g.some((b)=>e.tools?.find((E)=>E.name===b.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||y)return $U(e,o,g,i,u,p);return vU(e,o,g,i,u,p)}async function $U(e,o,i,u,p,g){let y=[],b=[];for(let E of i){await g({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await cC(e,o,E,u,p),w;if(S.kind==="immediate")w={toolCall:E,result:S.result,isError:S.isError};else{let A=await pC(S,p,mC(E,g));w=await lC(e,o,S,A,u,p)}await Nc(w,g);let R=Ph(w);if(await Ch(R,g),y.push(w),b.push(R),p?.aborted)break}return{messages:b,terminate:uC(y)}}async function vU(e,o,i,u,p,g){let y=[];for(let S of i){await g({type:"tool_execution_start",toolCallId:S.id,toolName:S.name,args:S.arguments});let w=await cC(e,o,S,u,p);if(w.kind==="immediate"){let R={toolCall:S,result:w.result,isError:w.isError};if(await Nc(R,g),y.push(R),p?.aborted)break;continue}if(y.push(async()=>{if(p?.aborted){let P={toolCall:S,result:Gs("Operation aborted"),isError:!0};return await Nc(P,g),P}let R=await pC(w,p,mC(S,g)),A=await lC(e,o,w,R,u,p);return await Nc(A,g),A}),p?.aborted)break}let b=await Promise.all(y.map((S)=>typeof S==="function"?S():Promise.resolve(S))),E=[];for(let S of b){let w=Ph(S);await Ch(w,g),E.push(w)}return{messages:E,terminate:uC(b)}}function uC(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function MU(e,o){if(!e.prepareArguments)return o;let i=e.prepareArguments(o.arguments);if(i===o.arguments)return o;return{...o,arguments:i}}async function cC(e,o,i,u,p,g=e.tools??[]){let y=g.find((b)=>b.name===i.name);if(!y)return{kind:"immediate",result:Gs(`Tool ${i.name} not found`),isError:!0};try{let b=MU(y,i),E=nu(y,b);if(u.beforeToolCall){let S=await u.beforeToolCall({assistantMessage:o,toolCall:i,args:E,context:e},p);if(p?.aborted)return{kind:"immediate",result:Gs("Operation aborted"),isError:!0};if(S?.block){let w=Gs(S.reason||"Tool execution was blocked");if(S.terminate===!0)w.terminate=!0;return{kind:"immediate",result:w,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Gs("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:y,args:E}}catch(b){return{kind:"immediate",result:Gs(b instanceof Error?b.message:String(b)),isError:!0}}}function mC(e,o){return(i)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function pC(e,o,i){let u=[],p=!0,g=performance.now(),y=()=>Math.round(performance.now()-g);try{let b=await e.tool.execute(e.toolCall.id,e.args,o,(S)=>{if(!p)return;u.push(Promise.resolve(i(S)))}),E=y();return p=!1,await Promise.all(u),{result:b,isError:b.isError===!0,durationMs:E}}catch(b){let E=y();return p=!1,await Promise.all(u),{result:Gs(b instanceof Error?b.message:String(b)),isError:!0,durationMs:E}}finally{p=!1}}async function lC(e,o,i,u,p,g){let{result:y,isError:b}=u;if(p.afterToolCall)try{let E=await p.afterToolCall({assistantMessage:o,toolCall:i.toolCall,args:i.args,result:y,isError:b,context:e},g);if(E){let S=E.structuredContent??(E.content?void 0:y.structuredContent);if(y={...y,content:E.content??y.content,details:E.details??y.details,usage:E.usage??y.usage,terminate:E.terminate??y.terminate},S===void 0)delete y.structuredContent;else y.structuredContent=S;b=E.isError??b}}catch(E){y=Gs(E instanceof Error?E.message:String(E)),b=!0}return{toolCall:i.toolCall,result:y,isError:b,durationMs:u.durationMs}}function Gs(e){return{content:[{type:"text",text:e}],details:{}}}async function Nc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function 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 Ch(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function OU(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var _U={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},LU={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 NU(e){let o=e?.tools?.slice()??[],i=e?.messages?.slice()??[],u=Vn(e?.systemPrompt,o.map(nt));if(i[0]?.role!=="system"&&u)i.unshift(u);return{get systemPrompt(){return qo(i)},model:e?.model??LU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(p){o=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class $h{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 o=e??{};this._state=NU(o.initialState),this.convertToLlm=o.convertToLlm??OU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Lc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new $h(o.steeringMode??"one-at-a-time"),this.followUpQueue=new $h(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=Xr(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let i=this.normalizePromptInput(e,o);await this.runPromptMessages(i)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(o&&o.length>0)i.push(...o);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(i)=>{await oC(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await sC(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,i=()=>{},u=new Promise((p)=>{i=p});this.activeRun={promise:u,resolve:i,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(p){await this.handleRunFailure(p,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:_U,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,o)}}function _e(e,...o){return Object.assign(e,{aliases:o})}function ya(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function DU(e){let o=[],i="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(i)o.push(i);i="";continue}if(u>="A"&&u<="Z"&&i&&!/[A-Z]$/.test(i))o.push(i),i="";i+=u}if(i)o.push(i);return o}function dC(e,o){if(e.some((C)=>C.name===o))return o;let i=e.map((C)=>C.name),u=(C)=>i.filter((q)=>ya(q)===C),p=u(ya(o));if(p.length===1&&p[0])return p[0];if(p.length>1)return o;let g=o.split(/[.:/]/).pop()??o,y=g===o?[]:u(ya(g));if(y.length===1&&y[0])return y[0];let b=new Map;for(let C of e)for(let q of C.aliases??[]){let X=ya(q);b.set(X,(b.get(X)??new Set).add(C.name))}let E=(C)=>[...new Set([...u(C),...b.get(C)??[]])],S=E(ya(g));if(S.length===1&&S[0])return S[0];if(S.length>1)return o;let w=DU(g),R=new Set;w.forEach((C,q)=>{R.add(ya(C));let X=w[q+1];if(X)R.add(ya(C+X))});let A=new Set;for(let C of R)for(let q of E(C))A.add(q);let P=[...A];return P.length===1&&P[0]?P[0]:o}function x(e){return e}function En(e,o){let i=o.indexOf("/");if(i<=0)return;return e.getModel(o.slice(0,i),o.slice(i+1))}function tt(e){return`${e.provider}/${e.id}`}function qU(e,o,i){let u=async(g,y)=>{try{if(o){let E=g instanceof Request?g:void 0;o({at:Date.now(),method:y?.method??E?.method??"GET",url:typeof g==="string"?g:g instanceof URL?g.toString():g.url,headers:fC(y?.headers??E?.headers),body:FU(y?.body!==void 0?y.body:E?.body??void 0)})}}catch{}let b=await e(g,y);if(i)try{let E=Date.now(),{status:S,statusText:w}=b,R=fC(b.headers);if(!b.body)return i({at:E,status:S,statusText:w,headers:R,body:""}),b;let A="",P=new TextDecoder,C=new TransformStream({transform(j,V){V.enqueue(j),A+=P.decode(j,{stream:!0}),i({at:E,status:S,statusText:w,headers:R,body:A})},flush(){A+=P.decode(),i({at:E,status:S,statusText:w,headers:R,body:A})}}),q=b.body.pipeThrough(C),X=new Response(q,b);try{Object.defineProperty(X,"url",{value:b.url})}catch{}return X}catch{}return b},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:p})}function fC(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,p)=>{o[p]=u}),o;let i=Array.isArray(e)?e:Object.entries(e);for(let u of i)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function FU(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 jU(e,o){return dC(e,o)}function UU(e,o,i){let u=Date.now(),p=new WeakSet,g=(E)=>{if(!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;let S=Date.now(),w=Math.max(10,S-u);E.generationMs=w},y=async(E)=>{if(!i||!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;if(g(E),p.has(E))return;p.add(E),Object.assign(E,await i(E))},b=(E)=>{let S=E?.content;if(!Array.isArray(S))return;for(let w of S)if(w&&w.type==="toolCall"&&typeof w.name==="string")w.name=jU(o(),w.name)};return{async*[Symbol.asyncIterator](){for await(let E of e){let{partial:S,message:w}=E;b(S),await y(w),b(w),yield E}},result:async()=>{let E=await e.result();return g(E),await y(E),b(E),E}}}function Dc(e,o){let i=(o??[]).filter((b)=>b.kind==="path").map((b)=>`<file path=${JSON.stringify(b.data)} />`),u=(o??[]).filter((b)=>b.kind==="text").map((b)=>`<file name=${JSON.stringify(b.name)}>
37
+ ${b.data}
38
+ </file>`),p=(o??[]).filter((b)=>b.kind==="image").map((b)=>({type:"image",data:b.data,mimeType:b.mimeType})),g=(o??[]).filter((b)=>b.kind==="image"&&b.id).map((b)=>`<image id=${JSON.stringify(b.id)} name=${JSON.stringify(b.name)} />`);return{merged:[...i,...u,...g,...e.trim()?[e]:[]].join(`
39
+
40
+ `),images:p}}function Mh(e,o){let{merged:i,images:u}=Dc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:i},...u]:i,timestamp:Date.now()}}function hC(e){let o=new Set;for(let b of e.tools){let E=b.name.toLowerCase();if(o.has(E))throw Error(`Tool names collide ignoring case: ${b.name}`);o.add(E)}let i=new vh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(b,E,S)=>{let{captureRequest:w,captureResponse:R}=e,A=w||R?{...S,fetch:qU(S?.fetch??globalThis.fetch,w?(C)=>w({...C,model:tt(b)}):void 0,R?(C)=>R({...C,model:tt(b)}):void 0)}:S,P=b.api==="openai-completions"||b.api==="openai-responses"?{...b,compat:{...b.compat,supportsDeveloperRole:!1}}:b;return UU(e.models.streamSimple(P,E,A),()=>i.state.tools,e.hooks.response)},convertToLlm:(b)=>b,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:b,model:E})=>{let S=b.messages.findIndex((P)=>P.role!=="system"),w=b.messages.slice(0,S===-1?b.messages.length:S),R=e.hooks.prepare,A=e.hooks.tools?.()??b.tools;if(A){i.state.tools=A;let P=w[0];if(P?.role==="system")w[0]={...P,toolsAdded:A.map(nt),toolsRemoved:void 0}}return{context:{...b,tools:A,messages:await R(w,A,E)}}}:void 0}),u=new Map,p=new Map,g=new WeakSet,y;return i.subscribe((b)=>{if(b.type==="message_update"&&b.message.role==="assistant"){p.clear(),e.hooks.draft(yC(b.message));return}if(b.type==="tool_execution_update"){let S=u.get(b.toolCallId)??Be(b.toolName,b.args),w=Array.isArray(b.partialResult?.content)?b.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";p.set(b.toolCallId,{type:"tool_call",id:b.toolCallId,name:S.name,input:S.input,...S.source?{source:S.source}:{},output:w}),e.hooks.draft([...p.values()]);return}if(b.type==="tool_execution_end"){if(p.delete(b.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(b.type!=="message_end")return;if(g.has(b.message)){e.steerConsumed?.(b.message);return}let E=b.message.role==="user"&&y?{type:"user",text:y.text,...y.attachments?.length?{attachments:y.attachments}:{}}:BU(b.message);if(b.message.role==="user")y=void 0;if(E?.type==="assistant"){for(let S of E.parts)if(S.type==="tool_call")u.set(S.id,S)}if(E?.type==="tool_result"){let S=u.get(E.callID);if(S?.source)Object.assign(E,{name:S.name,source:S.source})}if(E)e.hooks.message(E,b.message);if(b.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(b,E)=>{y={text:b,attachments:E};let{merged:S,images:w}=Dc(b,E);return i.prompt(S,w.length>0?w:void 0)},retry:async()=>{let b=i.state.messages;if(b.at(-1)?.role==="assistant")i.state.messages=b.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(b)=>{g.add(b),i.steer(b)},unsteer:(b)=>{let S=i.steeringQueue?.messages;if(!S)return!1;let w=S.indexOf(b);if(w<0){let A=JSON.stringify(b);w=S.findIndex((P)=>JSON.stringify(P)===A)}if(w<0)return!1;let[R]=S.splice(w,1);if(R)g.delete(R);return!0},abort:()=>i.abort()}}function Oh(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 gC(e){let{name:i,source:u}=Be(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:i,...u?{source:u}:{},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 yC(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...Be(o.name,o.arguments)}})}function BU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:yC(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class pt extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function k(e){return e}import{createHash as xC}from"crypto";import{existsSync as GU}from"fs";import{readFile as IC,realpath as cl}from"fs/promises";import{dirname as KU,isAbsolute as bC,relative as EC,resolve as SC,sep as wC}from"path";var TC=[...qg];class ml extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class pl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let i=KU(SC(e)),u=SC(i,o??"web.tsx");if(!o&&!GU(u))return;let p=EC(await cl(i),await cl(u));if(bC(p)||p===".."||p.startsWith(`..${wC}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let i=this.pending.get(e);if(i)return i;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let i=this.cache.get(e);if(i){let S=!0;for(let[w,R]of i.inputs){let A=await IC(w).catch(()=>{return});if(!A||xC("sha256").update(A).digest("hex")!==R){S=!1;break}}if(S)return i.source;this.cache.delete(e)}let u=await cl(o),p=new Map,g=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:TC,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(S){S.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(w)=>{if(!TC.includes(w.path))throw Error(`Unsupported shared web import: ${w.path}`);return{path:w.path,external:!0}}),S.onLoad({filter:/.*/},async(w)=>{let R=EC(u,await cl(w.path));if(bC(R)||R===".."||R.startsWith(`..${wC}`))throw Error("Plugin web imports must stay inside its plugin directory");let A=await IC(w.path);p.set(w.path,xC("sha256").update(A).digest("hex"));return})}}]}).catch((S)=>{let R=(S instanceof AggregateError?S.errors:[S]).map((A)=>A instanceof Error?A.message:String(A));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:S})});if(!g.success)throw new ml(g.logs.filter((S)=>S.level==="error").map((S)=>({file:S.position?.file??null,line:S.position?.line??null,message:S.message})));let y=g.outputs.find((S)=>S.kind==="entry-point"&&S.path.endsWith(".js")),b=g.outputs.find((S)=>S.path.endsWith(".css"));if(!y||g.outputs.some((S)=>S!==y&&S!==b))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let E=await y.text();return this.cache.set(e,{source:E,css:await b?.text(),inputs:p}),E}}function _o(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Ps(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function ll(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((o)=>o.type==="text"?o.text:"[image]").join("")}function su(e){return e.role==="assistant"&&e.content.length>0}function us(e){let o=[],i=new Map,u=0;for(let p of e){let g=p.raw;if(g.role==="assistant"){if(su(g))u++;for(let y of g.content){if(y.type!=="toolCall")continue;let b={call:y,step:u,message:g};o.push(b),i.set(y.id,b)}}else if(g.role==="toolResult"){let y=i.get(g.toolCallId);if(y)y.result=g}}return o}var dl=new Set(["edit","write"]),RC=new Set(["grep","glob"]);function ao(e,o){let i=Be(e.name,e.arguments).input?.[o];return typeof i==="string"?i:void 0}function kC(e){return[...new Set(us(e).flatMap((o)=>dl.has(Be(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&ao(o.call,"path")?[ao(o.call,"path")]:[]))]}function _h(e){return!e.result?"pending":e.result.isError?"error":"completed"}function fl(e){let o=[{source:"ASSISTANT_TOOL",text:`${Be(e.call.name,e.call.arguments).name}(${_o(Be(e.call.name,e.call.arguments).input)}) [${_h(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:ou(e.result)});return o}function D(e){let o=0,i=0,u=0;for(let p of e){let g=p.codePointAt(0);if(g<=127)o++;else if(g>=19968&&g<=40959||g>=12288&&g<=12351||g>=65280&&g<=65519||g>=131072&&g<=173791)i++;else u++}return Math.max(0,Math.ceil(o/4+i+u/2))}var Lh=8192;function F(e){let o=e,i=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let p of o.content)if(p.type==="text")u+=p.text;else i++;else if(o.role==="assistant")for(let p of o.content)if(p.type==="text")u+=p.text;else if(p.type==="thinking")u+=p.thinking;else u+=`${p.name}${_o(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")u+=p.text;else i++;else u=_o(e);return D(u)+16+i*Lh}function Ni(e=[]){return e.reduce((o,i)=>o+D(i.name+i.description+_o(i.parameters))+16,0)}function Fn(e,o){let i=e.replace(/\s+/g," ").trim();if(D(i)<=o)return i;let u=Math.min(i.length,o*4);while(u>0&&D(i.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${i.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function To(e,o,i=Number.POSITIVE_INFINITY){if(D(e)<=o&&e.length<=i)return e;let u=`
43
+ [... omitted; use history tools for the full text ...]
44
+ `,p=Math.floor((o-D(u))/2);if(p<=0)return"";let g=(y)=>{let b=0,E=Math.max(0,Math.min(e.length,p*4,Math.floor((i-u.length)/2)));while(b<E){let S=Math.ceil((b+E)/2),w=y?e.slice(-S):e.slice(0,S);if(D(w)<=p)b=S;else E=S-1}if(!b)return"";return y?e.slice(-b).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,b).replace(/[\uD800-\uDBFF]$/,"")};return`${g(!1)}${u}${g(!0)}`}function hl(e,o){if(D(e.join(`
45
+ `))<=o)return e;let i=(w)=>`- [... ${w} steps omitted; use history tools for the full text ...]`,u=o-D(i(e.length)),p=[],g=[],y=0,b=0,E=e.length-1;while(b<=E){let w=p.length<=g.length,R=w?e[b]:e[E],A=D(`${R}
46
+ `);if(y+A>u)break;if(y+=A,w)p.push(e[b++]);else g.unshift(e[E--])}let S=E-b+1;return[...p,...S>0?[i(S)]:[],...g]}function Ks(e){let o=[],i;for(let u of e){let p=u.entry;if(p.type==="run"&&p.state==="start"){i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=HU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!u.raw)continue;if(!i&&p.type==="user"&&p.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);i.records.push(u)}for(let u of o)u.records=Nh(u.records);return o}function Nh(e){if(e.length<=1)return[...e];let o=[],i=[],u=new Set;for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;let y=g.raw?.role;if(y==="assistant"){let E=g.raw.content?.filter((S)=>S.type==="toolCall")??[];if(E.length>0)for(let S of E)u.add(S.id);if(o.push(g),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="toolResult"){let b=g.raw;if(b.toolCallId)u.delete(b.toolCallId);if(o.push(g),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="user"){if(o.length===0){o.push(g);continue}let b=e.slice(p+1).some((E)=>E.raw?.role==="assistant");if(u.size>0||b){i.push(g);continue}o.push(g);continue}o.push(g)}if(i.length>0)o.push(...i);return o}function HU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&ca(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ca(i)?"interrupted":"failed";default:return"interrupted"}}function xa(e){for(let o=e.length-1;o>=0;o--){let i=e[o]?.entry;if(i?.type==="compaction")return i.through}return 0}function gl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((i)=>i.entry.seq<=o)}function Dh(e,o){return e.find((i)=>i.start<o&&!gl(i,o)&&i.records.some((u)=>u.entry.seq<=o))}function iu(e){let o=xa(e),u=Ks(e).findLast((p)=>p.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function yl(e){let o=xa(e);return Dh(Ks(e),o)?.end}function qc(e,o){let i=xa(e),u=Ks(e).at(-1);if(!u||u.end!==void 0)return;let p=u.records.filter((w)=>w.entry.seq>i),g=[],y=new Set;for(let w of p){let R=w.raw,A=F(w.raw);if(R.role==="assistant"){for(let P of R.content)if(P.type==="toolCall")y.add(P.id)}else if(R.role==="toolResult")y.delete(R.toolCallId);if(su(R)||!g.length||R.role==="user"&&g.at(-1)?.assistant)g.push({end:w.entry.seq,tokens:A,assistant:su(R),pending:y.size});else{let P=g.at(-1);P.end=w.entry.seq,P.tokens+=A,P.pending=y.size}}let b=g.findLastIndex((w)=>w.assistant),E=0,S;for(let w=g.length-1;w>=0;w--){let R=g[w];if(w<b&&R.assistant&&R.pending===0&&(E<=o||S===void 0))S=R.end;if(E+=R.tokens,E>o&&S!==void 0)break}if(E<=o)return;return S}var AC=2000;function Di(e,o){let i=D(o);if(i<=AC)return o;let u=new TextEncoder().encode(o).length,p=o.split(`
47
+ `).length,g=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${p} lines, approximately ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
48
+ `),y="</user-text-reference>",b=AC-D(`${g}
49
+
50
+ ${y}`);if(b<=0)return o;let E=`${g}
51
+ ${To(o,b,o.length-g.length-y.length-3)}
52
+ ${y}`;return E.length<o.length&&D(E)<i?E:o}function PC(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let p=Di(e.entry.seq,o.content);return p===o.content?o:{...o,content:p}}let i=!1,u=o.content.map((p)=>{if(p.type!=="text")return p;let g=Di(e.entry.seq,p.text);if(g!==p.text)i=!0;return g===p.text?p:{...p,text:g}});return i?{...o,content:u}:o}function qh(e,o=!1){let i=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),u=i.flatMap((P)=>{let C=P.raw.content;return typeof C==="string"?[]:C.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=o?To(i.map((C)=>Ps(C.raw)).join(`
53
+
54
+ `),600):i.map((C,q)=>`<user-message sequence="${q+1}">
55
+ ${Di(C.entry.seq,Ps(C.raw))}
56
+ </user-message>`).join(`
57
+
58
+ `);y=[`<chunk-input id="${e.id}" status="${g}"${o?' excerpt="true"':""}>`,P,...o?[p]:[],"</chunk-input>"].join(`
59
+ `)}let E=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,S=E?ll(E):"",w=[];if(g!=="completed"){let P=us(e.records),C=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 ae=X.has(ee);for(let H of ee.content)if(H.type==="text"&&ee!==E&&H.text.trim())if(ae)V.push(`ASSISTANT: ${Fn(H.text,50)}`);else j.push(`- ASSISTANT: ${Fn(H.text,50)}`);else if(H.type==="toolCall"){let ue=C.get(H);if(!ue)continue;if(ae){if(q.includes(ue))for(let he of fl(ue))V.push(`${he.source}: ${To(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${H.name}(${Fn(_o(H.arguments),40)}) [${_h(ue)}]`)}}w.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...j.length?[`Earlier steps, oldest first:
60
+ ${hl(j,o?300:800).join(`
61
+ `)}`]:[],...V)}let R=kC(e.records),A=[`<chunk-summary id="${e.id}" status="${g}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,S?o?To(S,600):S:"No final assistant response was recorded.",...w,...R.length?[`Recorded file changes:
62
+ ${To(R.join(`
63
+ `),250)}`]:[],...o&&g==="completed"?[p]:[],"</chunk-summary>"].join(`
64
+ `);return{input:y,images:u,summary:A,tokens:WU(y,A,u.length)}}function WU(e,o,i){return(e?D(e)+16:0)+D(o)+16+i*Lh}var zU=["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."],VU="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.",JU=1500,QU=80,XU=240;function CC(e,o,i){let u=[],p=0,g=Math.min(o.target,o.hard);for(let b=e.length-1;b>=0;b--){let E=e[b],S=qh(E),w=p+S.tokens>g?qh(E,!0):void 0,R=w&&w.tokens<S.tokens?w:S;if(!(!i&&b===e.length-1&&E.status!=="completed")&&p+R.tokens>o.hard)break;p+=R.tokens,u.push({run:E,content:R})}u.reverse();let y=e.slice(0,e.length-u.length);return{visible:u,archived:y,tokens:p}}function $C(e){let{runs:o,visible:i,archived:u,partial:p}=e,g=u.flatMap((E)=>{let S=E.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>Ps(R.raw));if(!S.length)return[];let w=E===o[0]?XU:QU;return[`- ${E.id} [${E.status}]: ${Fn(S.join(" / "),w)}`]}),y=new Map(o.map((E,S)=>[E,S+1])),b=[...i.map((E)=>y.get(E)??0),...p?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...zU,...p?[VU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((E)=>E.id).join(", "):"none"}`,`visible sequences: ${b.length?`${b[0]}..${b.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...g.length?["archived requests, oldest first:",To(g.join(`
65
+ `),JU)]:[],"</conversation-checkpoint>"].join(`
66
+ `)}function vC(e,o){let i=e.split(`
67
+ `),u=o.split(`
68
+ `),p=new Set(i),g=new Set(u),y=[...i.filter((E)=>E.trim()&&!g.has(E)).map((E)=>`- ${Fn(E,40)}`),...u.filter((E)=>E.trim()&&!p.has(E)).map((E)=>`+ ${Fn(E,40)}`)],b=i.find((E)=>E.trim()&&g.has(E));return[...y.slice(0,6),...y.length>6?[`\u2026 ${y.length-6} more changed lines`]:[],...b&&y.every((E)=>E.startsWith("+"))?[`@ ${Fn(b,40)}`]:[]]}function xl(e,o){if(!o)return e;let i=o.endsWith("/")?o:`${o}/`;return e.startsWith(i)?e.slice(i.length):e}function YU(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((i)=>{let u=i&&typeof i==="object"?i.path:void 0;return typeof u==="string"?[u]:[]})}function ZU(e,o){let i=ao(e,"path");if(dl.has(e.name)&&i)return`file:${xl(i,o)}`;let u=ao(e,"command");if(u)return`command:${u}`;return`${e.name}:${_o(e.arguments)}`}function eB(e,o){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let g of us(e)){let y=u.get(g.step)??[];y.push(g),u.set(g.step,y)}let p=new Map;for(let g of e){let y=g.raw;if(!su(y))continue;let b=++i.steps,E=ll(y);if(E)i.narration.push({step:b,text:Fn(E,60)});for(let{call:S,result:w}of u.get(b)??[]){if(!w)continue;let R=Be(S.name,S.arguments),A={...S,name:R.name,arguments:R.input},P=ZU(A,o),C=ou(w);if(w.isError){let ee=ao(A,"command"),ae=ee?`${A.name} \`${Fn(ee,40)}\``:`${A.name} ${P.startsWith("file:")?P.slice(5):Fn(_o(A.arguments),40)}`,H={step:b,key:P,what:ae,detail:To(C.trim().split(`
69
+ `).slice(0,8).join(`
70
+ `),200)};i.errors.push(H);let ue=p.get(P)??[];ue.push(H),p.set(P,ue);continue}for(let ee of p.get(P)??[])ee.resolved=b;p.delete(P);let q=ao(A,"path");if(dl.has(A.name)&&q){let ee=xl(q,o),ae=i.files.get(ee)??{count:0,first:b,last:b,diffs:[]};if(ae.count++,ae.last=b,ae.diffs.push({step:b,lines:A.name==="edit"?ao(A,"old_string")!==void 0?vC(ao(A,"old_string")??"",ao(A,"new_string")??""):[]:vC("",ao(A,"content")??"")}),ae.diffs.length>3)ae.diffs.shift();i.files.set(ee,ae);continue}let X=A.name==="read"?[...q?[q]:[],...YU(A)]:[];if(X.length){for(let ee of X){let ae=xl(ee,o),H=i.reads.get(ae)??[];H.push(b),i.reads.set(ae,H)}continue}if(RC.has(A.name)){let ee=q?` in ${xl(q,o)}`:"",ae=A.name==="grep"&&ao(A,"glob")?` (${ao(A,"glob")})`:"",H=`${A.name} ${ao(A,"pattern")??""}${ee}${ae}`.replace(/\s+/g," "),ue=i.searches.get(H)??{steps:[],head:""};ue.steps.push(b),ue.head=Fn(C.trim().split(`
71
+ `)[0]??"",25),i.searches.set(H,ue);continue}let j=ao(A,"command");if(j){let ee=C.trim().split(`
72
+ `);i.commands.push({step:b,command:Fn(j,40),exit:"0",lines:ee.length,tail:ee.slice(-3).map((ae)=>Fn(ae,40))});continue}let V=`${A.name} ${Fn(_o(A.arguments),40)}`,J=i.other.get(V)??[];J.push(b),i.other.set(V,J)}}return i}function MC(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Fc(e,o,i){let u=(S,w)=>w===void 0||!S.length?S:hl(S,w),p=[`<work-state chunk="${o.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${o.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],g=[...e.files];p.push("",`## Modified files (${g.length})`),g.forEach(([S,w],R)=>{if(p.push(`- ${S}: ${w.count} change${w.count>1?"s":""} (step ${w.first}${w.last!==w.first?`-${w.last}`:""})`),R<g.length-i.diffFiles)return;for(let A of w.diffs)p.push(` step ${A.step}:`,...A.lines.map((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",...u(e.narration.map((S)=>`- ${S.step}. ${S.text}`),i.narration));let y=[...e.reads].map(([S,w])=>`- ${S} @ ${w.join(",")}`);p.push("",`## Files read (${y.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(y,i.lists));let b=[...e.searches].map(([S,w])=>`- ${S} \u2192 ${w.head||"(no output)"} (${MC(w.steps)})`);p.push("",`## Searches (${b.length})`,...u(b,i.lists));let E=e.commands.map((S)=>[`- ${S.step}. \`${S.command}\` exit=${S.exit}, ${S.lines} output lines, last ${S.tail.length}:`,...S.tail.map((w)=>` ${w}`)].join(`
75
+ `));if(p.push("",`## Commands (${E.length})`,...u(E,i.lists)),e.other.size){let S=[...e.other].map(([w,R])=>`- ${w} (${MC(R)})`);p.push("",`## Other tool calls (${S.length})`,...u(S,i.lists))}return p.push("</work-state>"),p.join(`
76
+ `)}function Il(e,o,i,u){let p=eB(e,u),g=Fc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(D(g)<=i)return g;let y={...p,narration:[]};for(let S of[Number.POSITIVE_INFINITY,20,10,5]){let w=D(Fc(y,o,{diffFiles:S}));if(w>i*0.7)continue;return Fc(p,o,{narration:Math.max(500,i-w),diffFiles:S})}let b=Math.max(300,Math.floor(i*0.1)),E=D(Fc(y,o,{diffFiles:0,lists:b}));return Fc(p,o,{narration:Math.max(500,i-E),diffFiles:0,lists:b})}function bl(e){return{role:"user",content:e,timestamp:0}}function Fh(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function OC(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:bl(e.input)}function au(e){let o=[];for(let i of e){let u=o.at(-1),p=i;if(u?.role==="user"&&p.role==="user"){let g=(y)=>typeof y.content==="string"?[{type:"text",text:y.content}]:y.content;o[o.length-1]={...p,content:[...g(u),{type:"text",text:`
77
+
78
+ `},...g(p)]};continue}o.push(i)}return o}function tB(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Re(e,o,i,u={}){let p=xa(e),g=Ks(e),y=g.filter((Ee)=>gl(Ee,p)),b=Dh(g,p),E=[],S=[],w=0;for(let Ee of g){if(gl(Ee,p))continue;let se=[];for(let pe of Ee.records){if(Ee===b&&pe.entry.seq<=p)continue;let qe=pe.raw.role==="user"?PC(pe):pe.raw;w+=F(qe),E.push(qe),se.push(qe)}if(u.inspect&&se.length)S.push({id:`recent-${Ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Ee.id}`,tokens:se.reduce((pe,qe)=>pe+F(qe),0),detail:JSON.stringify(se,tB,2)})}if(!y.length&&!b)return{items:S,messages:au(E),visible:0,archived:0,open:w,tokens:w,untrimmed:w};let R=CC(y,i,!!b),{visible:A,archived:P}=R,C=R.tokens,q=[],X="",j="";if(b){let Ee=b.records.filter((pe)=>pe.entry.seq<=p),se=Ee.filter((pe)=>pe.entry.type==="user"&&!pe.entry.notices&&pe.raw.role==="user");if(se.length){X=[`<chunk-input id="${b.id}" status="partial">`,...se.map((qe,xt)=>`<user-message sequence="${xt+1}">
79
+ ${Di(qe.entry.seq,Ps(qe.raw))}
80
+ </user-message>`),"</chunk-input>"].join(`
81
+ `);let pe=se.flatMap((qe)=>{let xt=qe.raw.content;return typeof xt==="string"?[]:xt.filter((Je)=>Je.type==="image")});q.push(pe.length?{role:"user",content:[{type:"text",text:X},...pe],timestamp:0}:bl(X))}j=Il(Ee,b,i.index,u.cwd),q.push(Fh(j,o))}let V=e.flatMap((Ee)=>{let se=Ee.raw;if(Ee.entry.seq>p||se?.role!=="toolResult"||se.toolName!=="skill")return[];return[bl(se.content.filter((pe)=>pe.type==="text").map((pe)=>pe.text).join(`
82
+ `))]}),J="",ee=()=>{J=$C({runs:y,visible:A.map((se)=>se.run),archived:P,partial:!!b,tokens:C,budget:i});let Ee=[bl(J)];for(let{content:se}of A){if(se.input)Ee.push(OC(se));Ee.push(Fh(se.summary,o))}return[...Ee,...V,...q]},ae=(Ee)=>Ee.reduce((se,pe)=>se+F(pe),0),H=ee(),ue=ae(H)+w,he=ue,{trim:$e}=u;while($e&&$e.fixed+ue>$e.limit){let Ee=b||A.at(-1)?.run.status==="completed"?A:A.slice(0,-1);if(!Ee.length)break;let se=0,pe=0;for(let qe of Ee)if(pe++,se+=qe.content.tokens,se>=$e.fixed+ue-$e.limit)break;P=[...P,...A.slice(0,pe).map((qe)=>qe.run)],A=A.slice(pe),C-=se,H=ee(),ue=ae(H)+w}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:F(H[0]),detail:J},...A.map(({run:Ee,content:se})=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"sealed",tokens:(se.input?F(OC(se)):0)+F(Fh(se.summary,o)),detail:[se.input,se.summary].filter(Boolean).join(`
83
+
84
+ `)})),...P.map((Ee)=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...b?[{id:b.id,label:`Chunk ${b.id}`,state:"folded",tokens:ae(q),detail:[X,j].filter(Boolean).join(`
85
+
86
+ `)}]:[],...S]:[],messages:au([...H,...E]),visible:A.length,archived:P.length,open:w,tokens:ue,untrimmed:he}}function ce(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var jh=0.97,rB=0.97,_C=0.5,nB=0.05,oB=20000,sB=24000;function jc(e){return{target:oB,hard:sB,index:Math.floor(ce(e)*nB)}}function Uh(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class Uc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,i=()=>{return}){this.records=e;this.fold=o;this.cwd=i}budget(e){return jc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(ce(e)*jh/this.ratio)}prepare(e,o,i,u){let p=ce(i),g=jc(i),y=e.reduce((H,ue)=>H+F(ue),0)+Ni(o),b=this.records().at(-1)?.entry.seq??0,E=()=>u?[...u,...this.records().filter((H)=>H.entry.seq>b)]:this.records(),S=()=>Re(E(),i,g,{cwd:this.cwd(),trim:{fixed:y,limit:Math.floor(p*jh/this.ratio)}}),w=E().findLast((H)=>H.raw?.role==="assistant"),R=w?E().filter((H)=>H.entry.seq>w.entry.seq&&H.raw):[],A=w?.raw,P=()=>w!==void 0&&(w.entry.seq===this.reshapedAfter||E().some((H)=>H.entry.type==="compaction"&&H.entry.seq>w.entry.seq)),C=this.dueSeal(i);if(C!==void 0)this.fold(C,!1),this.reshapedAfter=w?.entry.seq??-1;let q=S(),X=R.reduce((H,ue)=>H+F(ue.raw),0);if(this.lastEstimate===0&&w&&A&&!P()){let H=A.usage.input+A.usage.cacheRead+A.usage.cacheWrite,ue=y+q.untrimmed-F(A)-X;if(H>0&&ue>0)this.ratio=Math.min(2,Math.max(0.5,H/ue))}let V=((H)=>{let ue=y+H.untrimmed,he=y+H.tokens;return((w&&A&&!P()&&Uh(A)>0?Uh(A)+Math.round(this.ratio*X):void 0)??Math.round(ue*this.ratio))-Math.round((ue-he)*this.ratio)})(q);if(V>p*rB){let H=V-q.open*this.ratio,ue=Math.max(1000,Math.floor((p*_C-H-g.index)/this.ratio)),he=w?.entry.seq??-1,$e=E().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,Ee=Math.max(this.lastFoldSeq,$e),pe=(Ee>0?E().filter((qe)=>qe.entry.seq>Ee&&qe.raw?.role==="assistant").length:999)<=1;if(!pe||this.consecutivePartialFolds<2){let qe=qc(E(),ue);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=pe?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=iB(J,Math.floor((p-y)/this.ratio)),ee=y+J.reduce((H,ue)=>H+F(ue),0);return this.lastEstimate=ee,{messages:au([...e,...J]),estimate:ee}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(yl(o)===void 0){let i=o.findLast((b)=>b.raw?.role==="assistant"),u=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||o.some((b)=>b.entry.type==="compaction"&&b.entry.seq>i.entry.seq)),y=(i?o.filter((b)=>b.entry.seq>i.entry.seq&&b.raw):[]).reduce((b,E)=>b+F(E.raw),0);if(p||!u||Uh(u)+y<Math.floor(ce(e)*jh))return}return iu(o)}recover(e){let o=ce(e),i=jc(e),u=Re(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((o*_C-(o-u.open*this.ratio)-i.index)/this.ratio),g=qc(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 iB(e,o){let i=e.reduce((p,g)=>p+F(g),0);if(i<=o)return e;let u=[];for(let p of e){let g=p;if(g.role!=="toolResult"||i<=o){u.push(p);continue}let y=F(p);if(y<=1500){u.push(p);continue}let b=Math.max(500,Math.floor(y/2)),E=g.content.map((R)=>{if(R.type!=="text")return R;return{...R,text:To(R.text,b)}}),S={...g,content:E},w=F(S);i-=y-w,u.push(S)}return u}var aB=2000;function uu(e,o){let i=[];for(let u of o.replace(/\r\n/g,`
87
+ `).split(`
88
+ `))for(let p=0;p<Math.max(u.length,1);){let g=Math.min(u.length,p+aB);if(g<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(g-1)))g--;i.push({source:e,text:u.slice(p,g)}),p=g>p?g:p+1}return i}function cu(e){let o=[],i=us(e.records),u=new Map(i.map((g)=>[g.call,g])),p=new Set(i.flatMap((g)=>g.result?[g.result]:[]));for(let g of e.records){let y=g.raw;if(y.role==="user")o.push(...uu(g.entry.type==="user"&&g.entry.notices?"NOTICE":"USER",Ps(y)));else if(y.role==="assistant"){for(let b of y.content)if(b.type==="text"&&b.text.trim())o.push(...uu("ASSISTANT",b.text));else if(b.type==="toolCall"){let E=u.get(b);if(E)for(let S of fl(E))o.push(...uu(S.source,S.text))}}else if(y.role==="toolResult"&&!p.has(y))o.push(...uu(y.isError?"TOOL_ERROR":"TOOL_OUTPUT",ou(y)))}return o.map((g,y)=>({chunk:e.id,line:y,...g}))}function El(e,o){let i=e.find((u)=>u.entry.seq===o);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return uu("USER",Ps(i.raw)).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function Sl(e,o){let i=e.find((u)=>u.entry.seq===o)?.entry;if(i?.type!=="extension"||!i.display)return;return uu("EXTENSION",i.display.text).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function Bc(e,o=""){return e.map((i,u)=>{let p=e[u-1],g=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${o}${g?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
89
+ `)}import{join as Cg}from"path";import{existsSync as ZC}from"fs";import{realpath as e$}from"fs/promises";import{dirname as t$,isAbsolute as TB,join as r$,relative as RB,resolve as Vh,sep as kB}from"path";import{existsSync as uB,watch as cB}from"fs";import{readdir as mB,stat as pB}from"fs/promises";import{basename as Bh,dirname as lB,join as LC,resolve as dB}from"path";class Gh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,i,u=150){this.host=e;this.slots=o;this.watching=i;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let i=[],u=[];for(let b of[...new Set(e)]){let E;try{E=await mB(b)}catch(S){if(S instanceof Error&&"code"in S&&S.code==="ENOENT")continue;throw S}for(let S of E.sort()){let w=LC(b,S),R=(await pB(w)).isDirectory()?LC(w,"index.ts"):w;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(A){let P=Bh(R)==="index.ts"?Bh(lB(R)):Bh(R,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let C={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};i.push({definition:C,path:R}),this.slots.set(P,{definition:C,path:R,enabled:!0,discoveryFailed:!0,error:A instanceof Error?A.message:String(A)})}}}let p=o.filter((b)=>![...u,...i].some((E)=>E.definition.id===b.definition.id)),g=[...p,...u],y=this.order(g.map(({definition:b})=>b));for(let b of y){let E=g.find((w)=>w.definition===b)?.path,S=p.some((w)=>w.definition===b);try{await this.host.install(b,E,S)}catch(w){this.slots.set(b.id,{definition:b,path:E,builtin:S,enabled:!0,error:w instanceof Error?w.message:String(w)})}}if(this.watching())for(let b of[...g,...i]){if(!uB(b.path))continue;let E=cB(b.path,()=>{let S=b.definition.id,w=this.debounceTimers.get(S);if(w)clearTimeout(w);let R=setTimeout(()=>{this.debounceTimers.delete(S),this.host.reload(S).catch((A)=>{let P=this.slots.get(S);if(P)P.error=A instanceof Error?A.message:String(A)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(S,R)});E.on("error",(S)=>{let w=this.slots.get(b.definition.id);if(w)w.error=S.message,this.host.changed()}),this.watchers.push(E)}}order(e,o=!1){let i=new Map;for(let b of e){if(this.validate(b),i.has(b.id)||!o&&this.slots.has(b.id))throw Error(`Duplicate plugin: ${b.id}`);i.set(b.id,b)}let u=[],p=new Set,g=new Set,y=(b)=>{if(g.has(b.id))return;if(p.has(b.id))throw Error(`Plugin dependency cycle: ${b.id}`);p.add(b.id);for(let E of b.deps??[]){let S=i.get(E);if(S)y(S);else if(!this.slots.has(E))throw Error(`Missing plugin dependency: ${E}`)}p.delete(b.id),g.add(b.id),u.push(b)};for(let b of e)y(b);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${dB(e)}?v=${++this.revision}`);if(!o.default)throw Error("Plugin module must export a default definition");return this.validate(o.default),o.default}}async function NC(e,o,i=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,p;try{return await Promise.race([i?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((g,y)=>{p=setTimeout(()=>{u.abort(),y(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as fB}from"async_hooks";import{isDeepStrictEqual as DC}from"util";var Ia=new fB;function Cs(){let e=Ia.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function mu(e){let o=structuredClone(e),i=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let p of Object.values(u))i(p)};return i(o),o}function qC(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let E of["seq","time","session_id","raw"])if(E in o)throw Error(`Entry replacement contains protected field: ${E}`);let i=JSON.parse(JSON.stringify(o,(E,S)=>{if(typeof S==="function"||typeof S==="symbol"||typeof S==="number"&&!Number.isFinite(S))throw Error("Entry replacement must contain JSON values");return S}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let u=i,p=[];switch(e.type){case"user":p.push("text","attachments");break;case"assistant":p.push("parts","error");break;case"tool_result":p.push("output","images");break;case"extension":p.push("payload","display");break;case"notice_pending":p.push("notice");break;case"run":if(e.state==="end")p.push("error");break;case"compaction":break}let g={...e};for(let E of new Set([...Object.keys(e),...Object.keys(u)])){if(!p.includes(E)&&!DC(g[E],u[E]))throw Error(`Entry replacement changed protected field: ${E}`);if(["seq","time","session_id","raw"].includes(E))throw Error(`Entry replacement contains protected field: ${E}`)}let y=(E)=>E===void 0||typeof E==="string",b=!0;switch(e.type){case"user":b=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((E)=>E&&typeof E.name==="string"&&typeof E.mimeType==="string"&&Qc.includes(E.kind)&&typeof E.data==="string"));break;case"assistant":b=y(u.error)&&Array.isArray(u.parts)&&u.parts.every((E)=>E&&(["text","thinking"].includes(E.type)&&typeof E.text==="string"||E.type==="tool_call"&&typeof E.id==="string"&&typeof E.name==="string"&&("input"in E)));break;case"tool_result":b=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((E)=>E&&typeof E.mimeType==="string"&&typeof E.data==="string"));break;case"extension":{let E=u.display;b="payload"in u&&(E===void 0||E!==null&&typeof E==="object"&&("text"in E)&&typeof E.text==="string"&&(!("title"in E)||y(E.title)));break}case"notice_pending":{let S=["text"],w=g.notice,R=u.notice;if(b=!!R&&typeof R==="object"&&!Array.isArray(R),!b)break;let A=R;for(let P of new Set([...Object.keys(w),...Object.keys(A)]))if(S.includes(P)){if(typeof A[P]!=="string")b=!1}else if(!DC(w[P],A[P]))b=!1;break}case"run":b=y(u.error);break;case"compaction":break}if(!b)throw Error("Invalid entry replacement content");return i}function FC(e,o,i,u,p,g){let y=u;for(let b of i.generations)for(let E of b.hooks.get("entry.before_append")??[]){if(b.disabled)break;let S={phase:"before",violated:!1};try{let w=Ia.run(S,()=>{let R=mu(y),A=performance.now(),P=E(R,{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 C=P===void 0?void 0:qC(y,P);if(S.violated)throw Error("entry.before_append attempted a database write");return{validated:C,slow:performance.now()-A>e}});if(w.validated&&JSON.stringify(w.validated)!==JSON.stringify(y))y=w.validated;if(w.slow)throw Error("entry.before_append exceeded budget");b.beforeFailures=0,b.failures=0}catch(w){b.failures=b.beforeFailures++,o(b,w)}}return y}function hB(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return mu(o);return structuredClone(o)}async function jC(e,o,i,u,p,g,y,b,E="end"){let S=g;for(let w of u){if(w.disabled)continue;let R=w.hooks.get(p)??[];for(let A of R){if(w.disabled)break;let P=w.hookOptions.get(A);if(p==="prompt.fragments"&&(P?.promptPosition??"end")!==E)continue;let C=p==="prompt.fragments"?JSON.stringify([y?.id,S]):void 0,q=C===void 0?void 0:w.promptCache.get(A)?.get(C);try{let X=hB(p,S),j=P?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:y,connection:b}):j,J=await o((ee)=>A(X,{runtime:e.runtime,session:y,connection:b,signal:ee}),V);if(C!==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 ae=w.promptCache.get(A)??new Map;ae.set(C,[...ee]),w.promptCache.set(A,ae)}if(w.failures=0,J!==void 0&&p!=="entry.after_append")S=J}catch(X){if(q)S=structuredClone(q);if(i(w,X),P?.errorMode==="propagate")throw X}}}return S}class Gc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,i,u,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,i,u,p)}has(e,o){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((u)=>o===void 0||(i.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...i)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((i)=>i(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let u of i.historyResolvers){let p=u(e,o);if(p)return p}}}policy(e){return this.generations.findLast((o)=>!o.disabled&&o.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as gB}from"fs";import{dirname as yB,resolve as UC}from"path";var Kh=new WeakMap;function BC(e){return[...e].map((o)=>{let i=Boolean(o.path&&(Boolean(o.definition.webEntry)||gB(UC(yB(UC(o.path)),"web.tsx"))));if(o.current&&!Kh.has(o.current))Kh.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:i,webRevision:o.current?Kh.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class Hh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,i){this.host=e;this.deadline=o;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,i){let u=this.host.pin(),p=(async()=>{try{let g=[];for(let y of u.generations){if(y.disabled)continue;for(let b of y.hooks.get(e)??[]){let E=y.hookOptions.get(b)?.timeoutMs,S=typeof E==="function"?E({runtime:this.host.runtime,session:o,connection:i}):E;g.push(this.deadline((w)=>b(o,{runtime:this.host.runtime,session:o,connection:i,signal:w}),S,!0).catch((w)=>this.fail(y,w)))}}await Promise.all(g)}finally{await u.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,o,i){let u=i===void 0?void 0:mu(i),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Ia.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,p),this.pending.add(p);let g=()=>{if(this.pending.delete(p),this.entryQueues.get(o)===p)this.entryQueues.delete(o)};p.then(g,g)}}function GC(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 xB(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 IB(e,o){let i=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!i)throw Error("Completion session not found");let u=o.model??i?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=En(e.options.models,u);if(!p&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!p){let g=(await e.models()).models.filter((b)=>b.available===!0),y=p?tt(p):u;if(!g.some((b)=>b.id===y)){let b=g[0];if(b)p=En(e.options.models,b.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function KC(e,o){xB(o);let i=await IB(e,o),u=o.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>i.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let p="",g=!1;try{let y=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],b=e.options.models.streamSimple(i,{messages:y},{maxTokens:u,signal:o.signal});for await(let E of b){if(o.signal?.aborted)throw Error("cancelled");if(E.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${GC(E.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(E.type==="text_delta")p+=E.delta;if(E.type==="done"){if(E.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(E.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${E.reason}\uFF09`);g=!0}}}catch(y){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${GC(y instanceof Error?y.message:String(y))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!g)throw Error("Model completion ended without a stop response; retry");return{text:p,model:tt(i)}}var bB=["active","archived","all"];function HC(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function EB(e){let{projectID:o,children:i,archive:u,since:p}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!bB.includes(u))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 SB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function WC(e){function o(i,u={}){let{types:p,bodies:g}=u;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let y=HC(u.limit),b=u.after??0;if(!Number.isSafeInteger(b)||b<0)throw Error("sessions after must be a non-negative integer");let E=(e.get(i)?.entries(b)??[]).filter((S)=>p===void 0||p.includes(S.type)).slice(0,y);return structuredClone(g===!1?E.map(SB):E)}return{list(i={}){EB(i);let u=i.limit===void 0?void 0:HC(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(u===void 0?p:p.slice(0,u))},get(i){return structuredClone(e.get(i)?.info())},entries:o}}async function zC(e,o,i,u,p,g){let y={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},b=e.runtime.store.db,E=new Map,S=!1,w=!0,R=()=>{if(!w||y.disposed)throw Error("Plugin registration scope is closed")},A=(j,V)=>{if(R(),!S){E.set(j,V);return}if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)},P={get:(j)=>{R();let V=E.has(j)?E.get(j):b.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");A(j,J)},delete:(j)=>A(j,null)},C=()=>{if(R(),S)throw Error("Register resources during setup only")},q=[...o.migrations??[]].sort((j,V)=>j.version-V.version),X=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||X.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(X.add(j.version),b.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,j.version))continue;b.transaction(()=>{if(j.sql!==void 0)b.run(j.sql);else j.up({...P,db:b});for(let[V,J]of E)if(J===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,J);b.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,j.version)})(),e.runtime.store.invalidateEntryCache(),E.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:WC(e.runtime),complete:(j)=>KC(e.runtime,j),kv:P,database:b,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{C(),y.gates.push(j)},registerNoticeSource:(j,V)=>{if(C(),!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(C(),j.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(y.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);y.services.set(j.name,V)},on:(j,V,J)=>{if(C(),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)=>{C(),y.historyResolvers.push(j)},registerTool:(j,V)=>{if(C(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||wB(e,p,o.id).has(j.name.toLowerCase())||y.tools.some((ee)=>ee.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let J=i?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;y.tools.push({...j,defer:J,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(C(),!(j.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>j.path===V||j.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(j.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(y.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");y.routes.push(j)},registerWebSocket:(j)=>{if(C(),!j.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(y.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");y.websockets.push(j)},registerCommand:(j)=>{C(),y.commands.push(j)},registerWebContribution:(j)=>{C(),y.web.push(j)},registerToolPolicy:(j,V)=>{C(),y.policies.set(j,V)},appendExtension:(j,V)=>{if(Cs(),R(),!S)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{C(),y.deactivators.push(j)},onDispose:(j)=>{C(),y.disposers.push(j)}})),b.transaction(()=>{for(let[j,V]of E)if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)})(),E.clear(),S=!0,y}catch(j){throw w=!1,await g(y),j}}function wB(e,o,i){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,g]of o){if(p===i)continue;for(let y of g.current?.tools??[])u.add(y.name.toLowerCase())}return u}class Wh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(i){e.error=i instanceof Error?i.message:String(i)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(i){e.error=i instanceof Error?i.message:String(i)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function VC(e,o,i,u){for(let p of o){let g=p.current;if(!g||g.disabled||g.retired)continue;let y=g.websockets.find((b)=>b.path===u);if(!y)continue;return{connect:(b)=>{let E=!1;g.references++,g.connections.add(b);let S={send:(R)=>{if(E||g.retired||g.disabled)return;b.send(R)},close:(R,A)=>b.close(R,A)},w=async(R)=>{if(E||g.retired||g.disabled){b.close(1012,"Plugin unavailable");return}try{await i(R),g.failures=0}catch(A){if(g.failures++,g.error=A instanceof Error?A.message:String(A),b.close(1011,"Plugin callback failed"),g.failures>=e.failureThreshold){g.disabled=!0;for(let P of g.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>w(()=>y.open?.(S)),message:(R)=>w(()=>y.message(S,R)),close:async()=>{if(E)return;E=!0,g.connections.delete(b);try{await i(()=>y.close?.(S))}catch(R){g.error=R instanceof Error?R.message:String(R)}finally{g.references--,await e.collect(g)}}}}}}return}function zh(e,o){let i=e.split("/"),u=new URL(o.url).pathname.split("/");if(i.length!==u.length)return;let p={};return i.every((y,b)=>{let E=u[b];if(E===void 0)return!1;if(!y.startsWith(":"))return E===y;try{p[y.slice(1)]=decodeURIComponent(E)}catch{return!1}return E.length>0})?p:void 0}async function JC(e,o,i,u,p){let g=e.pin();try{let y=g.generations.find((b)=>b.definition.id===i)?.commands.find((b)=>b.id===u);if(!y)throw new f("Plugin command is unavailable");return await o(()=>y.execute(p))}finally{await g.release()}}function QC(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((p)=>p.method===o.method&&zh(p.path,o)!==void 0))}finally{i.release()}}function XC(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((p)=>p.public===!0&&p.method===o.method&&zh(p.path,o)!==void 0))}finally{i.release()}}async function YC(e,o,i){let u=e.pin(),p=!0;try{for(let g of u.generations)for(let y of g.routes){if(y.method!==i.method)continue;let b=zh(y.path,i);if(b){let E=await o(()=>y.handler(i,b),y.timeoutMs);if(!E)return;if(E.body&&E.body instanceof ReadableStream){p=!1;let S=!1,w=()=>{if(S)return;S=!0,u.release()},R=E.body.getReader(),A=new ReadableStream({async pull(P){try{let{done:C,value:q}=await R.read();if(C)P.close(),w();else P.enqueue(q)}catch(C){P.error(C),w()}},async cancel(P){try{await R.cancel(P)}finally{w()}}});return new Response(A,{status:E.status,statusText:E.statusText,headers:E.headers})}return E}}return}finally{if(p)await u.release()}}class Jh{runtime;options;slots=new Map;retirement=new Wh(this.deadline.bind(this));observers=new Hh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new pl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,o={}){this.runtime=e;this.options=o;if(o.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(o.beforeAppendBudgetMs)||o.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new Gh(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=o.current.services.get(e.name);if(!e.validate(i))throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let i of e)this.directories.add(Vh(i));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await e$(e),i=[...this.directories,r$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>r$(u.directory,".basalt","plugins"))];for(let u of i){if(!ZC(u))continue;let p=RB(await e$(u),o);if(p&&p!==".."&&!p.startsWith(`..${kB}`)&&!TB(p)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),i=await this.checkEntry(o);if(!i.ok)throw new pt(i.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,i)})}async installDefinition(e,o,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:o,builtin:i,enabled:u?.enabled!==0};if(p.enabled)p.current=await this.stage(e,i);this.slots.set(e.id,p)}reload(e){return this.exclusive(async()=>{let o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let b=await this.checkEntry(o.path);if(!b.ok)throw new pt(b.errors)}let i=o.builtin&&!ZC(o.path)?o.definition:await this.catalog.read(o.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((b)=>b.definition.id===e?i:b.definition),!0),p=await this.stage(i),g=o.current;o.definition=i,o.current=p,o.error=void 0,o.discoveryFailed=!1;let y=new Map(this.slots);this.slots.clear();for(let b of u){let E=y.get(b.id);if(E)this.slots.set(b.id,E)}if(g)await this.retirement.retire(g)}catch(i){throw o.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,o){return this.exclusive(async()=>{let i=this.require(e);if(o===i.enabled&&(!o||i.current&&!i.current.disabled))return;if(!o){for(let y of this.slots.values())if(y.enabled&&y.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${y.definition.id}`)}let u=o&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let p=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let g=i.current;if(i.definition=u,o)i.discoveryFailed=!1;if(i.enabled=o,i.current=p,i.error=void 0,g)await this.retirement.retire(g)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let i of e.deps??[])if(i===e.id||!this.slots.get(i)?.current||this.slots.get(i)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${i}`);return zC(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,i){this.observers.notify(e,o,i)}resolveHistory(e,o){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let u of i.current.historyResolvers){let p=u(e,o);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Gc(this,e)}async invoke(e,o,i,u,p,g="end"){return jC(this,this.deadline.bind(this),this.fail.bind(this),e,o,i,u,p,g)}pinEntry(e){if(Ia.getStore()?.phase==="after")return;let o;for(let i of this.slots.values()){let u=i.current;if(!i.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Gc(this,o)}beforeEntry(e,o,i,u){return FC(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,i,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,i){this.observers.finishEntry(e,o,i)}deadline(e,o=this.timeoutMs,i=!1){return NC(e,o,i)}appendExtension(e,o){return Cs(),new Promise((i)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),i(p)})}list(){return BC(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(i&&o.path)await this.webBuilder.build(i,t$(Vh(o.path)));return{ok:!0}}catch(o){if(o instanceof ml)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!i)return;return this.webBuilder.build(i,t$(Vh(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let i=await this.webBuilder.entry(o.path,o.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,o,i){return JC(this,this.deadline.bind(this),e,o,i)}hasRoute(e){return QC(this,e)}isPublicRoute(e){return XC(this,e)}route(e){return YC(this,this.deadline.bind(this),e)}websocket(e){return VC(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 AB}from"path";var PB=500,CB=1000,$B=3600000,vB=5000,MB=2000,OB=3,_B=1073741824;class Qh{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=AB(e.dataDir,Si),this.features={...wi(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,i=o?.backfill;if(!o||!i)return{...e,state:"backfilling"};if(i.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=n$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=n$(this.options.store.path).size}catch{}return Math.max(_B,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(),Yn(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.worker;if(!o)return e();Atomics.store(this.flags,He,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Et,0,vB);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??=vi(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,He,0),Atomics.store(this.flags,Et,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<OB&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He);let o=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(MB)]),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,PB-(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)Yn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),$B),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,CB-(performance.now()-this.lastPush)),i=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),p=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(u)};if(o===0)i();else this.statusTimer=setTimeout(i,o),this.statusTimer.unref?.()}}import{existsSync as du,mkdirSync as jB,readdirSync as p$,readFileSync as a$,realpathSync as Xh,statSync as Al,writeFileSync as Yh}from"fs";import{dirname as kl,isAbsolute as Zh,relative as l$,resolve as UB}from"path";import{existsSync as Kc}from"fs";import{dirname as FB,join as lu}from"path";import{mkdirSync as LB,writeFileSync as NB}from"fs";import{tmpdir as DB}from"os";import{join as o$}from"path";var wl=2000,Te=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function pu(e,o){return e.map((i,u)=>{let p=i.length>wl?`${i.slice(0,wl)}\u2026 [line truncated]`:i;return`${String(o+u).padStart(6)} ${p}`}).join(`
90
+ `)}function de(e,o){if(e.length<=o)return e;let i=Math.floor(o*0.4),u=o-i,p=e.length-i-u,g=e.slice(i,e.length-u).split(`
91
+ `).length-1;return`${e.slice(0,i)}
92
+
93
+ \u2026 [${p} characters, ~${g} lines omitted] \u2026
94
+
95
+ ${e.slice(-u)}`}var qB=0;function rt(e,o,i){if(e.length<=o)return e;let u=de(e,o);try{let p=i?sd(i):o$(DB(),"basalt-output");LB(p,{recursive:!0});let g=o$(p,`${process.pid}-${Date.now().toString(36)}-${qB++}.txt`);return NB(g,e),`${u}
96
+ [Full output saved to ${g}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var s$=120000,i$=600000,ba;function tr(){if(ba!==void 0)return ba||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let p=lu(u,"bash.exe");if(Kc(p))return ba=p,p}for(let u of o){let p=lu(u,"git.exe");if(Kc(p)){let g=FB(u),y=lu(g,"bin","bash.exe");if(Kc(y))return ba=y,y;let b=lu(g,"usr","bin","bash.exe");if(Kc(b))return ba=b,b}}let i=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?lu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?lu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of i)if(Kc(u))return ba=u,u;ba="";return}class Tl{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let i=0;while(i<o.length){if(o[i]<128){i+=1;continue}let p=o[i+1];if(p===void 0)break;let g=p>=48&&p<=57?4:2;if(i+g>o.length)break;i+=g}return this.gbkPending=o.slice(i),this.gbk.decode(o.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let i=new Uint8Array(this.sniffPending.length+e.length);if(i.set(this.sniffPending),i.set(e,this.sniffPending.length),i.length<2)return this.sniffPending=i,"";this.sniffPending=void 0;let u=i[0]===255&&i[1]===254,p=!1;for(let g=1;g<i.length;g+=2)if(i[g]===0){p=!0;break}this.isUtf16=u||p,o=i}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Ea(e,o){let i=process.platform==="win32",u=o??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[tr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=tr();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,o){let i=await je(e,o.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:u,isWindows:p}=Ea(e,o.shell),g=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,...em(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((ee)=>ee.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),y=!1,b=()=>{try{if(p)g.kill();else process.kill(-g.pid,"SIGKILL")}catch{}},E=setTimeout(()=>{y=!0,b()},o.timeout);o.signal?.addEventListener("abort",b,{once:!0});let S=Te*2,w="",R="",A=0,P=0,C="",q=(ee=!1)=>{let ae=A-w.length-R.length,H=ae>0?`${w}
97
+ \u2026 [${ae} characters omitted] \u2026
98
+ ${R}`:w+R;if(!ee)return de(H,Te);return rt(C.length===A?C:H,Te,o.cwd)},X=()=>{let ee=new Tl;return async(ae)=>{for await(let ue of ae){let he=ee.decode(ue);if(A+=he.length,C.length<4000000)C+=he;if(w.length<S)w+=he;else R=(R+he).slice(-S);if(o.onOutput){let $e=performance.now();if($e-P>=80)P=$e,o.onOutput(q())}}let H=ee.flush();if(H){if(A+=H.length,C.length<4000000)C+=H;if(w.length<S)w+=H;else R=(R+H).slice(-S)}}},j=Promise.all([X()(g.stdout),X()(g.stderr)]),V=await g.exited;if(clearTimeout(E),o.signal?.removeEventListener("abort",b),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
99
+ [background processes are still running; their later output is not captured]`;return{output:q(!0),code:y?null:V,timedOut:y}}class eg{seen=new Map;mark(e,o=Al(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Al(e).mtimeMs!==o?"changed":void 0}}var u$=2000,BB=500,GB=10485760,Rl=20,KB=6,HB=40000,WB=80000;function zB(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,o,i=[],u){let p=(C)=>Zh(C)?C:UB(e,C),g=(C)=>{let q=l$(e,C);return q&&!q.startsWith("..")&&!Zh(q)?q:C},y=(C)=>{let q=C;while(!du(q)&&kl(q)!==q)q=kl(q);let X=Xh(q);if(i.some((j)=>du(j)&&m$(Xh(j),X))&&!m$(Xh(e),X))throw Error("External directories are read-only")},b=(C,q,X)=>{let j=p(C);if(!du(j))throw Error(`No such file or directory: ${j}${XB(j)}`);let V=Al(j);if(V.isDirectory()){let pe=p$(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),qe=pe.slice(0,BB),xt=pe.length-qe.length;return c(`${qe.join(`
100
+ `)}${xt>0?`
101
+ \u2026 and ${xt} more entries`:""}`||"(empty directory)").content}let J=a$(j),ee=zB(J);if(ee){if(V.size>GB)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return o.mark(j),[{type:"text",text:`Read image ${g(j)} (${ee}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:ee}]}if(J.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);o.mark(j);let ae=J.toString("utf8");if(!ae)return c("(empty file)").content;let H=ae.replace(/\r?\n$/,"").split(/\r?\n/),ue=(q??1)-1;if(ue>=H.length)throw Error(`offset ${q} is past the end of the file (${H.length} lines)`);let he=Math.min(H.length,ue+(X??u$)),$e=0,Ee=ue;while(Ee<he){let pe=H[Ee]?.length??0;if(Ee>ue&&$e+pe>HB)break;$e+=pe,Ee++}let se=pu(H.slice(ue,Ee),ue+1);if(Ee<he)se+=`
102
+
103
+ (Showing lines ${ue+1}-${Ee} of ${H.length} (truncated at line ${Ee} due to safety budget). Use offset/limit to read specific windows.)`;else if(ue>0||Ee<H.length)se+=`
104
+
105
+ (Showing lines ${ue+1}-${Ee} of ${H.length}. Use offset/limit to read other parts.)`;return c(se).content},E=x({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
106
+ - path may be absolute or relative to the working directory.
107
+ - By default reads up to ${u$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
108
+ - Lines longer than ${wl} 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 ${Rl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
112
+ - Always read a file before editing or overwriting it.`,parameters:l({path:n(a({description:"File or directory path"})),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"})),paths:n(B(l({path:a({description:"File or directory path"}),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:Rl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(C,q){let X=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(X.length===0)throw Error("Give path, or paths to read several files");if(X.length===1){let ae=X[0];return{content:b(ae.path,ae.offset,ae.limit),details:void 0}}if(X.length>Rl)throw Error(`Read at most ${Rl} paths per call`);let j=[],V=[],J=0,ee=(ae)=>{let H=j.at(-1);if(ae.type==="text"&&H?.type==="text")H.text+=`
113
+
114
+ ${ae.text}`;else j.push(ae)};for(let ae of X){let H=`==> ${g(p(ae.path))} <==`;if(J>=WB){ee({type:"text",text:`${H}
115
+ (Skipped due to total read safety budget; read in separate calls)`});continue}try{let ue=b(ae.path,ae.offset,ae.limit);for(let he=0;he<ue.length;he++){let $e=ue[he];if(!$e)continue;if($e.type==="text")J+=$e.text.length,ee(he===0?{...$e,text:`${H}
116
+ ${$e.text}`}:$e);else ee($e)}}catch(ue){let he=ue instanceof Error?ue.message:String(ue);V.push(he),ee({type:"text",text:`${H}
117
+ Error: ${he}`})}}if(V.length===X.length)throw Error(V.join(`
118
+ `));return{content:j,details:void 0}}}),S=async(C,q,X,j)=>{let V=j?.update,J=await rr(C,{cwd:e,timeout:120000,signal:X,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:V?(he)=>V(c(`${j.prefix}
119
+
120
+ $ ${C}
121
+ ${he.trimEnd()}`)):void 0}),ee=J.output.trimEnd()||"(no output)",ae=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,H=J.timedOut||J.code!==0,ue=H?`
122
+ ${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
123
+
124
+ $ ${C}
125
+ ${ee}
126
+ [${ae}]${ue}`,failed:H}},w=(C,q=!1)=>{let X=o.check(C);if(X==="changed")return`Note: ${g(C)} 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(C)} existed and had not been read; it was replaced whole.`;return},R=x({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
127
+ - An existing file is replaced whole, including changes made since you last read it.
128
+ - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
129
+ - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
130
+ - Do not create documentation or README files unless asked.`,parameters:l({path:a({description:"File path"}),content:a({description:"The full file content"}),then_run:n(a({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(C,q,X,j){let V=p(q.path);y(V);let J=du(V),ee;if(J){if(Al(V).isDirectory())throw Error(`${V} is a directory`);ee=w(V,!0)}jB(kl(V),{recursive:!0}),Yh(V,q.content),o.mark(V);let ae=q.content?q.content.split(`
131
+ `).length:0,H=`${J?"Overwrote":"Created"} ${g(V)} (${ae} lines)${ee?`
132
+ ${ee}`:""}`;if(q.then_run){let ue=await S(q.then_run,`${g(V)} was written as given`,X,{prefix:H,update:j});if(H+=ue.out,ue.failed)return{...c(H),isError:!0}}return c(H)}}),A=(C,q,X,j)=>{let V=p(C);if(!du(V))throw Error(`File not found: ${V} (use write to create it)`);y(V);let J=w(V),ee=a$(V,"utf8"),ae=ee,H=ae.includes(`\r
133
+ `),ue=[],he=[],$e=0,Ee=0;return q.forEach((se,pe)=>{let qe=j?`edits[${X+pe}]: `:"";try{if(se.old_string===se.new_string)throw Error(`${qe}old_string and new_string are identical`);if(!se.old_string)throw Error(`${qe}old_string is empty (use write to create or replace a whole file)`);let xt=H&&!se.old_string.includes(`\r
134
+ `),Je=xt?se.old_string.replace(/\n/g,`\r
135
+ `):se.old_string,Yt=xt?se.new_string.replace(/\n/g,`\r
136
+ `):se.new_string,Fe=VB(ae,Je).map((At)=>[At,At+Je.length]);if(Fe.length===0)Fe=JB(ae,Je);if(Fe.length===0)throw Error(`${qe}old_string not found in ${g(V)}; read the relevant lines and copy the exact text.${QB(ae,Je)}`);if(Fe.length>1&&!se.replace_all){let At=Fe.map(([st])=>c$(ae,st)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${At}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=c$(ae,Fe[0][0]),Dt=se.replace_all?Fe:[Fe[0]],lt="",Mt=0;for(let[At,st]of Dt)lt+=ae.slice(Mt,At)+Yt,Mt=st;ae=lt+ae.slice(Mt),$e++,Ee+=Dt.length;let yr=ae.split(/\r?\n/),pr=Ue+Yt.split(/\r?\n/).length-1,jt=Math.max(1,Ue-1),ot=Math.min(yr.length,pr+1);if(ot-jt+1<=KB+2)ue.push(pu(yr.slice(jt-1,ot),jt));else ue.push(`${pu(yr.slice(jt-1,Ue+1),jt)}
137
+ \u2026 (${pr-Ue-3} lines as given)
138
+ ${pu(yr.slice(pr-2,ot),pr-1)}`)}catch(xt){he.push(xt instanceof Error?xt.message:String(xt))}}),{path:V,original:ee,content:ae,echoes:ue,applied:$e,total:Ee,count:q.length,note:J,failed:he}},P=x({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
139
+ - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
140
+ - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
141
+ - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
142
+ - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
143
+ - To create a file use write; to delete or move files use bash.
144
+ - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
145
+ - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(a({description:"File path (the default for edits items without their own path)"})),old_string:n(a({description:"The exact text to replace (only when edits is absent)"})),new_string:n(a({description:"The replacement text (only when edits is absent)"})),replace_all:n(O({description:"Replace every occurrence (default false)"})),edits:n(B(l({path:n(a({description:"The file of this replacement, when it is not path"})),old_string:a({description:"The exact text to replace"}),new_string:a({description:"The replacement text"}),replace_all:n(O({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(a({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(C,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,pe)=>{if(!se.path)throw Error(`${J?`edits[${pe}]: `:""}path is required`);let qe=p(se.path),xt=ee.get(qe)??{raw:se.path,steps:[],offset:pe};xt.steps.push(se.step),ee.set(qe,xt)});let ae=[],H=[];for(let se of ee.values())try{let pe=A(se.raw,se.steps,se.offset,J);if(pe.applied>0)ae.push(pe);H.push(...pe.failed)}catch(pe){let qe=pe instanceof Error?pe.message:String(pe);H.push(`${J?`edits[${se.offset}]: `:""}${qe}`)}if(ae.length===0)throw Error(H.join(`
146
+ `));let ue=[];try{for(let se of ae)Yh(se.path,se.content),ue.push(se)}catch(se){for(let pe of ue)Yh(pe.path,pe.original);throw se}for(let se of ae)o.mark(se.path);let $e=ae.map((se)=>{let pe=se.total===1?"1 occurrence":`${se.total} occurrences`,qe=se.note?`
147
+ ${se.note}`:"";if(!J)return`Edited ${g(se.path)} (${pe}).${qe}
148
+ ${se.echoes[0]}`;let xt=se.failed.length>0?`, ${se.failed.length} failed`:"";return`Edited ${g(se.path)} (${se.applied} edits${xt}, ${pe}). 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
+ `),Ee=!1;if(q.then_run){let se=await S(q.then_run,"The edits above were applied",X,{prefix:$e,update:j});if($e+=se.out,se.failed)Ee=!0}if(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
+ - `)}`,Ee=!0;return Ee?{...c($e),isError:!0}:c($e)}});return[_e(E,"cat","view","read_file","view_file","open_file","open"),_e(R,"write_file","create_file","new_file","save_file"),_e(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function VB(e,o){let i=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))i.push(u);return i}function c$(e,o){let i=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)i++;return i}function JB(e,o){let i=o.replace(/\r?\n$/,"").split(/\r?\n/).map((E)=>E.trimEnd()),u=[],p=e.split(`
158
+ `),g=0;for(let E of p)u.push(g),g+=E.length+1;let y=p.map((E)=>E.replace(/\r$/,"").trimEnd()),b=[];for(let E=0;E+i.length<=y.length;E++)if(i.every((S,w)=>y[E+w]===S)){let S=E+i.length-1,w=u[S]+p[S].replace(/\r$/,"").length,R=o.endsWith(`
159
+ `)&&w<e.length?e[w]==="\r"?2:1:0;b.push([u[E],w+R]),E+=i.length-1}return b}function QB(e,o){let i=(b)=>b.replace(/\s+/g," ").trim(),u=i(o);if(!u)return"";let p=e.split(/\r?\n/),g=o.split(/\r?\n/).length;for(let b=0;b+g<=p.length;b++)if(i(p.slice(b,b+g).join(`
160
+ `))===u)return` A match ignoring whitespace exists at line ${b+1}; copy the exact indentation and line breaks from the read output:
161
+ ${de(pu(p.slice(b,b+g),b+1),4000)}`;let y=o.split(/\r?\n/).find((b)=>b.trim())?.trim();if(y){let b=p.findIndex((E)=>E.includes(y));if(b!==-1)return` Its first line appears at line ${b+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function XB(e){let o=kl(e);if(!du(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let p=p$(o).filter((g)=>{let y=g.toLowerCase().replace(/\.[^.]*$/,"");return y&&(y.includes(u)||u.includes(y))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function m$(e,o){let i=l$(e,o);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!Zh(i)}var tg=20,rg=80,YB=5,ZB=(e)=>e!==void 0&&e>0?e:void 0;function f$(e,o){let i=El(e,o)??Sl(e,o);if(!i)throw Error(`No user message with seq ${o}`);return i}function Pl(e,o){let i=(y)=>{if(o)return o(y);if(y.source&&y.source!=="self"||y.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(y)=>{let b=i(y),E=ZB(y.seq);return{scope:b,seq:E,runs:()=>Ks(b.records),reference:`session_id=${b.sessionID}`,both:E!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
162
+ `:""}},p=x({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
163
+ - 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).
164
+ - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),pattern:a({minLength:1,description:"Text to search for"}),also:n(B(a({minLength:1}),{maxItems:YB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(a({description:"Only search this chunk"})),seq:n(_({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(O({description:"Default false"})),head_limit:n(_({minimum:1,maximum:tg,description:`Hits to return (default ${tg})`})),offset:n(_({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(y,b){let{scope:E,seq:S,runs:w,reference:R,both:A}=u(b),P;if(S!==void 0)P=[f$(E.records,S)];else{let ue=w(),he=b.chunk_id?ue.filter(($e)=>$e.id===b.chunk_id):ue;if(b.chunk_id&&!he.length)throw Error(`No chunk ${b.chunk_id}. Chunk IDs look like r12.`);P=he.map(cu)}let C=(ue)=>b.case_sensitive?ue:ue.toLowerCase(),q=[b.pattern,...(b.also??[]).filter(Boolean)].map(C),X=b.head_limit??tg,j=b.offset??0,V=[],J=new Map,ee=0;for(let ue of P)ue.forEach((he,$e)=>{let Ee=C(he.text);if(!q.every((pe)=>Ee.includes(pe)))return;if(J.set(he.chunk,(J.get(he.chunk)??0)+1),ee++,ee<=j||V.length>=X)return;let se=ue.slice(Math.max(0,$e-2),$e+3);V.push(`${R} chunk ${he.chunk} line ${he.line}:
165
+ ${Bc(se," ")}`)});if(!ee)return c(`${A}No matches`);if(!V.length)return c(`${A}No matches at offset ${j} (total ${ee})`);let ae=ee-j-V.length,H=J.size>1?` (all matches by chunk: ${[...J].map(([ue,he])=>`${ue} ${he}`).join(", ")})`:"";return c(`${A}${V.join(`
166
+
167
+ `)}${ae>0?`
168
+
169
+ \u2026 ${ae} more matches${H}; continue with offset=${j+V.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),g=x({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),chunk_id:n(a({description:"Chunk to read"})),seq:n(_({description:"User message to read (from a user-text-reference)"})),offset:n(_({minimum:0,description:"First line (default 0)"})),limit:n(_({minimum:1,maximum:rg,description:`Lines to return (default ${rg})`}))}),async execute(y,b){let{scope:E,seq:S,runs:w,reference:R,both:A}=u(b),P;if(S!==void 0)P=f$(E.records,S);else if(b.chunk_id){let j=w().find((V)=>V.id===b.chunk_id);if(!j)throw Error(`No chunk ${b.chunk_id}. Chunk IDs look like r12.`);P=cu(j)}else{let j=w().map((V)=>`${R} ${V.id} (${V.status}, ${cu(V).length} lines)`);return c(j.length?`Pass chunk_id or seq. Chunks in this session:
170
+ ${j.join(`
171
+ `)}`:"This session has no history yet")}let C=b.offset??0,q=P.slice(C,C+(b.limit??rg));if(!q.length)return c(`No lines at offset ${C} (total ${P.length})`);let X=P.length-C-q.length;return c(`${A}${R} ${S!==void 0?`seq=${S}`:b.chunk_id}
172
+ ${Bc(q)}${X>0?`
173
+
174
+ \u2026 ${X} more lines; continue with offset=${C+q.length}`:""}`)}});return[p,g]}import{statSync as eG}from"fs";import{isAbsolute as h$,relative as tG,resolve as g$}from"path";var Cl=200,rG=30000,$l=Bun.which("rg");async function ng(e,o,i){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,g,y]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(y>1)throw Error(g.trim()||`${e[0]} exited with ${y}`);return p}function y$(e){let o=(g)=>g?h$(g)?g:g$(e,g):e,i=(g)=>{let y=tG(e,g);return y&&!y.startsWith("..")&&!h$(y)?y:g},u=x({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
175
+ - Respects .gitignore and skips .git. Use it instead of find or ls -R.
176
+ - To search file contents, use grep.`,parameters:l({pattern:a({description:"Glob pattern, matched relative to path"}),path:n(a({description:"Directory to search (default: working directory)"}))}),async execute(g,y,b){let E=o(y.path),S;if($l)S=(await ng([$l,"--files","--hidden","--glob","!.git","--glob",y.pattern],E,b)).split(`
177
+ `).filter(Boolean);else{S=[];for await(let P of new Bun.Glob(y.pattern).scan({cwd:E,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(P))S.push(P)}if(!S.length)return c("No files found");let w=S.map((P)=>{let C=g$(E,P);try{return{path:C,time:eG(C).mtimeMs}}catch{return{path:C,time:0}}});w.sort((P,C)=>C.time-P.time);let R=w.slice(0,Cl).map((P)=>i(P.path)),A=S.length-R.length;return c(`${R.join(`
178
+ `)}${A>0?`
179
+ \u2026 ${A} more files; narrow the pattern`:""}`)}}),p=x({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
180
+ - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
181
+ - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
182
+ - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
183
+ - Use this instead of running grep or rg through bash.`,parameters:l({pattern:a({description:"Regular expression"}),path:n(a({description:"File or directory to search (default: working directory)"})),glob:n(a({description:"Only search files matching this glob"})),output:n(m([s("files"),s("content"),s("count")],{description:"Output mode (default files)"})),ignore_case:n(O()),context:n(_({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(g,y,b){let E=o(y.path),S=y.output??"files",w;if($l){let P=[$l,"--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,E),w=await ng(P,e,b)}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,E),w=await ng(P,e,b)}let R=`${e}/`,A=w.split(`
184
+ `).filter(Boolean).map((P)=>P.startsWith(R)?P.slice(R.length):P).filter((P)=>S!=="count"||!P.endsWith(":0"));if(!A.length)return c("No matches");if(S==="files"&&A.length>Cl)return c(`${A.slice(0,Cl).join(`
185
+ `)}
186
+ \u2026 ${A.length-Cl} more files; narrow the search`);return c(rt(A.join(`
187
+ `),rG,e))}});return[_e(u,"find","find_files","list_files","file_search","ls","list","list_dir"),_e(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function x$(e){return _e(x({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
188
+ 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.
189
+ - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
190
+ - 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.
191
+ - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:B(l({content:a({minLength:1,description:"What to do, in imperative form"}),status:m(Fg.map((o)=>s(o)))}))}),async execute(o,i){let u=i.todos.map((y)=>({content:y.content,status:y.status}));e(u);let p=u.filter((y)=>y.status==="completed").length,g=u.find((y)=>y.status==="in_progress");return c(`Todo list updated (${p}/${u.length} completed${g?`; in progress: ${g.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function I$(e){let o=ce(e);return{target:o,hard:o,index:o}}class vl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},i){this.records=e;this.cwd=o;if(i)this.defaultPolicy=new Uc(e,i,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??I$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??ce(e)}prepare(e,o,i,u,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,i,u);let g=e.reduce((S,w)=>S+F(w),0)+Ni(o),y=Math.max(0,ce(i)*this.recoveryRatio-g),b=Re(u??this.records(),i,I$(i),{cwd:this.cwd()}).messages,E=b.reduce((S,w)=>S+F(w),0);if(p&&E>y)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(E>y&&b.length>1){let S=b.shift();if(S)E-=F(S);while(b[0]?.role==="toolResult"){let w=b.shift();if(w)E-=F(w)}}if(E>y){let S=b.at(-1),w=S&&"content"in S&&typeof S.content==="string"?S.content:"[Context omitted: use history tools to retrieve earlier messages.]";b.length=0;let R=w;while(R&&F({role:"user",content:R,timestamp:0})>y)R=R.slice(Math.ceil(R.length/2));if(R)b.push({role:"user",content:R,timestamp:0});E=b.reduce((A,P)=>A+F(P),0)}return this.lastMessageCount=b.length,{messages:[...e,...b],estimate:g+E}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as b$,readFileSync as nG}from"fs";import{homedir as oG}from"os";import{dirname as sG,join as E$}from"path";var iG=`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.
192
+
193
+ # How to work
194
+
195
+ - 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.
196
+ - 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.
197
+ - 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.
198
+ - 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.
199
+
200
+ # Making changes
201
+
202
+ - 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.
203
+ - 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.
204
+ - 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.
205
+ - 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).
206
+ - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
207
+ - 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.
208
+
209
+ # Verifying
210
+
211
+ - 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.
212
+ - 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.
213
+ - 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.
214
+ - 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.
215
+ - 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.
216
+
217
+ # Tools
218
+
219
+ - Tool calls are the only way to act; describing an action does not perform it.
220
+ - 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.
221
+ - 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.
222
+ - 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.
223
+ - 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.
224
+ - 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.
225
+ - 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 &&.
226
+ - 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.
227
+
228
+ # Honesty
229
+
230
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
231
+ - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
232
+ - When the user asks you to run something, run it, even when you can predict the result.
233
+ - If a step failed, was skipped or could not be verified, say which one and why.
234
+
235
+ # Safety
236
+
237
+ - 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.
238
+ - 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.
239
+ - 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.
240
+ - Never print, log or commit secrets such as API keys, tokens or passwords.
241
+
242
+ # Communication
243
+
244
+ - Reply in the same language the user writes in.
245
+ - 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.
246
+ - 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.
247
+ - Do not use emojis unless the user does or asks for them.
248
+ - 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.
249
+ - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,aG=`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.
250
+
251
+ # Tools
252
+
253
+ - 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.
254
+ - 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.
255
+ - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
256
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
257
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
258
+
259
+ # Communication
260
+
261
+ - Reply in the same language the user writes in.
262
+ - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
263
+ - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,uG=["AGENTS.md","CLAUDE.md"],cG=20000;function S$(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?iG:aG}],i=[];if(e.globalInstructions?.trim())i.push(og("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of mG(e.project.directory))i.push(og(u.path,u.content));if(e.project.instructions.trim())i.push(og(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
264
+
265
+ # Instructions from the user and project
266
+
267
+ 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.
268
+
269
+ ${i.join(`
270
+
271
+ `)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
272
+
273
+ ${pG(e)}`}),o}function og(e,o){return`<instructions source="${e}">
274
+ ${de(o.trim(),cG)}
275
+ </instructions>`}function mG(e){let o=[],i=e;for(let u=0;u<20;u++){for(let g of uG){let y=E$(i,g);if(b$(y)){try{o.unshift({path:y,content:nG(y,"utf8")})}catch{}break}}if(b$(E$(i,".git"))||i===oG())break;let p=sG(i);if(p===i)break;i=p}return o}function pG(e){let o=e.now??new Date,i=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:g}=Ea("",e.shell),y=[`Working directory: ${p}`,`Shell: ${g}`,`Date: ${i} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)y.push(e.git??"Git: not a git repository");return`<environment>
276
+ ${y.join(`
277
+ `)}
278
+ </environment>`}async function w$(e){let o=async(...b)=>{try{let E=Bun.spawn(["git",...b],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0}),[S,w]=await Promise.all([new Response(E.stdout).text(),E.exited]);return w===0?S.trim():void 0}catch{return}},i=await o("rev-parse","--abbrev-ref","HEAD");if(i===void 0)return;let[u="",p=""]=await Promise.all([o("status","--short"),o("log","--oneline","-5")]),g=u?u.split(`
279
+ `):[],y=g.length>30?[...g.slice(0,30),`\u2026 ${g.length-30} more`]:g;return[`Git branch: ${i}`,`Git status at session start:${y.length?`
280
+ ${y.join(`
281
+ `)}`:" clean"}`,p?`Recent commits:
282
+ ${p}`:"Recent commits: none"].join(`
283
+ `)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Pl(e.records,e.history):[],u=e.directory??process.cwd();return[...d$(u,new eg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...y$(u),x$(e.onTodos),...i]}class qi{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!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 o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let i=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[u];else i[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let p=u,g=p.source??"core",y=u.name.toLowerCase(),b=p.defer??"always",E="suggestion";if(o.global)b=o.global,E="global";if(Object.hasOwn(o.sources,g))b=o.sources[g]??b,E="source";if(Object.hasOwn(o.tools,y))b=o.tools[y]??b,E="tool";if(g==="core"||p.builtin&&p.defer!=="defer")b="always",E="suggestion";return{name:u.name,source:g,mode:b,origin:E,deferred:b==="defer"}})}}function sg(e){return{name:e.name,description:e.description,parameters:e.parameters}}function ig(e,o){if(!o)return e;let i=Array.isArray(o.type)?o.type:[o.type],u=e;if(i.includes("number")||i.includes("integer")){let p=typeof u==="string"&&u.trim()?Number(u):u;if(typeof p!=="number"||!Number.isFinite(p))return u;let g=p;if(typeof o.maximum==="number"&&g>o.maximum)g=o.maximum;if(typeof o.minimum==="number"&&g<o.minimum)g=o.minimum;return g===p?u:g}if(typeof u==="string"&&(i.includes("object")||i.includes("array")))try{let p=JSON.parse(u),g=Array.isArray(p);if(typeof p==="object"&&p!==null&&!g&&i.includes("object")||g&&i.includes("array"))u=p}catch{}if(Array.isArray(u)){let p=o.items;if(!p||typeof p!=="object"||Array.isArray(p))return u;return u.map((g)=>ig(g,p))}if(typeof u==="object"&&u!==null&&o.properties){let p={...u};for(let[g,y]of Object.entries(o.properties))if(g in p)p[g]=ig(p[g],y);return p}return u}function lG(e){let o=e.prepareArguments;return{...e,prepareArguments:(i)=>{let u=ig(i,e.parameters);return o?o(u):u}}}function dG(e,o,i){let u=e.prepareArguments?e.prepareArguments(i):i;return nu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class ag{retrieved=new Map;stub(e,o){let i=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${i}
284
+ (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,p,g,y)=>{let b=JSON.stringify(sg(e)),E;try{E=dG(e,u,p??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
285
+ Schema: ${b}`),isError:!0}}let S=await e.execute(u,E,g,y),w=S.content.map((R)=>R.type==="text"?{...R,text:rt(R.text,Te,o)}:R);return{...S,content:w}}}}assemble(e,o,i,u){let p=e.map(lG),g=new Set(o.filter((b)=>b.deferred).map((b)=>b.name));if(!g.size)return p;let y=p.filter((b)=>g.has(b.name)&&i(b.name)).sort((b,E)=>b.name<E.name?-1:b.name>E.name?1:0);return[...p.filter((b)=>!g.has(b.name)),...y.map((b)=>this.stub(b,u)),_e(x({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:a(),max_results:n(_({minimum:1,maximum:100}))}),execute:async(b,E)=>{let S=E.query.trim().toLowerCase(),w=S.startsWith("select:")?S.slice(7).split(",").map((A)=>A.trim()):void 0,R=y.filter((A)=>i(A.name)&&(w?w.includes(A.name.toLowerCase()):`${A.name} ${A.description}`.toLowerCase().includes(S))).slice(0,E.max_results??5);return c(JSON.stringify(R.map((A)=>{let P=JSON.stringify(sg(A)),C=this.retrieved.get(A.name);if(C?.schema===P)return{name:A.name,status:"\u5DF2\u53D6\u56DE",callID:C.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(A.name,{schema:P,callID:b}),sg(A)})))}}),"tool_search")]}}async function Ml(e,o,i){let u=await o.setup(e),p=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!i)return u;if(i.has("session.setup"))u=await i.invoke("session.setup",u,e);if(i.has("tools.configure"))u=await i.invoke("tools.configure",u,e);let g=u.systemPrompt,y=u.systemParts?.at(-1);if(y?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let w=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),R=g.length-y.detail.length;g=g.slice(0,R)+w.join("")+y.detail}let b=await i.invoke("prompt.fragments",[],e),E=[...u.tools,...i.tools()],S=i.has("tools.visible")?await i.invoke("tools.visible",E,e):E;return{...u,systemPrompt:g+b.join(""),tools:S}}var fG=3,T$={attempts:1/0,delayMs:2000},hG=/\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 gG(e,o){if(e.stopReason!=="error")return!1;if(ca(e,o))return!1;return!hG.test(e.errorMessage??"")}function R$(e,o,i){if(ca(e,o))return!0;if(i?.preserveHistory!==!0)return!1;return e.errorMessage===(i.overflowError??"Context exceeds the request budget")}function yG(e,o){return new Promise((i,u)=>{if(o.aborted)return u(o.reason);let p=setTimeout(()=>{o.removeEventListener("abort",g),i()},e),g=()=>{clearTimeout(p),u(o.reason)};o.addEventListener("abort",g,{once:!0})})}async function k$(e,o,i,u,p,g,y,b,E=!1){let S=E?void 0:await o?.invoke("run.start",{text:g},e);if(S)g=S.text;if(b.throwIfAborted(),g===void 0)await u.resume();else await u.prompt(g,y);let w=0,R=0;while(w<fG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!R$(q,p.contextWindow,i)){if(!gG(q,p.contextWindow)||R>=T$.attempts)return;R++,await yG(T$.delayMs,b),await u.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}b.throwIfAborted(),w++,await u.retry()}let P=e.records.findLast((C)=>C.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&P?.stopReason==="error"&&R$(P,p.contextWindow,i))throw Error(i.overflowError??"Context exceeds the request budget")}async function A$(e,o,i,u,p,g){g.throwIfAborted();let y,b;try{b=await Promise.race([Ml(e,o,i()),new Promise((A,P)=>{y=()=>P(g.reason),g.addEventListener("abort",y,{once:!0})})])}finally{if(y)g.removeEventListener("abort",y)}g.throwIfAborted();let E=i(),S=(A)=>{if(!E)return A;return{...A,execute:async(P,C,q,X)=>{let j=u()??b.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?E.policy(j):void 0;if(j&&!V?.(A.name,e))throw Error(`Tool ${A.name} is unavailable under tool policy ${j}`);let J=await E.invoke("tool.before_call",{name:A.name,callID:P,args:C},e);if(J.block)throw Error(J.block);let ee=await z.run(e,()=>A.execute(P,J.args,q,X));return E.invoke("tool.after_result",ee,e)}}};if(E)b.tools=b.tools.map(S);let w=b.tools,R=()=>{if(!w.some((P)=>P.name==="history_grep")){if(e.records.some((C)=>C.entry.type==="compaction")){let q=Pl(()=>e.records,(X)=>e.resolveHistory(X)).map(S);for(let X of q)if(!w.some((j)=>j.name===X.name))w.push(X)}}let A=new qi(o.store).partition(w);return b.tools=p.assemble(w,A,(P)=>e.permitsTool(P),b.cwd),b.tools};return b.tools=R(),{setup:b,executionTools:w,assemble:R}}function P$(e,o,i,u,p,g,y){return{response:async(b)=>{let E=await o()?.invoke("model.after_response",b,e)??b;if(E.role==="assistant")for(let S of E.content){if(S.type!=="toolCall"||S.name.toLowerCase()!=="tool_call")continue;let w=S.arguments.name;if(typeof w==="string"){let R=y.find((A)=>A.name.toLowerCase()===w.toLowerCase());S.arguments.name=R?.name??w}}return E},payload:(b)=>o()?.invoke("model.before_request",b,e)??Promise.resolve(b),transformContext:(b)=>o()?.invoke("transformContext",b,e)??Promise.resolve(b),boundary:async()=>{if(u())return!0;let b=await o()?.invoke("step.after",{notices:[]},e);for(let S of b?.notices??[])e.notice(S);await g.work;let E=await g.flushNotices();if(E&&!p())e.agent?.steer(E)},prepare:async(b,E,S)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let w=await o()?.invoke("model.check",{},e);if(w?.error)throw Error(w.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let j of R?.notices??[])e.notice(j);await g.work,await g.flushNotices();let A=await o()?.invoke("projection.before",e.records,e),P=await o()?.invoke("projection.prefix",[],e)??[],C=e.context.prepare([...b,...P],E,S,A,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&C.estimate>ce(S))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=C.messages,X=await o()?.invoke("projection.after",q,e)??q;return au(X)}}}async function C$(e,o,i){let u=o.store.pendingNotices(e.id);if(!u.length)return;let p=u,g=o.plugins?.pin();try{if(g){let P=await g.invoke("notice.deliver",u,e);p=u.map((C,q)=>({...C,text:P[q]?.text??C.text}))}}finally{await g?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let y=p.map((P)=>P.text).join(`
286
+ `),b=p.map((P)=>o.plugins?.noticeSource(P.sourceKind)),E=Math.max(800,...b.map((P)=>P?.summaryLimit??800)),S=y.length>E?`
287
+ [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${b.find((P)=>P?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
288
+ ${y.slice(0,E)}${S}`,A={role:"user",content:R,timestamp:Date.now()};return i({type:"user",text:R,notices:u.map(({text:P,...C})=>C)},A),A}class ug{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,i,u,p,g,y,b){this.session=e;this.context=o;this.isStopped=i;this.isRunning=u;this.waiting=p;this.start=g;this.invalidateAgent=y;this.append=b}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let i of e){if(i.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:i.dedupeKey,sourceKind:i.sourceKind,sourceID:i.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((i)=>i.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((i)=>{this.failure=i}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=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((o)=>o.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var xG=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 cg(e){let o={};for(let[i,u]of Object.entries(e)){if(!xG.has(i.toLowerCase())){o[i]=u;continue}let p=/^bearer\s+/i.exec(u)?.[0];o[i]=p?`${p}***`:"***"}return o}function $$(e,o,i,u){let g=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((H,ue)=>({id:`system-${ue}`,label:H.label,detail:H.detail,tokens:D(H.detail)+(ue===0?16:0)})),y=i.tools.map((H)=>{let ue=H,he=ue.defer==="defer"||H.description.includes("(Parameters not inlined: use toolsearch");return{name:H.name,description:H.description,group:ue.group??"\u5185\u7F6E",schema:H.parameters,deferred:he}});g.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Ni(i.tools),detail:JSON.stringify(y,null,2)});let b=g.reduce((H,ue)=>H+ue.tokens,0),E=u!==void 0?e.records.filter((H)=>H.entry.seq<=u):e.records,S=Re(E,o,e.context.budget(o),{inspect:!0,cwd:i.cwd,trim:{fixed:b,limit:e.context.previewLimit(o)}}),w,R=0,A=0;for(let H of E){if(H.raw?.role!=="assistant")continue;let ue=H.raw.usage;w??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},w.input+=ue.input,w.output+=ue.output,w.cacheRead+=ue.cacheRead,w.cacheWrite+=ue.cacheWrite,w.cost+=ue.cost.total;let he=H.entry.generationMs??H.raw.generationMs;if(typeof he==="number"&&he>0&&ue.output>0)R+=he,A+=ue.output}if(w){let H=w.input+w.cacheRead+w.cacheWrite;if(H>0)w.cacheHitRate=w.cacheRead/H}if(w&&R>0&&A>0)w.generationMs=R,w.tps=Number((A/(R/1000)).toFixed(1));let P=b+S.tokens,C=e.context.calibrationRatio??1,q=Math.round(P*C),X=E.findLast((H)=>H.raw?.role==="assistant"),j=X?.raw,J=(X?E.filter((H)=>H.entry.seq>X.entry.seq&&H.raw):E.filter((H)=>H.raw)).length>0,ee,ae;if(j){let H=j.usage,ue=H.input+H.cacheRead+H.cacheWrite;if(ue>0)ee=ue,ae=H.cacheRead/ue}return{contextWindow:o.contextWindow,usableWindow:ce(o),items:[...g,...S.items],calibratedTokens:q,calibrationRatio:C,lastInputTokens:ee,lastCacheHitRate:ae,hasPendingOutput:J,tools:y,usage:w}}class dt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class ie extends Error{constructor(e="session"){super(`${e} is busy`)}}var mg="medium";class Ol{row;ctx;events;notices;lease;policyID;discovery=new ag;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Ml(this,this.ctx,e);return new qi(this.ctx.store).partition(o.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new ie;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,i){this.row=e;this.ctx=o;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new ug(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let p=this.entries(0,["extension","run"]),g=p.findLast((b)=>b.type==="extension"&&b.namespace==="session"&&b.kind==="stop_requested"),y=p.findLast((b)=>b.type==="run"&&b.state==="start");if(g&&g.seq>(y?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let b=this.records.some((S)=>S.entry.seq>u.seq&&S.entry.type==="user"),E=o.store.pendingNotices(e.id).some((S)=>S.wake&&S.recovery!=="discard");if(!this.stopped&&(b||E))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new vl(()=>this.records,()=>this.cwd,(b,E)=>this.appendCompaction(b,E)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=En(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:cg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:cg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??mg}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:i,model:u,thinking:p,metadata:g,created:y,updated:b,todos:E}=this.row;return{id:e,title:o,projectID:i,model:u,thinking:p??mg,metadata:g,created:y,updated:b,archivedAt:this.row.archivedAt,status:this.status,todos:E,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,o,i){return this.ctx.store.entriesAround(this.row.id,e,o,i)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,i=!0){return this.ctx.store.entries(this.row.id,e,o,i)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let i=En(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 u=this.ctx.plugins?.pin(),p;try{p=this.setup??await Ml(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new qi(this.ctx.store).partition(p.tools),(y)=>this.permitsTool(y),p.cwd);let g=$$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:g};return g})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new dt}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!En(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,Xl(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let i=Xl(o),u=Mh(e,i),p=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},u);if(this.recallableSteers.set(p.seq,u),this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((g)=>g.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let i=o.raw,u=this.pendingSteers.indexOf(i);if(u<0){let g=JSON.stringify(i);u=this.pendingSteers.findIndex((y)=>JSON.stringify(y)===g)}let p=!1;if(u>=0)this.pendingSteers.splice(u,1),p=!0;else p=this.agent?.unsteer(i)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new ie;if(e!==void 0)this.stopped=!1;let u=En(this.ctx.models,this.row.model);if(!u&&i===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let p=new AbortController;if(this.starting=p,!this.row.title&&e!==void 0)this.row={...this.row,title:IG(e,o)},this.ctx.store.updateSession(this.row);let g=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let y=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=y.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let b=this.records.filter((R)=>R.entry.seq>g),E=b.filter((R)=>R.entry.type==="user"&&!R.raw);if(E.length>1)return{reason:"interrupted"};let S=E[0];if(S?.entry.type==="user"){if(b.some((R)=>R.entry.seq>S.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=S.entry.text,o=S.entry.attachments,this.pendingUserSeq=S.entry.seq}for(let R of us(b.filter((A)=>A.raw))){if(R.result)continue;let{body:A,raw:P}=gC(R.call);this.append(A,P)}if(!S&&this.waitingForInput())return{reason:"waiting_user"};let w=this.records.findLast((R)=>R.entry.seq>g&&R.raw)?.raw;if(!S&&w?.role==="assistant")return Oh(w);if(!S&&!w&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let y=await this.prepareAgent(u,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let b=this.pendingSteers.shift();if(b)y.steer(b)}return await k$(this,this.lease,this.setup,y,u,e,o,p.signal,i!==void 0&&e===void 0),Oh(this.records.findLast((b)=>b.entry.seq>g&&b.raw?.role==="assistant")?.raw)}).then((y)=>p.signal.aborted?{reason:"aborted"}:y,(y)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(y)}).then(async(y)=>{try{if(!this.suspended&&y.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())y={reason:"waiting_user"};if(y.reason!=="interrupted")y=await this.lease?.invoke("run.end",{reason:y.reason,error:y.error},this)??y}}catch(b){y={reason:"error",error:String(b)}}finally{try{await this.lease?.release()}catch(b){y={reason:"error",error:String(b)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...y});let b=En(this.ctx.models,this.row.model);if(b)this.context.settle(b)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:i,executionTools:u,assemble:p}=await A$(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=i,this.row.parentID&&(!i.toolPolicy||!this.lease?.policy(i.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=i.cwd,this.agent=hC({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??mg,captureRequest:(g)=>{this.lastRequestSnapshot=g},captureResponse:(g)=>{this.lastResponseSnapshot=g},steerConsumed:(g)=>this.markSteerConsumed(g),hooks:{tools:p,...P$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(g,y)=>{if(this.suspended&&y.role==="assistant"&&(y.stopReason==="aborted"||y.stopReason==="error"))return;if(y.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,y);let b=this.loaded?.find((E)=>E.entry.seq===this.pendingUserSeq);if(b)b.raw=y;this.pendingUserSeq=void 0;return}if(y.role==="assistant")this.context.calibrate(y);this.append(g,y)},draft:(g)=>{this.draftParts=g,this.events.draft(g)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let i=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...i?{saved:i}:{}})}measureCompactionSavings(e,o){let i=En(this.ctx.models,this.row.model);if(!i)return;let u=this.context.budget(i),p=Re(this.records,i,u,{cwd:this.cwd}).tokens,g={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},y=Re([...this.records,g],i,u,{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,o){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function IG(e,o){let u=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
289
+ `)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var M$=new Set(["user","assistant","tool_result","run","compaction"]),bG=new Set(["user","assistant","toolResult"]);function O$(e,o,i){return{format:Ql,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...i?{project:i}:{},records:o.filter((u)=>M$.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function Bo(e){if(!gr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Ql)return EG(e);if(gr(e.info)&&Array.isArray(e.messages))return wG(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 EG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!gr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let i=0,u=e.records.flatMap((p,g)=>{let y=`records[${g}]`;if(!gr(p)||!gr(p.entry))throw new t(`${y} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let b=p.entry;if(b.type==="notice_pending"||b.type==="extension")return[];if(typeof b.type!=="string"||!M$.has(b.type))throw new t(`${y} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(b.type)}`);let{seq:E,time:S}=b;if(typeof E!=="number"||!Number.isSafeInteger(E)||E<=i)throw new t(`${y} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof S!=="number"||!Number.isFinite(S))throw new t(`${y} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=E,SG(b,y);let w=p.raw;if(w!==void 0&&!(gr(w)&&typeof w.role==="string"&&bG.has(w.role)))throw new t(`${y} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:b,...w===void 0?{}:{raw:w}}]});return{title:Lr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(L$):[],created:Hs(o.created)??Date.now(),updated:Hs(o.updated)??Date.now(),needsRaw:!1,records:u}}function SG(e,o){let i=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);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 wG(e){let o=e.info,i=gr(o.time)?o.time:{},u=gr(o.model)?o.model:void 0,p=e.messages.filter(gr).sort(TG),g=[],y=0,b=0,E=(X,j)=>{b=Math.max(b,j??b),y+=1,g.push({entry:{...X,seq:y,time:b}})},S=!1,w=(X,j)=>{if(!S)return;S=!1,E({type:"run",state:"end",reason:X,...j?{error:j}:{}},void 0)};for(let X of p){let j=gr(X.info)?X.info:{},V=Array.isArray(X.parts)?X.parts.filter(gr):[],J=Hs(gr(j.time)?j.time.created:void 0);if(j.role==="user"){w("done");let ee=RG(V);if(!ee)continue;E({type:"run",state:"start"},J),E(ee,J),S=!0}else if(j.role==="assistant"){if(!S)E({type:"run",state:"start"},J),S=!0;PG(j,V,E);let ee=_$(j.error);if(ee)w(ee.aborted?"aborted":"error",ee.aborted?void 0:ee.message)}}w("done");let R=p.findLast((X)=>gr(X.info)&&X.info.role==="assistant"),A=gr(R?.info)?R.info:void 0,P=Lr(u?.providerID)||Lr(A?.providerID),C=Lr(u?.id)||Lr(A?.modelID),q=P&&C?`${P}/${C}`:void 0;return{title:Lr(o.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(L$):[],created:Hs(i.created)??g[0]?.entry.time??Date.now(),updated:Hs(i.updated)??g.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:g}}function TG(e,o){let i=(p)=>(gr(p.info)&&gr(p.info.time)?Hs(p.info.time.created):void 0)??0,u=(p)=>gr(p.info)?Lr(p.info.id):"";return i(e)-i(o)||u(e).localeCompare(u(o))}function RG(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Lr(u.text)).join(`
290
+
291
+ `),i=e.flatMap((u)=>u.type==="file"?kG(u):[]);if(!o.trim()&&i.length===0)return;return{type:"user",text:o,...i.length?{attachments:i}:{}}}function kG(e){let o=Lr(e.mime)||"application/octet-stream",i=Lr(e.filename)||"file",u=Lr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(p){let g=p[3]??"";if(o.startsWith("image/"))return[{name:i,mimeType:o,kind:"image",data:p[2]?g:btoa(g)}];if(o.startsWith("text/")||o==="application/json"){let y=p[2]?new TextDecoder().decode(Uint8Array.from(atob(g),(b)=>b.charCodeAt(0))):g;return[{name:i,mimeType:o,kind:"text",data:y}]}return[]}if(u.startsWith("file://"))try{return[{name:i,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function AG(e){let o=[[]];for(let i of e){if(i.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")o.at(-1)?.push(i)}return o.filter((i)=>i.length>0)}function PG(e,o,i){let u=`${Lr(e.providerID)}/${Lr(e.modelID)}`,p=_$(e.error),g=AG(o);g.forEach((y,b)=>{let E=y.flatMap((R)=>{if(R.type==="reasoning")return Lr(R.text).trim()?[{type:"thinking",text:Lr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Lr(R.text).trim()?[{type:"text",text:Lr(R.text)}]:[];return[{type:"tool_call",id:v$(R.callID),name:Lr(R.tool),input:gr(R.state)&&gr(R.state.input)?R.state.input:{}}]}),S=b===g.length-1,w=CG(y);i({type:"assistant",parts:E,model:u,...S&&p&&!p.aborted?{error:p.message}:{}},w);for(let R of y){if(R.type!=="tool")continue;let A=gr(R.state)?R.state:{},P=A.status==="error",C=A.status==="pending"||A.status==="running",q=P?[Lr(A.output),Lr(A.error)].filter(Boolean).join(`
292
+ `):C?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Lr(A.output);i({type:"tool_result",callID:v$(R.callID),name:Lr(R.tool),output:q,isError:P||C},Hs(gr(A.time)?A.time.end:void 0))}})}function v$(e){return Lr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function _$(e){if(!gr(e))return;let o=gr(e.data)?e.data:{};return{message:Lr(o.message)||Lr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function CG(e){for(let o of e){let i=gr(o.time)?Hs(o.time.start):gr(o.state)?$G(o.state):void 0;if(i!==void 0)return i}return}function $G(e){return gr(e.time)?Hs(e.time.start):void 0}function L$(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 N$(e,o){let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let p=u.time;switch(u.type){case"user":return{entry:u,raw:vG(u,p)};case"assistant":{let g=u.parts.flatMap((b)=>{if(b.type==="text")return[{type:"text",text:b.text}];if(b.type==="thinking")return[];return[{type:"toolCall",id:b.id,name:b.name,arguments:MG(b.input)}]}),y=g.some((b)=>b.type==="toolCall");return{entry:u,raw:{role:"assistant",content:g,api:o.api,provider:o.provider,model:o.id,usage:i,stopReason:u.error?"error":y?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:p}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:p}};default:return{entry:u}}})}function vG(e,o){let i=(e.attachments??[]).flatMap((g)=>g.kind==="path"?[`<file path=${JSON.stringify(g.data)} />`]:g.kind==="text"?[`<file name=${JSON.stringify(g.name)}>
293
+ ${g.data}
294
+ </file>`]:[]),u=(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(`
295
+
296
+ `);return{role:"user",content:u.length?[{type:"text",text:p},...u]:p,timestamp:o}}function gr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e==="string"?e:""}function Hs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function MG(e){return gr(e)?e:{}}function or(e,o){let i=e.at(-1)?.entry.seq??0,u,p,g;for(let{entry:S}of e){if(S.type==="run"&&S.state==="start")u=S.seq;if(S.seq===o)if(S.type==="user"&&!S.notices)i=(u??S.seq)-1;else p=u;if(S.type==="run"&&S.state==="end"){if(p!==void 0&&u===p)g=S.seq;u=void 0}}let y=e.find((S)=>S.entry.seq===o)?.entry;if(o!==void 0&&!y)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(y&&!(y.type==="user"&&!y.notices)){if(p!==void 0&&g===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=g??y.seq}else if(o===void 0&&u!==void 0)i=e.findLast(({entry:S})=>S.type==="run"&&S.state==="end")?.entry.seq??0;let b=e.filter(({entry:S})=>S.seq<=i&&(S.type!=="compaction"||S.through<=i)),E=new Map(b.map(({entry:S},w)=>[S.seq,w+1]));return b.map((S,w)=>{let R=structuredClone(S);if(R.entry.seq=w+1,R.entry.type==="compaction"){let A=R.entry.through,P=b.findLast(({entry:C})=>C.seq<=A);R.entry.through=P?E.get(P.entry.seq)??0:0}return R})}function ir(e){let o=new Map,i=[];for(let u of e){if(u.type==="assistant"){for(let y of u.parts)if(y.type==="tool_call"&&y.name==="todo")o.set(y.id,y.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let p=o.get(u.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 F$}from"buffer";import{createHash as OG}from"crypto";import{isDeepStrictEqual as _l}from"util";var Ll="@blob:";function fu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function D$(e,o,i){if(typeof e!=="string"||e.length<256||e.startsWith(Ll))return;let u=F$.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let p=OG("sha256").update(u).digest("hex");return i.put(p,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Ll}${p}`}function q$(e,o){if(typeof e!=="string"||!e.startsWith(Ll))return;let i=o.get(e.slice(Ll.length));if(i===void 0)return;return F$.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Nl(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let g=D$(p.data,p.mimeType,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((p)=>{let g=D$(p.data,p.mimeType,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,images:u}}return e}function Fi(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let g=q$(p.data,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((p)=>{let g=q$(p.data,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,images:u}}return e}function Hc(e,o){if(!fu(o))return o;if(e.type==="user"){let{merged:i,images:u}=Dc(e.text,e.attachments),p=u.length>0?[{type:"text",text:i},...u]:i,g=Object.keys(o),{role:y,timestamp:b,content:E}=o;if(g.length===3&&y==="user"&&typeof b==="number"&&"content"in o&&_l(E,p))return{role:"user",timestamp:b};return o}if(e.type==="tool_result"){let{role:i,toolCallId:u,toolName:p,isError:g,timestamp:y,content:b}=o;if(i!=="toolResult"||u!==e.callID||typeof p!=="string"||g!==e.isError||typeof y!=="number")return o;let E=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!_l(o.details,e.meta):e.meta!==void 0)return o;let{role:w,toolCallId:R,toolName:A,content:P,details:C,isError:q,timestamp:X,...j}=o;if(_l(b,E))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:y};if(Array.isArray(b)){let V=e.images??[],J=0,ee=!0,ae=b.map((H)=>{if(fu(H)&&H.type==="image"){let ue=V[J++],he=Object.keys(H);if(ue&&he.length===3&&H.mimeType===ue.mimeType&&H.data===ue.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:ae,...j,timestamp:y}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let p=!1,g=u.map((y,b)=>{let E=e.parts[b];if(fu(y)){if(y.type==="text"&&E?.type==="text"&&y.text===E.text){p=!0;let S={...y};return delete S.text,S}if(y.type==="thinking"&&E?.type==="thinking"&&y.thinking===E.text){p=!0;let S={...y};return delete S.thinking,S}if(y.type==="toolCall"&&E?.type==="tool_call"&&y.id===E.id&&y.name===E.name&&"arguments"in y&&_l(y.arguments,E.input)){p=!0;let S={...y};return delete S.id,delete S.name,delete S.arguments,S}}return y});if(!p)return o;return{...o,content:g}}return o}function pg(e,o){if(!fu(o))return o;if(e.type==="user"){let{role:i,timestamp:u}=o;if(i==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:p,images:g}=Dc(e.text,e.attachments);return{role:"user",content:g.length>0?[{type:"text",text:p},...g]:p,timestamp:u}}return o}if(e.type==="tool_result"){let{role:i,timestamp:u}=o;if(i==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:g,toolName:y,content:b,timestamp:E,...S}=o,w;if(Array.isArray(b)){let R=e.images??[],A=0;w=b.map((P)=>{if(fu(P)&&P.type==="image"&&!("data"in P)){let C=R[A++];if(C)return{type:"image",mimeType:P.mimeType,data:C.data}}return P})}else w=[{type:"text",text:e.output},...(e.images??[]).map((R)=>({type:"image",mimeType:R.mimeType,data:R.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof y==="string"?y:e.name,content:w,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...S,timestamp:u}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u))return o;let p=!1,g=u.map((y,b)=>{let E=e.parts[b];if(fu(y)){if(y.type==="text"&&!("text"in y)&&E?.type==="text"){p=!0;let{type:S,...w}=y;return{type:S,text:E.text,...w}}if(y.type==="thinking"&&!("thinking"in y)&&E?.type==="thinking"){p=!0;let{type:S,...w}=y;return{type:S,thinking:E.text,...w}}if(y.type==="toolCall"&&!("arguments"in y)&&E?.type==="tool_call"){p=!0;let{type:S,...w}=y;return{type:S,id:E.id,name:E.name,arguments:structuredClone(E.input),...w}}}return y});if(!p)return o;return{...o,content:g}}return o}function j$(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(E,S,w){o.run(E,S,w)},get(E){return i.get(E)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),g=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),y=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),b=0;return e.transaction(()=>{for(let E of p){let S;try{S=JSON.parse(E.body)}catch{continue}let w=Fi(S,u),R=Nl(w,u),A=R===S?E.body:JSON.stringify(R),P=E.raw;if(E.raw!==null)try{let C=JSON.parse(E.raw),q=pg(w,C),X=Hc(w,q);P=JSON.stringify(X)}catch{P=E.raw}if(A!==E.body)g.run(A,P,E.session_id,E.seq),b++;else if(P!==E.raw)y.run(P,E.session_id,E.seq),b++}})(),b}import{Database as _G}from"bun:sqlite";import{chmodSync as U$,existsSync as LG,mkdirSync as NG}from"fs";import{dirname as DG}from"path";var lg=[`
297
+ CREATE TABLE projects (
298
+ id TEXT PRIMARY KEY,
299
+ name TEXT NOT NULL,
300
+ directory TEXT NOT NULL UNIQUE,
301
+ instructions TEXT NOT NULL DEFAULT '',
302
+ created INTEGER NOT NULL,
303
+ updated INTEGER NOT NULL
304
+ );
305
+ CREATE TABLE automations (
306
+ id TEXT PRIMARY KEY,
307
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
308
+ name TEXT NOT NULL,
309
+ prompt TEXT NOT NULL,
310
+ schedule TEXT NOT NULL,
311
+ model TEXT NOT NULL,
312
+ enabled INTEGER NOT NULL,
313
+ created INTEGER NOT NULL,
314
+ updated INTEGER NOT NULL,
315
+ next_run INTEGER,
316
+ last_run INTEGER,
317
+ last_session_id TEXT
318
+ );
319
+ CREATE TABLE sessions (
320
+ id TEXT PRIMARY KEY,
321
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
322
+ automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
323
+ title TEXT NOT NULL DEFAULT '',
324
+ model TEXT NOT NULL,
325
+ todos TEXT NOT NULL DEFAULT '[]',
326
+ created INTEGER NOT NULL,
327
+ updated INTEGER NOT NULL
328
+ );
329
+ CREATE INDEX sessions_project ON sessions(project_id);
330
+ CREATE TABLE entries (
331
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
332
+ seq INTEGER NOT NULL,
333
+ time INTEGER NOT NULL,
334
+ body TEXT NOT NULL,
335
+ raw TEXT,
336
+ PRIMARY KEY (session_id, seq)
337
+ ) WITHOUT ROWID;
338
+ `,"","","",`
339
+ ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
340
+ ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
341
+ ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
342
+ CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
343
+ ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
344
+ 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,
345
+ PRIMARY KEY (namespace, key));
346
+ CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
347
+ PRIMARY KEY (namespace, version));
348
+ 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);
349
+ CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
350
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
351
+ END;
352
+ CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
353
+ INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
354
+ END;
355
+ CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
356
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
357
+ END;
358
+ CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
359
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
360
+ END;
361
+ CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
362
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
363
+ END;
364
+ CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
365
+ INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
366
+ END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
367
+ WHERE json_extract(body,'$.type')='compaction';
368
+ CREATE TABLE IF NOT EXISTS blobs (
369
+ hash TEXT PRIMARY KEY,
370
+ mime TEXT NOT NULL,
371
+ data BLOB NOT NULL
372
+ ) WITHOUT ROWID;
373
+ 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 qG=[20,50,100,200,400,800];function FG(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function dg(e){let o=0;while(!0)try{return e()}catch(i){let u=qG[o];if(u===void 0||!FG(i))throw i;o++,Bun.sleepSync(u)}}function B$(e,o){if(e!==":memory:")NG(DG(e),{recursive:!0});let i=new _G(e,{create:!0,strict:!0}),u=(g,y=!0)=>new Proxy(function(...b){return Reflect.apply(g,this,b)},{apply(b,E,S){Cs();let w=o.length===0&&!i.inTransaction,R=y?Reflect.get(g,"immediate"):void 0,A=()=>{let P=[];o.push(P);let C=!1;try{let q=typeof R==="function"?Reflect.apply(R,g,S):Reflect.apply(b,E,S);return C=!0,q}finally{o.pop();let q=o.at(-1);if(C&&q)q.push(...P);else for(let X of P)if(C)X.commit();else X.rollback()}};return w?dg(A):A()},get(b,E){let S=Reflect.get(g,E);if(["deferred","immediate","exclusive"].includes(String(E))&&typeof S==="function")return u(S,!1);return S}}),p=new Proxy(i,{get(g,y){let b=Reflect.get(g,y,g);if(typeof b!=="function")return b;return(...E)=>{Cs();let R=(y==="run"||y==="exec")&&o.length===0&&!i.inTransaction?dg(()=>Reflect.apply(b,g,E)):Reflect.apply(b,g,E);if(y==="transaction"&&typeof R==="function")return u(R,!0);if(y!=="query"&&y!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(A,P,C){let q=Reflect.get(A,P,A);if(typeof q!=="function")return q;return(...X)=>{Cs();let J=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!i.inTransaction?dg(()=>Reflect.apply(q,A,X)):Reflect.apply(q,A,X);return J===A?C:J}}})}}});if(e!==":memory:")U$(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"),p.run("PRAGMA mmap_size = 268435456"),jG(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(LG(y))U$(y,384)}return p}function jG(e,o=lg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=i;u<o.length;u++)e.transaction(()=>{let p=o[u]??"",g=Array.isArray(p)?p:u>=4?UG(p):[p];for(let y of g)try{if(y.trim())e.run(y)}catch(b){if(!(b instanceof Error)||!/already exists|duplicate column name/i.test(b.message))throw b}e.run(`PRAGMA user_version = ${u+1}`)})()}function UG(e){let o=[],i=0,u=0,p=[],g=!1,y=0,b=(E)=>{let S=e.slice(i,E).trim();if(S)o.push(S);i=E+1,p=[],g=!1,y=0};while(u<e.length){let E=e[u];if(E==="'"||E==='"'||E==="`"||E==="["){let S=E==="["?"]":E;u++;while(u<e.length)if(e[u]===S)if(S!=="]"&&e[u+1]===S)u+=2;else break;else u++;u++;continue}if(E==="-"&&e[u+1]==="-"){let S=e.indexOf(`
374
+ `,u);u=S===-1?e.length:S+1;continue}if(E==="/"&&e[u+1]==="*"){let S=e.indexOf("*/",u+2);u=S===-1?e.length:S+2;continue}if(/[A-Za-z_]/.test(E)){let S=u+1;while(S<e.length&&/[A-Za-z0-9_$]/.test(e[S]))S++;let w=e.slice(u,S).toUpperCase();if(p.length<3)p.push(w),g=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(g){if(w==="BEGIN"||w==="CASE"&&y>0)y++;else if(w==="END"&&y>0)y--}u=S;continue}if(E===";"&&y===0)b(u);u++}return b(e.length),o}var Dl=({position:e,closed_at:o,...i})=>({...i,closedAt:o??null}),ql=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var fg=new Set(["user","run","extension","notice_pending","compaction"]);class Fl{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=B$(e,this.entryTransactions),this.blobs={put:(o,i,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,i,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Dl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Dl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Dl(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[i,u]of e.entries())o.run(i,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){this.db.query("DELETE FROM projects WHERE id = ?").run(e)}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(ql)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(ql)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(ql)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,i){this.insertSessionWithRecords(o,or(this.records(e),i))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:p}of o){let{seq:g,time:y,...b}=u,E=b,S=Nl(E,this.blobs),w=p===void 0?null:JSON.stringify(Hc(E,p));i.run(e.id,g,y,JSON.stringify(S),w)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)i.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.query("DELETE FROM sessions WHERE id = ?").run(e)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,i,u){Cs();let p=this.plugins,g=p?.pinEntry(i),y;try{return y=this.db.transaction(()=>{let b=Math.max(o??0,this.lastSeq(e)+1),S=(g&&p?p.beforeEntry(g,i,e,b):void 0)??i,w=JSON.stringify(S),R=g?JSON.parse(w):S,A={...R,seq:b,time:Date.now()},P=Nl(R,this.blobs),C=P===R&&!g?w:JSON.stringify(P),q=u===void 0?null:JSON.stringify(Hc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,b,A.time,C,q),A.type==="user"&&!(("notices"in A)&&A.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(A.time,e);return this.cacheAppended(e,A,C),A})(),y}finally{if(g&&p){let b={commit:()=>p.finishEntry(g,e,y),rollback:()=>p.finishEntry(g,e)},E=this.entryTransactions.at(-1);if(E)E.push(b);else b.commit()}}}setEntryRaw(e,o,i){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let p=Fi(JSON.parse(u.body),this.blobs),g=Hc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(g),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,i,u=!0){let p=i?.every((y)=>fg.has(y))?this.cachedEntries(e):void 0;if(p&&i)return p.filter((b)=>b.seq>o&&i.includes(b.type)).map((b)=>({...u?Fi(b,this.blobs):b}));return(i?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...i):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((y)=>({...Fi(JSON.parse(y.body),u?this.blobs:void 0),seq:y.seq,time:y.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let i=[...fg],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...i).map((p)=>({...JSON.parse(p.body),seq:p.seq,time:p.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,i){let u=this.smallEntries.get(e);if(!u||!fg.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(i),seq:o.seq,time:o.time})}entriesRange(e,o,i=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,i).map((u)=>({...Fi(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let i=this.lastSeq(e),u=(E)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,E),p=u(o),g=p?.type==="run"&&p.state==="start"?o+1:o;if(g>=i)return i;let y=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,g,g);if(!y)return i;if(y.end)return y.seq;let b=u(y.seq-1);return b?.type==="run"&&b.state==="start"&&y.seq-1>g?y.seq-2:y.seq-1}entriesAround(e,o,i,u){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let g=Math.min(Math.max(1,o),p),y=this.alignToUser(e,Math.max(1,g-i)),b=this.alignToTurnEnd(e,Math.min(p,g+u));return this.window(e,y,b,p)}entriesFrom(e,o,i){let u=this.lastSeq(e),p=Math.max(1,o);if(p>u)return{entries:[],from:p,to:u,hasBefore:u>0,hasAfter:!1};let g=this.alignToTurnEnd(e,Math.min(u,p+i-1));return this.window(e,p,g,u)}window(e,o,i,u){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,i+1),from:o,to:i,hasBefore:p!==null,hasAfter:i<u}}replayStart(e,o,i){let u=this.lastSeq(e),p=this.lastEntry(e,"compaction"),g=p?.type==="compaction"?p.through+1:1,y=Math.max(1,u-i+1,Math.min(g,u-o+1));return this.alignToUser(e,y)}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((i)=>{let u=Fi(JSON.parse(i.body),this.blobs);return{entry:{...u,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:pg(u,JSON.parse(i.raw))}}})}lastEntry(e,o){let i=this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return i?{...Fi(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,o){let i=this.truncationEpoch(e),u=o;if(this.plugins){let p=this.plugins.pin();try{let g=await p.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(g===null)return!1;o={...g,dedupeKey:u.dedupeKey,wake:u.wake&&g.wake,recovery:u.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==i)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((b)=>b.type==="notice_pending"&&b.notice.dedupeKey===o.dedupeKey||b.type==="user"&&b.notices?.some((E)=>E.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let g of i)if(g.type==="user"&&g.notices)for(let y of g.notices)u.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")u.add(g.payload.dedupeKey);let p=[];for(let g of i)if(g.type==="notice_pending"&&!u.has(g.notice.dedupeKey))p.push(g.notice);return p}}function ne(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as BG,readdirSync as K$,statSync as H$}from"fs";import{join as W$}from"path";function Wc(e){try{return H$(e).size}catch{return 0}}function z$(e){try{return Math.round(H$(e).mtimeMs)}catch{return}}function V$(e){let o=0,i=0;try{let u=K$(e,{withFileTypes:!0});for(let p of u){let g=W$(e,p.name);if(p.isDirectory()){let y=V$(g);o+=y.bytes,i+=y.files}else if(p.isFile())o+=Wc(g),i+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:i}}function GG(e){if(!BG(e))return[];try{return K$(e,{withFileTypes:!0}).flatMap((o)=>{let i=W$(KG(e),o.name),u=z$(i);if(o.isDirectory()){let p=V$(i);return[{name:o.name,kind:"directory",bytes:p.bytes,files:p.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Wc(i),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,i)=>i.bytes-o.bytes||o.name.localeCompare(i.name))}catch{return[]}}function KG(e){return e}function Ws(e,o){let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return 0;let u=Object.values(i)[0];return typeof u==="number"?u:0}function G$(e,o){try{let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return;let u=Object.values(i)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var HG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},WG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function zG(e){let o=new Map;try{let i=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let g of u)i.set(g.name,g.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let g of p){let y=i.get(g.name)??g.name;if(y.startsWith("sqlite_autoindex_")){let E=y.slice(17),S=E.lastIndexOf("_");if(S>0)y=E.slice(0,S)}let b=o.get(y)??{bytes:0,pages:0};o.set(y,{bytes:b.bytes+(Number(g.bytes)||0),pages:b.pages+(Number(g.pages)||0)})}}catch{}return o}function VG(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
375
+ count(*) AS total,
376
+ sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
377
+ sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
378
+ sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
379
+ sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
380
+ FROM sessions`).get(),u=e.db.query(`SELECT
381
+ count(*) AS total,
382
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
383
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
384
+ min(time) AS oldest_time,
385
+ max(time) AS newest_time
386
+ FROM entries`).get(),g=e.db.query(`SELECT
387
+ coalesce(json_extract(body, '$.type'), 'unknown') AS type,
388
+ count(*) AS count,
389
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
390
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes
391
+ FROM entries
392
+ GROUP BY type
393
+ ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((E)=>({type:String(E.type||"unknown"),count:Number(E.count)||0,bodyBytes:Number(E.body_bytes)||0,rawBytes:Number(E.raw_bytes)||0})),y=g.find((E)=>E.type==="compaction")?.count??0,b=[];try{let E=new Map,S=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let A of S)E.set(A.namespace,Number(A.max_ver)||0);let w=e.db.query(`SELECT
394
+ namespace,
395
+ count(*) AS keys,
396
+ coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
397
+ FROM plugin_kv
398
+ GROUP BY namespace
399
+ ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let A of w){R.add(A.namespace);let P=E.get(A.namespace);b.push({namespace:A.namespace,keys:Number(A.keys)||0,bytes:Number(A.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[A,P]of E.entries())if(!R.has(A))b.push({namespace:A,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:o,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:y,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:g,pluginNamespaces:b}}function jl(e,o){let i=Ws(e,"page_size"),u=Ws(e,"page_count"),p=Ws(e,"freelist_count"),g=e.db.query("PRAGMA journal_mode").get(),y=e.db.query("SELECT sqlite_version() AS v").get(),b=Ws(e,"synchronous"),E=Ws(e,"auto_vacuum"),S=Ws(e,"cache_size"),w=S<0?Math.abs(S)*1024:S*i,R=Ws(e,"foreign_keys")===1,A=Ws(e,"busy_timeout"),P=G$(e,"encoding")??"UTF-8",C=G$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?z$(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=zG(e),V=GG(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((J,ee)=>J+ee.bytes,0),database:{size:Wc(e.path),walSize:Wc(`${e.path}-wal`),shmSize:Wc(`${e.path}-shm`),sqliteVersion:y?.v??"unknown",journalMode:g?.journal_mode??"unknown",synchronous:HG[b]??String(b),foreignKeys:R,busyTimeout:A,encoding:P,autoVacuum:WG[E]??String(E),cacheSizeBytes:w,pageSize:i,pageCount:u,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Ws(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:C},analytics:VG(e),entries:V,tables:X.map(({name:J,sql:ee})=>{let ae=J.replaceAll('"','""'),H=e.db.query(`SELECT count(*) AS count FROM "${ae}"`).get().count,ue=e.db.query(`PRAGMA table_info("${ae}")`).all().map((se)=>se.name),he=e.db.query(`PRAGMA index_list("${ae}")`).all().length,$e=Boolean(ee&&/WITHOUT\s+ROWID/i.test(ee)),Ee=j.get(J);return{name:J,rows:H,...Ee?{bytes:Ee.bytes,pages:Ee.pages}:{},indexes:he,columns:ue,withoutRowid:$e}})}}function JG(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let g of i)for(let y of g.body.matchAll(/@blob:([0-9a-f]{64})/g)){let b=y[1];if(b)u.add(b)}let p=[];for(let g of o)if(!u.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 J$(e,o,i){let u=jl(e,o);if(i.vacuum)j$(e.db),e.invalidateEntryCache(),JG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:jl(e,o)}}var QG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Ul{plugins;builtinNames;registered=new Map;constructor(e,o){this.plugins=e;this.builtinNames=o}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let o=e.name.trim().toLowerCase();if(!o)throw Error("Tool name cannot be empty");if(QG.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function Q$(e,o){let i=Jr(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function X$(e,o){let u=(await e.options.models.getAvailable().catch(()=>[])).map((g)=>({...Q$(tt(g),g),available:!0})),p=new Set(u.map((g)=>g.id));for(let g of[o,...e.list(!0,{archive:"all"}).map((y)=>y.model)]){if(p.has(g))continue;let y=En(e.options.models,g);if(!y)continue;p.add(g),u.push({...Q$(g,y),available:!1})}return{models:u}}function Y$(e,o){if(typeof o!=="string"||!En(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as XG,statSync as YG}from"fs";import{basename as ZG,resolve as eK}from"path";class hg{runtime;sessions;emit;arm;constructor(e,o,i,u){this.runtime=e;this.sessions=o;this.emit=i;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new f("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=eK(e.directory.trim());if(!XG(o)||!YG(o).isDirectory())throw new t(`${o} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(o);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let u=Date.now(),p={id:ne("p"),name:e.name?.trim()||ZG(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((p)=>p.id)),i=new Set(e);if(!(i.size===e.length&&i.size===o.size&&e.every((p)=>o.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new ie("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let p of i)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as EK,readFileSync as SK}from"fs";import{homedir as wK}from"os";import{join as hu}from"path";var sv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),tK={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"]},rK=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),xg={'"':['"'],"\u201C":["\u201D",'"']},gg=(e)=>e!==void 0&&/\s/.test(e),iv=(e)=>[...new Set(e)],zc=(e)=>[...e].length;var nK={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function oK(e,o){let i=e.trim().toLowerCase(),u=new Date(o),p=u.getFullYear(),g=u.getMonth(),y=u.getDate();if(i==="today")return{start:new Date(p,g,y).getTime(),end:new Date(p,g,y+1).getTime()};if(i==="yesterday")return{start:new Date(p,g,y-1).getTime(),end:new Date(p,g,y).getTime()};let b=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(b)return{start:o-Number(b[1])*nK[b[2]]};if(/^\d{4}$/.test(i))return{start:new Date(Number(i),0,1).getTime(),end:new Date(Number(i)+1,0,1).getTime()};let E=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!E)return null;let S=Number(E[1]),w=Number(E[3]);if(w<1||w>12)return null;if(E[4]===void 0){if(E[5]!==void 0)return null;return{start:new Date(S,w-1,1).getTime(),end:new Date(S,w,1).getTime()}}let R=Number(E[4]),A=Number(E[5]??0),P=Number(E[6]??0),C=Number(E[7]??0);if(A>23||P>59||C>59)return null;let q=new Date(S,w-1,R,A,P,C);if(q.getMonth()!==w-1||q.getDate()!==R)return null;if(E[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(S,w-1,R+1).getTime()}}var sK=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Ig=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),bg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function yg(e,o,i,u,p,g){let y=i.trim(),b=(S,w)=>e.diagnostics.push({code:S,message:w,filter:o});if(!y)return b("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return b("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let E=p?[y]:y.split(",").map((S)=>S.trim()).filter(Boolean);switch(o){case"in":case"project":for(let S of E){let w=S.toLowerCase();if(o==="in"&&w==="this")e.currentSession=!0;else if(o==="in"&&w==="title")e.fields.push("title");else e.projectID.push(S)}return;case"session":for(let S of E)if(S.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(S);return;case"from":case"role":for(let S of E){let w=tK[S.toLowerCase()];if(w)e.fields.push(...w);else b("bad_filter_value",`${o}:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...E);return;case"model":e.model.push(...E);return;case"is":for(let S of E){let w=S.toLowerCase();if(w==="error")e.isError=!u;else if(w==="archived")e.archived=!u;else if(w==="compacted")e.compacted=!u;else b("bad_filter_value",`is:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let S=oK(y,g);if(!S)return b("bad_filter_value",`${o}:${y} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=Ig(e.after,S.start);else if(o==="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 iK(e,o){let i={},u=(C,q)=>{let X=iv([...C??[],...q]);return X.length?X:void 0},p=u(e?.projectID,o.projectID),g=u(e?.sessionID,o.sessionID),y=u(e?.fields,o.fields),b=u(e?.tools,o.tools),E=u(e?.model,o.model);if(p)i.projectID=p;if(g)i.sessionID=g;if(y)i.fields=y;if(b)i.tools=b;if(E)i.model=E;let S=o.isError??e?.isError,w=o.archived??e?.archived,R=o.compacted??e?.compacted;if(S!==void 0)i.isError=S;if(w!==void 0)i.archived=w;if(R!==void 0)i.compacted=R;let A=Ig(e?.after,o.after),P=bg(e?.before,o.before);if(A!==void 0)i.after=A;if(P!==void 0)i.before=P;if(A!==void 0&&P!==void 0&&A>=P)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function Z$(e,o){let i=xg[e[o]]??['"'],u="",p=o+1;while(p<e.length){let g=e[p],y=e[p+1];if(g==="\\"&&y!==void 0&&(y==="\\"||y==='"'||y==="\u201C"||y==="\u201D")){u+=y,p+=2;continue}if(i.includes(g))return{text:u,next:p+1,closed:!0};u+=g,p++}return{text:u,next:p,closed:!1}}function ev(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let i=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(i.length!==e.length-1)return;let u=i.toLowerCase();return sv.has(u)?u:void 0}function tv(e,o,i){let u=e==="word"&&!i&&zc(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:i,fuzzy:u}}function aK(e,o){let i=[],u=e.length,p=0;while(p<u){if(gg(e[p])){p++;continue}let g=!1;if(e[p]==="-"){if(p+1>=u||gg(e[p+1])){p++;continue}g=!0,p++}if(xg[e[p]]){let P=Z$(e,p);if(p=P.next,!P.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let C=P.text.trim();if(C)i.push({kind:"term",negated:g,term:tv("phrase",C,!1)});continue}let y=[],b;while(p<u&&!gg(e[p])){let P=e[p],C=e[p+1];if(P==="\\"&&C!==void 0&&rK.has(C)){y.push({c:C,esc:!0}),p+=2;continue}let q=xg[P]?ev(y):void 0;if(q){let X=Z$(e,p);if(p=X.next,!X.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});b={key:q,value:X.text,quoted:!0};break}y.push({c:P,esc:!1}),p++}if(b){i.push({kind:"filter",negated:g,...b});continue}let E=y.findIndex((P,C)=>C>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),S=E>0?ev(y.slice(0,E+1)):void 0;if(S){i.push({kind:"filter",negated:g,key:S,value:y.slice(E+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 w=y[y.length-1],R=y.length>1&&w!==void 0&&!w.esc&&w.c==="*",A=(R?y.slice(0,-1):y).map((P)=>P.c).join("");if(A)i.push({kind:"term",negated:g,term:tv("word",A,R)})}return i}var uK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function rv(e){let o=[];return{rest:e.replace(uK,(u,p,g,y,b)=>{let E=y.toLowerCase();if(!sv.has(E))return u;let S=b.startsWith('"')&&b.length>=2;return o.push({key:E,value:S?b.slice(1,-1).replace(/\\(["\\])/g,"$1"):b,negated:g==="-",quoted:S}),p}).trim(),filters:o}}var nv={n:`
400
+ `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function cK(e){let o=[...e],i=0,u=(w)=>{let R=o.slice(i,i+w).join("");if(R.length!==w||!/^[0-9a-fA-F]+$/.test(R))return;return i+=w,String.fromCodePoint(Number.parseInt(R,16))},p=()=>{let w=o[i++];if(w===void 0)return{kind:"lit",ch:"\\"};if(w in nv)return{kind:"lit",ch:nv[w]};if("dDwWsS".includes(w))return{kind:"any"};if(w==="b"||w==="B")return{kind:"zero"};if(w>="1"&&w<="9"){while(o[i]!==void 0&&/\d/.test(o[i]))i++;return{kind:"any"}}if(w==="k"||w==="p"||w==="P"){let R=o[i];if(R==="<"||R==="{"){let A=R==="<"?">":"}",P=o.indexOf(A,i);i=P<0?o.length:P+1}return{kind:"any"}}if(w==="c")return i++,{kind:"any"};if(w==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(w==="u"){if(o[i]==="{"){let A=o.indexOf("}",i),P=A<0?"":o.slice(i+1,A).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return i=A+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:w}},g=()=>{if(o[i]==="^")i++;while(i<o.length&&o[i]!=="]")i+=o[i]==="\\"?2:1;return i++,{kind:"any"}},y=()=>{let w="capture";if(o[i]==="?"){let A=o[i+1],P=o[i+2];if(A===":")w="plain",i+=2;else if(A==="="||A==="!")w="look",i+=2;else if(A==="<"&&(P==="="||P==="!"))w="look",i+=3;else if(A==="<"){let C=o.indexOf(">",i);i=C<0?o.length:C+1}else{w="opaque";while(i<o.length&&o[i]!==":"&&o[i]!==")")i++;if(o[i]===":")i++}}let R=S();if(o[i]===")")i++;if(w==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:w==="opaque"}},b=()=>{let w=o[i],R=1,A=!0;if(w==="*"||w==="?")R=0,i++;else if(w==="+")i++;else if(w==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(i,i+24).join(""));if(!P)return{quantified:!1,min:1};R=Number(P[1]),i+=P[0].length}else return{quantified:!1,min:1};if(o[i]==="?")i++;return{quantified:A,min:R}},E=()=>{let w=[];while(i<o.length){let R=o[i];if(R==="|"||R===")")break;i++;let A;if(R==="(")A=y();else if(R==="[")A=g();else if(R==="\\")A=p();else if(R===".")A={kind:"any"};else if(R==="^"||R==="$")A={kind:"zero"};else if(R==="*"||R==="+"||R==="?")A={kind:"zero"};else A={kind:"lit",ch:R};w.push({atom:A,...b()})}return w};function S(){let w=[E()];while(o[i]==="|")i++,w.push(E());return w}return S()}function ov(e){let o=[],i="",u=()=>{if(i)o.push([i]);i=""},p=(g)=>{for(let y of g){let b=y.atom;if(b.kind==="lit")if(y.min>=1){if(i+=b.ch,y.quantified)u()}else u();else if(b.kind==="group"&&!b.opaque&&y.min>=1)if(b.alts.length===1&&!y.quantified)p(b.alts[0]);else u(),o.push(...av(b.alts));else u()}};return p(e),u(),o}function av(e){if(e.length===1)return ov(e[0]);let o=[];for(let i of e){let u=ov(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!u.length)return[];o.push(u.reduce((p,g)=>zc(g)>zc(p)?g:p))}return[iv(o)]}var mK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function pK(e){return!/^\s*$/.test(e)&&(zc(e)>=2||mK.test(e))}function lK(e){let o;try{o=av(cK(e))}catch{return[]}let i=o.filter((E)=>E.every(pK)),u=i.filter((E)=>E.length===1).map((E)=>E[0]),p=i.filter((E)=>{if(E.length!==1)return!0;let S=E[0];return!u.some((w)=>w!==S&&w.includes(S))}),g=new Set,y=p.filter((E)=>{let S=JSON.stringify(E);if(g.has(S))return!1;return g.add(S),!0}),b=(E)=>Math.min(...E.map(zc));return y.sort((E,S)=>b(S)-b(E))}function dK(e){let o=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(o)}function fK(e,o){let i=`m${o?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(u){let p=u instanceof Error?u.message:String(u),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 Bl(e,o={}){let i=o.now??Date.now(),u=e.q??"",p=sK(),g=p.diagnostics,y,b=[];if(e.mode==="regex"){let q=rv(u);for(let X of q.filters)yg(p,X.key,X.value,X.negated,X.quoted,i);y=q.rest}else{let q=rv(u),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{b=[{include:[],exclude:[]}];for(let j of aK(u,g)){let V=b[b.length-1];if(j.kind==="or")b.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)}b=b.filter((j)=>j.include.length||j.exclude.length)}}let E=b.flatMap((q)=>[...q.include,...q.exclude]),S=y!==void 0?dK(y):E.some((q)=>/\p{Lu}/u.test(q.text)),w=e.caseSensitive??S,R=e.caseSensitive===void 0&&S,A,P;if(y){let q=fK(y,w);if("message"in q)P={code:"bad_regex",message:q.message};else{let X=lK(y);A={source:y,flags:q.flags,literals:X,deepScan:X.length===0}}}let C=iK(e.filters,p);return{mode:y!==void 0?"regex":"text",branches:b,...A?{regex:A}:{},filters:C,currentSession:p.currentSession,caseSensitive:w,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:b.some((q)=>q.include.some((X)=>X.fuzzy)),hasPositive:A!==void 0||b.some((q)=>q.include.length>0),hasFilters:Object.keys(C).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},uv=new WeakMap;function cv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,i=uv.get(e);if(i?.version===o)return i.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return uv.set(e,{version:o,terms:u}),u}var Eg=32,hK=1024,Vc=(e)=>`"${e.replaceAll('"','""')}"`;function gK(e,o){let i=Array.from({length:o.length+1},(u,p)=>p);for(let u=0;u<e.length;u++){let p=[u+1];for(let g=0;g<o.length;g++)p.push(Math.min((p[g]??0)+1,(i[g+1]??0)+1,(i[g]??0)+Number(e[u]!==o[g])));i=p}return i[o.length]??e.length}function wg(e,o){let i=Pt(o.trim());if(!i||i.length>64)return[];let u=cv(e),p=u.filter((b)=>b.t.startsWith(i)).slice(0,8).map((b)=>b.t);if(p.length>=8||i.length<4)return p;let g=i.length>=8?2:1,y=[];for(let b of u){if(Math.abs(b.t.length-i.length)>g)continue;if(gK(i,b.t)<=g)y.push(b.t);if(y.length>=8)break}return[...new Set([...p,...y])].slice(0,8)}function mv(e,o){let i=!1,u=[],p=[],g=o.filters,y=(X,j)=>{if(!j?.length)return;p.push(`${X} IN (${j.map(()=>"?").join(",")})`),u.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)u.push(X,X)}if(g.archived!==void 0)p.push(`s.archived_at IS ${g.archived?"NOT ":""}NULL`);let b=p.length?p.join(" AND "):"1",E=[...u];if(y("r.kind",g.fields?.map((X)=>Ne[X])),y("r.tool",g.tools),g.model?.length){p.push(`(${g.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let X of g.model)u.push(X,X)}if(g.isError!==void 0)p.push("r.err = ?"),u.push(Number(g.isError));if(g.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
401
+ SELECT max(json_extract(body,'$.through')) FROM store.entries
402
+ WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
403
+ ),0)) = ?`),u.push(Number(g.compacted));if(g.after!==void 0)p.push("r.time >= ?"),u.push(g.after);if(g.before!==void 0)p.push("r.time < ?"),u.push(g.before);let S=e.query("SELECT v FROM meta WHERE k='layout'").get(),w=S&&JSON.parse(S.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),A=(X)=>{let j=(ee)=>{let ae=Pt(ee);if(!X&&w){if([...ae].length<3){let se=[...ae].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ae,`${ae}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ae);if([...ae].length===1&&se.length>Eg)se.length=Eg,i=!0;if(!se.length)return Vc("__basalt_no_short_match__");return`(${se.map((pe)=>Vc(pe.term)).join(" OR ")})`}return Vc(ae)}let H=/^[\p{Script=Latin}\p{N}]+$/u.test(ee)?[ae]:Ti(ee),ue=H.filter((se)=>!/^[a-z0-9]{1,2}$/.test(se)),he=ue.length?ue:H;if(!he.length){R=!0;return}let $e=he.map((se,pe)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(se),xt=he.length>2&&pe>0&&pe<he.length-1;if(qe||xt){let Fe=e.query("SELECT n FROM term WHERE t=?").get(se)?.n??0;return{expression:Vc(se),frequency:Fe}}let Je=[se],Yt=0;for(let Fe of cv(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(Vc).join(" OR ")})`,frequency:Yt}});return $e.sort((se,pe)=>se.frequency-pe.frequency),`(${$e.slice(0,($e[0]?.frequency??1/0)<=hK?1:2).map((se)=>se.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((ee)=>ee.include.map((ae)=>ae.text));if(o.regex){let ee=V.map((ae)=>ae.map(j));if(ee.some((ae)=>ae.some((H)=>!H)))return;return ee.map((ae)=>`(${ae.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((ee)=>{let ae=ee.filter((H)=>!/^[a-z0-9]{1,2}$/i.test(H));return(ae.length?ae:ee).map(j)});if(J.some((ee)=>!ee.length||ee.some((ae)=>!ae)))return;return J.map((ee)=>`(${ee.join(" AND ")})`).join(" OR ")||void 0},P=A(!1),C=A(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:C,scan:R,where:p.length?p.join(" AND "):"1",bindings:u,forks:q,sessionWhere:b,sessionBindings:E,partial:i,candidateLimit:o.branches.some((X)=>X.include.length>0&&X.include.every((j)=>[...j.text].length<2))?512:void 0}}function pv(e){let o=1/0,i=-1/0;for(let u of e)o=Math.min(o,u.relevance),i=Math.max(i,u.relevance);return e.map((u)=>({...u,relevance:o===i?-1:-(0.5+0.5*(i-u.relevance)/(i-o))}))}function Gl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(Sg).map(([i,u])=>`WHEN ${Ne[i]} THEN ${u}`).join(" ")} ELSE 1 END) *
404
+ (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function lv(e,o,i,u){let p=Math.max(0,u-i)/86400000;return Math.max(0.000000001,-e)*Sg[o]*(0.3+0.7/(1+p/30))}function Tg(e,o){return e.sort((i,u)=>(o==="best"?u.score-i.score:0)||(o==="recent"?u.time-i.time:0)||(i.sessionID<u.sessionID?-1:Number(i.sessionID>u.sessionID))||u.seq-i.seq||i.field.localeCompare(u.field))}var kg=512;function dv(e,o,i){let u=performance.now(),p=o.partial;Ag(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[g,y]of[["fts",o.msg],["fts_out",o.out]]){if(!y)continue;let b=o.candidateLimit??2000,E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
405
+ ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(y,o.candidateLimit?b+1:b);if(o.candidateLimit&&E.length>b)E.length=b,p=!0;else if(!o.candidateLimit&&E.length===b){let w=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
406
+ AND rowid NOT IN (SELECT value FROM json_each(?))`).all(y,JSON.stringify(E.map((R)=>R.doc)));for(let R of w)E.push(R)}let S=pv(E);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
407
+ 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()-u),p}function fv(e,o,i,u,p){let g=performance.now();if(o.candidateLimit){let b=e.query(`
408
+ SELECT r.session_id,r.seq,${Gl(u)} AS score
409
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
410
+ ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
411
+ WHERE ${o.where} LIMIT ${o.candidateLimit+1}
412
+ `).all(...o.bindings);if(b.length>o.candidateLimit)b.length=o.candidateLimit,o.partial=!0;let E=new Map;for(let S of b){let w=i?S.seq:0,R=JSON.stringify([S.session_id,w]),A=E.get(R);if(!A||S.score>A.score)E.set(R,{...S,seq:w})}return p?.("filter",performance.now()-g),[...E.values()].sort((S,w)=>w.score-S.score||(S.session_id<w.session_id?-1:Number(S.session_id>w.session_id))||w.seq-S.seq)}let y=e.query(`
413
+ SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Gl(u)}) AS score
414
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
415
+ ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
416
+ WHERE ${o.where}
417
+ GROUP BY r.session_id${i?",r.seq":""}
418
+ ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
419
+ `).all(...o.bindings);return p?.("filter",performance.now()-g),y}var hv=new WeakMap,yK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
420
+ SELECT id,forked_from_id,forked_from_seq FROM store.sessions
421
+ WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
422
+ UNION
423
+ SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
424
+ FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
425
+ WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
426
+ )`;function Ag(e,o){if(!o.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${yK} 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();hv.set(e,new Map(i.map((u)=>[u.ancestor,u.through])))}function Rg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
427
+ SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
428
+ JOIN store.sessions ps ON ps.id=pr.session_id
429
+ WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
430
+ AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
431
+ AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
432
+ SELECT 1 FROM store.entries original JOIN store.entries copied
433
+ ON copied.session_id=r.session_id AND copied.seq=r.seq
434
+ WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
435
+ ))
436
+ ))`}function gv(e,o,i,u,p){let g=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let y=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,b=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
437
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${y>4000?"INDEXED BY ref_time":""}
438
+ ${b} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${Rg(o)}
439
+ ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${u} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],i);let E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(E===u){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(`
440
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${b}
441
+ WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
442
+ AND ${o.where} AND ${Rg(o)} AND NOT EXISTS (
443
+ SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
444
+ )`).run(S.session_id,S.seq,...o.bindings,...o.forks?o.bindings:[]),E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-g),E}function yv(e,o,i,u,p,g,y){let b=performance.now(),E=o.group==="none",S=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",w=e.query(`
445
+ SELECT r.session_id,${E?"r.seq":"0"} AS seq,
446
+ max(${Gl(p)}) AS relevance,max(r.time) AS time
447
+ FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
448
+ WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
449
+ GROUP BY r.session_id${E?",r.seq":""}
450
+ ORDER BY ${S},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(g),u,i);return y?.("group",performance.now()-b),w}function xv(e,o,i,u,p,g){let y=performance.now(),b=p?o:{...o,forks:!1},E=e.query(`
451
+ SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
452
+ ${b.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
453
+ WHERE r.session_id=? ${u?"AND r.seq=?":""}
454
+ AND ${o.where} AND ${Rg(b)}
455
+ ${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(i.session_id,...u?[i.seq]:[],...o.bindings,...b.forks?o.bindings:[]);return g?.("filter",performance.now()-y),E}function Pg(e,o,i,u){if(!o.forks)return[];let p=hv.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
456
+ SELECT DISTINCT r.session_id,s.title,e.body
457
+ FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
458
+ CROSS JOIN ref r ON r.session_id=l.child
459
+ JOIN store.sessions s ON s.id=r.session_id
460
+ LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
461
+ WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...o.bindings).filter((g)=>{if(i.seq===0)return g.title===u;if(!g.body)return!1;let y=JSON.parse(g.body);return Ke(y,!0).some((b)=>b.part===i.part&&b.kind===eo[i.kind]&&b.text===u)}).map((g)=>g.session_id)}function xK(e,o){let i=o?e:Pt(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let u="",p=[],g=[],y=0;for(let b of e){let E=o?b:Pt(b);u+=E;for(let S=0;S<E.length;S++)p.push(y),g.push(y+b.length);y+=b.length}return{normalized:u,starts:p,ends:g}}function Kl(e,o){if(o.regex){let E=new RegExp(o.regex.source,`${o.regex.flags}g`),S=[];for(let w of e.matchAll(E)){if(o.wholeWord&&!Iv(e,w.index,w.index+w[0].length))continue;S.push([w.index,w.index+w[0].length])}return S.length?S:void 0}let{normalized:i,starts:u,ends:p}=xK(e,o.caseSensitive),g=(E)=>{let S=o.caseSensitive?E.text:Pt(E.text),w=[],R=i.indexOf(S);while(R>=0&&S){let A=u?u[R]:R,P=p?p[R+S.length-1]:R+S.length,C=A===0||A!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(A-1,A))||/[a-z0-9][A-Z]/.test(e.slice(A-1,A+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(E.text));if(A!==void 0&&P!==void 0&&(!E.prefix||C)&&(!o.wholeWord||Iv(e,A,P)))w.push([A,P]);R=i.indexOf(S,R+Math.max(1,S.length))}return w};if(!o.branches.length)return[];let y=[],b=!1;for(let E of o.branches){if(E.exclude.some((w)=>g(w).length))continue;let S=E.include.map(g);if(S.some((w)=>!w.length))continue;b=!0,y.push(...S.flat())}return b?y:void 0}function Iv(e,o,i){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(i===e.length||!u.test(e.slice(i,i+1)))}function Hl(e,o){let i=e.split(`
462
+ `),u=new Set,p=0,g=i.map((y,b)=>{let E=p;if(o.some(([S,w])=>S<=E+y.length&&w>=E))for(let S=Math.max(0,b-1);S<=Math.min(i.length-1,b+1);S++)u.add(S);return p+=y.length+1,E});if(!u.size)u.add(0);return[...u].sort((y,b)=>y-b).slice(0,5).map((y)=>{let b=i[y]??"",E=g[y]??0,S=o.filter(([P,C])=>C>E&&P<E+b.length),w=Math.max(0,(S[0]?.[0]??E)-E-100),R=b.slice(w,w+300),A=S.map(([P,C])=>[Math.max(0,P-E-w),Math.min(R.length,C-E-w)]);return{text:R,line:y+1,ranges:A.filter(([P,C])=>P<C)}})}var bv=3;function IK(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 Ev(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function bK(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===o&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let u="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&&!IK(y))throw Error("invalid best cursor");let b=(E)=>Array.isArray(E)&&E.every((S)=>typeof S==="string"&&S.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&b(p)&&b(g))return{offset:i.offset,key:o,now:i.now,window:u,seen:p,emitted:g,after:y}}}catch{}throw Error("invalid search cursor")}function Nn(e,o){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return bK(e.cursor,i)}async function Gr(e,o,i){let u="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=Nn(o,i.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let b=Bl(o,{now:y.now});if(b.error){g({type:"error",...b.error});return}if(b.currentSession){if(!i.sessionID){g({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}b.filters.sessionID=[i.sessionID]}if(!o.deep&&b.regex?.deepScan){g({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let E=performance.now(),S=u.withIndex((Fe)=>mv(Fe,b));if(!S){g({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}i.onTiming?.("plan",performance.now()-E);let w=S.partial,R=y.after,A=new Map,P=new Map,C=[],q=!1,X=new Map,j=new WeakMap,V=new Map,J=new Map,{offset:ee,window:ae}=y,H=[...y.seen],ue=[...y.emitted],he=!1,$e=Math.max(1,Math.min(200,o.limit??30)),Ee=Math.min(S.candidateLimit??2000,o.group==="none"?kg:Math.min(2000,Math.max(kg,$e*32))),se=(Fe,Ue)=>{let Dt=A.get(Ue);if(Dt)return Dt;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)A.set(Ue,lt);return lt??void 0},pe=(Fe,Ue,Dt)=>{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 Mt=eo[Ue.kind];if(!Mt)return;let yr=lt.title;if(Ue.seq!==0){let st=`${Ue.session_id}:${Ue.seq}`,Jt=J.get(st);if(!Jt){let mn=Dt?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!Dt&&!mn)return;let Kt=Dt??JSON.parse(mn?.body??"null");Jt=Ke(Kt,!0),J.set(st,Jt)}let Zt=Jt.find((mn)=>mn.part===Ue.part&&mn.kind===Mt);if(!Zt)return;yr=Zt.text}let pr=Kl(yr,b);if(!pr)return;let jt=P.get(lt.id);if(jt===void 0)jt=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,jt);let ot=Ue.seq>0&&Ue.seq<=jt;if(b.filters.compacted!==void 0&&ot!==b.filters.compacted)return;let At={sessionID:lt.id,seq:Ue.seq,time:Ue.time,field:Mt,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:lv(Ue.relevance,Mt,Ue.time,y.now),flags:{archived:lt.archived_at!==null,compacted:ot,partial:yr.length>_i+Ai}};return X.set(At,{text:yr,ranges:pr}),C.push(At),q=!0,V.set(At,{doc:Ue.doc,part:Ue.part}),At},qe=(Fe)=>{let Ue=performance.now(),Dt=[...Fe].sort((ot,At)=>ot.time-At.time||ot.sessionID.localeCompare(At.sessionID)),lt=[],Mt=new Map;for(let ot of Dt){let At=V.get(ot),Jt=A.get(ot.sessionID),Zt=new Set;while(Jt?.forked_from_id&&Jt.forked_from_seq!==null&&ot.seq<=Jt.forked_from_seq&&!Zt.has(Jt.id))Zt.add(Jt.id),Jt=A.get(Jt.forked_from_id)??u.withIndex((Ro)=>se(Ro,Jt?.forked_from_id??""));let mn=`${Jt?.id??ot.sessionID}:${ot.seq}:${At?.part}:${At?.doc}`,Kt=Mt.get(mn);if(Kt){if(Kt.sessionID!==ot.sessionID)Kt.forks=[...new Set([...Kt.forks??[],ot.sessionID])]}else Mt.set(mn,ot),lt.push(ot)}let yr=[],pr=new Map,jt=new Map;for(let ot of lt){let At=`${ot.sessionID}:${ot.seq}`,st=jt.get(At);if(!st){jt.set(At,ot),j.set(ot,[ot]);continue}let Jt=[...j.get(st)??[st],ot],Zt=ot.score>st.score?ot:st;if(Zt.forks=[...new Set([...st.forks??[],...ot.forks??[]])],!Zt.forks.length)Zt.forks=void 0;Zt.flags={archived:st.flags.archived||ot.flags.archived,compacted:st.flags.compacted||ot.flags.compacted,partial:st.flags.partial||ot.flags.partial},jt.set(At,Zt),j.set(Zt,Jt)}for(let ot of Tg([...jt.values()],o.sort??"best")){let At=A.get(ot.sessionID);if(!At)continue;let st=o.group==="none"?void 0:pr.get(At.id);if(!st)st={session:{id:At.id,title:At.title,projectID:At.project_id,updated:At.updated},hits:[],more:0,...w&&o.group!=="none"?{moreIsLowerBound:!0}:{}},yr.push(st),pr.set(At.id,st);if(st.hits.length<bv||o.group==="none")st.hits.push(ot);else st.more++}return i.onTiming?.("group",performance.now()-Ue),yr},xt=(Fe)=>{for(let Ue of Fe)for(let Dt of Ue.hits){if(i.allowedSessionIDs&&Dt.forks)Dt.forks=Dt.forks.filter((yr)=>i.allowedSessionIDs?.has(yr));let lt=performance.now(),Mt=new Map;for(let yr of j.get(Dt)??[Dt]){let pr=X.get(yr);if(!pr)continue;for(let jt of Hl(pr.text,pr.ranges)){let ot=`${jt.line}:${jt.text}`,At=Mt.get(ot);if(!At)Mt.set(ot,jt);else At.ranges=[...new Map([...At.ranges,...jt.ranges].map((st)=>[st.join(":"),st])).values()]}}Dt.snippet=[...Mt.values()],i.onTiming?.("snippet",performance.now()-lt)}},Je=o.deep||S.scan,Yt=(Fe,Ue)=>{let Dt=se(Fe,Ue.session_id);if(!Dt)return[];let lt=xv(Fe,S,Ue,o.group==="none",Dt.forked_from_id!==null,i.onTiming);if(S.candidateLimit&&lt.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Mt=C.length,yr=performance.now();for(let pr of lt){if(i.signal?.aborted)break;let jt=pe(Fe,pr);if(!jt)continue;let ot=Pg(Fe,S,pr,X.get(jt)?.text??"");if(ot.length)jt.forks=ot}return i.onTiming?.("body",performance.now()-yr),C.slice(Mt)};if(Je){w=!1;let Fe=[],Ue=new Set,Dt=u.withIndex((st)=>{Ag(st,S);for(let Kt of st.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())A.set(Kt.id,Kt);let Jt=new Set(st.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 Ro=Kt.forked_from_id?A.get(Kt.forked_from_id):void 0;if(Ro)Zt(Ro);if(Jt.has(Kt.id))Fe.push(Kt)};for(let Kt of A.values())Zt(Kt);return(st.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
463
+ SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}
464
+ )`).get(...S.sessionBindings)?.n??0)+Jt.size})??0,lt=0,Mt=0,yr=0;if(b.regex?.deepScan)g({type:"groups",groups:[]});let pr=new Set,jt=new Set,ot=new Map,At=()=>{let st=qe(C),Jt=[];for(let Zt of st){let mn=Zt.session.id,Kt=o.group==="none"?void 0:ot.get(mn);if(o.group!=="none"&&jt.has(mn)&&!Kt)continue;if(!Kt){if(jt.add(mn),Mt<y.offset){Mt++;continue}if(yr>=$e){he=!0;break}yr++,ee++}if(o.group!=="none"){let Ro=(Kt?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,bv-(Kt?.shown??0));let gu=(Kt?.shown??0)+Zt.hits.length;Zt.more=Ro-gu,ot.set(mn,{shown:gu,count:Ro})}Jt.push(Zt)}if(Jt.length)xt(Jt),g({type:"groups",groups:Jt});C.length=0,X.clear(),V.clear(),J.clear()};for(let st of Fe){if(i.signal?.aborted||he)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||he)break;let mn=u.withIndex((Kt)=>{let Ro=Kt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(st.id,Math.max(0,Jt));if(Jt<0)Ro.unshift({seq:0,time:st.updated,body:null});for(let ji of Ro){if(i.signal?.aborted)break;let yu=ji.body?JSON.parse(ji.body):void 0;if(yu?.type==="assistant")Zt=yu.model;let Av=yu?Ke(yu,!0):[{part:0,kind:"title",text:st.title}];for(let jo of Av){if(i.signal?.aborted)break;let $s={session_id:st.id,seq:ji.seq,part:jo.part,doc:Number(BigInt(Bun.hash(jo.text))&0x1fffffffffffffn),kind:Ne[jo.kind],tool:jo.tool??null,err:Number(jo.err??!1),model:jo.model??(jo.tool?Zt:void 0)??null,time:ji.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
465
+ JOIN store.sessions s ON s.id=r.session_id WHERE ${S.where}`).get($s.session_id,$s.seq,$s.kind,$s.tool,$s.err,$s.model,$s.time,...S.bindings))continue;let zs=st,$g=new Set;while(zs.forked_from_id&&zs.forked_from_seq!==null&&ji.seq<=zs.forked_from_seq&&!$g.has(zs.id)){$g.add(zs.id);let xu=A.get(zs.forked_from_id);if(!xu)break;zs=xu}let vg=`${zs.id}:${ji.seq}:${jo.part}:${Bun.hash(jo.text)}`;if(pr.has(vg))continue;let Mg=pe(Kt,$s,yu);if(Mg){if(pr.add(vg),S.forks){let xu=Kt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(st.id,ji.seq,jo.part);if(xu){let Og=Pg(Kt,S,{...$s,doc:xu.doc},jo.text);if(Og.length)Mg.forks=Og}}}}}let gu=Ro.at(-1);if(gu)Jt=gu.seq;return Ro.length});if(mn===void 0){g({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=mn,g({type:"progress",scanned:lt,total:Dt}),i.signal?.aborted)return;if(At(),!mn||he)break;await Bun.sleep(0)}}}else u.withIndex((Fe)=>{if(w=dv(Fe,S,i.onTiming)||w,b.regex?b.regex.literals.every((lt)=>lt.some((Mt)=>[...Mt].length<3)):b.branches.some((lt)=>lt.include.length>0&&lt.include.every((Mt)=>[...Mt.text].length<3)))Fe.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let lt=fv(Fe,S,o.group==="none",y.now,i.onTiming);if(w||=S.partial,S.candidateLimit&&lt.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Mt=[];for(let pr of lt){if(i.signal?.aborted)return;let jt=Mt[$e]?.key.score;if(jt!==void 0&&pr.score+0.000000000001<jt)break;let ot=C.length,At=Yt(Fe,pr);C.splice(ot);let st=Tg([...At],"best")[0];if(!st)continue;let Jt={score:st.score,sessionID:st.sessionID,seq:o.group==="none"?st.seq:0};if(y.after&&Ev(Jt,y.after)<=0)continue;if(Mt.push({key:Jt,hits:At}),Mt.sort((Zt,mn)=>Ev(Zt.key,mn.key)),Mt.length>$e+1)Mt.length=$e+1}he=Mt.length>$e;let yr=Mt.slice(0,$e);for(let pr of yr)C.push(...pr.hits);R=yr.at(-1)?.key;return}let Dt=0;for(;;){if(i.signal?.aborted)return;let lt=gv(Fe,S,ae,Ee,i.onTiming),Mt=S.candidateLimit!==void 0&&ae+lt>=S.candidateLimit;w||=Mt;let yr=yv(Fe,o,ee,$e-Dt+1,y.now,H,i.onTiming);he=yr.length>$e-Dt;let pr=yr.slice(0,$e-Dt);if(!pr.length){if(lt<Ee||Mt){he=!1;break}ae+=lt,ee=0,H=[...new Set([...H,...ue])],ue=[];continue}for(let jt of pr)if(ee++,Yt(Fe,jt).length){if(Dt++,o.group!=="none")ue.push(jt.session_id)}if(Dt>=$e){he||=!Mt&&lt>=Ee;break}if(!he){if(lt<Ee||Mt)break;ae+=lt,ee=0,H=[...new Set([...H,...ue])],ue=[]}}});if(i.signal?.aborted)return;if(!Je){let Fe=qe(C);xt(Fe),g({type:"groups",groups:Fe})}if(!q){let Fe=b.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)g({type:"suggest",terms:u.withIndex((Ue)=>wg(Ue,Fe))??[]})}g({type:"done",cursor:he?Buffer.from(JSON.stringify(!Je&&o.sort!=="recent"?{...y,offset:0,window:0,seen:[],emitted:[],after:R}:{...y,offset:ee,window:ae,seen:H,emitted:ue})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:w,index:u.status()})}function Fo(e,o){return e.withIndex((i)=>wg(i,o))??[]}function Sv(e,o,i){let u=x({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(m([a({maxLength:2000}),$n()])),scope:n(m([s("session"),s("project"),s("all"),s(""),$n()])),fields:n(m([B(qr({type:"string",enum:[...Ln]})),$n()])),tool:n(m([a(),$n()])),isError:n(m([O(),$n()])),after:n(m([a(),Y(),$n()])),before:n(m([a(),Y(),$n()])),limit:n(m([_(),$n()])),session:n(m([a(),$n()])),seq:n(m([_(),$n()])),around:n(m([_(),$n()]))}),async execute(p,g,y){let b={query:g.query?.trim(),scope:g.scope||void 0,fields:g.fields?.length?g.fields:void 0,tool:g.tool?.trim(),isError:g.isError??void 0,after:g.after??void 0,before:g.before??void 0,limit:g.limit||void 0,session:g.session?.trim(),seq:g.seq??void 0,around:g.around??void 0},E=b.query?.trim(),S=!E&&Boolean(b.session?.trim())&&Number.isSafeInteger(b.seq)&&(b.seq??0)>=1;if(S&&b.around!==void 0&&(!Number.isInteger(b.around)||b.around<0||b.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(b.scope&&!["session","project","all"].includes(b.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(y?.aborted)throw Error("History search cancelled");let w=e.sessions().find((se)=>se.id===i);if(!w)throw Error("History session is unavailable");let R=(se)=>{if(se===void 0||se===0||typeof se==="string"&&!se.trim())return;if(typeof se==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(se))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let pe=typeof se==="number"?se:Date.parse(se);if(!Number.isFinite(pe)||Math.abs(pe)>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 pe},A=S?void 0:R(b.after),P=S?void 0:R(b.before);if(A!==void 0&&P!==void 0&&A>=P)throw Error("after must precede before");let C=[];if(S&&b.session&&b.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===b.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let pe=b.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(b.session,Math.max(1,b.seq-pe),b.seq+pe);if(!qe.some((Je)=>Je.seq===b.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:qe.map((Je)=>{let Yt={...JSON.parse(Je.body),seq:Je.seq,time:Je.time};return`[seq=${Je.seq}]
466
+ ${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
467
+ `).slice(0,4000)}`}).join(`
468
+
469
+ `)||"No history content"}],details:{groups:C,count:qe.length}}}if(!E)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(b.limit)?Math.max(1,Math.min(30,Math.trunc(b.limit??10))):10,X=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,j=new Set(e.sessions().filter((se)=>{if(b.scope==="session")return se.id===i;if((b.scope??"project")==="project"&&w.projectID)return se.projectID===w.projectID;return!0}).map((se)=>se.id)),V={q:E,filters:{tools:b.tool?.trim()?[b.tool.trim()]:void 0,isError:b.isError,after:A,before:P},group:"none",limit:q},J=Bl(V);if(J.error)throw Error(J.error.message);if(b.fields?.length){if(J.filters.fields=b.fields.filter((se)=>(se in Ne)),J.filters.fields.length!==b.fields.length)throw Error("Unknown search field")}if((b.scope??"project")==="session")J.filters.sessionID=[i];else if((b.scope??"project")==="project"&&w.projectID)J.filters.projectID=[w.projectID];let ee=o.status().state!=="ready",ae=!1;if(!ee){let se=J.filters.fields??Object.keys(Ne).filter((xt)=>(xt in Ne)),pe=se.filter((xt)=>xt!=="title"),qe=pe.length?[pe]:[];if(se.includes("title"))qe.push(["title"]);for(let xt of qe){if(C.length>=q&&ae)break;if(await Gr(o,{...V,limit:Math.max(1,q-C.length),filters:{...J.filters,fields:xt}},{signal:y,excludeEntry:X===void 0?void 0:{sessionID:i,seq:X},sessionID:i,allowedSessionIDs:j,onEvent(Je){if(Je.type==="groups")C.push(...Je.groups);if(Je.type==="done")ae||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")ee=!0;else throw Error(Je.message)}}),ee)break}}let H=[],ue=0;if(ee){C.length=0;let se=performance.now()+2000;e:for(let pe of e.sessions()){if(!j.has(pe.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(pe.id))continue;if(J.filters.projectID&&(!pe.projectID||!J.filters.projectID.includes(pe.projectID)))continue;let qe=Number.MAX_SAFE_INTEGER,xt=!0;for(;;){let Je=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(pe.id,qe);if(xt)Je.push({body:"null",seq:0,time:pe.updated}),xt=!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(ue>=1e4||performance.now()>se){ae=!0;break e}if(ue++,pe.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:pe.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 Dt=Kl(Ue.text,J);if(!Dt)continue;if(C.length>=q&&Ue.kind!=="title"){ae=!0;break e}(Ue.kind==="title"?H:C).push({session:{id:pe.id,title:pe.title,projectID:pe.projectID,updated:pe.updated},more:0,hits:[{sessionID:pe.id,seq:Yt.seq,time:Yt.time,field:Ue.kind,tool:Ue.tool,isError:Boolean(Ue.err),snippet:Hl(Ue.text,Dt),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-C.length))ae=!0;if(C.push(...H.slice(0,q)),C.sort((se,pe)=>Number(se.hits[0]?.field==="title")-Number(pe.hits[0]?.field==="title")),C.length>q)ae=!0;C.length=Math.min(C.length,q);let he=new Map;for(let se of C)for(let pe of se.hits){let qe=he.get(se.session.id)??[];qe.push(`[${se.session.title.replace(/[\r\n]/g," ")} \xB7 ${pe.sessionID} \xB7 ${pe.seq} \xB7 ${new Date(pe.time).toISOString()} \xB7 ${pe.field}${pe.tool?`/${pe.tool}`:""}]
470
+ ${pe.snippet.slice(0,3).map((xt)=>{let Je=xt.text;for(let[Yt,Fe]of[...xt.ranges].sort((Ue,Dt)=>Dt[0]-Ue[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Fe)}\u3011${Je.slice(Fe)}`;return Je}).join(`
471
+ `)}`),he.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",o.status().state==="disabled")$e="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let Ee=C.reduce((se,pe)=>se+pe.hits.length,0);return{content:[{type:"text",text:[$e,ee&&ae?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ue} \u6761`:"",[...he.values()].map((se)=>se.join(`
472
+
473
+ `)).join(`
474
+
475
+ `),Ee===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${Ee} \u6761\uFF1B${ae?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
476
+ `)}],details:{groups:C,count:Ee}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}async function wv(e,o){let i=o.projectID?e.store.project(o.projectID):void 0,u=i?.directory??process.cwd(),g=o.info().kind==="sub",y=()=>g||o.records.some((S)=>S.entry.type==="compaction"),b=e.options.tools??nr({directory:i?.directory,records:()=>o.records,history:(S)=>e.resolveHistory(o.id,S),onTodos:(S)=>o.setTodos(S),shell:()=>e.serverShell(),hasCompacted:y});if(e.options.tools===void 0)b.push(Sv(e.store,e.search,o.id));let E=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:S$({project:i,globalInstructions:RK(e),git:i?await w$(i.directory):void 0,shell:e.serverShell()});return{systemPrompt:E.map((S)=>S.detail).join(""),systemParts:E,tools:[...b,...e.tools.snapshot()],cwd:u}}var TK=[hu(".basalt","AGENTS.md"),hu(".agents","AGENTS.md"),hu(".opencode","AGENTS.md"),hu(".claude","CLAUDE.md"),hu(".codex","AGENTS.md")];function RK(e){let o=e.options.homeDir??wK();for(let i of TK){let u=hu(o,i);try{if(EK(u))return SK(u,"utf8")}catch{return}}return}class zr{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new hg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Fl(Cg(e.dataDir,"basalt.db")),this.plugins=new Jh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Ul(this.plugins,()=>this.builtinToolNames()),this.search=new Qh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let i=this.open(o,"restore");this.sessions.set(o.id,i),this.restored.add(i)}}static async create(e){let o=new zr(e);try{return await o.initialize(),o}catch(i){throw await o.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Cg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Cg(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 X$(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...jl(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>J$(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let u=o.archive??"active";return u==="all"||i.archivedAt!==null===(u==="archived")}).sort((i,u)=>u.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let i=this.get(e);if(!i)throw new t("History session is unavailable");return i.resolveHistory(o)}openStoredSession(e,o="restore"){let i=this.open(e,o);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let o=e.model??this.defaultModel;if(!En(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),u={id:ne("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let p=this.open(u);return this.sessions.set(u.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,o,i){o={...o,archivedAt:null},this.store.copySession(e,o,i);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new f("no such session");let i=o.info(),u=i.projectID?this.store.project(i.projectID):void 0;return O$(i,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let i=[o.model,e.model,this.defaultModel].find((y)=>y!==void 0&&En(this.options.models,y)!==void 0),u=i?En(this.options.models,i):void 0;if(!i||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:ne("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:i,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?N$(e.records,u):e.records);let g=this.open(p);return this.sessions.set(p.id,g),this.emit({type:"session",session:g.info()}),g}truncateHistory(e,o){let i=this.sessions.get(e.id);if(!i)throw new f("no such session");if(i.assertWritable(),i.status==="busy")throw new ie;if(!En(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);i.close();for(let p of this.sessions.values()){if(p.info().parentID!==e.id)continue;if(p.status==="busy")p.abort();p.close()}this.store.truncateSession(e,o);let u=this.open(e,"replay");return this.sessions.set(e.id,u),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)}),u}setArchived(e,o){let i=this.sessions.get(e);if(!i)throw new f("no such session");if(i.info().parentID)throw new t("\u8BF7\u5F52\u6863\u6216\u6062\u590D\u6240\u5C5E\u4F1A\u8BDD\uFF08\u542B\u5B50\u4F1A\u8BDD\uFF09");let u=this.sessionTree(i);if(u.some((p)=>p.status==="busy"))throw new ie;if(i.isArchived===o)return i.info();this.store.setArchived(u.map((p)=>p.id),o?Date.now():null);for(let p of u)p.refreshArchive();for(let p of u)p.archiveChanged();return i.info()}sessionTree(e){let o=[e];for(let i=0;i<o.length;i++){let u=o[i];if(!u)continue;for(let p of this.sessions.values())if(p.info().parentID===u.id)o.push(p)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new f("no such session");if(o.status==="busy")throw new ie;let i=this.sessionTree(o).slice(1),u=()=>{for(let p of i)p.close(),this.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return u();o.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(u)}open(e,o="create"){let i=e.id,u=new Ol(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>wv(this,p)},{entry:(p)=>{this.emit({type:"entry",sessionID:i,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:i,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(p)=>this.emit({type:"draft",sessionID:i,parts:p}),changed:()=>{let p=this.sessions.get(i);if(p)this.emit({type:"session",session:p.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new qi(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!Jl.includes(e))throw new t(`Invalid shell type; must be ${Jl.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return Y$(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(i){console.error("runtime listener failed",i)}}}var Ce={now:()=>Date.now(),after(e,o){let i=setTimeout(o,e);return()=>clearTimeout(i)}};var Tv=1048576,Rv=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,i,u){this.cwd=e;this.outputLimit=o;this.terminal=i;this.shellPreference=u}setTerminalObserver(e){this.terminal=e}start(e,o,i){let u=i?.observer,p=i?.clock??Ce;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let X=nd(e);if(X.length>0)throw Error(od(X))}if(this.list().filter((X)=>X.state==="running").length>=Rv)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${Rv}\uFF09`);let y=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:b,isWindows:E}=Ea(e,y),S=Bun.spawn(b,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!E,windowsHide:!0,env:{...process.env,...em(this.cwd)}}),w={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:S,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(w.id,w);let R=()=>{for(let X of w.waiters.splice(0))X()},A=async(X,j)=>{let V=new Tl;for await(let ee of X){let ae=V.decode(ee);w.output+=ae,u?.output(ae,j);let H=Buffer.from(w.output);if(H.length>Tv){let ue=H.length-Tv;while(ue<H.length&&(H[ue]??0)>>6===2)ue++;let he=H.subarray(ue).toString(),$e=w.output.length-he.length;w.unreadDroppedBytes+=Buffer.byteLength(w.output.slice(Math.max(0,w.readAt-w.dropped),$e)),w.output=he,w.dropped+=$e}R()}let J=V.flush();if(w.output+=J,J)u?.output(J,j)},P,C=Promise.all([A(S.stdout,"stdout"),A(S.stderr,"stderr")]).catch((X)=>{P=X,this.kill(w)}),q=!1;if(w.done=(async()=>{if(w.code=await S.exited,w.timer?.(),this.kill(w),await C,P)throw P;if(w.state==="running")w.state="exited";if(q=!0,u?.end(w.state,w.code),!u&&w.state!=="killed")this.terminal?.(w);R()})().catch((X)=>{if(w.state="exited",w.output+=`
477
+ [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(X)}]`,!q)u?.end(w.state,w.code);if(u)throw X;if(!u)this.terminal?.(w,X);R()}),o!==void 0)w.timer=p.after(o,()=>{if(w.state==="running")w.state="timeout",this.kill(w)});return w}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128&&e.proc.exitCode===null)throw Error("\u65E0\u6CD5\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B\u6811\uFF0C\u8BF7\u68C0\u67E5\u8FDB\u7A0B\u6743\u9650")}else process.kill(-e.proc.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,o,i=0,u=!1,p){let g=this.find(e),y=o?new RegExp(o):void 0,b=Date.now()+i;p?.throwIfAborted();while(g.state==="running"){p?.throwIfAborted();let A=g.output.slice(Math.max(0,g.readAt-g.dropped));if((y?y.test(A):!u)||Date.now()>=b)break;await new Promise((P,C)=>{let q=()=>{clearTimeout(j);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);C(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,b-Date.now()));g.waiters.push(X),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let E=g.unreadDroppedBytes;g.unreadDroppedBytes=0;let S=g.output.slice(Math.max(0,g.readAt-g.dropped));g.readAt=g.dropped+g.output.length;let w=S.slice(-this.outputLimit),R=E+Buffer.byteLength(S.slice(0,S.length-w.length));return{job:g,output:`${R?`[truncated ${R} bytes]
478
+ `:""}${w}`}}async write(e,o,i=!1,u){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let g=p.proc.stdin;if(!g||typeof g==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let y=await je(o,u);if(y)throw Error(y);g.write(o)}if(i)await g.end();else await g.flush()}async stop(e){let o=this.find(e);if(o.state==="running")o.state="killed",this.kill(o);return await o.done,{id:o.id,state:o.state,code:o.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var Wl=new WeakMap,zl=new WeakMap;function sr(e,o){let i=Wl.get(e);if(!i)i=o(),Wl.set(e,i);return i}function ar(e){zl.set(e,(zl.get(e)??0)+1)}function lr(e,o){let i=(zl.get(o)??1)-1;if(zl.set(o,i),i>0)return!1;if(o.close(),Wl.get(e)===o)Wl.delete(e);return!0}async function N(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function v(e,o){let i=e[o];if(!i)throw new t(`${o} is required`);return i}var Dn=100,cr=1e4,kK=60000,AK=200,kn=()=>a(),kv=()=>n(_({minimum:1,maximum:cr})),Jc=()=>n(a({minLength:1,maxLength:128})),PK=m([l({click:m([kn(),l({selector:kn()})])}),l({type:l({label:kn(),text:kn()})}),l({waitText:kn(),timeoutMs:kv()}),l({expectText:kn(),within:n(kn())}),l({waitSelector:kn(),timeoutMs:kv()}),l({expectCount:l({selector:kn(),n:_({minimum:0})})}),l({snapshot:l({selector:kn(),depth:n(_({minimum:0,maximum:AK}))})}),l({expectCalls:l({onOpen:n(B(kn())),onClose:n(_({minimum:0}))})}),l({expectValue:l({label:kn(),value:kn()})})]),CK=l({status:_({minimum:100,maximum:599}),body:Rr(),delayMs:n(_({minimum:0,maximum:cr}))}),$K=m([s("paths"),s("request"),s("verify"),s("ui_test"),s("list"),s("docs"),s("check"),s("load"),s("reload"),s("enable"),s("disable")]),vK=m([s("page"),s("tab"),s("card"),s("sidebar")]),gi=l({action:$K,path:n(a({minLength:1,maxLength:4096})),method:n(kn()),body:n(bs(kn(),Rr())),importTimeoutMs:n(_({minimum:1,maximum:cr})),timeoutMs:n(_({minimum:1,maximum:kK})),sessionID:Jc(),scope:n(m([s("user"),s("all")])),id:Jc(),slot:Jc(),view:Jc(),codeBlock:Jc(),kind:n(vK),props:n(bs(kn(),Rr())),context:n(bs(kn(),Rr())),steps:n(B(PK,{maxItems:Dn})),mockRoutes:n(bs(kn(),CK)),topic:n(a({maxLength:100})),grep:n(a({minLength:1,maxLength:200}))});
479
+ export{t,f,Fr,Wr,li,$r,er,Io,Ln,ci,ui,pi,Bt,di,mi,Hr,Mo,hi,Be,fi,ut,Ft,z,Lo,je,et,B,n,l,qr,O,_,s,Y,a,m,h,le,On,Oo,No,Do,Uo,_e,x,tt,pt,k,D,F,Re,ce,Te,c,de,rt,tr,rr,nr,dt,ie,Bo,or,ir,ne,Nn,Gr,Fo,zr,Ce,Wt,sr,ar,lr,N,v,Wo,Dn,cr,gi};