@bkm016/basalt 0.1.3 → 0.1.5

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 (287) hide show
  1. package/README.md +53 -5
  2. package/{chunk-y648fzx0.js → chunk-0039s4jt.js} +3 -3
  3. package/{chunk-m40gxwq4.js → chunk-00gwse5r.js} +3 -3
  4. package/{chunk-t6zs4kw0.js → chunk-0fwdxd45.js} +2 -2
  5. package/{chunk-6hssbcgj.js → chunk-0j0qggej.js} +1 -1
  6. package/chunk-0n99m9m4.js +2 -0
  7. package/{chunk-d8gtbw9g.js → chunk-0stvywr8.js} +1 -1
  8. package/{chunk-ztsjgssj.js → chunk-1xa7d5mh.js} +1 -1
  9. package/chunk-2nb3d92s.js +2 -0
  10. package/chunk-2nkfxhef.js +3868 -0
  11. package/chunk-2pa1z37c.js +2 -0
  12. package/{chunk-fw2bpqmw.js → chunk-2qcpq99g.js} +1 -1
  13. package/{chunk-981f9dw8.js → chunk-36cqq0ga.js} +6 -6
  14. package/{chunk-3cjsd292.js → chunk-3c330qna.js} +2 -2
  15. package/chunk-3k627vf2.js +3 -0
  16. package/{chunk-r7fpkb49.js → chunk-3k7ejpkc.js} +1 -1
  17. package/chunk-4g5f43ea.js +3 -0
  18. package/{chunk-fjtvjrkg.js → chunk-539ekagy.js} +4 -4
  19. package/{chunk-97rzj7f6.js → chunk-5v4g21rw.js} +1 -1
  20. package/{chunk-aefadsy6.js → chunk-6dsq0fns.js} +2 -2
  21. package/{chunk-pbcy6zdt.js → chunk-7as47pcw.js} +1 -1
  22. package/{chunk-g2t6t8fk.js → chunk-7jezts2n.js} +2 -2
  23. package/{chunk-8tjad3r0.js → chunk-7qq99360.js} +6 -6
  24. package/{chunk-gp7y0fja.js → chunk-7tgqhveh.js} +15 -15
  25. package/{chunk-mvfsxdx6.js → chunk-7w0mefgk.js} +10 -10
  26. package/{chunk-y58ygzn9.js → chunk-818nd6s1.js} +3 -3
  27. package/{chunk-vv7fp27r.js → chunk-8mezk0cb.js} +2 -2
  28. package/{chunk-rtzqqngy.js → chunk-8xb636vr.js} +5 -5
  29. package/{chunk-2esbgxps.js → chunk-980drajf.js} +15 -15
  30. package/{chunk-c7x1zq39.js → chunk-9z7sdh5e.js} +3 -3
  31. package/{chunk-10xzzn07.js → chunk-a4b75ekk.js} +2 -2
  32. package/{chunk-5j1krv9v.js → chunk-ar3dbfp9.js} +1 -1
  33. package/{chunk-vk1gxk1t.js → chunk-aw65h276.js} +1 -1
  34. package/{chunk-75m78j7x.js → chunk-b9fqretv.js} +2 -2
  35. package/{chunk-y0m980k3.js → chunk-bgkegf0k.js} +22 -22
  36. package/{chunk-0y7ne3d0.js → chunk-bwawt15q.js} +2 -2
  37. package/{chunk-pxsrqrd0.js → chunk-c4qr1f41.js} +2 -2
  38. package/chunk-dddsrff6.js +478 -0
  39. package/{chunk-xfvvh1s5.js → chunk-e63c1186.js} +1 -1
  40. package/{chunk-8296hw9m.js → chunk-ebzkckyw.js} +2 -2
  41. package/chunk-eegztdzb.js +2 -0
  42. package/{chunk-hwr56pfj.js → chunk-gw05p4g3.js} +1 -1
  43. package/{chunk-k23t7vhs.js → chunk-h1rypb99.js} +5 -5
  44. package/{chunk-nbb9trwz.js → chunk-hq5ke1yp.js} +2 -2
  45. package/{chunk-jwdb0ccj.js → chunk-jvwg4rn1.js} +3 -3
  46. package/{chunk-fm0k0qtz.js → chunk-jyrwk08p.js} +2 -2
  47. package/chunk-kns4kv7b.js +3 -0
  48. package/{chunk-8d46jtbj.js → chunk-mat08ab1.js} +2 -2
  49. package/{chunk-bannb9xm.js → chunk-mkp28k1x.js} +2 -2
  50. package/{chunk-d2j735sd.js → chunk-npez1492.js} +2 -2
  51. package/{chunk-shadcb9z.js → chunk-nx3jnbv8.js} +2 -2
  52. package/{chunk-ykens1hy.js → chunk-nxkmd29x.js} +1 -1
  53. package/{chunk-y7nma9rk.js → chunk-pjr91g6k.js} +2 -2
  54. package/{chunk-m8vkwdgr.js → chunk-r0jc8e7t.js} +4 -4
  55. package/chunk-rxj6tct8.js +2 -0
  56. package/{chunk-362g64pd.js → chunk-sqaam5ak.js} +1 -1
  57. package/{chunk-gzxnene8.js → chunk-srjgvdvs.js} +12 -12
  58. package/{chunk-r9aatvwm.js → chunk-stj493dn.js} +2 -2
  59. package/{chunk-k6w6y71k.js → chunk-t7sc0wwc.js} +2 -2
  60. package/{chunk-27gntzs5.js → chunk-v4k3qmdm.js} +2 -2
  61. package/{chunk-x1xss1d7.js → chunk-vt1anydc.js} +4 -4
  62. package/chunk-wd3z74av.js +2 -0
  63. package/{chunk-z55bmysw.js → chunk-wfyrfvfn.js} +1 -1
  64. package/{chunk-v9fea96h.js → chunk-wnzvnskb.js} +2 -2
  65. package/{chunk-cjc90f84.js → chunk-x89em726.js} +3 -3
  66. package/{chunk-1qpces5a.js → chunk-xtq1xpq0.js} +2 -2
  67. package/chunk-yna8bwqc.js +2 -0
  68. package/{chunk-k506w58v.js → chunk-zn0g0859.js} +2 -2
  69. package/{chunk-qe0teyn1.js → chunk-zrkh5dw7.js} +1 -1
  70. package/chunk-zzwjt7fp.js +2 -0
  71. package/compiled.js +12 -12
  72. package/package.json +1 -1
  73. package/ui-test-worker.js +20 -20
  74. package/web/chunk-01hcjafh.js +2 -0
  75. package/web/{chunk-n8sky2q6.js → chunk-07agqp8h.js} +1 -1
  76. package/web/{chunk-tx8240k4.js → chunk-0k9aec1s.js} +20 -20
  77. package/web/{chunk-74j07k8k.js → chunk-0p1nmj5n.js} +2 -2
  78. package/web/chunk-0qr891eq.js +70 -0
  79. package/web/{chunk-ts7zrf5b.js → chunk-0whceqes.js} +2 -2
  80. package/web/chunk-0ytga215.js +1 -0
  81. package/web/{chunk-h288yd5w.js → chunk-12z7d0hp.js} +3 -3
  82. package/web/chunk-14bad871.js +2 -0
  83. package/web/chunk-1amzv4ha.js +1 -0
  84. package/web/chunk-1cfh0e2e.js +324 -0
  85. package/web/chunk-1pasbxwh.js +89 -0
  86. package/web/{chunk-j0bwwc1g.js → chunk-1s2hp6h1.js} +1 -1
  87. package/web/chunk-26bwh1sb.js +169 -0
  88. package/web/{chunk-b0a8nbj0.js → chunk-2nht58dc.js} +5 -5
  89. package/web/chunk-2y0rc1fe.js +1 -0
  90. package/web/chunk-3hkgdw6f.js +36 -0
  91. package/web/chunk-4a4j030b.js +1 -0
  92. package/web/{chunk-4fzj0azw.js → chunk-4m3zdd41.js} +6 -6
  93. package/web/chunk-4w298aqs.js +1 -0
  94. package/web/{chunk-2hd1pe9w.js → chunk-56krfj3b.js} +7 -7
  95. package/web/{chunk-ds7srg4p.js → chunk-5nda24gv.js} +1 -1
  96. package/web/{chunk-5hmfk69r.js → chunk-5shygfgb.js} +19 -19
  97. package/web/chunk-65nwc4cf.js +1 -0
  98. package/web/chunk-6bwgdvf6.js +1 -0
  99. package/web/chunk-6enn8p66.js +1 -0
  100. package/web/chunk-6stt9d18.js +1 -0
  101. package/web/{chunk-4gavbw65.js → chunk-7a3c137d.js} +1 -1
  102. package/web/chunk-7e47b1sn.js +1 -0
  103. package/web/chunk-7pypx5h8.js +2 -0
  104. package/web/chunk-7znyd1mj.js +39 -0
  105. package/web/{chunk-0z0jycs8.js → chunk-892nf39p.js} +7 -7
  106. package/web/chunk-8r0s8tx7.js +1 -0
  107. package/web/chunk-9dy7z3ej.js +2 -0
  108. package/web/chunk-9mq2cdtq.js +1 -0
  109. package/web/chunk-9w5tf22s.js +1 -0
  110. package/web/{chunk-es28k2t7.js → chunk-9xgspn75.js} +2 -2
  111. package/web/{chunk-0xc2c540.js → chunk-abhad4zj.js} +56 -56
  112. package/web/chunk-advfpyb9.js +140 -0
  113. package/web/chunk-affear07.js +3 -0
  114. package/web/chunk-ahztazsg.js +1 -0
  115. package/web/chunk-aqt7kc3s.js +106 -0
  116. package/web/chunk-b5hah4mf.js +1 -0
  117. package/web/chunk-b8tfetd8.js +1 -0
  118. package/web/{chunk-7yc083xj.js → chunk-bnb9xhgw.js} +15 -15
  119. package/web/{chunk-n1dmrz44.js → chunk-c01176kn.js} +2 -2
  120. package/web/chunk-c3nn0vvc.js +1 -0
  121. package/web/chunk-c53xmf48.js +30 -0
  122. package/web/chunk-ckgpy4r4.js +1 -0
  123. package/web/chunk-crzseqbx.js +24 -0
  124. package/web/chunk-d22wq71s.js +1 -0
  125. package/web/{chunk-97b62pvb.js → chunk-d60dpf69.js} +19 -19
  126. package/web/{chunk-sn9ecfvy.js → chunk-d6ddkh6e.js} +1 -1
  127. package/web/{chunk-cg3jterp.js → chunk-d9wdsjkk.js} +2 -2
  128. package/web/{chunk-ttg6tbwx.js → chunk-da7m1kva.js} +2 -2
  129. package/web/chunk-dbnrfxt1.js +8 -0
  130. package/web/chunk-ddxf8e84.js +1 -0
  131. package/web/chunk-dzg1pv80.js +200 -0
  132. package/web/{chunk-xnq41dgs.js → chunk-e8h45nyr.js} +1 -1
  133. package/web/chunk-ej9vb61c.js +1 -0
  134. package/web/chunk-f9k3xrwb.js +2 -0
  135. package/web/{chunk-7xk0ntav.js → chunk-fjag6yg8.js} +2 -2
  136. package/web/chunk-fnnrrzqa.js +78 -0
  137. package/web/{chunk-n90cqdvg.js → chunk-fv6vm14n.js} +2 -2
  138. package/web/{chunk-axkyft9f.js → chunk-g5jxwkdh.js} +1 -1
  139. package/web/{chunk-ep37qp12.js → chunk-g8kkc6vz.js} +1 -1
  140. package/web/chunk-g9sqbafw.js +2 -0
  141. package/web/{chunk-g46f421r.js → chunk-gcv91974.js} +4 -4
  142. package/web/{chunk-7qxhk1kz.js → chunk-gxqaa4sv.js} +7 -7
  143. package/web/chunk-gxsb5tx3.js +1 -0
  144. package/web/{chunk-54thej0t.js → chunk-gyp6v7jd.js} +2 -2
  145. package/web/chunk-h0c42zy3.js +1 -0
  146. package/web/chunk-h2ag4kvz.js +2 -0
  147. package/web/{chunk-eqsd8zta.js → chunk-h6gh63xj.js} +2 -2
  148. package/web/{chunk-6m69hczt.js → chunk-h6k1x096.js} +2 -2
  149. package/web/{chunk-24mfx6w1.js → chunk-j1bw5v1g.js} +2 -2
  150. package/web/chunk-j34q5jn6.js +1 -0
  151. package/web/{chunk-0pbjgdgp.js → chunk-ja7w629n.js} +2 -2
  152. package/web/{chunk-zbj1trar.js → chunk-jam45rqg.js} +2 -2
  153. package/web/{chunk-23c1df7e.js → chunk-jcdw85mv.js} +1 -1
  154. package/web/chunk-jfvxxp5c.js +1 -0
  155. package/web/chunk-jg6fmz2d.js +1 -0
  156. package/web/{chunk-90xqeczk.js → chunk-k67v6dyg.js} +40 -40
  157. package/web/chunk-ka7c5rhx.js +99 -0
  158. package/web/{chunk-acybsx44.js → chunk-kza0t0gj.js} +1 -1
  159. package/web/{chunk-7520nrbb.js → chunk-m8knte9z.js} +1 -1
  160. package/web/{chunk-v5cnt7c8.js → chunk-mnzramhc.js} +1 -1
  161. package/web/{chunk-7v5rxabp.js → chunk-mpfgr049.js} +1 -1
  162. package/web/chunk-mz1dabxh.js +1 -0
  163. package/web/chunk-mz9b5bsa.js +1 -0
  164. package/web/chunk-p53n0hwr.js +1 -0
  165. package/web/chunk-paywgcf7.js +40 -0
  166. package/web/chunk-pfcnr9tw.js +1 -0
  167. package/web/chunk-pyg1mr80.js +303 -0
  168. package/web/chunk-q7xkscc5.js +1 -0
  169. package/web/{chunk-xzp7jf7e.js → chunk-qcge7d6s.js} +2 -2
  170. package/web/chunk-qmbgb79a.js +1139 -0
  171. package/web/{chunk-5b2nw6j1.js → chunk-qq5gh5zr.js} +1 -1
  172. package/web/chunk-qrdh9j62.js +1 -0
  173. package/web/{chunk-w7snhcyg.js → chunk-s24qs1bn.js} +9 -9
  174. package/web/chunk-sd22cnjy.js +1 -0
  175. package/web/{chunk-ydtrc1ay.js → chunk-sd3cdqcm.js} +2 -2
  176. package/web/{chunk-rykfak98.js → chunk-sf101c23.js} +2 -2
  177. package/web/{chunk-p9hsd3rn.js → chunk-sfq6cw45.js} +2 -2
  178. package/web/chunk-svqj4az8.js +1 -0
  179. package/web/chunk-t7jwyvvr.js +1 -0
  180. package/web/{chunk-47q4hmfp.js → chunk-tcp77cp2.js} +2 -2
  181. package/web/chunk-tf18d2dk.css +1 -0
  182. package/web/chunk-thbqwq6b.js +1 -0
  183. package/web/chunk-v0g4cqc1.js +4 -0
  184. package/web/chunk-vhzys0rr.js +292 -0
  185. package/web/chunk-vnt34mkb.js +1 -0
  186. package/web/chunk-vqfz99ff.js +1 -0
  187. package/web/chunk-vttgyb5v.js +2 -0
  188. package/web/chunk-x7sb3bwf.js +370 -0
  189. package/web/chunk-xce8n339.js +1 -0
  190. package/web/{chunk-mb4qx9hy.js → chunk-xk1t58c4.js} +12 -12
  191. package/web/chunk-xsrvw7dt.js +4 -0
  192. package/web/chunk-xtss82z2.js +1 -0
  193. package/web/{chunk-2j4m0bh1.js → chunk-y7jq61nv.js} +2 -2
  194. package/web/{chunk-7ba8vrfc.js → chunk-ybw6vgf6.js} +2 -2
  195. package/web/{chunk-24h1rfje.js → chunk-yvgs6bm3.js} +4 -4
  196. package/web/{chunk-sb1cjpq8.js → chunk-z4aj066q.js} +1 -1
  197. package/web/chunk-zazs8p6c.js +1 -0
  198. package/web/{chunk-n8gfjj9a.js → chunk-zc1mk10n.js} +19 -19
  199. package/web/{chunk-5qqw2e0t.js → chunk-zqht0jzx.js} +6 -6
  200. package/web/{chunk-mwj9tpkz.js → chunk-zz397b0v.js} +12 -12
  201. package/web/index.html +1 -1
  202. package/worker.js +1 -1
  203. package/chunk-06hdzq5n.js +0 -2
  204. package/chunk-09rj27b2.js +0 -2
  205. package/chunk-1zdwrgd4.js +0 -2
  206. package/chunk-5c9j8qe4.js +0 -478
  207. package/chunk-9mmz6wt3.js +0 -2
  208. package/chunk-bpw6q7g0.js +0 -3
  209. package/chunk-bxn5kmpz.js +0 -3753
  210. package/chunk-n6e43rvk.js +0 -3
  211. package/chunk-pmqtkqsf.js +0 -2
  212. package/chunk-ry0z4ev6.js +0 -2
  213. package/chunk-v258nxcz.js +0 -2
  214. package/chunk-zmsgwr3s.js +0 -2
  215. package/web/chunk-0s80zw00.js +0 -1
  216. package/web/chunk-166qe5j6.js +0 -2
  217. package/web/chunk-1c95wfvq.js +0 -1
  218. package/web/chunk-329rtxa9.js +0 -1
  219. package/web/chunk-33qwz9bc.js +0 -2
  220. package/web/chunk-3qjnwsph.js +0 -1
  221. package/web/chunk-4rm1vy7w.js +0 -1
  222. package/web/chunk-59kqahb3.js +0 -1
  223. package/web/chunk-61jahh35.js +0 -292
  224. package/web/chunk-6beqrmtq.js +0 -1
  225. package/web/chunk-6gxf3vsg.js +0 -1
  226. package/web/chunk-6parf7sy.js +0 -2
  227. package/web/chunk-89fkdgbp.js +0 -2
  228. package/web/chunk-8qgpfxkz.js +0 -1
  229. package/web/chunk-9a3q0jsh.js +0 -36
  230. package/web/chunk-9bgey148.js +0 -169
  231. package/web/chunk-9xh96b33.js +0 -2
  232. package/web/chunk-a5sg33w2.js +0 -3
  233. package/web/chunk-a91vxtx4.js +0 -1
  234. package/web/chunk-agec7jj4.js +0 -1
  235. package/web/chunk-c516cghj.js +0 -1
  236. package/web/chunk-cqp1d4p0.js +0 -1
  237. package/web/chunk-cwtdnacf.js +0 -1
  238. package/web/chunk-dg1vas6z.js +0 -8
  239. package/web/chunk-dy2gm1fs.js +0 -1
  240. package/web/chunk-f91wzwtk.js +0 -1
  241. package/web/chunk-fc0nx23g.js +0 -1
  242. package/web/chunk-fhnypcrm.js +0 -1139
  243. package/web/chunk-fv60p68p.js +0 -1
  244. package/web/chunk-g1ev11wx.js +0 -1
  245. package/web/chunk-h18tnrf2.js +0 -1
  246. package/web/chunk-hfaffkrh.js +0 -1
  247. package/web/chunk-hszjc2ny.js +0 -70
  248. package/web/chunk-j2vt8c8v.js +0 -1
  249. package/web/chunk-jqa39f8t.js +0 -78
  250. package/web/chunk-jvbbrnpa.js +0 -1
  251. package/web/chunk-jzfd7cyh.js +0 -2
  252. package/web/chunk-ka3q31t1.js +0 -1
  253. package/web/chunk-ka9ak8wr.js +0 -1
  254. package/web/chunk-m2d1sp30.js +0 -1
  255. package/web/chunk-mnjd59jk.js +0 -1
  256. package/web/chunk-ng0nbfhh.js +0 -1
  257. package/web/chunk-nz9nxk48.js +0 -1
  258. package/web/chunk-phw908hn.js +0 -1
  259. package/web/chunk-pjmmma1k.js +0 -1
  260. package/web/chunk-pxe3vna4.js +0 -1
  261. package/web/chunk-q7yn4m3t.js +0 -1
  262. package/web/chunk-qh15dxav.css +0 -1
  263. package/web/chunk-qnhqexe0.js +0 -1
  264. package/web/chunk-rcx1aee5.js +0 -99
  265. package/web/chunk-rjqj6ffe.js +0 -1
  266. package/web/chunk-rks7ksv3.js +0 -106
  267. package/web/chunk-rtf2zzzv.js +0 -1
  268. package/web/chunk-sgvp8vge.js +0 -1
  269. package/web/chunk-sjjwte12.js +0 -1
  270. package/web/chunk-srrfphes.js +0 -1
  271. package/web/chunk-t7bwsdbr.js +0 -1
  272. package/web/chunk-tse9gvyq.js +0 -89
  273. package/web/chunk-vd6y2pcm.js +0 -39
  274. package/web/chunk-vpa55vje.js +0 -4
  275. package/web/chunk-vymqrpm3.js +0 -303
  276. package/web/chunk-wdtnhpd6.js +0 -4
  277. package/web/chunk-wmvd6j0b.js +0 -200
  278. package/web/chunk-xvsmtetz.js +0 -30
  279. package/web/chunk-y3ajqthy.js +0 -370
  280. package/web/chunk-yd1ez3wd.js +0 -2
  281. package/web/chunk-yfbxtg5p.js +0 -1
  282. package/web/chunk-ywp4s71k.js +0 -40
  283. package/web/chunk-z4x331rx.js +0 -140
  284. package/web/chunk-z6bpamwq.js +0 -24
  285. package/web/chunk-zmdnxn6m.js +0 -2
  286. package/web/install.ps1 +0 -91
  287. package/web/install.sh +0 -177
@@ -0,0 +1,478 @@
1
+ // @bun
2
+ import{Bo,jr,W}from"./chunk-r0jc8e7t.js";import{Ho,$e,Tt,qo,Jn,Go,Ei,Pi,ft,zo,Oe,Xr,Ke}from"./chunk-h1rypb99.js";import{qn,Ti,zr}from"./chunk-mat08ab1.js";import{Ce,te,Fo,Gn,I,zn,mt,Ie,dr,N,Me,jn,ht,pe,$t,ne,Vr,Wo,Le,re,nt,Vn,$o,ge,ki,vi,ye,Kn,d,Ri,Q,Kr,G,Ci}from"./chunk-7qq99360.js";import{Qn,M,Xn,Ve,_i,Ht,Te}from"./chunk-nx3jnbv8.js";import{r,Xe}from"./chunk-bwawt15q.js";var Bg=r(function(XK,Ug){var AM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Zl=/[\n\r\u2028\u2029]/,CM=/[\s#!"$&'():;<=>@\\^`|~]/g;Ug.exports=function(n){var i=!1;return n.map(function(c){if(i&&typeof c==="string"&&Zl.test(c))throw TypeError("a token after a `comment` must not contain line terminators");if(c==="")return"''";if(c&&typeof c==="object"){if("op"in c&&c.op==="glob"){if(typeof c.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Zl.test(c.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(c.pattern==="")return"''";return c.pattern.replace(CM,"\\$&")}if("op"in c&&typeof c.op==="string"){if(AM.indexOf(c.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(c.op));return c.op.replace(/[\s\S]/g,"\\$&")}if("comment"in c&&typeof c.comment==="string"){if(Zl.test(c.comment))throw TypeError("`comment` must not contain line terminators");return i=!0,"#"+c.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(c)&&/!/.test(c))return"'"+c.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(c)&&!/'/.test(c))return"'"+c+"'";if(/["'\s]/.test(c))return'"'+c.replace(/(["\\$`])/g,"\\$1")+'"';return String(c).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var Qg=r(function(YK,Jg){var zg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Gg=new RegExp("^"+zg+"$"),Kg="|&;()<> \\t",PM="'([^']*?)'",Vg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Hg="\\$'"+Vg+"'",rm=new RegExp("\\$'"+Vg+"(?:(')|\\\\?$)","g"),$M="abeEfnrtv",MM=`\x07\b\x1B\x1B\f
3
+ \r \v`,vM=/^#$/,ed="'",Wg='"',Eu="$",Bi="",OM=4294967296;for(tm=0;tm<4;tm++)Bi+=(OM*Math.random()).toString(16);var tm,_M=new RegExp("^"+Bi);function LM(e,n){var i=n.lastIndex,c=[],p;while(p=n.exec(e))if(c[c.length]=p,n.lastIndex===p.index)n.lastIndex+=1;return n.lastIndex=i,c}function NM(e,n,i){var c=typeof e==="function"?e(i):e[i];if(typeof c>"u"&&i!="")c="";else if(typeof c>"u")c="$";if(typeof c==="object")return n+Bi+JSON.stringify(c)+Bi;return n+c}var DM=/\\([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 qM(e,n){var i=n.charAt(0);if(i==="c"){var c=n.charAt(1);return c==="?"?"\x7F":String.fromCharCode(c.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var p=parseInt(n.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(i>="0"&&i<="7")return String.fromCharCode(parseInt(n,8)&255);var g=$M.indexOf(n);return g<0?n:MM.charAt(g)}function FM(e){return e.replace(DM,qM).split("\x00")[0]}function jM(e,n){return rm.lastIndex=n,!!rm.exec(e)[1]}function UM(e,n,i){if(!i)i={};var c=i.escape||"\\",p=i.splitUnquoted===!0?`
4
+ `:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",g="(\\"+c+`['"$\\`+c+Kg+"]|\\$\\$|\\$(?!"+Hg.slice(2)+`)|[^\\s'"$`+Kg+"])+",y='"(?:\\'+c+'[\\s\\S]|[^"\\'+c+'])*"',x=new RegExp(["("+zg+")","("+Hg+"|"+g+"|"+y+"|"+PM+")+"].join("|"),"g"),b=LM(e,x);if(b.length===0)return[];if(!n)n={};var S=!1;return b.map(function(T){var A=T[0];if(!A||S)return;if(Gg.test(A))return{op:A};var C=!1,P=!1,L="",q=[],X=!1,j=null,V=!1,J;function ee(){J+=1;var me,qe,xt=A.charAt(J);if(xt==="{"){if(J+=1,A.charAt(J)==="}")throw Error("Bad substitution: "+A.slice(J-2,J+1));var Je=1;me=J;while(Je>0&&me<A.length){if(A.charAt(me)==="{"&&A.charAt(me-1)==="$")Je+=1;else if(A.charAt(me)==="}")Je-=1;me+=1}if(Je!==0)throw Error("Bad substitution: "+A.slice(J));me-=1,qe=A.slice(J,me),J=me}else if(/[*@#?$!-]/.test(xt))qe=xt;else{var Yt=A.slice(J);if(me=Yt.match(/[^\w\d_]/),!me)qe=Yt,J=A.length;else qe=Yt.slice(0,me.index),J+=me.index-1}return NM(n,"",qe)}function ie(){if(j===null)return;if(j===0){if(L!=="")q[q.length]=L,L=""}else{q[q.length]=L,L="";for(var me=1;me<j;me+=1)q[q.length]=""}j=null}for(J=0;J<A.length;J++){var H=A.charAt(J);if(p&&H!==Eu)ie();if(V=V||!C&&(H==="*"||H==="?"),P)L+=H,P=!1;else if(C)if(H===C)C=!1;else if(C==ed)L+=H;else if(H===c)if(J+=1,H=A.charAt(J),H===Wg||H===c||H===Eu)L+=H;else L+=c+H;else if(H===Eu)L+=ee();else L+=H;else if(H===Wg||H===ed)C=H,X=!0;else if(Gg.test(H))return{op:A};else if(vM.test(H)){S=!0;var ce={comment:e.slice(T.index+J+1)};if(L.length)return[L,ce];return[ce]}else if(H===c)P=!0;else if(H===Eu&&A.charAt(J+1)===ed&&jM(A,J))ie(),X=!0,L+=FM(A.slice(J+2,rm.lastIndex-1)),J=rm.lastIndex-1;else if(H===Eu){var fe=ee();if(!p)L+=fe;else for(var _e=0;_e<fe.length;_e+=1){var be=fe.charAt(_e);if(p.indexOf(be)<0)ie(),L+=be;else if(j===null)j=be===" "||be==="\t"||be===`
5
+ `?0:1;else if(be!==" "&&be!=="\t"&&be!==`
6
+ `)j+=1}}else L+=H}if(V)return{op:"glob",pattern:L};if(p){if(j!==null&&j>0){q[q.length]=L,L="";for(var se=1;se<j;se+=1)q[q.length]=""}if(L!==""||X&&q.length===0)q[q.length]=L;return q}return L}).reduce(function(T,A){if(typeof A>"u")return T;return[].concat(A).forEach(function(C){T[T.length]=C}),T},[])}Jg.exports=function(n,i,c){var p=UM(n,i,c);if(typeof i!=="function")return p;return p.reduce(function(g,y){if(typeof y==="object")return g[g.length]=y,g;var x=y.split(RegExp("("+Bi+".*?"+Bi+")","g"));if(x.length===1)return g[g.length]=x[0],g;return x.filter(Boolean).forEach(function(b){g[g.length]=_M.test(b)?JSON.parse(b.split(Bi)[1]):b}),g},[])}});var Uo={};Xe(Uo,{ArchivedError:()=>pt,BadRequestError:()=>t,BusyError:()=>oe,DEFAULT_TIMEOUT:()=>o$,FoldingPolicy:()=>Gc,MAX_ATTACHMENTS:()=>et,MAX_TIMEOUT:()=>s$,MAX_TOOL_OUTPUT:()=>Pe,NotFoundError:()=>f,PluginCheckError:()=>ut,ProcessRegistry:()=>Wt,Type:()=>oo,aliased:()=>we,budget:()=>Bc,calls:()=>ms,clip:()=>je,clipSaved:()=>rt,dataDir:()=>Pt,definePlugin:()=>R,estimateMessage:()=>F,estimateTokens:()=>O,estimateTools:()=>Di,extensionTranscript:()=>Hc,findWindowsBash:()=>tr,foldPoint:()=>jc,foldedThrough:()=>ya,formatLines:()=>Wc,gateShellCommand:()=>ze,groupRuns:()=>Ms,historyTodos:()=>ir,newID:()=>ue,normalizeRunRecords:()=>Nh,processRegistry:()=>sr,project:()=>ke,projectUserText:()=>qi,releaseProcesses:()=>lr,requestBody:()=>U,resolveShellCommand:()=>ba,retainProcesses:()=>ar,routeParam:()=>E,runShell:()=>rr,sealPoint:()=>iu,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>bl,text:()=>u,timerClock:()=>Re,tool:()=>v,toolSession:()=>K,transcript:()=>mu,usable:()=>We,userTranscript:()=>Kc,validAttachment:()=>Et,workState:()=>Sl});var Oo={};Xe(Oo,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>bR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>wR,EventStream:()=>Qn,InMemoryCredentialStore:()=>Gn,InMemoryModelsStore:()=>zn,ModelsError:()=>I,StringEnum:()=>Mq,Type:()=>oo,appendAssistantMessageDiagnostic:()=>Te,calculateCost:()=>Q,clampThinkingLevel:()=>G,cleanupSessionResources:()=>Ti,collapseSystemMessages:()=>Le,contentText:()=>dr,createAssistantMessageDiagnostic:()=>Ht,createAssistantMessageEventStream:()=>Xn,createFauxCore:()=>IR,createInitialSystemMessage:()=>jn,createModels:()=>Kn,createProvider:()=>d,declarationsEqual:()=>Vn,defaultProviderAuthContext:()=>Fo,envApiKeyAuth:()=>h,extractDiagnosticError:()=>_i,fauxAssistantMessage:()=>Mo,fauxProvider:()=>Lo,fauxText:()=>Ln,fauxThinking:()=>Io,fauxToolCall:()=>mq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>Vr,getCurrentSystemPrompt:()=>Wo,getCurrentTools:()=>ne,getDeclaredTools:()=>ge,getInitialSystemMessage:()=>pe,getModelType:()=>mt,getOverflowPatterns:()=>kq,getSupportedThinkingLevels:()=>Kr,getSystemMessageText:()=>N,getToolStateChanges:()=>$o,hasApi:()=>Ri,hasNonAdditiveToolChanges:()=>vi,hasToolRedefinitions:()=>ki,isContextOverflow:()=>li,isModelType:()=>Ie,isRecoverableLength:()=>Rq,isRetryableAssistantError:()=>RR,lazyApi:()=>te,lazyOAuth:()=>ae,lazyStream:()=>Ce,modelsAreEqual:()=>Ci,normalizeContext:()=>ht,parseJsonWithRepair:()=>jr,parseStreamingJson:()=>W,reduceAssistantMessageFrames:()=>Sq,registerSessionResourceCleanup:()=>qn,renderSystemMessageUpdate:()=>Me,repairJson:()=>Bo,resolveTranscript:()=>re,resolveTranscriptTools:()=>ye,retryAssistantCall:()=>$q,retryDelayMs:()=>TR,toToolDeclaration:()=>nt,uuidv7:()=>zr,validateToolArguments:()=>nu,validateToolCall:()=>gU,withoutInitialSystemMessage:()=>$t});var z={};Xe(z,{Counted:()=>cd,Entries:()=>mn,EntriesRegExp:()=>md,Every:()=>on,EveryAll:()=>kn,GraphemeCount:()=>dv,HasPropertyKey:()=>le,IsArray:()=>Be,IsBigInt:()=>Nr,IsBoolean:()=>cn,IsClassInstance:()=>dy,IsConstructor:()=>ad,IsDeepEqual:()=>Ta,IsEqual:()=>_,IsFunction:()=>ls,IsGreaterEqualThan:()=>Sa,IsGreaterThan:()=>Ki,IsInteger:()=>sm,IsLessEqualThan:()=>ds,IsLessThan:()=>Tu,IsMaxLength:()=>fy,IsMinLength:()=>hy,IsMultipleOf:()=>ly,IsNull:()=>lo,IsNumber:()=>_t,IsObject:()=>at,IsObjectNotArray:()=>Jo,IsString:()=>gt,IsSymbol:()=>ud,IsUndefined:()=>Bt,IsUnsafePropertyKey:()=>Ru,IsValueLike:()=>Hi,Keys:()=>Se,ShiftLeft:()=>It,Some:()=>wa,SomeAll:()=>gy,Symbols:()=>yy,Values:()=>pd});var Yi={};Xe(Yi,{Hash:()=>xd,HashCode:()=>Xy});var Lt={};Xe(Lt,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Ae,ExtendsUnion:()=>jd,IsExtendsFalse:()=>Gd,IsExtendsTrue:()=>Bd,IsExtendsTrueLike:()=>no,IsExtendsUnion:()=>Ud,Match:()=>br});var oo={};Xe(oo,{Any:()=>Ca,Array:()=>B,BigInt:()=>Mu,Boolean:()=>D,Call:()=>mw,Capitalize:()=>yw,Codec:()=>hm,Conditional:()=>Rw,Constructor:()=>hs,ConstructorParameters:()=>Aw,Cyclic:()=>xs,Decode:()=>tx,DecodeBuilder:()=>fm,Dependent:()=>Xi,Encode:()=>rx,EncodeBuilder:()=>dm,Enum:()=>Uy,Evaluate:()=>Tn,Exclude:()=>Pw,Extends:()=>wn,ExtendsResult:()=>Lt,Extract:()=>Mw,Function:()=>gs,Generic:()=>Zs,Identifier:()=>vu,Immutable:()=>nx,Index:()=>Lw,Infer:()=>$u,InstanceType:()=>iT,Instantiate:()=>Ao,Integer:()=>w,Interface:()=>HS,Intersect:()=>Cn,IsAny:()=>Mr,IsArray:()=>wt,IsBigInt:()=>uo,IsBoolean:()=>Wn,IsCall:()=>ja,IsCodec:()=>Hn,IsConstructor:()=>Yr,IsCyclic:()=>Qt,IsDependent:()=>Dr,IsEnum:()=>rn,IsEnumValue:()=>jy,IsFunction:()=>Zr,IsGeneric:()=>Aa,IsIdentifier:()=>ax,IsImmutable:()=>Zi,IsInfer:()=>tn,IsInteger:()=>ln,IsIntersect:()=>He,IsKind:()=>ve,IsLiteral:()=>yt,IsNever:()=>ao,IsNull:()=>bs,IsNumber:()=>kr,IsObject:()=>Qe,IsOptional:()=>an,IsParameter:()=>px,IsReadonly:()=>ta,IsRecord:()=>Gt,IsRef:()=>jt,IsRefine:()=>gm,IsRest:()=>si,IsSchema:()=>Pr,IsString:()=>nn,IsSymbol:()=>Es,IsTemplateLiteral:()=>ur,IsThis:()=>$m,IsTuple:()=>lt,IsUndefined:()=>es,IsUnion:()=>xe,IsUnknown:()=>en,IsUnsafe:()=>lm,IsVoid:()=>co,KeyOf:()=>uT,Literal:()=>a,Lowercase:()=>xw,Mapped:()=>gT,Module:()=>oR,Never:()=>zt,NonNullable:()=>bT,Null:()=>Pn,Number:()=>Y,Object:()=>s,Omit:()=>ST,Optional:()=>o,Parameter:()=>ra,Parameters:()=>RT,Partial:()=>AT,Pick:()=>_T,Readonly:()=>ox,ReadonlyObject:()=>If,ReadonlyType:()=>DT,Record:()=>Ss,RecordKey:()=>oi,RecordPattern:()=>dn,RecordValue:()=>fr,Ref:()=>sn,Refine:()=>sx,Required:()=>YT,Rest:()=>oa,ReturnType:()=>eR,Script:()=>uR,String:()=>l,Symbol:()=>Ma,TemplateLiteral:()=>lS,This:()=>Pm,Tuple:()=>Ur,Uncapitalize:()=>Iw,Undefined:()=>_a,Union:()=>m,Unknown:()=>Rr,Unsafe:()=>Wr,Uppercase:()=>bw,Void:()=>Mm,With:()=>hp});var eu={};Xe(eu,{Clear:()=>Uk,Entries:()=>qF,Get:()=>UF,Has:()=>jF,IsDate:()=>Xa,IsDateTime:()=>Tp,IsDuration:()=>Rp,IsEmail:()=>kp,IsHostname:()=>_p,IsIPv4:()=>Dp,IsIPv6:()=>qp,IsIdnEmail:()=>Lp,IsIdnHostname:()=>Np,IsIri:()=>jp,IsIriReference:()=>Fp,IsJsonPointer:()=>Bp,IsJsonPointerUriFragment:()=>Up,IsRegex:()=>Gp,IsRelativeJsonPointer:()=>Kp,IsTime:()=>Ya,IsUri:()=>zp,IsUriReference:()=>Hp,IsUriTemplate:()=>Wp,IsUrl:()=>Vp,IsUuid:()=>Jp,Reset:()=>Gk,Set:()=>FF,Test:()=>Bk});var bu="shell-guard",Og=["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 _g(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Lg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function wM(e,n){if(e===n)return 0;let i=Array.from({length:n.length+1},(c,p)=>p);for(let c=1;c<=e.length;c++){let p=i[0]??0;i[0]=c;for(let g=1;g<=n.length;g++){let y=i[g]??0;i[g]=Math.min((i[g]??0)+1,(i[g-1]??0)+1,p+(e[c-1]===n[g-1]?0:1)),p=y}}return i[n.length]??0}function Ng(e,n){let i=_g(e);if(!i)return[];let c=Lg(e),p=[];for(let g of n){let y=g.id.indexOf("/"),x=y>=0?g.id.slice(y+1):"",S=[g.id,g.name,x].filter(Boolean).map((A)=>({compact:_g(A),tokens:Lg(A)})).filter((A)=>A.compact.length>0),T=Number.POSITIVE_INFINITY;for(let A of S)if(A.compact===i)T=Math.min(T,0);else if(A.compact.includes(i)||i.includes(A.compact)){let C=Math.abs(A.compact.length-i.length);T=Math.min(T,1+C/Math.max(A.compact.length,i.length))}else{let C=0;for(let P of c)if(A.tokens.has(P))C++;if(C>0){let P=C/Math.max(c.size,A.tokens.size);T=Math.min(T,10+(1-P)*10)}}if(!Number.isFinite(T)&&i.length>=4){let A=Math.max(2,Math.floor(i.length*0.34));for(let C of S){if(Math.abs(C.compact.length-i.length)>A)continue;let P=wM(i,C.compact);if(P<=A)T=Math.min(T,100+P)}}if(Number.isFinite(T))p.push({model:g,score:T})}return p.sort((g,y)=>g.score-y.score||g.model.id.localeCompare(y.model.id))}function TM(e,n,i=5){return Ng(e,n).slice(0,Math.max(1,i)).map((c)=>c.model)}function pi(e,n){let i=Ng(e,n);if(i.length===0)return;let c=i.filter((g)=>g.score===0);if(c.length===1&&c[0])return c[0].model;if(c.length>1)return;let p=i.filter((g)=>g.score<10);if(p.length===1&&p[0])return p[0].model;return}function di(e,n){let i=[...n].sort((y,x)=>y.id.localeCompare(x.id)),c=(y)=>y.name===y.id?y.id:`${y.id} (${y.name})`,p=TM(e,i).map(c),g=i.map(c);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${g.length}): ${g.length>0?g.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
+ `)}var mi=["openai-completions","openai-responses","anthropic-messages"];function Fr(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let n=e.trim().toLowerCase();if(!n)return;let i=n.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let c=Number.parseFloat(i[1]??"");if(!Number.isFinite(c)||c<=0)return;let p=i[2];if(p==="k")return Math.round(c*1000);if(p==="m")return Math.round(c*1e6);return Math.round(c)}function Jl(e){if(e>=1e6&&e%1e5===0)return`${e/1e6}m`;if(e>=1000&&e%1000===0)return`${e/1000}k`;return String(e)}function RM(e){let n=e.trim();if(!n)return;let i,c,p=n,g=p.match(/\s*\[(.*?)\]\s*$/);if(g&&g.index!==void 0){p=p.slice(0,g.index).trim();let T=g[1]?.split(",").map((C)=>C.trim()).filter(Boolean)??[],A=0;for(let C of T){let P=C.indexOf("=");if(P>=0){let L=C.slice(0,P).trim().toLowerCase(),q=Fr(C.slice(P+1).trim());if(L==="context"||L==="ctx"||L==="window"||L==="contextwindow")i=q;else if(L==="max"||L==="output"||L==="maxtokens")c=q}else{let L=Fr(C);if(A===0)i=L;else if(A===1)c=L;A++}}}else{let T=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(T?.[1]&&T[2])p=T[1].trim(),i=Fr(T[2])}let y=p.indexOf("="),x,b;if(y<0)x=p.trim(),b=x;else x=p.slice(0,y).trim(),b=p.slice(y+1).trim()||x;if(!x)return;let S={id:x,name:b};if(i!==void 0)S.contextWindow=i;if(c!==void 0)S.maxTokens=c;return S}function er(e){return e.split(/\r?\n/).map(RM).filter((n)=>n!==void 0)}function ko(e){return e.map((n)=>{let i=n.name===n.id?n.id:`${n.id}=${n.name}`,c=[];if(n.contextWindow!==void 0)c.push(Jl(n.contextWindow));if(n.maxTokens!==void 0)if(n.contextWindow!==void 0)c.push(Jl(n.maxTokens));else c.push(`max=${Jl(n.maxTokens)}`);return c.length>0?`${i} [${c.join(", ")}]`:i}).join(`
8
+ `)}var Dg=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var In=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],hi=["text","regex"],fi=["best","recent"],gi=["session","none"];var Ft=4,yi="https://basalt.work",bi=["https://basalt.work","https://www.basalt.work"],Mn=7420;var Ql=["auto","bash","powershell","cmd"],Si="Bkm016/Basalt";var Ro=["active","archived","all"];var qg=["pending","in_progress","completed"],Xl="basalt-session",em=["image","text","path"];var Fg=["defer","always"],jg=["global","tool","source"];function Ee(e,n){if(e.toLowerCase()!=="tool_call"||!n||typeof n!=="object")return{name:e,input:n};let i=n;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:n};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:n}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:n};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:n}}}function xi(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var et=10,kM=15000000;function Et(e){if(!e||typeof e!=="object")return!1;let n=e;return typeof n.name==="string"&&n.name.length>0&&n.name.length<=255&&typeof n.mimeType==="string"&&n.mimeType.length>0&&typeof n.kind==="string"&&em.includes(n.kind)&&typeof n.data==="string"&&n.data.length>0&&n.data.length<=kM}function Yl(e){return e?.map((n)=>({...n,id:`att_${crypto.randomUUID().slice(0,8)}`}))}var BM=Bg(),td=Qg();import{AsyncLocalStorage as GM}from"async_hooks";var K=new GM;var KM=3,Xg=160,HM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),WM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),ey=/^[A-Za-z_][A-Za-z0-9_]*=/,zM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),VM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),JM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,QM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),XM=new Set(["command","builtin","nohup","time","exec"]),YM=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir","-S","--split-string"]],["nice",["-n","--adjustment"]]]);function nm(e){return{out:e.out,depth:e.depth+1}}function Yg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function rd(e,n,i,c){let p=e.length,g=0,y=n;while(y<p){let x=e.charAt(y);if(x==="\\"){y+=2;continue}if(x==="'"||x==='"'||x==="`"){let b=y+1;while(b<p){let S=e.charAt(b);if(S==="\\"){b+=2;continue}if(S===x)break;b++}y=b+1;continue}if(x===i)g++;else if(x===c){if(g--,g===0)return y+1}y++}return p}function ZM(e){let n={text:"",subs:[],heredocs:[]},i=[],c=[],p=e.length,g=0,y=0,x=null,b=(S)=>{if(e.charAt(S)==="`"){let P=S+1;while(P<p){let L=e.charAt(P);if(L==="\\"){P+=2;continue}if(L==="`")break;P++}return n.subs.push(e.slice(S+1,P)),P<p?P+1:p}if(e.charAt(S+1)==="("){let P=rd(e,S+1,"(",")");if(e.charAt(S+2)==="(")return i.push(e.slice(S,P)),P;return n.subs.push(e.slice(S+2,P-1)),P}let A=rd(e,S+1,"{","}"),C=e.slice(S+2,A-1);for(let P=0;P<C.length;P++){let L=C.charAt(P);if(L==="\\"){P++;continue}if(L==="`"){let q=C.indexOf("`",P+1);n.subs.push(q<0?C.slice(P+1):C.slice(P+1,q)),P=q<0?C.length:q;continue}if(L==="$"&&C.charAt(P+1)==="("){let q=rd(C,P+1,"(",")");n.subs.push(C.slice(P+2,q-1)),P=q-1}}return A};while(g<p){let S=e.charAt(g);if(x==="'"){if(S==="'")x=null;i.push(S),g++;continue}if(x==='"'){if(S==="\\"){if(!'$`"\\\n'.includes(e.charAt(g+1)))i.push("\\");i.push(S,e.charAt(g+1)),g+=2;continue}if(S==='"'){x=null,i.push(S),g++;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=b(g);continue}i.push(S),g++;continue}if(S==="'"||S==='"'){x=S,i.push(S),g++;continue}if(S==="\\"){i.push(S,e.charAt(g+1)),g+=2;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=b(g);continue}if(S==="#"){let T=i.at(-1);if(T===void 0||`
9
+ ;&|()`.includes(T)){while(g<p&&e.charAt(g)!==`
10
+ `)g++;continue}i.push(S),g++;continue}if(S==="<"&&e.charAt(g+1)==="<"&&e.charAt(g+2)!=="<"){let T=g+2;if(e.charAt(T)==="-")T++;i.push(e.slice(g,T));let A=T;while(A<p&&(e.charAt(A)===" "||e.charAt(A)==="\t"))A++;let C="";while(A<p){let P=e.charAt(A);if(P==="'"||P==='"'){let L=e.indexOf(P,A+1);if(L<0)break;C+=e.slice(A+1,L),A=L+1;continue}if(P==="\\"){C+=e.charAt(A+1),A+=2;continue}if(` \r
11
+ ;&|()<>`.includes(P))break;C+=P,A++}if(C)c.push(C);g=T;continue}if(S===`
12
+ `){if(c.length>0){let T=JM.test(i.slice(y).join(""));g++;for(let A of c.splice(0)){let C=g,P=p;while(g<p){let L=e.indexOf(`
13
+ `,g),q=L<0?p:L;if(e.slice(g,q).trim()===A){P=g,g=L<0?p:L+1;break}g=L<0?p:L+1}if(T&&P>C)n.heredocs.push(e.slice(C,P))}}else g++;i.push(";",`
14
+ `),y=i.length;continue}i.push(S),g++}return n.text=i.join(""),n}function Su(e,n){if(n.depth>KM)return;let i=ZM(e),c;try{c=td(i.text)}catch{return}let p=[];for(let g of c){if(typeof g==="string"){p.push({kind:"word",text:g});continue}if("pattern"in g){p.push({kind:"word",text:g.pattern});continue}if("op"in g)p.push({kind:"op",text:g.op})}ev(p,n);for(let g of i.subs)Su(g,nm(n));for(let g of i.heredocs)Su(g,nm(n))}function ev(e,n){let i=[],c=()=>{if(i.length>0)tv(i,n);i=[]};for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;if(g.kind==="op"){if(zM.has(g.text)){c();continue}if(VM.has(g.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(g.text)}c()}function tv(e,n){let i=0;for(;;){let y=e[i];if(y===void 0)return;if(WM.has(y)||ey.test(y)){i++;continue}let x=nv(Yg(y),e,i);if(x===i)break;i=x}let c=e[i];if(c===void 0)return;let p=Yg(c),g=e.slice(i+1);if(p==="git"){sv(c,g,n);return}if(HM.has(p)){rv(g,n);return}if(p==="powershell"||p==="pwsh")Zg(g,/^-(command|c)$/i,n);if(p==="cmd")Zg(g,/^\/[ck]$/i,n)}function Zg(e,n,i){for(let c=0;c<e.length;c++)if(n.test(e[c]??"")){let p=e.slice(c+1).join(" ");if(p.trim())Su(p,nm(i));return}}function rv(e,n){for(let i=0;i<e.length;i++){let c=e[i]??"";if(c==="-o"||c==="-O"||c==="--init-file"||c==="--rcfile"){i++;continue}if(c.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(c);if(p){let g=p[1]||e[i+1];if(g)Su(g,nm(n));return}if(c.startsWith("-")||c==="")continue;return}}function nv(e,n,i){if(XM.has(e)){let g=i+1;while(n[g]?.startsWith("-"))g++;return g}let c=YM.get(e);if(!c)return i;let p=i+1;for(;;){let g=n[p];if(g===void 0)return p;if(c.includes(g)){p+=2;continue}if(ey.test(g)||g.startsWith("-")){p++;continue}return p}}function Vo(e,n){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(n))}function eo(e,n){return e.some((i)=>i===`--${n}`||i.startsWith(`--${n}=`))}var ov={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Vo(e,"f")||Vo(e,"i")||eo(e,"force")||eo(e,"interactive"))&&!(Vo(e,"n")||eo(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Vo(e,"f")||eo(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Vo(e,"f")||eo(e,"force")||Vo(e,"C")||eo(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>Vo(e,"f")||eo(e,"force")||eo(e,"force-with-lease")||eo(e,"force-if-includes")||eo(e,"delete")||eo(e,"mirror")||e.some((n)=>n.startsWith("+")||n.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>eo(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Vo(e,"D")||Vo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>eo(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>Vo(e,"f")||eo(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(Vo(e,"f")||eo(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function sv(e,n,i){let c=0;for(;;){let b=n[c];if(b===void 0)break;if(QM.has(b)){c+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(b)||/^-[Cc].+/.test(b)||b.startsWith("-")){c++;continue}break}let p=n[c]?.toLowerCase();if(!p)return;let g=ov[p];if(!g)return;let y=g(n.slice(c+1));if(!y)return;let x=[e,...n.slice(c)].join(" ");i.out.push({rule:p,fragment:x.length>Xg?`${x.slice(0,Xg)}\u2026`:x,reason:y})}function od(e){let n={out:[],depth:0};return Su(e,n),n.out}function ty(e){let n=e.slice(0,5).map((c)=>`${c.fragment}\uFF08${c.reason}\uFF09`),i=e.length>n.length?` \u7B49 ${e.length} \u5904`:"";return`${n.join("\uFF1B")}${i}`}var nd=new Map;function iv(e,n,i,c,p){let g=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((y)=>{let x=(S)=>{if(!nd.delete(g))return;p?.removeEventListener("abort",b),y(S)},b=()=>{ry(e,g),x("aborted")};if(nd.set(g,{session:e,finish:x}),e.appendExtension({namespace:bu,kind:"requested",schemaVersion:1,payload:{id:g,sessionID:e.id,command:n.slice(0,4000),summary:c.slice(0,5).map(({fragment:S,reason:T})=>({fragment:S,reason:T})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)b();else p?.addEventListener("abort",b,{once:!0})})}function ry(e,n){try{e.appendExtension({namespace:bu,kind:"cancelled",schemaVersion:1,payload:{id:n,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Co(e,n,i){let c=nd.get(n);if(!c||c.session!==e){if(!av(e,n))return"unknown";return ry(e,n),"expired"}return e.appendExtension({namespace:bu,kind:"answered",schemaVersion:1,payload:{id:n,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),c.finish(i?"approved":"denied"),"answered"}function av(e,n){let i=!1;for(let c of e.entries()){if(c.type!=="extension"||c.namespace!==bu)continue;let p=c.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==n)continue;if(c.kind==="requested")i=!0;else if(c.kind==="answered"||c.kind==="cancelled")return!1}return i}function sd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${ty(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function ze(e,n){let i=od(e);if(!i.at(0))return;let p=ty(i),g=K.getStore();if(g?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(n?.aborted)return`${sd(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let y=await iv(g,e,p,i,n);if(y==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${y==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{homedir as uv}from"os";import{join as wu}from"path";function Pt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let n=uv();if(process.platform==="win32")return wu(e.LOCALAPPDATA??wu(n,"AppData","Local"),"basalt");if(process.platform==="darwin")return wu(n,"Library","Application Support","basalt");return wu(e.XDG_DATA_HOME??wu(n,".local","share"),"basalt")}var ps={assign:0,create:0,clone:0,discard:0,update:0};function Gi(e,n,i){return e>=n&&e<=i}function sy(e){return e===8205}function cv(e){return Gi(e,55296,56319)}function ny(e){return Gi(e,127462,127487)}function iy(e){return Gi(e,65024,65039)}function ay(e){return Gi(e,768,879)||Gi(e,6832,6911)||Gi(e,7616,7679)||Gi(e,65056,65071)}function om(e){return e>65535?2:1}function oy(e,n){while(n<e.length){let i=e.codePointAt(n);if(ay(i)||iy(i))n+=om(i);else break}return n}function id(e,n){let i=e.codePointAt(n),c=n+om(i);c=oy(e,c);while(c<e.length-1&&sy(e.codePointAt(c))){let p=e.codePointAt(c+1);c+=1+om(p),c=oy(e,c)}if(ny(i)&&c<e.length&&ny(e.codePointAt(c)))c+=om(e.codePointAt(c));return c}function uy(e){return e>=768&&(cv(e)||ay(e)||iy(e)||sy(e))}function cy(e){let n=0,i=0;while(i<e.length)i=id(e,i),n++;return n}function mv(e,n){let i=0,c=0;while(c<e.length)if(c=id(e,c),++i>=n)return!0;return!1}function pv(e,n){let i=0,c=0;while(c<e.length)if(c=id(e,c),++i>n)return!1;return!0}function my(e,n){if(n===0)return!0;if(e.length<n)return!1;let i=0;while(!0){if(uy(e.charCodeAt(i)))return mv(e,n);if(++i>=n)return!0}}function py(e,n){if(e.length<=n)return!0;let i=0;while(!0){if(uy(e.charCodeAt(i)))return pv(e,n);if(++i>n)return!1}}function Be(e){return Array.isArray(e)}function Nr(e){return _(typeof e,"bigint")}function cn(e){return _(typeof e,"boolean")}function ad(e){if(Bt(e)||!ls(e))return!1;let n=Function.prototype.toString.call(e);if(/^class\s/.test(n))return!0;if(/\[native code\]/.test(n))return!0;return!1}function ls(e){return _(typeof e,"function")}function sm(e){return Number.isInteger(e)}function lo(e){return _(e,null)}function _t(e){return Number.isFinite(e)}function Jo(e){return at(e)&&!Be(e)}function at(e){return _(typeof e,"object")&&!lo(e)}function gt(e){return _(typeof e,"string")}function ud(e){return _(typeof e,"symbol")}function Bt(e){return _(e,void 0)}function _(e,n){return e===n}function Ki(e,n){return e>n}function Tu(e,n){return e<n}function ds(e,n){return e<=n}function Sa(e,n){return e>=n}function ly(e,n){if(Nr(e)||Nr(n))return BigInt(e)%BigInt(n)===0n;let i=0.0000000001;if(!_t(e))return!0;if(sm(e)&&1/n%1===0)return!0;let c=e%n;return Math.min(Math.abs(c),Math.abs(c-n),Math.abs(c+n))<i}function dy(e){if(!at(e))return!1;let n=globalThis.Object.getPrototypeOf(e);if(lo(n))return!1;return _(typeof n.constructor,"function")&&!(_(n.constructor,globalThis.Object)||_(n.constructor.name,"Object"))}function Hi(e){return Nr(e)||cn(e)||lo(e)||_t(e)||gt(e)||Bt(e)}function dv(e){return cy(e)}function fy(e,n){return py(e,n)}function hy(e,n){return my(e,n)}function on(e,n,i){return e.every((c,p)=>p<n||i(c,p))}function kn(e,n,i){let c=!0;return e.forEach((p,g)=>{if(g>=n&&!i(p,g))c=!1}),c}function wa(e,n){return e.some((i,c)=>n(i,c))}function gy(e,n){let i=!1;return e.forEach((c,p)=>{if(n(c,p))i=!0}),i}function cd(e,n){return e.reduce((i,c,p)=>n(c,p)?++i:i,0)}function It(e,n,i){return _(e.length,0)?i():n(e[0],e.slice(1))}function Ru(e){return _(e,"__proto__")||_(e,"constructor")||_(e,"prototype")}function le(e,n){return Ru(n)?Object.prototype.hasOwnProperty.call(e,n):(n in e)}function md(e){return Se(e).map((n)=>[new RegExp(`^${n}$`),e[n]])}function mn(e){return Object.entries(e)}function Se(e){return Object.getOwnPropertyNames(e)}function yy(e){return Object.getOwnPropertySymbols(e)}function pd(e){return Object.values(e)}function fv(e,n){if(!at(n))return!1;let i=Se(e);return _(i.length,Se(n).length)&&i.every((c)=>Ta(e[c],n[c]))}function hv(e,n){return Be(n)&&_(e.length,n.length)&&e.every((i,c)=>Ta(e[c],n[c]))}function Ta(e,n){return Be(e)?hv(e,n):at(e)?fv(e,n):_(e,n)}var gv=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function yv(e){return gv.test(e)}function En(e,n){return`(${e} && ${n})`}function xr(e,n){return`(${e} || ${n})`}function Un(e){return`!(${e})`}function im(e){return`Array.isArray(${e})`}function xy(e){return`typeof ${e} === "bigint"`}function xv(e){return`typeof ${e} === "boolean"`}function Iv(e){return`Number.isInteger(${e})`}function bv(e){return`${e} === null`}function Iy(e){return`Number.isFinite(${e})`}function by(e){return En(Ey(e),Un(im(e)))}function Ey(e){return`typeof ${e} === "object" && ${e} !== null`}function Sy(e){return`typeof ${e} === "string"`}function Ev(e){return`typeof ${e} === "symbol"`}function ld(e){return`${e} === undefined`}function Sv(e){return`typeof ${e} === "function"`}function wv(e){return`Guard.IsConstructor(${e})`}function io(e,n){return`${e} === ${n}`}function wy(e,n){return`${e} > ${n}`}function dd(e,n){return`${e} < ${n}`}function Wi(e,n){return`${e} <= ${n}`}function ku(e,n){return`${e} >= ${n}`}function Tv(e,n){return`Guard.IsMinLength(${e}, ${n})`}function Rv(e,n){return`Guard.IsMaxLength(${e}, ${n})`}function fs(e,n,i,c){return _(n,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${c}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${n}) || (${c}))`}function kv(e,n,i){return`${e}.some((${n[0]}, ${n[1]}) => ${i})`}function Av(e,n,i){return`((value) => { let result = false; value.forEach((${n[0]}, ${n[1]}) => { if (${i}) result = true }); return result })(${e})`}function am(e,n,i){return`${e}.reduce((result, ${n[0]}, ${n[1]}) => (${i}) ? ++result : result, 0)`}function Ty(e){return`Object.entries(${e})`}function zi(e){return`Object.getOwnPropertyNames(${e})`}function Vi(e,n){return _(n,'"__proto__"')||_(n,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${n})`:`${n} in ${e}`}function Ry(e,n){return`Guard.IsDeepEqual(${e}, ${n})`}function Cv(e){return`[${e.join(", ")}]`}function Qs(e,n){return`((${e.join(", ")}) => ${n})`}function Ir(e,n){return`${e}(${n.join(", ")})`}function fd(e,n){return`new ${e}(${n.join(", ")})`}function bt(e,n){return`${e}${yv(n)?`.${n}`:`[${De(n)}]`}`}function De(e){if(!Hi(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function Pv(e,n,i){return`(${e} ? ${n} : ${i})`}function um(e){return`{ ${e.join("; ")}; }`}function _s(e,n){return`const ${e} = ${n}`}function ky(e,n){return`if(${e}) { ${n} }`}function cm(e){return`return ${e}`}function An(e){return _(e.length,0)?"true":e.reduce((n,i)=>En(n,i))}function hd(e){return _(e.length,0)?"false":e.reduce((n,i)=>xr(n,i))}function $v(e,n){return`Guard.IsMultipleOf(${e}, ${n})`}function Mv(e){return e instanceof Boolean}function vv(e){return e instanceof Number}function Ov(e){return e instanceof String}function Ay(e){return globalThis.ArrayBuffer.isView(e)}function Cy(e){return e instanceof globalThis.RegExp}function _v(e){return e instanceof globalThis.Date}function Lv(e){return e instanceof globalThis.Set}function Nv(e){return e instanceof globalThis.Map}var qv={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Qo(){return qv}function Xs(e){return Qo().immutableTypes?Object.freeze(e):e}function pn(e,n){return ps.assign+=1,Xs({...e,...n})}function Fv(e){return e}function jv(e){return le(e,"~kind")||le(e,"~unsafe")}function Uv(e){let n={};for(let i of Se(e)){if(Ru(i))continue;let c=Object.getOwnPropertyDescriptor(e,i);if(c.value=Ji(c.value),_(c.enumerable,!0))n[i]=c.value;else Object.defineProperty(n,i,c)}return n}function Bv(e){let n={};for(let i of Se(e)){if(Ru(i))continue;n[i]=Ji(e[i])}for(let i of yy(e))n[i]=Ji(e[i]);return n}function Gv(e){return dy(e)?Fv(e):jv(e)?Uv(e):Bv(e)}function Kv(e){return e.map((n)=>Ji(n))}function Hv(e){return e.slice()}function Wv(e){return new RegExp(e.source,e.flags)}function zv(e){return new Map(Ji([...e.entries()]))}function Vv(e){return new Set(Ji([...e.values()]))}function Ji(e){return Ay(e)?Hv(e):Cy(e)?Wv(e):Nv(e)?zv(e):Lv(e)?Vv(e):Be(e)?Kv(e):at(e)?Gv(e):e}function Ra(e){return ps.clone+=1,Ji(e)}function Jv(e,n){for(let i of Object.keys(n))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:n[i]});return e}function Py(e,n){return{...e,...n}}function Mt(e,n,i={}){ps.create+=1;let c=Py(n,i),p=Qo().enumerableKind?Py(c,e):Jv(c,e);return Xs(p)}function Xo(e,n){ps.discard+=1;let i={};for(let c of Se(e)){if(n.includes(c))continue;let p=Object.getOwnPropertyDescriptor(e,c);p.value=Ra(p.value),Object.defineProperty(i,c,p)}return Xs(i)}function St(e,n,i){ps.update+=1;let c=Qo(),p=Ra(e);for(let g of Object.keys(n))Object.defineProperty(p,g,{configurable:!0,writable:!0,enumerable:c.enumerableKind,value:n[g]});for(let g of Object.keys(i))Object.defineProperty(p,g,{configurable:!0,enumerable:!0,writable:!0,value:i[g]});return Xs(p)}function ve(e,n){return at(e)&&le(e,"~kind")&&_(e["~kind"],n)}function Pr(e){return at(e)}function Ne(e,n,i){return Mt({"~kind":"Deferred"},{type:"deferred",action:e,parameters:n,options:i},{})}function Ys(e){return ve(e,"Deferred")}function Qv(e){return St(e,{"~readonly":!0},{})}function Cu(e,n){return St(Qv(e),{},n)}function $y(e,n,i,c){let p=de(e,n,i);return Cu(p,c)}function Xv(e){return St(e,{"~optional":!0},{})}function Pu(e,n){return St(Xv(e),{},n)}function My(e,n,i,c){let p=de(e,n,i);return Pu(p,c)}function B(e,n){return Mt({"~kind":"Array"},{type:"array",items:e},n)}function wt(e){return ve(e,"Array")}function ka(e){return Xo(e,["~kind","type","items"])}function hs(e,n,i={}){return Mt({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:n},i)}function Yr(e){return ve(e,"Constructor")}function vy(e){return Xo(e,["~kind","type","parameters","instanceType"])}function gs(e,n,i={}){return Mt({["~kind"]:"Function"},{type:"function",parameters:e,returnType:n},i)}function Zr(e){return ve(e,"Function")}function Oy(e){return Xo(e,["~kind","type","parameters","returnType"])}function sn(e,n){return Mt({["~kind"]:"Ref"},{$ref:e},n)}function jt(e){return ve(e,"Ref")}function Zs(e,n){return Mt({"~kind":"Generic"},{type:"generic",parameters:e,expression:n})}function Aa(e){return ve(e,"Generic")}function Ca(e){return Mt({["~kind"]:"Any"},{},e)}function Mr(e){return ve(e,"Any")}var _y="(?!)";function zt(e){return Mt({"~kind":"Never"},{not:{}},e)}function ao(e){return ve(e,"Never")}function ys(e,n={}){return Ne("AddOptional",[e],n)}function Qi(e,n={}){return Pu(e,n)}function o(e){return Qi(e)}function an(e){return Pr(e)&&le(e,"~optional")}function Ly(e){return Se(e).filter((n)=>!an(e[n]))}function mm(e){return Se(e)}function pm(e){return pd(e)}function s(e,n={}){let i=Ly(e),c=i.length>0?{required:i}:{};return Mt({"~kind":"Object"},{type:"object",...c,properties:e},n)}function Qe(e){return ve(e,"Object")}function Ny(e){return Xo(e,["~kind","type","properties","required"])}function Rr(e){return Mt({["~kind"]:"Unknown"},{},e)}function en(e){return ve(e,"Unknown")}function xs(e,n,i){let c=Se(e).reduce((p,g)=>({...p,[g]:St(e[g],{},{$id:g})}),{});return Mt({["~kind"]:"Cyclic"},{$defs:c,$ref:n},i)}function Qt(e){return ve(e,"Cyclic")}function Wr(e){return St(e,{["~unsafe"]:null},{})}function lm(e){return Jo(e)&&le(e,"~unsafe")&&lo(e["~unsafe"])}function Sn(e,n){return n[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function $u(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p,p],1:(c)=>[c,Rr(),Rr()]});return Mt({["~kind"]:"Infer"},{type:"infer",name:n,extends:i},{})}function tn(e){return ve(e,"Infer")}function Xi(e,n,i,c={}){return Mt({"~kind":"Dependent"},{if:e,then:n,else:i},c)}function Dr(e){return ve(e,"Dependent")}function Dy(e){return Xo(e,["~kind","if","then","else"])}function qy(e){return Jo(e)}function Fy(e){return Se(e).filter((i)=>isNaN(i)).reduce((i,c)=>[...i,e[c]],[])}function jy(e){return gt(e)||_t(e)}function Uy(e,n){let i=qy(e)?Fy(e):e;return Mt({"~kind":"Enum"},{enum:i},n)}function rn(e){return ve(e,"Enum")}function Cn(e,n={}){return Mt({"~kind":"Intersect"},{allOf:e},n)}function He(e){return ve(e,"Intersect")}function By(e){return Xo(e,["~kind","allOf"])}var gd=void 0;function Yv(){try{return Ky("null")(),!0}catch{return!1}}function Gy(){if(Bt(gd))gd=Yv();return gd&&Qo().useAcceleration}function Ky(...e){return new globalThis.Function(...e)}function qr(){throw Error("Unreachable")}function Zv(e){let n=new Set,i=e;while(i&&i!==Object.prototype){for(let c of Reflect.ownKeys(i))if(c!=="constructor"&&typeof c!=="symbol")n.add(c);i=Object.getPrototypeOf(i)}return[...n]}function eO(e){return typeof e==="number"}var Bn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Bn||(Bn={}));var Pa=BigInt("14695981039346656037"),[tO,rO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],nO=Array.from({length:256}).map((e,n)=>BigInt(n)),Vy=new Float64Array(1),Jy=new DataView(Vy.buffer),Qy=new Uint8Array(Vy.buffer);function yn(e){Pa=Pa^nO[e],Pa=Pa*tO%rO}function oO(e){yn(Bn.Array);for(let n of e)ei(n)}function sO(e){yn(Bn.BigInt),Jy.setBigInt64(0,e);for(let n of Qy)yn(n)}function Wy(e){yn(Bn.Boolean),yn(e?1:0)}function iO(e){yn(Bn.Constructor),ei(e.toString())}function aO(e){yn(Bn.Date),ei(e.getTime())}function uO(e){yn(Bn.Function),ei(e.toString())}function cO(e){yn(Bn.Null)}function zy(e){yn(Bn.Number),Jy.setFloat64(0,e,!0);for(let n of Qy)yn(n)}function mO(e){yn(Bn.Object);for(let n of Zv(e).sort())ei(n),ei(e[n])}function pO(e){yn(Bn.RegExp),yd(e.toString())}var lO=new TextEncoder;function yd(e){yn(Bn.String);for(let n of lO.encode(e))yn(n)}function dO(e){yn(Bn.Symbol),ei(e.toString())}function fO(e){yn(Bn.TypeArray);let n=new Uint8Array(e.buffer);for(let i=0;i<n.length;i++)yn(n[i])}function hO(e){return yn(Bn.Undefined)}function ei(e){return Ay(e)?fO(e):_v(e)?aO(e):Cy(e)?pO(e):Mv(e)?Wy(e.valueOf()):Ov(e)?yd(e.valueOf()):vv(e)?zy(e.valueOf()):eO(e)?zy(e):Be(e)?oO(e):cn(e)?Wy(e):Nr(e)?sO(e):ad(e)?iO(e):lo(e)?cO(e):at(e)?mO(e):gt(e)?yd(e):ud(e)?dO(e):Bt(e)?hO(e):ls(e)?uO(e):qr()}function Xy(e){return Pa=BigInt("14695981039346656037"),ei(e),Pa}function xd(e){return Xy(e).toString(16).padStart(16,"0")}function Yy(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 gO=Yy;function Zy(){return gO}class dm{constructor(e,n){this.type=e,this.decode=n}Encode(e){let n=this.type,i=Hn(n)?(g)=>this.decode(n["~codec"].decode(g)):this.decode,c=Hn(n)?(g)=>n["~codec"].encode(e(g)):e,p={decode:i,encode:c};return St(this.type,{"~codec":p},{})}}class fm{constructor(e){this.type=e}Decode(e){return new dm(this.type,e)}}function hm(e){return new fm(e)}function tx(e,n){return hm(e).Decode(n).Encode(()=>{throw Error("Encode not implemented")})}function rx(e,n){return hm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(n)}function Hn(e){return Pr(e)&&le(e,"~codec")&&at(e["~codec"])&&le(e["~codec"],"encode")&&le(e["~codec"],"decode")}function nx(e){return $a(e)}function Zi(e){return Pr(e)&&le(e,"~immutable")}function Is(e,n={}){return Ne("AddReadonly",[e],n)}function ea(e,n={}){return Cu(e,n)}function ox(e){return ea(e)}function ta(e){return Pr(e)&&le(e,"~readonly")}function xO(e,n){let i=gm(e)?[...e["~refine"],n]:[n];return St(e,{"~refine":i},{})}function sx(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,()=>"Refine Error"]});return xO(n,{check:i,error:c})}function IO(e){return Jo(e)&&le(e,"check")&&le(e,"error")&&ls(e.check)&&ls(e.error)}function gm(e){return Pr(e)&&le(e,"~refine")&&Be(e["~refine"])&&on(e["~refine"],0,(n)=>IO(n))}var ix="-?(?:0|[1-9][0-9]*)n";function Mu(e){return Mt({"~kind":"BigInt"},{type:"bigint"},e)}function uo(e){return ve(e,"BigInt")}function D(e){return Mt({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return ve(e,"Boolean")}function vu(e){return Mt({"~kind":"Identifier"},{name:e})}function ax(e){return ve(e,"Identifier")}var ym="-?(?:0|[1-9][0-9]*)";function w(e){return Mt({"~kind":"Integer"},{type:"integer"},e)}function ln(e){return ve(e,"Integer")}class ux extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function bO(e){return Nr(e)?"bigint":cn(e)?"boolean":_t(e)?"number":gt(e)?"string":(()=>{throw new ux(e)})()}function a(e,n){return Mt({"~kind":"Literal"},{type:bO(e),const:e},n)}function xm(e){return Nr(e)||cn(e)||_t(e)||gt(e)}function cx(e){return yt(e)&&Nr(e.const)}function mx(e){return yt(e)&&cn(e.const)}function Im(e){return yt(e)&&_t(e.const)}function bm(e){return yt(e)&&gt(e.const)}function yt(e){return ve(e,"Literal")}function Pn(e){return Mt({"~kind":"Null"},{type:"null"},e)}function bs(e){return ve(e,"Null")}var Em="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Y(e){return Mt({"~kind":"Number"},{type:"number"},e)}function kr(e){return ve(e,"Number")}function Ma(e){return Mt({"~kind":"Symbol"},{type:"symbol"},e)}function Es(e){return ve(e,"Symbol")}function ra(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,g],1:(p)=>[p,Rr(),Rr()]});return Mt({"~kind":"Parameter"},{name:n,extends:i,equals:c},{})}function px(e){return ve(e,"Parameter")}var Sm=".*";function l(e){return Mt({"~kind":"String"},{type:"string"},e)}function nn(e){return ve(e,"String")}function m(e,n={}){return Mt({"~kind":"Union"},{anyOf:e},n)}function xe(e){return ve(e,"Union")}function lx(e){return Xo(e,["~kind","anyOf"])}function Ou(e){let n=dx(e);return _(n.length,2)?n[0]:[]}function EO(e){return!0}function fx(e){return It(e,(n,i)=>SO(n)?fx(i):!1,()=>!0)}function hx(e){return _(e.length,0)?!1:fx(e)}function SO(e){return xe(e)?hx(e.anyOf):yt(e)?EO(e.const):!1}function wm(e){return hx(e)}function Tm(e){return Mt({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function gx(e,n,i=[]){return It(e,(c,p)=>gx(p,n,[...i,`${c}${n}`]),()=>i)}function wO(e,n){return _(e.length,0)?[`${n}`]:gx(e,n)}function yx(e,n,i=[]){return It(n,(c,p)=>yx(e,p,[...i,...xx(e,c)]),()=>i)}function xx(e,n){return xe(n)?yx(e,n.anyOf):yt(n)?wO(e,n.const):qr()}function Ix(e,n){return It(n,(i,c)=>Ix(xx(e,i),c),()=>e)}function TO(e){return e.map((n)=>a(n))}function RO(e){let n=Ix([],e),i=TO(n);return m(i)}function kO(e){return _(e.length,0)?qr():_(e.length,1)&&yt(e[0])?e[0]:RO(e)}function Id(e){let n=Ou(e);return _(n.length,0)?l():wm(n)?kO(n):Tm(e)}function _u(e){let n=Id(e);return ur(n)?l():n}function to(e,n){let c={[e]:n};return Mt({["~kind"]:"Record"},{type:"object",patternProperties:c})}function bx(e){return to(Yo,e)}function Ex(e){return s({true:e,false:e})}function Ur(e,n={}){let[i,c,p]=[e,e.length,!1];return Mt({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:c},n)}function lt(e){return ve(e,"Tuple")}function Sx(e){return Xo(e,["~kind","type","items","minItems","additionalItems"])}function AO(e){return Xo(e,["~readonly"])}function bd(e,n){return St(AO(e),{},n)}function wx(e,n,i,c){let p=de(e,n,i);return bd(p,c)}function Tx(e,n={}){return Ne("RemoveReadonly",[e],n)}function Rx(e,n={}){return bd(e,n)}function CO(e){return Xo(e,["~optional"])}function Ed(e,n){return St(CO(e),{},n)}function kx(e,n,i,c){let p=de(e,n,i);return Ed(p,c)}function Ax(e,n={}){return Ne("RemoveOptional",[e],n)}function Rm(e,n={}){return Ed(e,n)}function Sd(e){return e.reduceRight((i,c,p)=>({[p]:c,...i}),{})}function Cx(e){let n=Sd(e.items);return s(n)}function wd(e){return Qe(e)||lt(e)}function PO(e,n){return ta(e)?ta(n)?!0:!1:!1}function $O(e,n){return an(e)?an(n)?!0:!1:!1}function MO(e,n){let i=PO(e,n),c=$O(e,n),p=Ar([e,n]),g=Rx(Rm(p));return i&&c?ea(Qi(g)):i&&!c?ea(g):!i&&c?Qi(g):g}function vO(e,n,i){return i in e?i in n?MO(e[i],n[i]):e[i]:(i in n)?n[i]:zt()}function OO(e,n){return[...new Set([...Se(e),...Se(n)])].reduce((p,g)=>({...p,[g]:vO(e,n,g)}),{})}function Px(e){return Qe(e)?e.properties:lt(e)?Sd(e.items):{}}function $x(e,n){let i=Px(e),c=Px(n),p=OO(i,c);return s(p)}function _O(e,n){let i=va(e,n);return _(i,Nu)?e:_(i,Du)?n:_(i,Lu)?n:zt()}function LO(e,n){let i=wd(e),c=wd(n);return i&&c?$x(e,n):i&&!c?e:!i&&c?n:_O(e,n)}function Mx(e,n){return ao(e)?e:Mr(e)?e:en(e)?n:ao(n)?n:Mr(n)?n:en(n)?e:LO(e,n)}function NO(e,n){return xe(e)||xe(n)}function DO(e,n){let i=To(e),c=To(n);return NO(i,c)?Ar([i,c]):Mx(i,c)}function vx(e,n,i=[]){return It(n,(c,p)=>vx(e,p,[...i,DO(c,e)]),()=>_(i.length,0)?[e]:i)}function Ox(e,n,i=[]){return It(e,(c,p)=>Ox(p,n,[...i,...qu([c],n)]),()=>i)}function qu(e,n=[]){return It(e,(i,c)=>xe(i)?qu(c,Ox(i.anyOf,n)):qu(c,vx(i,n)),()=>n)}function qO(e,n){let i=wn({},e,n);return no(i)?[]:[e]}function _x(e,n,i=[]){return It(e,(c,p)=>_x(p,n,[...i,...qO(c,n)]),()=>i)}function km(e,n){let i=To(e),c=xe(i)?i.anyOf:[i],p=_x(c,n);return ro(p)}function Zo(e,n,i){let c=Ar([e,n]),p=km(i,e);return ro([c,p])}function Yn(e,n=[]){return It(e,(i,c)=>Yn(c,[...n,a(i)]),()=>ro(n))}function Ar(e){let n=qu(e),i=Td(n);return ro(i)}function $n(e){let n=_u(e);return To(n)}function ro(e){let n=Td(e);return ti(n)}function To(e){return Dr(e)?Zo(e.if,e.then,e.else):rn(e)?Yn(e.enum):He(e)?Ar(e.allOf):ur(e)?$n(e.pattern):xe(e)?ro(e.anyOf):e}function ti(e){return _(e.length,1)?e[0]:_(e.length,0)?zt():m(e)}function Lx(e,n){let i=Yn(e);return ri(i,n)}function Nx(e,n){return to(ni,n)}function Dx(e,n){let i=Ar(e);return ri(i,n)}function qx(e,n){return gt(e)||_t(e)?s({[e]:n}):_(e,!1)?s({false:n}):_(e,!0)?s({true:n}):s({})}function Fx(e,n){return to(Oa,n)}function jx(e,n){return le(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?to(e.pattern.toString(),n):to(Yo,n)}function Ux(e,n){let i=Ou(e);return wm(i)?ri($n(e),n):to(e,n)}function FO(e){return xe(e)?na(e.anyOf):[e]}function na(e,n=[]){return It(e,(i,c)=>na(c,[...n,...FO(i)]),()=>n)}function jO(e){return e.some((n)=>nn(n)||kr(n)||ln(n))}function UO(e,n){return _(jO(e),!0)?to(Yo,n):void 0}function BO(e,n){return e.reduce((i,c)=>yt(c)&&(gt(c.const)||_t(c.const))?{...i,[c.const]:n}:i,{})}function GO(e,n){let i=BO(e,n);return s(i)}function Bx(e,n){let i=na(e),c=UO(i,n);return Pr(c)?c:GO(i,n)}function ri(e,n){return Mr(e)?bx(n):Wn(e)?Ex(n):rn(e)?Lx(e.enum,n):ln(e)?Nx(e,n):He(e)?Dx(e.allOf,n):yt(e)?qx(e.const,n):kr(e)?Fx(e,n):xe(e)?Bx(e.anyOf,n):nn(e)?jx(e,n):ur(e)?Ux(e.pattern,n):s({})}function Rd(e,n,i){return ct([e])?St(ri(e,n),{},i):Am(e,n,i)}function Gx(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return Rd(g,y,p)}var ni=`^${ym}$`,Oa=`^${Em}$`,Yo=`^${Sm}$`;function Am(e,n,i={}){return Ne("Record",[e,n],i)}function Ss(e,n,i={}){return Rd(e,n,i)}function Kx(e,n){return to(e,n)}function Cm(e){return _(e,Yo)?l():_(e,ni)?w():_(e,Oa)?Y():Id(e)}function dn(e){return Se(e.patternProperties)[0]}function oi(e){let n=dn(e);return Cm(n)}function fr(e){return e.patternProperties[dn(e)]}function Gt(e){return ve(e,"Record")}function oa(e){return Mt({"~kind":"Rest"},{type:"rest",items:e},{})}function si(e){return ve(e,"Rest")}function Pm(e){return Mt({["~kind"]:"This"},{$ref:"#"},e)}function $m(e){return ve(e,"This")}function _a(e){return Mt({"~kind":"Undefined"},{type:"undefined"},e)}function es(e){return ve(e,"Undefined")}function Mm(e){return Mt({"~kind":"Void"},{type:"void"},e)}function co(e){return ve(e,"Void")}function HO(e,n){return _(e,"Array")?B(n[0]):_(e,"Capitalize")?Om(n[0]):_(e,"ConstructorParameters")?qm(n[0]):_(e,"Evaluate")?aE(n[0]):_(e,"Exclude")?Fm(n[0],n[1]):_(e,"Extract")?jm(n[0],n[1]):_(e,"Index")?Bu(n[0],n[1]):_(e,"InstanceType")?Um(n[0]):_(e,"Lowercase")?_m(n[0]):_(e,"NonNullable")?Bm(n[0]):_(e,"Omit")?Gm(n[0],n[1]):_(e,"Parameters")?Km(n[0]):_(e,"Partial")?Hm(n[0]):_(e,"Pick")?Wm(n[0],n[1]):_(e,"Readonly")?zm(n[0]):_(e,"KeyOf")?Gu(n[0]):_(e,"Record")?Am(n[0],n[1]):_(e,"Required")?Vm(n[0]):_(e,"ReturnType")?Jm(n[0]):_(e,"Uncapitalize")?Lm(n[0]):_(e,"Uppercase")?Nm(n[0]):Uu(sn(e),n)}function sa(){throw Error("Unreachable")}function Jx(e,n=[]){return It(e,(i,c)=>Jx(c,[...n,i[1]]),()=>n)}function Ls(e){return _(e.length,3)?[e[0],...Jx(e[1])]:[]}function Qx(e){return ra(e[0],e[2],e[4])}function Xx(e){return ra(e[0],e[2],e[2])}function Yx(e){return ra(e[0],Rr(),e[2])}function Zx(e){return ra(e,Rr(),Rr())}function eI(e){return e}function tI(e){return Ls(e)}function rI(e){return e[1]}function nI(e){return Ls(e)}function oI(e){return e[1]}function sI(e){return HO(e[0],e[1])}function iI(e){return null}function aI(e){return l()}function uI(e){return Y()}function cI(e){return D()}function mI(e){return _a()}function pI(e){return Pn()}function lI(e){return w()}function dI(e){return Mu()}function fI(e){return Rr()}function hI(e){return Ca()}function gI(e){return s({})}function yI(e){return zt()}function xI(e){return Ma()}function II(e){return Mm()}function bI(e){return Pm()}function EI(e){return a(BigInt(e))}function SI(e){return a(_(e,"true"))}function wI(e){return a(parseFloat(e))}function TI(e){return a(e)}function RI(e){return e[1]}function kI(e){return a(e)}function AI(e){return _(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function CI(e){return e[1]}function PI(e){return vm(e)}function $I(e){return _(e.length,6)?Xi(e[1],e[3],e[5]):Xi(e[1],e[3],Rr())}function MI(e){return e.length>0}function vI(e){return e.reduce((n,i)=>_(i.length,3)?[...n,[i[1]]]:[...n,[]],[])}function OI(e){return _(e.length,6)?[e[1],e[3],e[5]]:[]}function _I(e){return Be(e)&&_(e.length,3)?e[1]:e}function LI(e){return _(e.length,2)?e[1]:[]}function Hx(e,n){return n.reduce((i,c)=>{let p=c;return _(p.length,1)?Bu(i,p[0]):_(p.length,0)?B(i):sa()},e)}function Wx(e,n){return _(n.length,3)?Dm(e,n[0],n[1],n[2]):e}function WO(e,n){return Be(n)&&_(n.length,0)?e:Qm(e,n)}function NI(e){let[n,i,c,p,g]=e;return WO(n?Wx(Gu(Hx(i,c)),p):Wx(Hx(i,c),p),g)}function kd(e,n){return _(n.length,3)?(()=>{let[i,c,p]=n,g=kd(c,p);if(_(i,"&"))return He(g)?Cn([e,...g.allOf]):Cn([e,g]);if(_(i,"|"))return xe(g)?m([e,...g.anyOf]):m([e,g]);sa()})():e}function DI(e){return e}function qI(e){let[n,i]=e;return kd(n,i)}function FI(e){return e}function jI(e){let[n,i]=e;return kd(n,i)}function UI(e){return iE(e[1])}function BI(e){return e[1]}function GI(e){return Zs(e[0],e[2])}function KI(e){return _(e.length,4)?$u(e[1],e[3]):_(e.length,2)?$u(e[1],Rr()):sa()}function HI(e){return e}function WI(e){return`${e}`}function zI(e){return e}function VI(e){return e}function JI(e){return ln(e[3])?ni:kr(e[3])?Oa:Es(e[3])?Yo:nn(e[3])?Yo:sa()}function QI(e){return e}function XI(e){return e.length>0}function YI(e){return e.length>0}function ZI(e){let[n,i,c,p,g]=e;return{[i]:n&&c?Is(ys(g)):n&&!c?Is(g):!n&&c?ys(g):g}}function eb(e){return e}function tb(e){return Ls(e)}function rb(e){return e.reduce((n,i)=>le(i,ni)||le(i,Oa)||le(i,Yo)?[n[0],pn(n[1],i)]:[pn(n[0],i),n[1]],[{},{}])}function nb(e){return rb(e[1])}function ob(e){let[n,i]=e,c=_(Se(i).length,0)?{}:{patternProperties:i};return s(n,c)}function sb(e){return _(e.length,5)?Is(ys(e[4])):_(e.length,3)?e[2]:_(e.length,4)?_(e[2],"readonly")?Is(e[3]):ys(e[3]):sa()}function ib(e){if(!Be(e)||!_(e.length,3))return e;let[n,i,c]=e;return n&&c?Is(ys(i)):n&&!c?Is(i):!n&&c?ys(i):i}function ab(e){return _(e.length,2)?oa(e[1]):_(e.length,1)?e[0]:sa()}function ub(e){return Ls(e)}function cb(e){return Ur(e[1])}function mb(e){return Is(ys(e[4]))}function pb(e){return Is(e[3])}function lb(e){return ys(e[3])}function db(e){return e[2]}function fb(e){return e}function hb(e){return _(e.length,2)?oa(e[1]):_(e.length,1)?e[0]:sa()}function gb(e){return Ls(e)}function yb(e){return gs(e[1],e[4])}function xb(e){return hs(e[2],e[5])}function zx(e,n){return _(e,"remove")?Tx(n):_(e,"add")?Is(n):n}function Ib(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function Vx(e,n){return _(e,"remove")?Ax(n):_(e,"add")?ys(n):n}function bb(e){return _(e.length,2)&&_(e[0],"-")?"remove":_(e.length,2)&&_(e[0],"+")?"add":_(e.length,1)?"add":"none"}function Eb(e){return _(e.length,2)?[e[1]]:[]}function Sb(e){return Be(e[6])&&_(e[6].length,1)?Fu(vu(e[3]),e[5],e[6][0],zx(e[1],Vx(e[8],e[10]))):Fu(vu(e[3]),e[5],sn(e[3]),zx(e[1],Vx(e[8],e[10])))}function wb(e){return sn(e)}function Tb(e){return BigInt(e)}function Rb(e){return parseFloat(e)}function kb(e){return _(e,"true")}function Ab(e){return e}function Cb(e){return null}function Pb(e){return}function $b(e){return{[e[0]]:e[2]}}function Mb(e){return Ls(e)}function zO(e){return e.reduce((n,i)=>pn(n,i),{})}function vb(e){return zO(e[1])}function Ob(e){return Ls(e)}function _b(e){return e[1]}function Lb(e){return e}function Nb(e){return Mu()}function Db(e){return l()}function qb(e){return Y()}function Fb(e){return w()}function jb(e){return zt()}function Ub(e){return a(e)}function Bb(e){return e}function Gb(e){return m(e[1])}function Kb(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function Hb(e){return[e[0],...e[1]]}function Wb(e){return e}function zb(e){return e[1]}function Vb(e){return Ls(e)}function Jb(e){return _(e.length,2)?e[1]:[]}function Qb(e){let n=e[2],i=e[3],[c,p]=e[4],g=_(Se(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Zs(n,ju(i,c,g))}}function Xb(e){let n=e[2],[i,c]=e[3],p=_(Se(c).length,0)?{}:{patternProperties:c};return{[e[1]]:ju(n,i,p)}}function Yb(e){return{[e[1]]:Zs(e[2],e[4])}}function Zb(e){return{[e[1]]:e[3]}}function eE(e){return null}function tE(e){return e}function rE(e){return Ls(e)}function nE(e){return e[1]}function oE(e){let[n,i]=[e[0],e[1]];return uE(pn(n,rb(i)[0]))}function sE(e){return e}function Ku(e){return _(e.length,2)}function Rt(e,n,i){return Ku(e)?n(e[0],e[1]):i()}function QO(e,n){return _(n.indexOf(e),0)?[e,n.slice(e.length)]:[]}function Or(e,n){for(let i=0;i<e.length;i++){let c=QO(e[i],n);if(Ku(c))return c}return[]}function Ad(e,n){return Array.from({length:n-e+1},(i,c)=>String.fromCharCode(e+c))}var cE=[...Ad(97,122),...Ad(65,90)],Cd="0",Pd=Ad(49,57),La=[Cd,...Pd],mE=" ",Na=`
15
+ `;var ii="_",Xm=".",pE="$",Ym="-";var lE="//",dE="/*",YO="*/";function fE(e){let n=e.indexOf(YO);return _(n,-1)?"":e.slice(n+2)}function hE(e){let n=e.indexOf(Na);return _(n,-1)?"":e.slice(n)}function ZO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Zm(e){let n=ZO(e);return n.startsWith(dE)?Zm(fE(n.slice(2))):n.startsWith(lE)?Zm(hE(n.slice(2))):n}function xn(e){let n=e.trimStart();return n.startsWith(dE)?xn(fE(n.slice(2))):n.startsWith(lE)?xn(hE(n.slice(2))):n}function ep(e,n){return Rt(Or([e],n),(i,c)=>[i,c],()=>["",n])}function e_(e,n){return e.includes(n)}function Da(e,n,i,c=""){return Rt(Or(e,i),(p,g)=>e_(n,p)?Da(e,n,g,c):Da(e,n,g,`${c}${p}`),()=>[c,i])}function t_(e){return Or(Pd,e)}var r_=[...La,ii];function n_(e){return Da(r_,[ii],e)}function o_(e){return Rt(Or([Cd],e),(n,i)=>[n,i],()=>Rt(t_(e),(n,i)=>Rt(n_(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[]))}function tp(e){return o_(xn(e))}function s_(e){return ep(Ym,e)}function i_(e){return Rt(s_(e),(n,i)=>Rt(tp(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function gE(e){return i_(xn(e))}function a_(e){return Rt(gE(e),(n,i)=>Rt(Or(["n"],i),(c,p)=>[`${n}`,p],()=>[]),()=>[])}function $d(e){return a_(e)}function Md(e,n){return Or([e],n)}function Z(e,n){return _(e,"")?["",n]:e.startsWith(Na)?Md(e,Zm(n)):e.startsWith(mE)?Md(e,n):Md(e,xn(n))}var yE=[...cE,ii,pE];function u_(e){return Or(yE,e)}var c_=[...yE,...La];function xE(e,n=""){return Rt(Or(c_,e),(i,c)=>xE(c,`${n}${i}`),()=>[n,e])}function m_(e){return Rt(u_(e),(n,i)=>Rt(xE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function Br(e){return m_(xn(e))}var p_=[...La,ii];function l_(e){return Ku(Or([Xm],e))}function IE(e){return Rt(Da(p_,[ii],e),(n,i)=>_(n,"")?[]:[n,i],()=>[])}function d_(e){return Rt(Or([Xm],e),(n,i)=>Rt(IE(i),(c,p)=>[`0${n}${c}`,p],()=>[]),()=>[])}function f_(e){return Rt(tp(e),(n,i)=>Rt(Or([Xm],i),(c,p)=>Rt(IE(p),(g,y)=>[`${n}${c}${g}`,y],()=>[`${n}`,p]),()=>[`${n}`,i]),()=>[])}function h_(e){return l_(e)?d_(e):f_(e)}function bE(e){return h_(xn(e))}function g_(e){return ep(Ym,e)}function y_(e){return Rt(g_(e),(n,i)=>Rt(bE(i),(c,p)=>[`${n}${c}`,p],()=>[]),()=>[])}function rp(e){return y_(xn(e))}function x_(e){return _(e,"")?[]:[e.slice(0,1),e.slice(1)]}function EE(e,n){return It(e,(i,c)=>n.startsWith(i)?!0:EE(c,n),()=>!1)}function ai(e,n,i=""){return Rt(x_(n),(c,p)=>EE(e,n)?[i,n]:ai(e,p,`${i}${c}`),()=>[])}function I_(e,n,i){return Rt(Or([e],i),(c,p)=>Rt(ai([n],p),(g,y)=>Rt(Or([n],y),(x,b)=>[`${g}`,b],()=>[]),()=>[]),()=>[])}function b_(e,n,i){return Rt(Or([e],i),(c,p)=>Rt(ai([Na,n],p),(g,y)=>Rt(Or([n],y),(x,b)=>[`${g}`,b],()=>[]),()=>[]),()=>[])}function SE(e,n,i,c){return i?I_(e,n,xn(c)):b_(e,n,xn(c))}function E_(e,n){return Or(e,n)}function S_(e,n){return SE(e,e,!1,n)}function w_(e,n){return Rt(E_(e,n),(i,c)=>S_(i,`${i}${c}`),()=>[])}function np(e,n){return w_(e,xn(n))}function wE(e,n){return Rt(ai(e,n),(i,c)=>_(i,"")?[]:[i,c],()=>[])}var k=(e,n,i=()=>[])=>e.length===2?n(e):i(),R_=(e)=>k(k(Br(e),([n,i])=>k(Z("extends",i),([c,p])=>k(vt(p),([g,y])=>k(Z("=",y),([x,b])=>k(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[Qx(n),i]),k_=(e)=>k(k(Br(e),([n,i])=>k(Z("extends",i),([c,p])=>k(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Xx(n),i]),A_=(e)=>k(k(Br(e),([n,i])=>k(Z("=",i),([c,p])=>k(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Yx(n),i]),C_=(e)=>k(Br(e),([n,i])=>[Zx(n),i]),kE=(e)=>k(k(R_(e),([n,i])=>[n,i],()=>k(k_(e),([n,i])=>[n,i],()=>k(A_(e),([n,i])=>[n,i],()=>k(C_(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[eI(n),i]),AE=(e,n=[])=>k(k(Z(",",e),([i,c])=>k(kE(c),([p,g])=>[[i,p],g])),([i,c])=>AE(c,[...n,i]),()=>[n,e]),P_=(e)=>k(k(k(kE(e),([n,i])=>k(AE(i),([c,p])=>k(k(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[tI(n),i]),_d=(e)=>k(k(Z("<",e),([n,i])=>k(P_(i),([c,p])=>k(Z(">",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[rI(n),i]),CE=(e,n=[])=>k(k(Z(",",e),([i,c])=>k(vt(c),([p,g])=>[[i,p],g])),([i,c])=>CE(c,[...n,i]),()=>[n,e]),$_=(e)=>k(k(k(vt(e),([n,i])=>k(CE(i),([c,p])=>k(k(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[nI(n),i]),M_=(e)=>k(k(Z("<",e),([n,i])=>k($_(i),([c,p])=>k(Z(">",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[oI(n),i]),v_=(e)=>k(k(Br(e),([n,i])=>k(M_(i),([c,p])=>[[n,c],p])),([n,i])=>[sI(n),i]),PE=(e)=>k(k(k(Z(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[iI(n),i]),$E=(e)=>k(Z("string",e),([n,i])=>[aI(n),i]),ME=(e)=>k(Z("number",e),([n,i])=>[uI(n),i]),O_=(e)=>k(Z("boolean",e),([n,i])=>[cI(n),i]),__=(e)=>k(Z("undefined",e),([n,i])=>[mI(n),i]),L_=(e)=>k(Z("null",e),([n,i])=>[pI(n),i]),vE=(e)=>k(Z("integer",e),([n,i])=>[lI(n),i]),N_=(e)=>k(Z("bigint",e),([n,i])=>[dI(n),i]),D_=(e)=>k(Z("unknown",e),([n,i])=>[fI(n),i]),q_=(e)=>k(Z("any",e),([n,i])=>[hI(n),i]),F_=(e)=>k(Z("object",e),([n,i])=>[gI(n),i]),j_=(e)=>k(Z("never",e),([n,i])=>[yI(n),i]),OE=(e)=>k(Z("symbol",e),([n,i])=>[xI(n),i]),U_=(e)=>k(Z("void",e),([n,i])=>[II(n),i]),B_=(e)=>k(Z("this",e),([n,i])=>[bI(n),i]),G_=(e)=>k(k(Z("${",e),([n,i])=>k(vt(i),([c,p])=>k(Z("}",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[RI(n),i]),vd=(e)=>k(ai(["${","`"],e),([n,i])=>[kI(n),i]),_E=(e)=>k(k(k(vd(e),([n,i])=>k(G_(i),([c,p])=>k(_E(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k(k(vd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k(k(vd(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[AI(n),i]),Ld=(e)=>k(k(Z("`",e),([n,i])=>k(_E(i),([c,p])=>k(Z("`",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[CI(n),i]),K_=(e)=>k(Ld(e),([n,i])=>[PI(n),i]),H_=(e)=>k(k(k(Z("if",e),([n,i])=>k(vt(i),([c,p])=>k(Z("then",p),([g,y])=>k(vt(y),([x,b])=>k(Z("else",b),([S,T])=>k(vt(T),([A,C])=>[[n,c,g,x,S,A],C])))))),([n,i])=>[n,i],()=>k(k(Z("if",e),([n,i])=>k(vt(i),([c,p])=>k(Z("then",p),([g,y])=>k(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>[])),([n,i])=>[$I(n),i]),W_=(e)=>k($d(e),([n,i])=>[EI(n),i]),z_=(e)=>k(k(Z("true",e),([n,i])=>[n,i],()=>k(Z("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[SI(n),i]),V_=(e)=>k(rp(e),([n,i])=>[wI(n),i]),J_=(e)=>k(np(["'",'"'],e),([n,i])=>[TI(n),i]),Q_=(e)=>k(k(k(Z("keyof",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[MI(n),i]),LE=(e,n=[])=>k(k(k(Z("[",e),([i,c])=>k(vt(c),([p,g])=>k(Z("]",g),([y,x])=>[[i,p,y],x]))),([i,c])=>[i,c],()=>k(k(Z("[",e),([i,c])=>k(Z("]",c),([p,g])=>[[i,p],g])),([i,c])=>[i,c],()=>[])),([i,c])=>LE(c,[...n,i]),()=>[n,e]),X_=(e)=>k(LE(e),([n,i])=>[vI(n),i]),Y_=(e)=>k(k(k(Z("extends",e),([n,i])=>k(vt(i),([c,p])=>k(Z("?",p),([g,y])=>k(vt(y),([x,b])=>k(Z(":",b),([S,T])=>k(vt(T),([A,C])=>[[n,c,g,x,S,A],C])))))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[OI(n),i]),Z_=(e)=>k(k(k(Z("(",e),([n,i])=>k(vt(i),([c,p])=>k(Z(")",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k($E(e),([n,i])=>[n,i],()=>k(ME(e),([n,i])=>[n,i],()=>k(O_(e),([n,i])=>[n,i],()=>k(__(e),([n,i])=>[n,i],()=>k(L_(e),([n,i])=>[n,i],()=>k(vE(e),([n,i])=>[n,i],()=>k(N_(e),([n,i])=>[n,i],()=>k(D_(e),([n,i])=>[n,i],()=>k(q_(e),([n,i])=>[n,i],()=>k(F_(e),([n,i])=>[n,i],()=>k(j_(e),([n,i])=>[n,i],()=>k(OE(e),([n,i])=>[n,i],()=>k(U_(e),([n,i])=>[n,i],()=>k(B_(e),([n,i])=>[n,i],()=>k(W_(e),([n,i])=>[n,i],()=>k(z_(e),([n,i])=>[n,i],()=>k(V_(e),([n,i])=>[n,i],()=>k(J_(e),([n,i])=>[n,i],()=>k(K_(e),([n,i])=>[n,i],()=>k(H_(e),([n,i])=>[n,i],()=>k(mL(e),([n,i])=>[n,i],()=>k(dL(e),([n,i])=>[n,i],()=>k(IL(e),([n,i])=>[n,i],()=>k(xL(e),([n,i])=>[n,i],()=>k(wL(e),([n,i])=>[n,i],()=>k(v_(e),([n,i])=>[n,i],()=>k(TL(e),([n,i])=>[n,i],()=>[])))))))))))))))))))))))))))),([n,i])=>[_I(n),i]),eL=(e)=>k(k(k(Z("with",e),([n,i])=>k(YE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[LI(n),i]),NE=(e)=>k(k(Q_(e),([n,i])=>k(Z_(i),([c,p])=>k(X_(p),([g,y])=>k(Y_(y),([x,b])=>k(eL(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[NI(n),i]),DE=(e)=>k(k(k(Z("&",e),([n,i])=>k(NE(i),([c,p])=>k(DE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[DI(n),i]),qE=(e)=>k(k(NE(e),([n,i])=>k(DE(i),([c,p])=>[[n,c],p])),([n,i])=>[qI(n),i]),FE=(e)=>k(k(k(Z("|",e),([n,i])=>k(qE(i),([c,p])=>k(FE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[FI(n),i]),op=(e)=>k(k(qE(e),([n,i])=>k(FE(i),([c,p])=>[[n,c],p])),([n,i])=>[jI(n),i]),tL=(e)=>k(k(Z("readonly",e),([n,i])=>k(op(i),([c,p])=>[[n,c],p])),([n,i])=>[UI(n),i]),rL=(e)=>k(k(Z("|",e),([n,i])=>k(op(i),([c,p])=>[[n,c],p])),([n,i])=>[BI(n),i]),nL=(e)=>k(k(_d(e),([n,i])=>k(Z("=",i),([c,p])=>k(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[GI(n),i]),oL=(e)=>k(k(k(Z("infer",e),([n,i])=>k(Br(i),([c,p])=>k(Z("extends",p),([g,y])=>k(op(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>k(k(Z("infer",e),([n,i])=>k(Br(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>[])),([n,i])=>[KI(n),i]),vt=(e)=>k(k(oL(e),([n,i])=>[n,i],()=>k(rL(e),([n,i])=>[n,i],()=>k(tL(e),([n,i])=>[n,i],()=>k(op(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[HI(n),i]),sL=(e)=>k(rp(e),([n,i])=>[WI(n),i]),iL=(e)=>k(Br(e),([n,i])=>[zI(n),i]),aL=(e)=>k(np(["'",'"'],e),([n,i])=>[VI(n),i]),uL=(e)=>k(k(Z("[",e),([n,i])=>k(Br(i),([c,p])=>k(Z(":",p),([g,y])=>k(k(vE(y),([x,b])=>[x,b],()=>k(ME(y),([x,b])=>[x,b],()=>k($E(y),([x,b])=>[x,b],()=>k(OE(y),([x,b])=>[x,b],()=>[])))),([x,b])=>k(Z("]",b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[JI(n),i]),jE=(e)=>k(k(sL(e),([n,i])=>[n,i],()=>k(iL(e),([n,i])=>[n,i],()=>k(aL(e),([n,i])=>[n,i],()=>k(uL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[QI(n),i]),UE=(e)=>k(k(k(Z("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[XI(n),i]),BE=(e)=>k(k(k(Z("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[YI(n),i]),GE=(e)=>k(k(UE(e),([n,i])=>k(jE(i),([c,p])=>k(BE(p),([g,y])=>k(Z(":",y),([x,b])=>k(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[ZI(n),i]),sp=(e)=>k(k(k(Z(",",e),([n,i])=>k(Z(`
16
+ `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z(";",e),([n,i])=>k(Z(`
17
+ `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z(",",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k(k(Z(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k(k(Z(`
18
+ `,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))))),([n,i])=>[eb(n),i]),KE=(e,n=[])=>k(k(sp(e),([i,c])=>k(GE(c),([p,g])=>[[i,p],g])),([i,c])=>KE(c,[...n,i]),()=>[n,e]),cL=(e)=>k(k(k(GE(e),([n,i])=>k(KE(i),([c,p])=>k(k(sp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[tb(n),i]),Nd=(e)=>k(k(Z("{",e),([n,i])=>k(cL(i),([c,p])=>k(Z("}",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[nb(n),i]),mL=(e)=>k(Nd(e),([n,i])=>[ob(n),i]),pL=(e)=>k(k(k(Br(e),([n,i])=>k(Z("?",i),([c,p])=>k(Z(":",p),([g,y])=>k(Z("readonly",y),([x,b])=>k(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[n,i],()=>k(k(Br(e),([n,i])=>k(Z(":",i),([c,p])=>k(Z("readonly",p),([g,y])=>k(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>k(k(Br(e),([n,i])=>k(Z("?",i),([c,p])=>k(Z(":",p),([g,y])=>k(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[n,i],()=>k(k(Br(e),([n,i])=>k(Z(":",i),([c,p])=>k(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>[])))),([n,i])=>[sb(n),i]),TE=(e)=>k(k(pL(e),([n,i])=>[n,i],()=>k(k(UE(e),([n,i])=>k(vt(i),([c,p])=>k(BE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>[])),([n,i])=>[ib(n),i]),HE=(e)=>k(k(k(Z("...",e),([n,i])=>k(TE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(TE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[ab(n),i]),WE=(e,n=[])=>k(k(Z(",",e),([i,c])=>k(HE(c),([p,g])=>[[i,p],g])),([i,c])=>WE(c,[...n,i]),()=>[n,e]),lL=(e)=>k(k(k(HE(e),([n,i])=>k(WE(i),([c,p])=>k(k(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[ub(n),i]),dL=(e)=>k(k(Z("[",e),([n,i])=>k(lL(i),([c,p])=>k(Z("]",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[cb(n),i]),fL=(e)=>k(k(Br(e),([n,i])=>k(Z("?",i),([c,p])=>k(Z(":",p),([g,y])=>k(Z("readonly",y),([x,b])=>k(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[mb(n),i]),hL=(e)=>k(k(Br(e),([n,i])=>k(Z(":",i),([c,p])=>k(Z("readonly",p),([g,y])=>k(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[pb(n),i]),gL=(e)=>k(k(Br(e),([n,i])=>k(Z("?",i),([c,p])=>k(Z(":",p),([g,y])=>k(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[lb(n),i]),yL=(e)=>k(k(Br(e),([n,i])=>k(Z(":",i),([c,p])=>k(vt(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[db(n),i]),RE=(e)=>k(k(fL(e),([n,i])=>[n,i],()=>k(hL(e),([n,i])=>[n,i],()=>k(gL(e),([n,i])=>[n,i],()=>k(yL(e),([n,i])=>[n,i],()=>[])))),([n,i])=>[fb(n),i]),zE=(e)=>k(k(k(Z("...",e),([n,i])=>k(RE(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(RE(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[])),([n,i])=>[hb(n),i]),VE=(e,n=[])=>k(k(Z(",",e),([i,c])=>k(zE(c),([p,g])=>[[i,p],g])),([i,c])=>VE(c,[...n,i]),()=>[n,e]),JE=(e)=>k(k(k(zE(e),([n,i])=>k(VE(i),([c,p])=>k(k(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[gb(n),i]),xL=(e)=>k(k(Z("(",e),([n,i])=>k(JE(i),([c,p])=>k(Z(")",p),([g,y])=>k(Z("=>",y),([x,b])=>k(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[yb(n),i]),IL=(e)=>k(k(Z("new",e),([n,i])=>k(Z("(",i),([c,p])=>k(JE(p),([g,y])=>k(Z(")",y),([x,b])=>k(Z("=>",b),([S,T])=>k(vt(T),([A,C])=>[[n,c,g,x,S,A],C])))))),([n,i])=>[xb(n),i]),bL=(e)=>k(k(k(Z("+",e),([n,i])=>k(Z("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z("-",e),([n,i])=>k(Z("readonly",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z("readonly",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[Ib(n),i]),EL=(e)=>k(k(k(Z("+",e),([n,i])=>k(Z("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z("-",e),([n,i])=>k(Z("?",i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z("?",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])))),([n,i])=>[bb(n),i]),SL=(e)=>k(k(k(Z("as",e),([n,i])=>k(vt(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Eb(n),i]),wL=(e)=>k(k(Z("{",e),([n,i])=>k(bL(i),([c,p])=>k(Z("[",p),([g,y])=>k(Br(y),([x,b])=>k(Z("in",b),([S,T])=>k(vt(T),([A,C])=>k(SL(C),([P,L])=>k(Z("]",L),([q,X])=>k(EL(X),([j,V])=>k(Z(":",V),([J,ee])=>k(vt(ee),([ie,H])=>k(PE(H),([ce,fe])=>k(Z("}",fe),([_e,be])=>[[n,c,g,x,S,A,P,q,j,J,ie,ce,_e],be]))))))))))))),([n,i])=>[Sb(n),i]),TL=(e)=>k(Br(e),([n,i])=>[wb(n),i]),RL=(e)=>k($d(e),([n,i])=>[Tb(n),i]),kL=(e)=>k(rp(e),([n,i])=>[Rb(n),i]),AL=(e)=>k(k(Z("true",e),([n,i])=>[n,i],()=>k(Z("false",e),([n,i])=>[n,i],()=>[])),([n,i])=>[kb(n),i]),CL=(e)=>k(np(['"',"'"],e),([n,i])=>[Ab(n),i]),PL=(e)=>k(Z("null",e),([n,i])=>[Cb(n),i]),$L=(e)=>k(Z("undefined",e),([n,i])=>[Pb(n),i]),QE=(e)=>k(k(jE(e),([n,i])=>k(Z(":",i),([c,p])=>k(Dd(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[$b(n),i]),XE=(e,n=[])=>k(k(sp(e),([i,c])=>k(QE(c),([p,g])=>[[i,p],g])),([i,c])=>XE(c,[...n,i]),()=>[n,e]),ML=(e)=>k(k(k(QE(e),([n,i])=>k(XE(i),([c,p])=>k(k(sp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Mb(n),i]),YE=(e)=>k(k(Z("{",e),([n,i])=>k(ML(i),([c,p])=>k(Z("}",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[vb(n),i]),ZE=(e,n=[])=>k(k(Z(",",e),([i,c])=>k(Dd(c),([p,g])=>[[i,p],g])),([i,c])=>ZE(c,[...n,i]),()=>[n,e]),vL=(e)=>k(k(k(Dd(e),([n,i])=>k(ZE(i),([c,p])=>k(k(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Ob(n),i]),OL=(e)=>k(k(Z("[",e),([n,i])=>k(vL(i),([c,p])=>k(Z("]",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[_b(n),i]),Dd=(e)=>k(k(RL(e),([n,i])=>[n,i],()=>k(kL(e),([n,i])=>[n,i],()=>k(AL(e),([n,i])=>[n,i],()=>k(CL(e),([n,i])=>[n,i],()=>k(PL(e),([n,i])=>[n,i],()=>k($L(e),([n,i])=>[n,i],()=>k(YE(e),([n,i])=>[n,i],()=>k(OL(e),([n,i])=>[n,i],()=>[])))))))),([n,i])=>[Lb(n),i]),_L=(e)=>k(Z("-?(?:0|[1-9][0-9]*)n",e),([n,i])=>[Nb(n),i]),LL=(e)=>k(Z(".*",e),([n,i])=>[Db(n),i]),NL=(e)=>k(Z("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([n,i])=>[qb(n),i]),DL=(e)=>k(Z("-?(?:0|[1-9][0-9]*)",e),([n,i])=>[Fb(n),i]),qL=(e)=>k(Z("(?!)",e),([n,i])=>[jb(n),i]),FL=(e)=>k(wE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([n,i])=>[Ub(n),i]),jL=(e)=>k(k(_L(e),([n,i])=>[n,i],()=>k(LL(e),([n,i])=>[n,i],()=>k(NL(e),([n,i])=>[n,i],()=>k(DL(e),([n,i])=>[n,i],()=>k(qL(e),([n,i])=>[n,i],()=>k(UL(e),([n,i])=>[n,i],()=>k(FL(e),([n,i])=>[n,i],()=>[]))))))),([n,i])=>[Bb(n),i]),UL=(e)=>k(k(Z("(",e),([n,i])=>k(qd(i),([c,p])=>k(Z(")",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[Gb(n),i]),eS=(e)=>k(k(k(Od(e),([n,i])=>k(Z("|",i),([c,p])=>k(eS(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k(k(Od(e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[]))),([n,i])=>[Kb(n),i]),Od=(e)=>k(k(jL(e),([n,i])=>k(qd(i),([c,p])=>[[n,c],p])),([n,i])=>[Hb(n),i]),qd=(e)=>k(k(eS(e),([n,i])=>[n,i],()=>k(Od(e),([n,i])=>[n,i],()=>[])),([n,i])=>[Wb(n),i]),dx=(e)=>k(k(Z("^",e),([n,i])=>k(qd(i),([c,p])=>k(Z("$",p),([g,y])=>[[n,c,g],y]))),([n,i])=>[zb(n),i]),tS=(e,n=[])=>k(k(Z(",",e),([i,c])=>k(vt(c),([p,g])=>[[i,p],g])),([i,c])=>tS(c,[...n,i]),()=>[n,e]),BL=(e)=>k(k(k(vt(e),([n,i])=>k(tS(i),([c,p])=>k(k(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Vb(n),i]),rS=(e)=>k(k(k(Z("extends",e),([n,i])=>k(BL(i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[Jb(n),i]),GL=(e)=>k(k(Z("interface",e),([n,i])=>k(Br(i),([c,p])=>k(_d(p),([g,y])=>k(rS(y),([x,b])=>k(Nd(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[Qb(n),i]),KL=(e)=>k(k(Z("interface",e),([n,i])=>k(Br(i),([c,p])=>k(rS(p),([g,y])=>k(Nd(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[Xb(n),i]),HL=(e)=>k(k(Z("type",e),([n,i])=>k(Br(i),([c,p])=>k(_d(p),([g,y])=>k(Z("=",y),([x,b])=>k(vt(b),([S,T])=>[[n,c,g,x,S],T]))))),([n,i])=>[Yb(n),i]),WL=(e)=>k(k(Z("type",e),([n,i])=>k(Br(i),([c,p])=>k(Z("=",p),([g,y])=>k(vt(y),([x,b])=>[[n,c,g,x],b])))),([n,i])=>[Zb(n),i]),zL=(e)=>k(k(k(Z("export",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[eE(n),i]),nS=(e)=>k(k(k(Z(";",e),([n,i])=>k(Z(`
19
+ `,i),([c,p])=>[[n,c],p])),([n,i])=>[n,i],()=>k(k(Z(";",e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>k(k(Z(`
20
+ `,e),([n,i])=>[[n],i]),([n,i])=>[n,i],()=>[]))),([n,i])=>[tE(n),i]),oS=(e,n=[])=>k(k(nS(e),([i,c])=>k(Fd(c),([p,g])=>[[i,p],g])),([i,c])=>oS(c,[...n,i]),()=>[n,e]),VL=(e)=>k(k(k(Fd(e),([n,i])=>k(oS(i),([c,p])=>k(k(nS(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[n,c,g],y]))),([n,i])=>[n,i],()=>k([[],e],([n,i])=>[n,i],()=>[])),([n,i])=>[rE(n),i]),Fd=(e)=>k(k(zL(e),([n,i])=>k(k(GL(i),([c,p])=>[c,p],()=>k(KL(i),([c,p])=>[c,p],()=>k(HL(i),([c,p])=>[c,p],()=>k(WL(i),([c,p])=>[c,p],()=>[])))),([c,p])=>k(PE(p),([g,y])=>[[n,c,g],y]))),([n,i])=>[nE(n),i]),JL=(e)=>k(k(Fd(e),([n,i])=>k(VL(i),([c,p])=>[[n,c],p])),([n,i])=>[oE(n),i]),sS=(e)=>k(k(JL(e),([n,i])=>[n,i],()=>k(nL(e),([n,i])=>[n,i],()=>k(vt(e),([n,i])=>[n,i],()=>[]))),([n,i])=>[sE(n),i]);function iS(e){let n=Ld(`\`${e}\``);return _(n.length,2)?n[0]:qr()}function XL(e){return e.join("|")}function YL(e){return e.slice(1,e.length-1)}function ZL(e,n,i){return ui(n,`${i}${e}`)}function eN(e,n){return ui(e,`${n}${ix}`)}function tN(e,n){return ui(e,`${n}${ym}`)}function rN(e,n){return ui(e,`${n}${Em}`)}function nN(e,n){return Hu(m([a("false"),a("true")]),e,n)}function oN(e,n){return ui(e,`${n}${Sm}`)}function sN(e,n,i){return ui(n,`${i}${YL(e)}`)}function iN(e,n,i){let c=Wu(e,{});return Hu(c,n,i)}function aN(e,n,i){let c=Yn(e);return Hu(c,n,i)}function aS(e,n,i,c=[]){return It(e,(p,g)=>aS(g,n,i,[...c,Hu(p,[],"")]),()=>ui(n,`${i}(${XL(c)})`))}function Hu(e,n,i){return rn(e)?aN(e.enum,n,i):ln(e)?tN(n,i):yt(e)?ZL(e.const,n,i):uo(e)?eN(n,i):Wn(e)?nN(n,i):kr(e)?rN(n,i):nn(e)?oN(n,i):ur(e)?sN(e.pattern,n,i):cS(e)?iN(e.parameters[0],n,i):xe(e)?aS(e.anyOf,n,i):_y}function ui(e,n){return It(e,(i,c)=>Hu(i,c,n),()=>n)}function uN(e){return`^${ui(e,"")}$`}function uS(e){let n=uN(e);return Tm(n)}function Wu(e,n){return ct(e)?St(uS(e),{},n):vm(e,n)}function mS(e,n,i,c){let p=ho(e,n,i);return Wu(p,c)}function vm(e,n={}){return Ne("TemplateLiteral",[e],n)}function cS(e){return Pr(e)&&le(e,"action")&&_(e.action,"TemplateLiteral")}function pS(e){return Wu(e,{})}function cN(e){let n=iS(e);return pS(n)}function lS(e,n={}){let i=gt(e)?cN(e):pS(e);return St(i,{},n)}function ur(e){return ve(e,"TemplateLiteral")}function jd(e){return Mt({["~kind"]:"ExtendsUnion"},{inferred:e})}function Ud(e){return at(e)&&le(e,"~kind")&&le(e,"inferred")&&_(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function Ae(e){return Mt({["~kind"]:"ExtendsTrue"},{inferred:e})}function Bd(e){return at(e)&&le(e,"~kind")&&le(e,"inferred")&&_(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ze(){return Mt({["~kind"]:"ExtendsFalse"},{})}function Gd(e){return at(e)&&le(e,"~kind")&&_(e["~kind"],"ExtendsFalse")}function no(e){return Ud(e)||Bd(e)}function br(e,n,i){return no(e)?n(e.inferred):i()}function mN(e,n,i,c){return br(kt(e,i,c),(p)=>Ae(pn(pn(e,p),{[n]:i})),()=>Ze())}function pN(e,n){return Ae(e)}function lN(e,n,i,c,p){return br(kt(e,n,i),(g)=>br(kt(g,n,c),(y)=>Ae(y),()=>Ze()),()=>br(kt(e,n,p),(g)=>Ae(g),()=>Ze()))}function dN(e,n,i){let c=Yn(i);return kt(e,n,c)}function dS(e,n,i){return It(i,(c,p)=>br(kt(e,n,c),(g)=>dS(g,n,p),()=>Ze()),()=>Ae(e))}function fN(e,n,i){let c=$n(i);return kt(e,n,c)}function fS(e,n,i){return It(i,(c,p)=>br(kt(e,n,c),(g)=>Ae(g),()=>fS(e,n,p)),()=>Ze())}function Dt(e,n,i){return Mr(i)?pN(e,n):Dr(i)?lN(e,n,i.if,i.then,i.else):rn(i)?dN(e,n,i.enum):tn(i)?mN(e,i.name,n,i.extends):He(i)?dS(e,n,i.allOf):ur(i)?fN(e,n,i.pattern):xe(i)?fS(e,n,i.anyOf):en(i)?Ae(e):Ze()}function hS(e,n,i){return tn(i)?Dt(e,n,i):Mr(i)?Ae(e):en(i)?Ae(e):jd(e)}function hN(e,n){let i=Zi(e),c=Zi(n);return i&&c?!0:!i&&c?!0:i&&!c?!1:!0}function gS(e,n,i,c){return wt(c)?hN(n,c)?kt(e,i,c.items):Ze():Dt(e,n,c)}function yS(e,n,i){return uo(i)?Ae(e):Dt(e,n,i)}function xS(e,n,i){return Wn(i)?Ae(e):Dt(e,n,i)}function gN(e,n,i,c,p){let g=tn(c)?n:c,y=tn(c)?c:n,x=an(n),b=an(c);return!x&&b?Ze():br(kt(e,g,y),(S)=>zu(S,i,p),()=>Ze())}function yN(e,n,i,c){return It(c,(p,g)=>gN(e,n,i,p,g),()=>an(n)?Ae(e):Ze())}function xN(e,n,i){return It(n,(c,p)=>yN(e,c,p,i),()=>Ae(e))}function zu(e,n,i){return xN(e,n,i)}function ip(e,n,i){return co(i)?Ae(e):kt(e,n,i)}function IS(e,n,i,c){return Mr(c)?Ae(e):en(c)?Ae(e):Yr(c)?br(zu(e,n,c.parameters),(p)=>ip(p,i,c.instanceType),()=>Ze()):Ze()}function bS(e,n,i,c,p){return br(kt(e,n,p),()=>kt(e,i,p),()=>kt(e,c,p))}function ES(e,n,i){let c=Yn(n);return kt(e,c,i)}function SS(e,n,i,c){return Mr(c)?Ae(e):en(c)?Ae(e):Zr(c)?br(zu(e,n,c.parameters),(p)=>ip(p,i,c.returnType),()=>Ze()):Ze()}function wS(e,n,i){return ln(i)?Ae(e):kr(i)?Ae(e):Dt(e,n,i)}function TS(e,n,i){let c=Ar(n);return kt(e,c,i)}function ap(e,n,i){return n===i?Ae(e):Ze()}function IN(e,n,i){return yt(i)?ap(e,n,i.const):uo(i)?Ae(e):Dt(e,a(n),i)}function bN(e,n,i){return yt(i)?ap(e,n,i.const):Wn(i)?Ae(e):Dt(e,a(n),i)}function EN(e,n,i){return yt(i)?ap(e,n,i.const):kr(i)?Ae(e):Dt(e,a(n),i)}function SN(e,n,i){return yt(i)?ap(e,n,i.const):nn(i)?Ae(e):Dt(e,a(n),i)}function RS(e,n,i){return Nr(n.const)?IN(e,n.const,i):cn(n.const)?bN(e,n.const,i):_t(n.const)?EN(e,n.const,i):gt(n.const)?SN(e,n.const,i):qr()}function kS(e,n,i){return tn(i)?Dt(e,n,i):Ae(e)}function AS(e,n,i){return bs(i)?Ae(e):Dt(e,n,i)}function CS(e,n,i){return kr(i)?Ae(e):Dt(e,n,i)}function wN(e,n,i){return an(n)?an(i)?Ae(e):Ze():Ae(e)}function TN(e,n,i){return tn(i)&&ao(i.extends)?Ze():br(kt(e,n,i),(c)=>wN(c,n,i),()=>Ze())}function RN(e,n){return e.reduce((i,c)=>(c in n)?no(n[c])?{...i,...n[c].inferred}:qr():qr(),{})}function kN(e,n,i){let c={};for(let y of Se(i))c[y]=y in n?TN({},n[y],i[y]):an(i[y])?tn(i[y])?Ae(pn(e,{[i[y].name]:i[y].extends})):Ae(e):Ze();let p=pd(c).every((y)=>no(y)),g=p?RN(Se(c),c):{};return p?Ae(g):Ze()}function AN(e,n,i){let c=kN(e,n,i);return no(c)?Ae(pn(e,c.inferred)):Ze()}function CN(e,n,i){return AN(e,n,i)}function PN(e,n){return Se(n).reduce((i,c)=>({...i,[c]:le(e,c)?xe(i[c])?m([...i[c].anyOf,n[c]]):m([e[c],n[c]]):n[c]}),e)}function PS(e,n,i,c){return It(n,(p,g)=>br(kt({},e[p],i),(y)=>PS(e,g,i,PN(c,y)),()=>Ze()),()=>Ae(c))}function $N(e,n,i,c){let p=Se(n);return PS(n,p,c,e)}function $S(e,n,i){return Gt(i)?$N(e,n,dn(i),fr(i)):Qe(i)?CN(e,n,i.properties):Dt(e,s(n),i)}function MN(e,n){return _(Se(n).length,0)?Ae(e):Ze()}function vN(e,n,i,c,p){return kt(e,i,p)}function MS(e,n,i,c){return Gt(c)?vN(e,Cm(n),i,Cm(dn(c)),fr(c)):Qe(c)?MN(e,c.properties):Mr(c)?Ae(e):en(c)?Ae(e):Ze()}function vS(e,n,i){return nn(i)?Ae(e):Dt(e,n,i)}function OS(e,n,i){return Es(i)?Ae(e):Dt(e,n,i)}function _S(e,n,i){let c=$n(n);return kt(e,c,i)}function Kd(e,n){return Mt({"~kind":"Inferrable"},{name:e,type:n},{})}function Vu(e){return at(e)&&le(e,"~kind")&&le(e,"name")&&le(e,"type")&&_(e["~kind"],"Inferrable")&&gt(e.name)&&at(e.type)}function Hd(e){return si(e)?tn(e.items)?wt(e.items.extends)?Kd(e.items.name,e.items.extends.items):en(e.items.extends)?Kd(e.items.name,e.items.extends):void 0:qr():void 0}function up(e){return tn(e)?Kd(e.name,e.extends):void 0}function Wd(e,n,i=[]){return It(e,(c,p)=>br(kt({},c,n),()=>Wd(p,n,[...i,c]),()=>{return}),()=>i)}function LS(e,n,i,c){let p=Wd(i,c);return Be(p)?Ae(pn(e,{[n]:Ur(p)})):Ze()}function cp(e,n,i,c){let p=Wd(i,c);return Be(p)?Ae(pn(e,{[n]:m(p)})):Ze()}function ON(e){return[...e].reverse()}function zd(e,n){return n?ON(e):e}function _N(e){let n=e.length>0?e[0]:void 0,i=Pr(n)?Hd(n):void 0;return Pr(i)}function LN(e,n,i,c,p,g){return br(kt(e,i,p),(y)=>NS(y,n,c,g),()=>Ze())}function NN(e,n,i,c,p){let g=Hd(c);return Vu(g)?LS(e,g.name,zd(i,n),g.type):It(i,(y,x)=>LN(e,n,y,x,c,p),()=>Ze())}function DN(e,n,i,c){return It(c,(p,g)=>NN(e,n,i,p,g),()=>_(i.length,0)?Ae(e):Ze())}function NS(e,n,i,c){return DN(e,n,i,c)}function qN(e,n,i){let c=ci(e,hr([],[]),i),p=_N(c);return NS(e,p,zd(n,p),zd(c,p))}function DS(e,n,i){let c=up(i);return Vu(c)?cp(e,c.name,n,c.type):It(n,(p,g)=>br(kt(e,p,i),(y)=>DS(y,g,i),()=>Ze()),()=>Ae(e))}function qS(e,n,i){let c=ci(e,hr([],[]),n);return lt(i)?qN(e,c,i.items):wt(i)?DS(e,c,i.items):Dt(e,Ur(c),i)}function FS(e,n,i){return co(i)?Ae(e):es(i)?Ae(e):Dt(e,n,i)}function jS(e,n,i){return It(i,(c,p)=>br(kt(e,n,c),(g)=>Ae(g),()=>jS(e,n,p)),()=>Ze())}function Vd(e,n,i){return It(n,(c,p)=>br(jS(e,c,i),(g)=>Vd(g,p,i),()=>Ze()),()=>Ae(e))}function US(e,n,i){let c=up(i);return Vu(c)?cp(e,c.name,n,c.type):xe(i)?Vd(e,n,i.anyOf):Vd(e,n,[i])}function BS(e,n,i){return tn(i)?Dt(e,n,i):Mr(i)?Ae(e):en(i)?Ae(e):Ze()}function GS(e,n,i){return co(i)?Ae(e):Dt(e,n,i)}function kt(e,n,i){return Mr(n)?hS(e,n,i):wt(n)?gS(e,n,n.items,i):uo(n)?yS(e,n,i):Wn(n)?xS(e,n,i):Yr(n)?IS(e,n.parameters,n.instanceType,i):Dr(n)?bS(e,n.if,n.then,n.else,i):rn(n)?ES(e,n.enum,i):Zr(n)?SS(e,n.parameters,n.returnType,i):ln(n)?wS(e,n,i):He(n)?TS(e,n.allOf,i):yt(n)?RS(e,n,i):ao(n)?kS(e,n,i):bs(n)?AS(e,n,i):kr(n)?CS(e,n,i):Qe(n)?$S(e,n.properties,i):Gt(n)?MS(e,dn(n),fr(n),i):nn(n)?vS(e,n,i):Es(n)?OS(e,n,i):ur(n)?_S(e,n.pattern,i):lt(n)?qS(e,n.items,i):es(n)?FS(e,n,i):xe(n)?US(e,n.anyOf,i):en(n)?BS(e,n,i):co(n)?GS(e,n,i):Ze()}function FN(e,n){return Ar([...e,s(n)])}function Jd(e,n,i){return ct(e)?St(FN(e,n),{},i):ju(e,n,i)}function KS(e,n,i,c,p){let g=ho(e,n,i),y=Ju(e,n,c);return Jd(g,y,p)}function ju(e,n,i={}){return Ne("Interface",[e,n],i)}function qa(e){return Pr(e)&&le(e,"action")&&_(e.action,"Interface")}function HS(e,n,i={}){return Jd(e,n,i)}function jN(e,n,i){return e.includes(i)?!0:Qu([...e,i],n,n[i])}function WS(e,n,i){let c=pm(i);return ia(e,n,c)}function ia(e,n,i){return It(i,(c,p)=>Qu(e,n,c)?!0:ia(e,n,p),()=>!1)}function Qu(e,n,i){return jt(i)?jN(e,n,i.$ref):wt(i)?Qu(e,n,i.items):Yr(i)?ia(e,n,[...i.parameters,i.instanceType]):Zr(i)?ia(e,n,[...i.parameters,i.returnType]):qa(i)?WS(e,n,i.parameters[1]):He(i)?ia(e,n,i.allOf):Qe(i)?WS(e,n,i.properties):xe(i)?ia(e,n,i.anyOf):lt(i)?ia(e,n,i.items):Gt(i)?Qu(e,n,fr(i)):!1}function zS(e,n,i){return Qu(e,n,i)}function UN(e,n){return n.reduce((i,c)=>zS([c],e,e[c])?[...i,c]:i,[])}function VS(e){let n=mm(e);return UN(e,n)}function BN(e,n,i){return i.includes(n)?i:(n in e)?Xu(e,e[n],[...i,n]):qr()}function JS(e,n,i){let c=pm(n);return Fa(e,c,i)}function Fa(e,n,i){return n.reduce((c,p)=>Xu(e,p,c),i)}function Xu(e,n,i){return jt(n)?BN(e,n.$ref,i):wt(n)?Xu(e,n.items,i):Yr(n)?Fa(e,[...n.parameters,n.instanceType],i):Zr(n)?Fa(e,[...n.parameters,n.returnType],i):qa(n)?JS(e,n.parameters[1],i):He(n)?Fa(e,n.allOf,i):Qe(n)?JS(e,n.properties,i):xe(n)?Fa(e,n.anyOf,i):lt(n)?Fa(e,n.items,i):Gt(n)?Xu(e,fr(n),i):i}function QS(e,n,i){return Xu(e,i,[n])}function GN(e){return Ca()}function KN(e){return Se(e).reduce((n,i)=>({...n,[i]:aa(e[i])}),{})}function Yu(e){return e.reduce((n,i)=>[...n,aa(i)],[])}function aa(e){return jt(e)?GN(e.$ref):wt(e)?B(aa(e.items),ka(e)):Yr(e)?hs(Yu(e.parameters),aa(e.instanceType)):Zr(e)?gs(Yu(e.parameters),aa(e.returnType)):He(e)?Cn(Yu(e.allOf)):Qe(e)?s(KN(e.properties)):Gt(e)?Ss(oi(e),aa(fr(e))):xe(e)?m(Yu(e.anyOf)):lt(e)?Ur(Yu(e.items)):e}function HN(e,n){return n in e?aa(e[n]):Rr()}function XS(e){return HN(e.$defs,e.$ref)}function WN(e,n,i){let c=ho(e,hr([],[]),n),p=Ju({},hr([],[]),i);return Ar([...c,s(p)])}function zN(e,n){return Se(e).filter((c)=>n.includes(c)).reduce((c,p)=>{let g=e[p],y=qa(g)?WN(e,g.parameters[0],g.parameters[1]):g;return{...c,[p]:y}},{})}function YS(e,n,i){let c=QS(e,n,i),p=zN(e,c);return xs(p,n)}function ZS(e,n){return n in e?jt(e[n])?ZS(e,e[n].$ref):e[n]:zt()}function ws(e,n){return ZS(e,n)}function ew(e){return Qt(e)?XS(e):lm(e)?Rr():e}function wn(e,n,i){let c=ew(n),p=ew(i);return kt(e,c,p)}var Lu=0,Zu=1,Nu=2,Du=3;function va(e,n){let i=[wn({},e,n),wn({},n,e)];return no(i[0])&&no(i[1])?Lu:no(i[0])&&Gd(i[1])?Nu:Gd(i[0])&&no(i[1])?Du:Zu}function Qd(e,n,i=[],c=n){return It(n,(p,g)=>{let y=va(e,p);return _(y,Nu)||_(y,Lu)?c:_(y,Zu)?Qd(e,g,[...i,p],c):Qd(e,g,i,c)},()=>[...i,e])}function VN(e,n,i){let c=To(e);return Mr(c)?[c]:en(c)?[c]:ao(c)?mp(n,i):Qe(c)?mp(n,[...i,c]):mp(n,Qd(c,i))}function mp(e,n=[]){return It(e,(i,c)=>VN(i,c,n),()=>n)}function Td(e){let n=mp(e);return na(n)}function Xd(e,n){return St(To(e),{},n)}function tw(e,n,i,c){let p=de(e,n,i);return Xd(p,c)}function ec(e,n=[]){return Ys(e)&&_(e.action,"Conditional")?jt(e.parameters[0])?ec(e.parameters[2],ec(e.parameters[3],[...n,e.parameters[0].$ref])):ec(e.parameters[2],ec(e.parameters[3],n)):Ys(e)&&_(e.action,"Mapped")?Ys(e.parameters[1])&&_(e.parameters[1].action,"KeyOf")&&jt(e.parameters[1].parameters[0])?[...n,e.parameters[1].parameters[0].$ref]:n:n}function JN(e,n){return e.reduce((i,c)=>[...i,n.includes(c.name)],[])}function ow(e,n,i=[]){return It(e,(c,p)=>It(n,(g,y)=>ow(p,y,[...i,[g,c]]),()=>i),()=>i)}function QN(e){return ur(e)?$n(e.pattern):rn(e)?Yn(e.enum):e}function XN(e){let n=QN(e);return xe(n)?[...n.anyOf]:[n]}function YN(e,n){return e.reduce((i,c)=>[...i,[...c,n]],[])}function rw(e,n){return n.reduce((i,c)=>[...i,...YN(e,c)],[])}function nw(e){return e.reduce((n,i)=>_(i[0],!0)?rw(n,XN(i[1])):rw(n,[i[1]]),[[]])}function sw(e,n,i){let c=ec(i),p=JN(e,c),g=ow(n,p);return Ys(i)&&_(i.action,"Conditional")?nw(g):Ys(i)&&_(i.action,"Mapped")?nw(g):[n]}function ZN(){return["(not-resolvable)",zt()]}function eD(){return["(not-generic)",zt()]}function tD(e,n,i){return[e,Zs(n,i)]}function rD(e,n,i){return n in e?iw(e,n,e[n],i):ZN()}function iw(e,n,i,c){return Aa(i)?tD(n,i.parameters,i.expression):jt(i)?rD(e,i.$ref,c):eD()}function aw(e,n,i){return iw(e,"(anonymous)",n,i)}function nD(e,n,i){if(tn(n)||ja(n)||no(wn({},n,i)))return;let c={parameter:e,expect:i,actual:n};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:c})}function uw(e,n,i,c,p){let g=de(e,n,p);return nD(i,g,c),pn(e,{[i]:g})}function oD(e,n,i,c,p){let g=de(e,n,i.extends),y=de(e,n,i.equals);return It(p,(x,b)=>Yd(uw(e,n,i.name,g,x),n,c,b),()=>Yd(uw(e,n,i.name,g,y),n,c,[]))}function Yd(e,n,i,c){return It(i,(p,g)=>oD(e,n,p,g,c),()=>e)}function cw(e,n,i,c){return Yd(e,n,i,c)}var Zd=0,ef=0;function sD(){if(Tu(ef,Qo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function iD(){sD(),ef++,Zd++}function aD(){if(Zd--,_(Zd,0))ef=0}function uD(e){return Ki(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function cD(e,n){return _(uD(e),n)}function mD(e,n,i,c,p,g){iD();try{let y=cw(e,n,c,g),x=de(y,hr([...n.callstack,i.$ref],n.visited),p);return de(y,hr([],[]),x)}finally{aD()}}function pD(e,n,i,c,p,g){return g.reduce((y,x)=>{let b=mD(e,n,i,c,p,x);return[...y,b]},[])}function lD(e,n,i,c,p,g){let y=sw(c,g,p),x=pD(e,n,i,c,p,y);return _(x.length,1)?x[0]:ro(x)}function pp(e,n,i,c){let p=ho(e,n,c),g=aw(e,i,c),y=g[0],x=g[1];return Aa(x)?cD(n,y)?Uu(sn(y),p):lD(e,n,sn(y),x.parameters,x.expression,p):Uu(i,p)}function Uu(e,n){return Mt({["~kind"]:"Call"},{type:"call",target:e,arguments:n},{})}function mw(e,n){return pp({},hr([],[]),e,n)}function ja(e){return ve(e,"Call")}function dD(e){return Xo(e,["~immutable"])}function pw(e,n){return St(dD(e),{},n)}function lw(e,n,i,c){let p=de(e,n,i);return pw(p,c)}function dw(e,n){return e(n)}function fw(e,n){return gt(n)?a(dw(e,n)):a(n)}function hw(e,n){let i=$n(n);return Ns(e,i)}function gw(e,n){let i=n.map((c)=>Ns(e,c));return m(i)}function Ns(e,n){return yt(n)?fw(e,n.const):ur(n)?hw(e,n.pattern):xe(n)?gw(e,n.anyOf):n}function Om(e,n={}){return Ne("Capitalize",[e],n)}function yw(e,n={}){return tf(e,n)}function _m(e,n={}){return Ne("Lowercase",[e],n)}function xw(e,n={}){return rf(e,n)}function Lm(e,n={}){return Ne("Uncapitalize",[e],n)}function Iw(e,n={}){return nf(e,n)}function Nm(e,n={}){return Ne("Uppercase",[e],n)}function bw(e,n={}){return of(e,n)}var fD=(e)=>e[0].toUpperCase()+e.slice(1),hD=(e)=>e.toLowerCase(),gD=(e)=>e[0].toLowerCase()+e.slice(1),yD=(e)=>e.toUpperCase();function tf(e,n){return ct([e])?St(Ns(fD,e),{},n):Om(e,n)}function rf(e,n){return ct([e])?St(Ns(hD,e),{},n):_m(e,n)}function nf(e,n){return ct([e])?St(Ns(gD,e),{},n):Lm(e,n)}function of(e,n){return ct([e])?St(Ns(yD,e),{},n):Nm(e,n)}function Ew(e,n,i,c){let p=de(e,n,i);return tf(p,c)}function Sw(e,n,i,c){let p=de(e,n,i);return rf(p,c)}function ww(e,n,i,c){let p=de(e,n,i);return nf(p,c)}function Tw(e,n,i,c){let p=de(e,n,i);return of(p,c)}function Dm(e,n,i,c,p={}){return Ne("Conditional",[e,n,i,c],p)}function Rw(e,n,i,c,p={}){return sf({},hr([],[]),e,n,i,c,p)}function xD(e,n,i,c,p,g){let y=wn(e,i,c);return Ud(y)?m([de(y.inferred,n,p),de(e,n,g)]):Bd(y)?de(y.inferred,n,p):de(e,n,g)}function sf(e,n,i,c,p,g,y){return ct([i,c])?St(xD(e,n,i,c,p,g),{},y):Dm(i,c,p,g,y)}function kw(e,n,i,c,p,g,y){let x=de(e,n,i),b=de(e,n,c);return sf(e,n,x,b,p,g,y)}function qm(e,n={}){return Ne("ConstructorParameters",[e],n)}function Aw(e,n={}){return af(e,n)}function ID(e){let n=Yr(e)?e.parameters:[],i=ci({},hr([],[]),n);return Ur(i)}function af(e,n){return ct([e])?St(ID(e),{},n):qm(e,n)}function Cw(e,n,i,c){let p=de(e,n,i);return af(p,c)}function Fm(e,n,i={}){return Ne("Exclude",[e,n],i)}function Pw(e,n,i={}){return tc(e,n,i)}function tc(e,n,i){return ct([e,n])?St(km(e,n),{},i):Fm(e,n,i)}function $w(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return tc(g,y,p)}function jm(e,n,i={}){return Ne("Extract",[e,n],i)}function Mw(e,n,i={}){return uf(e,n,i)}function bD(e,n){let i=wn({},e,n);return no(i)?[e]:[]}function vw(e,n,i=[]){return It(e,(c,p)=>vw(p,n,[...i,...bD(c,n)]),()=>i)}function Ow(e,n){let i=To(e),c=xe(i)?i.anyOf:[i],p=vw(c,n);return ro(p)}function uf(e,n,i){return ct([e,n])?St(Ow(e,n),{},i):jm(e,n,i)}function _w(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return uf(g,y,p)}function ED(e){return e.reduce((n,i)=>xm(i)?[...n,a(i)]:n,[])}function Ua(e){let n=ED(e);return m(n)}function Bu(e,n,i={}){return Ne("Index",[e,n],i)}function Lw(e,n,i={}){let c=Be(n)?Ua(n):n;return cf(e,c,i)}function Nw(e,n){let i=ws(e,n);return go(i)}function Dw(e,n,i){let c=Zo(e,n,i);return go(c)}function SD(e,n){let i=Se(e).filter((T)=>!le(n,T)),c=Se(n).filter((T)=>!le(e,T)),p=Se(e).filter((T)=>le(n,T)),g=i.reduce((T,A)=>({...T,[A]:e[A]}),{}),y=c.reduce((T,A)=>({...T,[A]:n[A]}),{}),x=p.reduce((T,A)=>({...T,[A]:Ar([e[A],n[A]])}),{}),b=pn(g,y);return pn(b,x)}function qw(e){return e.reduce((n,i)=>SD(n,go(i)),{})}function Fw(e){return e}function jw(e){let n=Cx(Ur(e));return go(n)}function wD(e,n){return Se(e).filter((p)=>(p in n)).reduce((p,g)=>({...p,[g]:ro([e[g],n[g]])}),{})}function Uw(e,n){return It(e,(i,c)=>Uw(c,wD(n,go(i))),()=>n)}function Bw(e){return It(e,(n,i)=>Uw(i,go(n)),()=>qr())}function go(e){return Qt(e)?Nw(e.$defs,e.$ref):Dr(e)?Dw(e.if,e.then,e.else):He(e)?qw(e.allOf):xe(e)?Bw(e.anyOf):lt(e)?jw(e.items):Qe(e)?Fw(e.properties):{}}function Ba(e){let n=go(e);return s(n)}var TD=new RegExp("^(?:0|[1-9][0-9]*)$");function Ga(e){let n=`${e}`;return TD.test(n)?parseInt(n):e}function RD(e){return a(Ga(e))}function Gw(e){return e.map((n)=>Kw(n))}function Kw(e){return He(e)?Cn(Gw(e.allOf)):xe(e)?m(Gw(e.anyOf)):yt(e)?RD(e.const):e}function Hw(e,n){let i=Kw(n),c=wn({},i,Y());return no(c)?e:yt(n)&&_(n.const,"length")?Y():zt()}function Ww(e,n){let i=ws(e,n);return mo(i)}function zw(e,n,i){let c=Zo(e,n,i);return mo(c)}function Vw(e){let n=Yn(e);return mo(n)}function Jw(e){let n=Ar(e);return mo(n)}function Qw(e){return[`${e}`]}function Xw(e){let n=$n(e);return mo(n)}function Yw(e){return e.reduce((n,i)=>[...n,...mo(i)],[])}function mo(e){return Qt(e)?Ww(e.$defs,e.$ref):Dr(e)?zw(e.if,e.then,e.else):rn(e)?Vw(e.enum):He(e)?Jw(e.allOf):yt(e)?Qw(e.const):ur(e)?Xw(e.pattern):xe(e)?Yw(e.anyOf):[]}function Ka(e){return mo(e)}function rc(e,n){return n.map((i)=>nc(e,i))}function nc(e,n){return wt(n)?B(nc(e,n.items)):Yr(n)?hs(rc(e,n.parameters),nc(e,n.instanceType)):Zr(n)?gs(rc(e,n.parameters),nc(e,n.returnType)):lt(n)?Ur(rc(e,n.items)):xe(n)?m(rc(e,n.anyOf)):He(n)?Cn(rc(e,n.allOf)):$m(n)?s(e):n}function Zw(e,n){return nc(e,n)}function kD(e,n){let i=n in e?e[n]:zt();return Zw(e,i)}function eT(e,n){return n.reduce((i,c)=>[...i,kD(e,c)],[])}function AD(e,n){let i=Ka(n),c=eT(e,i);return ro(c)}var CD=new RegExp(ni);function PD(e){return e.filter((i)=>CD.test(i))}function $D(e){let n=mm(e),i=PD(n),c=eT(e,i);return ro(c)}function tT(e,n){return kr(n)?$D(e):AD(e,n)}function MD(e){return a(Ga(e))}function rT(e){return e.map((n)=>mf(n))}function mf(e){return He(e)?Cn(rT(e.allOf)):xe(e)?m(rT(e.anyOf)):yt(e)?MD(e.const):e}function vD(e,n){return e.reduceRight((i,c,p)=>{let g=wn({},a(p),n);return no(g)?[c,...i]:i},[])}function OD(e,n){let i=mf(n),c=vD(e,i);return ti(c)}function _D(e){return ti(e)}function nT(e,n){return yt(n)&&_(n.const,"length")?a(e.length):kr(n)||ln(n)?_D(e):OD(e,n)}function oT(e,n){return wt(e)?Hw(e.items,n):Qe(e)?tT(e.properties,n):lt(e)?nT(e.items,n):zt()}function LD(e){return Qt(e)||Dr(e)||He(e)||xe(e)?Ba(e):e}function cf(e,n,i){return ct([e,n])?St(oT(LD(e),n),{},i):Bu(e,n,i)}function sT(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return cf(g,y,p)}function Um(e,n={}){return Ne("InstanceType",[e],n)}function iT(e,n={}){return pf(e,n)}function ND(e){return Yr(e)?e.instanceType:zt()}function pf(e,n){return ct([e])?St(ND(e),{},n):Um(e,n)}function aT(e,n,i,c={}){let p=de(e,n,i);return pf(p,c)}function Gu(e,n={}){return Ne("KeyOf",[e],n)}function uT(e,n={}){return lf(e,n)}function cT(){return m([Y(),l(),Ma()])}function mT(e){return Y()}function DD(e){return e.reduce((i,c)=>xm(c)?[...i,a(Ga(c))]:qr(),[])}function pT(e){let n=Se(e),i=DD(n);return ti(i)}function lT(e){return oi(e)}function dT(e){let n=e.map((i,c)=>a(c));return ti(n)}function fT(e){return Mr(e)?cT():wt(e)?mT(e.items):Qe(e)?pT(e.properties):Gt(e)?lT(e):lt(e)?dT(e.items):zt()}function qD(e){return Qt(e)||Dr(e)||He(e)||xe(e)?Ba(e):e}function lf(e,n){return ct([e])?St(fT(qD(e)),{},n):Gu(e,n)}function hT(e,n,i,c){let p=de(e,n,i);return lf(p,c)}function Fu(e,n,i,c,p={}){return Ne("Mapped",[e,n,i,c],p)}function gT(e,n,i,c,p={}){return df({},hr([],[]),e,n,i,c,p)}function FD(e){let n=$n(e);return lp(n)}function jD(e){return e.reduce((n,i)=>[...n,...lp(i)],[])}function UD(e){let n=Yn(e);return lp(n)}function BD(e){return _t(e)?[a(`${e}`)]:[a(e)]}function lp(e){return rn(e)?UD(e.enum):yt(e)?BD(e.const):ur(e)?FD(e.pattern):xe(e)?jD(e.anyOf):[e]}function yT(e){return lp(e)}function GD(e){return ur(e)?$n(e.pattern):e}function KD(e,n,i,c,p,g){let y=pn(e,{[i.name]:c}),x=de(y,n,p),b=GD(x),S=de(y,n,g);return Im(b)||bm(b)?{[b.const]:S}:{}}function HD(e,n,i,c,p,g){return c.reduce((y,x)=>[...y,KD(e,n,i,x,p,g)],[])}function WD(e){return e.reduce((n,i)=>[...n,s(i)],[])}function xT(e,n,i,c,p,g){let y=yT(c),x=HD(e,n,i,y,p,g),b=WD(x);return Ar(b)}function df(e,n,i,c,p,g,y){return ct([c])?St(xT(e,n,i,c,p,g),{},y):Fu(i,c,p,g,y)}function IT(e,n,i,c,p,g,y){let x=de(e,n,c);return df(e,n,i,x,p,g,y)}function zD(e,n,i){let c=pn(e,n);return Se(n).filter((g)=>i.includes(g)).reduce((g,y)=>({...g,[y]:YS(c,y,n[y])}),{})}function VD(e,n,i){let c=pn(e,n);return Se(n).filter((g)=>!i.includes(g)).reduce((g,y)=>({...g,[y]:de(c,hr([],[]),n[y])}),{})}function JD(e,n,i){let c=VS(n),p=zD(e,n,c),g=VD(e,n,c),y={...p,...g};return St(y,{},i)}function dp(e,n,i,c){return JD(e,i,c)}function Bm(e,n={}){return Ne("NonNullable",[e],n)}function bT(e,n={}){return ff(e,n)}function QD(e){let n=m([Pn(),_a()]);return tc(e,n,{})}function ff(e,n){return ct([e])?St(QD(e),{},n):Bm(e,n)}function ET(e,n,i,c){let p=de(e,n,i);return ff(p,c)}function Gm(e,n,i={}){return Ne("Omit",[e,n],i)}function ST(e,n,i={}){let c=Be(n)?Ua(n):n;return hf(e,c,i)}function fp(e){let n=Ba(e);return Qe(n)?n.properties:qr()}function XD(e,n){return Se(e).reduce((c,p)=>n.includes(p)?c:{...c,[p]:e[p]},{})}function wT(e,n){let i=fp(e),c=Ka(n),p=XD(i,c);return s(p)}function hf(e,n,i){return ct([e,n])?St(wT(e,n),{},i):Gm(e,n,i)}function TT(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return hf(g,y,p)}function Km(e,n={}){return Ne("Parameters",[e],n)}function RT(e,n={}){return gf(e,n)}function YD(e){let n=Zr(e)?e.parameters:[],i=ci({},hr([],[]),n);return Ur(i)}function gf(e,n){return ct([e])?St(YD(e),{},n):Km(e,n)}function kT(e,n,i,c){let p=de(e,n,i);return gf(p,c)}function Hm(e,n={}){return Ne("Partial",[e],n)}function AT(e,n={}){return yf(e,n)}function CT(e,n){let i=ws(e,n),c=Ts(i);return xs(pn(e,{[n]:c}),n)}function PT(e,n,i){let c=Zo(e,n,i);return Ts(c)}function $T(e){let n=Ar(e);return Ts(n)}function MT(e){let n=e.map((i)=>Ts(i));return m(n)}function vT(e){let n=Se(e).reduce((c,p)=>({...c,[p]:Qi(e[p])}),{});return s(n)}function Ts(e){return Qt(e)?CT(e.$defs,e.$ref):Dr(e)?PT(e.if,e.then,e.else):He(e)?$T(e.allOf):xe(e)?MT(e.anyOf):Qe(e)?vT(e.properties):s({})}function yf(e,n){return ct([e])?St(Ts(e),{},n):Hm(e,n)}function OT(e,n,i,c){let p=de(e,n,i);return yf(p,c)}function Wm(e,n,i={}){return Ne("Pick",[e,n],i)}function _T(e,n,i={}){let c=Be(n)?Ua(n):n;return xf(e,c,i)}function ZD(e,n){return Se(e).reduce((c,p)=>n.includes(p)?pn(c,{[p]:e[p]}):c,{})}function LT(e,n){let i=fp(e),c=Ka(n),p=ZD(i,c);return s(p)}function xf(e,n,i){return ct([e,n])?St(LT(e,n),{},i):Wm(e,n,i)}function NT(e,n,i,c,p){let g=de(e,n,i),y=de(e,n,c);return xf(g,y,p)}function zm(e,n={}){return Ne("ReadonlyObject",[e],n)}function If(e,n={}){return bf(e,n)}var DT=If;function qT(e){return $a(B(e))}function FT(e,n){let i=ws(e,n),c=Rs(i);return xs(pn(e,{[n]:c}),n)}function jT(e,n,i){let c=Zo(e,n,i);return Rs(c)}function UT(e){let n=Ar(e);return Rs(n)}function BT(e){let n=Se(e).reduce((c,p)=>({...c,[p]:ea(e[p])}),{});return s(n)}function GT(e){return $a(Ur(e))}function KT(e){let n=e.map((i)=>Rs(i));return m(n)}function Rs(e){return wt(e)?qT(e.items):Qt(e)?FT(e.$defs,e.$ref):Dr(e)?jT(e.if,e.then,e.else):He(e)?UT(e.allOf):Qe(e)?BT(e.properties):lt(e)?GT(e.items):xe(e)?KT(e.anyOf):e}function bf(e,n){return ct([e])?St(Rs(e),{},n):zm(e)}function HT(e,n,i,c){let p=de(e,n,i);return bf(p,c)}function WT(e,n,i,c){return n.visited.includes(c)?i:(c in e)?de(e,hr(n.callstack,[...n.visited,c]),e[c]):i}function zT(e,n){let i=ws(e,n),c=ks(i);return xs(pn(e,{[n]:c}),n)}function VT(e,n,i){let c=Zo(e,n,i);return ks(c)}function JT(e){let n=Ar(e);return ks(n)}function QT(e){let n=e.map((i)=>ks(i));return m(n)}function XT(e){let n=Se(e).reduce((c,p)=>({...c,[p]:Rm(e[p])}),{});return s(n)}function ks(e){return Qt(e)?zT(e.$defs,e.$ref):Dr(e)?VT(e.if,e.then,e.else):He(e)?JT(e.allOf):xe(e)?QT(e.anyOf):Qe(e)?XT(e.properties):s({})}function Vm(e,n={}){return Ne("Required",[e],n)}function YT(e,n={}){return Ef(e,n)}function Ef(e,n){return ct([e])?St(ks(e),{},n):Vm(e,n)}function ZT(e,n,i,c){let p=de(e,n,i);return Ef(p,c)}function Jm(e,n={}){return Ne("ReturnType",[e],n)}function eR(e,n={}){return Sf(e,n)}function eq(e){return Zr(e)?e.returnType:zt()}function Sf(e,n){return ct([e])?St(eq(e),{},n):Jm(e,n)}function tR(e,n,i,c={}){let p=de(e,n,i);return Sf(p,c)}function Qm(e,n){return Ne("With",[e,n],{})}function hp(e,n){return wf(e,n)}function wf(e,n){return ct([e])?St(e,{},n):Qm(e,n)}function rR(e,n,i,c){let p=de(e,n,i);return wf(p,c)}function tq(e){return si(e)?lt(e.items)?Tf(e.items.items):tn(e.items)?[e]:jt(e.items)?[e]:[zt()]:[e]}function Tf(e){return e.reduce((i,c)=>[...i,...tq(c)],[])}function hr(e,n){return{callstack:e,visited:n}}function ct(e){return It(e,(n,i)=>jt(n)?!1:ct(i),()=>!0)}function Ju(e,n,i){return Se(i).reduce((c,p)=>({...c,[p]:de(e,n,i[p])}),{})}function ci(e,n,i){let c=ho(e,n,i);return Tf(c)}function ho(e,n,i){return i.map((c)=>de(e,n,c))}function rq(e,n){let i=an(e)?Pu(n,{}):n,c=ta(e)?Cu(i,{}):i;return Zi(e)?oc(c,{}):c}function nq(e,n,i,c,p){return _(i,"AddImmutable")?nR(e,n,c[0],p):_(i,"RemoveImmutable")?lw(e,n,c[0],p):_(i,"AddReadonly")?$y(e,n,c[0],p):_(i,"RemoveReadonly")?wx(e,n,c[0],p):_(i,"AddOptional")?My(e,n,c[0],p):_(i,"RemoveOptional")?kx(e,n,c[0],p):_(i,"Capitalize")?Ew(e,n,c[0],p):_(i,"Conditional")?kw(e,n,c[0],c[1],c[2],c[3],p):_(i,"ConstructorParameters")?Cw(e,n,c[0],p):_(i,"Evaluate")?tw(e,n,c[0],p):_(i,"Exclude")?$w(e,n,c[0],c[1],p):_(i,"Extract")?_w(e,n,c[0],c[1],p):_(i,"Index")?sT(e,n,c[0],c[1],p):_(i,"InstanceType")?aT(e,n,c[0],p):_(i,"Interface")?KS(e,n,c[0],c[1],p):_(i,"KeyOf")?hT(e,n,c[0],p):_(i,"Lowercase")?Sw(e,n,c[0],p):_(i,"Mapped")?IT(e,n,c[0],c[1],c[2],c[3],p):_(i,"Module")?dp(e,n,c[0],p):_(i,"NonNullable")?ET(e,n,c[0],p):_(i,"Pick")?NT(e,n,c[0],c[1],p):_(i,"Parameters")?kT(e,n,c[0],p):_(i,"Partial")?OT(e,n,c[0],p):_(i,"Omit")?TT(e,n,c[0],c[1],p):_(i,"ReadonlyObject")?HT(e,n,c[0],p):_(i,"Record")?Gx(e,n,c[0],c[1],p):_(i,"Required")?ZT(e,n,c[0],p):_(i,"ReturnType")?tR(e,n,c[0],p):_(i,"TemplateLiteral")?mS(e,n,c[0],p):_(i,"Uncapitalize")?ww(e,n,c[0],p):_(i,"Uppercase")?Tw(e,n,c[0],p):_(i,"With")?rR(e,n,c[0],c[1]):Ne(i,c,p)}function oq(e,n,i){let c=jt(i)?WT(e,n,i,i.$ref):wt(i)?B(de(e,n,i.items),ka(i)):ja(i)?pp(e,n,i.target,i.arguments):Yr(i)?hs(ho(e,n,i.parameters),de(e,n,i.instanceType),vy(i)):Zr(i)?gs(ho(e,n,i.parameters),de(e,n,i.returnType),Oy(i)):Dr(i)?Xi(de(e,n,i.if),de(e,n,i.then),de(e,n,i.else),Dy(i)):He(i)?Cn(ho(e,n,i.allOf),By(i)):Qe(i)?s(Ju(e,n,i.properties),Ny(i)):Gt(i)?Kx(dn(i),de(e,n,fr(i))):si(i)?oa(de(e,n,i.items)):lt(i)?Ur(ci(e,n,i.items),Sx(i)):xe(i)?m(ho(e,n,i.anyOf),lx(i)):i;return rq(i,c)}function de(e,n,i){return Ys(i)?nq(e,n,i.action,i.parameters,i.options):oq(e,n,i)}function Ao(e,n){return de(e,hr([],[]),n)}function sq(e){return St(e,{"~immutable":!0},{})}function oc(e,n){return St(sq(e),{},n)}function nR(e,n,i,c){let p=de(e,n,i);return oc(p,c)}function iE(e,n={}){return Ne("AddImmutable",[e],n)}function $a(e,n={}){return oc(e,n)}function aE(e,n={}){return Ne("Evaluate",[e],n)}function Tn(e,n={}){return Xd(e,n)}function uE(e,n={}){return Ne("Module",[e],n)}function oR(e,n={}){return dp({},hr([],[]),e,n)}function iq(e,n){let i=va(e,n);return _(i,Du)?1:_(i,Zu)?1:0}function sR(e,n,i=[]){return It(n,(c,p)=>_(iq(e,c),1)?sR(e,p,[...i,c]):[...i,e,...n],()=>[...i,e])}function iR(e,n=[]){return It(e,(i,c)=>iR(c,sR(i,n)),()=>n)}function aR(e){return iR(e)}function uR(...e){let[n,i,c]=Sn(e,{2:(y,x)=>gt(y)?[{},y,x]:[y,x,{}],3:(y,x,b)=>[y,x,b],1:(y)=>[{},y,{}]}),p=sS(i),g=Be(p)&&_(p.length,2)?de(n,hr([],[]),p[0]):zt();return St(g,{},c)}function h(e,n){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let c=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:c}},resolve:async({ctx:i,credential:c,signal:p})=>{if(p.throwIfAborted(),c?.key)return{auth:{apiKey:c.key},env:c.env,source:"stored credential"};for(let g of n){let y=await i.env(g);if(p.throwIfAborted(),y)return{auth:{apiKey:y},source:g}}return}}}function ae(e){let n,i=()=>(n??=e.load(),n);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(c,p)=>(await i()).login(c,p),refresh:async(c,p)=>(await i()).refresh(c,p),toAuth:async(c)=>(await i()).toAuth(c)}}var lR="faux",dR="faux",fR="faux-1",aq="Faux Model",uq="http://localhost:0",cq=3,cR=5,xp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Ln(e){return{type:"text",text:e}}function Io(e){return{type:"thinking",thinking:e}}function mq(e,n,i={}){return{type:"toolCall",id:i.id??Af("tool"),name:e,arguments:n}}function pq(e){if(typeof e==="string")return[Ln(e)];return Array.isArray(e)?e:[e]}function Mo(e,n={}){return{role:"assistant",content:pq(e),api:lR,provider:dR,model:fR,usage:xp,stopReason:n.stopReason??"stop",...n.deferred===void 0?{}:{deferred:n.deferred},...n.errorMessage===void 0?{}:{errorMessage:n.errorMessage},...n.responseId===void 0?{}:{responseId:n.responseId},timestamp:n.timestamp??Date.now()}}function hR(e){return Math.ceil(e.length/4)}function Af(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function gR(e){if(typeof e==="string")return e;return e.map((n)=>{if(n.type==="text")return n.text;return`[image:${n.mimeType}:${n.data.length}]`}).join(`
21
+ `)}function yR(e){return e.map((n)=>{if(n.type==="text")return n.text;if(n.type==="thinking")return n.thinking;return`${n.name}:${JSON.stringify(n.arguments)}`}).join(`
22
+ `)}function lq(e){return[e.toolName,...e.content.map((n)=>gR([n]))].join(`
23
+ `)}function dq(e){if(e.role==="system")return[N(e),...e.toolsRemoved?.map((n)=>`tool-:${JSON.stringify(n)}`)??[],...e.toolsAdded?.map((n)=>`tool+:${JSON.stringify(n)}`)??[]].filter((n)=>n.length>0).join(`
24
+ `);if(e.role==="user")return gR(e.content);if(e.role==="assistant")return yR(e.content);return lq(e)}function xR(e,n=e.length){let i=n>0?(n-1)*2:0;for(let c=0;c<n;c++)i+=e[c].length;return i}function fq(e,n){let i=0;while(i<e.length&&i<n.length&&e[i]===n[i])i++;let c=(p)=>i===p.length?"":(i>0?`
25
+
26
+ `:"")+p.slice(i).join(`
27
+
28
+ `);return xR(e,i)+hq(c(e),c(n))}function hq(e,n){let i=Math.min(e.length,n.length),c=0;while(c<i&&e[c]===n[c])c++;return c}function mR(e,n,i,c){let p=n.messages.map((C)=>`${C.role}:${dq(C)}`),g=xR(p),y=Math.ceil(g/4),x=hR(yR(e.content)),b=y,S=0,T=0,A=i?.sessionId;if(A&&i?.cacheRetention!=="none"){let C=c.get(A);if(C){let P=fq(C,p);S=Math.ceil(P/4),T=Math.ceil((g-P)/4),b=Math.max(0,y-S)}else T=y;c.set(A,p)}return{...e,usage:{input:b,output:x,cacheRead:S,cacheWrite:T,totalTokens:b+x+S+T,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function Rf(e,n,i){let c=[],p=0;while(p<e.length){let g=n+Math.floor(Math.random()*(i-n+1)),y=Math.max(1,g*4);c.push(e.slice(p,p+y)),p+=y}return c.length>0?c:[""]}function gq(e,n,i,c){let p=structuredClone(e);return{...p,api:n,provider:i,model:c,timestamp:p.timestamp??Date.now(),usage:p.usage??xp}}function pR(e,n){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:xp,stopReason:"deferred",deferred:n,timestamp:Date.now()}}function gp(e,n,i,c){return{role:"assistant",content:[],api:n,provider:i,model:c,usage:xp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function sc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function kf(e,n){if(!n||n<=0)return new Promise((c)=>queueMicrotask(c));let i=hR(e)/n*1000;return new Promise((c)=>setTimeout(c,i))}async function yp(e,n,i,c,p,g){let y={...n,content:[],stopReason:"pending"};if(g?.aborted){let x=sc(y);e.push({type:"error",reason:"aborted",error:x}),e.end(x);return}e.push({type:"start",partial:{...y}});for(let x=0;x<n.content.length;x++){if(g?.aborted){let S=sc(y);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}let b=n.content[x];if(b.type==="thinking"){y.content=[...y.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:x,partial:{...y}});for(let S of Rf(b.thinking,i,c)){if(await kf(S,p),g?.aborted){let T=sc(y);e.push({type:"error",reason:"aborted",error:T}),e.end(T);return}y.content[x].thinking+=S,e.push({type:"thinking_delta",contentIndex:x,delta:S,partial:{...y}})}e.push({type:"thinking_end",contentIndex:x,content:b.thinking,partial:{...y}});continue}if(b.type==="text"){y.content=[...y.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:x,partial:{...y}});for(let S of Rf(b.text,i,c)){if(await kf(S,p),g?.aborted){let T=sc(y);e.push({type:"error",reason:"aborted",error:T}),e.end(T);return}y.content[x].text+=S,e.push({type:"text_delta",contentIndex:x,delta:S,partial:{...y}})}e.push({type:"text_end",contentIndex:x,content:b.text,partial:{...y}});continue}y.content=[...y.content,{type:"toolCall",id:b.id,name:b.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:x,partial:{...y}});for(let S of Rf(JSON.stringify(b.arguments),i,c)){if(await kf(S,p),g?.aborted){let T=sc(y);e.push({type:"error",reason:"aborted",error:T}),e.end(T);return}e.push({type:"toolcall_delta",contentIndex:x,delta:S,partial:{...y}})}y.content[x].arguments=b.arguments,e.push({type:"toolcall_end",contentIndex:x,toolCall:b,partial:{...y}})}if(n.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(n.stopReason==="error"||n.stopReason==="aborted"){e.push({type:"error",reason:n.stopReason,error:n}),e.end(n);return}e.push({type:"done",reason:n.stopReason,message:n}),e.end(n)}function IR(e){let n=e.api??Af(lR),i=e.provider??dR,c=Math.max(1,Math.min(e.tokenSize?.min??cq,e.tokenSize?.max??cR)),p=Math.max(c,e.tokenSize?.max??cR),g=[],y=e.tokensPerSecond,x={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},b=new Map,S=new Map,A=((e.models?.length)?e.models:[{id:fR,name:aq,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((V)=>({id:V.id,name:V.name??V.id,api:n,provider:i,baseUrl:uq,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),C=async(V,J,ee,ie)=>{let H=typeof V==="function"?await V(J,ee,x,ie):V;return mR(gq(H,n,i,ie.id),J,ee,b)},P=(V,J,ee)=>{let ie=Xn(),H=g.shift();return x.callCount++,queueMicrotask(async()=>{try{if(await ee?.onResponse?.({status:200,headers:{}},V),!H){let fe=gp(Error("No more faux responses queued"),n,i,V.id);fe=mR(fe,J,ee,b),ie.push({type:"error",reason:"error",error:fe}),ie.end(fe);return}if(ee?.deferred){let fe={provider:V.provider,modelId:V.id,api:V.api,id:Af("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};S.set(fe.id,{handle:fe,step:H,context:J,options:ee,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await yp(ie,pR(V,fe),c,p,y,ee.signal);return}let ce=await C(H,J,ee,V);await yp(ie,ce,c,p,y,ee?.signal)}catch(ce){let fe=gp(ce,n,i,V.id);ie.push({type:"error",reason:"error",error:fe}),ie.end(fe)}}),ie},L=(V,J,ee)=>P(V,J,ee),q=(V,J,ee)=>{let ie=Xn();return x.deferredFetchCount++,queueMicrotask(async()=>{try{await ee?.onResponse?.({status:200,headers:{}},V);let H=S.get(J.id);if(!H||H.handle.provider!==J.provider||H.handle.modelId!==J.modelId||H.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(H.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(H.pendingFetches>0){H.pendingFetches--,await yp(ie,pR(V,H.handle),c,p,y,ee?.signal);return}if(!H.final){let{deferred:ce,signal:fe,onResponse:_e,...be}=H.options??{};try{H.final=await C(H.step,H.context,be,H.model)}catch(se){H.final=gp(se,n,i,H.model.id)}}await yp(ie,H.final,c,p,y,ee?.signal)}catch(H){let ce=gp(H,n,i,V.id);ie.push({type:"error",reason:"error",error:ce}),ie.end(ce)}}),ie},X=async(V,J,ee)=>{x.cancelledDeferred.push(structuredClone(J));let ie=S.get(J.id);if(ie)ie.cancelled=!0;await ee?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return A[0];return A.find((J)=>J.id===V)}return{api:n,provider:i,models:A,stream:P,streamSimple:L,fetchDeferred:q,cancelDeferred:X,getModel:j,state:x,setResponses(V){g=[...V]},appendResponses(V){g.push(...V)},getPendingResponseCount(){return g.length}}}function Lo(e={}){let n=IR(e);return{provider:d({id:n.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:n.models,api:{stream:n.stream,streamSimple:n.streamSimple,fetchDeferred:n.fetchDeferred,cancelDeferred:n.cancelDeferred}}),api:n.api,models:n.models,getModel:n.getModel,state:n.state,setResponses:n.setResponses,appendResponses:n.appendResponses,getPendingResponseCount:n.getPendingResponseCount}}function yq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function xq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Iq(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 bq(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function ic(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Ha(e){ic(e.contentIndex);let n=e.partial.content[e.contentIndex];if(!n)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return n}function Pf(e){let n=JSON.stringify(e);if(n===void 0)throw Error("Tool-call arguments are not JSON-serializable");return n}var Eq=Pf(W(""));function $f(e,n){if(typeof e==="string")return typeof n==="string"&&n.startsWith(e);if(Array.isArray(e))return Array.isArray(n)&&e.length<=n.length&&e.every((c,p)=>$f(c,n[p]));if(typeof e!=="object"||e===null)return Object.is(e,n);if(typeof n!=="object"||n===null||Array.isArray(n))return!1;let i=n;return Object.entries(e).every(([c,p])=>Object.hasOwn(i,c)&&$f(p,i[c]))}class bR{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:bq(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let n=Ha(e);if(n.type!=="text")throw Error(`text_start event points to ${n.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:n.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:yq(n)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let n=Ha(e);if(n.type!=="text")throw Error(`text_end event points to ${n.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...n.textSignature===void 0?{}:{textSignature:n.textSignature}}}case"thinking_start":{let n=Ha(e);if(n.type!=="thinking")throw Error(`thinking_start event points to ${n.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:n.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:xq(n)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let n=Ha(e);if(n.type!=="thinking")throw Error(`thinking_end event points to ${n.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...n.thinkingSignature===void 0?{}:{thinkingSignature:n.thinkingSignature},...n.redacted===void 0?{}:{redacted:n.redacted}}}case"toolcall_start":{let n=Ha(e);if(n.type!=="toolCall")throw Error(`toolcall_start event points to ${n.type} block at index ${e.contentIndex}`);let i=Pf(n.arguments),c=i===Eq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:c,catchupJson:"",snapshotArguments:c?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Iq(n)}}case"toolcall_delta":{let n=this.block(e.contentIndex,"toolCall");if(n.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(n.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};n.catchupJson+=e.delta;let i=W(n.catchupJson);if(Pf(i)!==n.snapshotArguments){let p=W(n.snapshotArguments);if(!$f(p,i))return}n.caughtUp=!0,n.snapshotArguments="";let c=n.catchupJson;return n.catchupJson="",c.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:c}}case"toolcall_end":{let n=Ha(e);if(n.type!=="toolCall")throw Error(`toolcall_end event points to ${n.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,n){if(ic(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,n)}block(e,n){ic(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${n} block ${e} has not started`);if(i.kind!==n)throw Error(`Assistant message block ${e} is ${i.kind}, not ${n}`);return i}endBlock(e,n){this.block(e,n),this.blocks.delete(e)}encodeTextDelta(e,n,i){let c=this.block(e,i);if(c.kind==="toolCall")throw Error("Unreachable text encoder state");let p=c.deltaChars;c.deltaChars+=n.length;let g=Math.max(0,c.coveredChars-p);if(g>=n.length)return;let y=g===0?n:n.slice(g);return i==="text"?{type:"text_delta",contentIndex:e,delta:y}:{type:"thinking_delta",contentIndex:e,delta:y}}}function Cf(e,n,i,c,p){if(ic(i),i!==e.content.length){let g=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${g}`)}e.content.push(structuredClone(c)),n.set(i,p)}function ua(e,n,i,c,p){ic(i);let g=n.get(i),y=e.content[i];if(!g||!y)throw Error(`${p} frame has no started block at index ${i}`);if(g.kind!==c||y.type!==c)throw Error(`${p} frame expected ${c} block at index ${i}, found ${y.type}`);if(g.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:y,state:g}}function Sq(e){let n,i,c=new Map;for(let p of e){if(p.type==="start"){if(n)throw Error("Assistant message frame sequence contains more than one start frame");if(i!==void 0)throw Error(`${i} frame appears before the start frame`);n=structuredClone(p.partial);continue}if(!n){i??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);Cf(n,c,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:g}=ua(n,c,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");g.text+=p.delta;break}case"text_end":{let{block:g,state:y}=ua(n,c,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");if(g.text=p.content,delete g.textSignature,p.textSignature!==void 0)g.textSignature=p.textSignature;y.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);Cf(n,c,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:g}=ua(n,c,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");g.thinking+=p.delta;break}case"thinking_end":{let{block:g,state:y}=ua(n,c,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");if(g.thinking=p.content,delete g.thinkingSignature,delete g.redacted,p.thinkingSignature!==void 0)g.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)g.redacted=p.redacted;y.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);Cf(n,c,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:g,state:y}=ua(n,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");y.json=p.json,g.arguments=W(p.json);break}case"toolcall_delta":{let{block:g,state:y}=ua(n,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call frame state");y.json+=p.delta;break}case"toolcall_end":{let{block:g,state:y}=ua(n,c,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(g.id=p.id,g.name=p.name,g.arguments=structuredClone(p.arguments),delete g.thoughtSignature,delete g.namespace,p.thoughtSignature!==void 0)g.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)g.namespace=p.namespace;y.ended=!0;break}}}if(!n)return;for(let[p,g]of c){if(g.kind!=="toolCall"||g.ended||g.json.length===0)continue;let y=n.content[p];if(y?.type!=="toolCall")throw Error("Unreachable tool-call frame state");y.arguments=W(g.json)}return n}var ER=[/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],wq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,Tq=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function li(e,n){if(e.stopReason==="error"&&e.errorMessage){if(!Tq.some((c)=>c.test(e.errorMessage))){if(ER.some((c)=>c.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&wq.test(e.errorMessage))return!0}}if(n&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>n)return!0}if(n&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=n*0.99)return!0}return!1}function Rq(e,n){return e.stopReason==="length"&&n>0&&e.usage.output<n}function kq(){return[...ER]}function SR(e){return new RegExp(e.join("|"),"i")}var Aq=SR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),Cq=SR(["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"]),wR=60000;function TR(e,n){let i=e.baseDelayMs*2**Math.max(0,n-1),c=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(c,e.maxAgentDelayMs??wR)}class Ip extends Error{constructor(){super("Aborted")}}function Pq(e,n){return new Promise((i,c)=>{if(n?.aborted){c(new Ip);return}let p=setTimeout(i,e);n?.addEventListener("abort",()=>{clearTimeout(p),c(new Ip)},{once:!0})})}async function $q(e,n,i,c){let p=n?.enabled?n.maxRetries:0,g=0,y;for(;;){let x=await e();if(x.stopReason==="aborted"){if(y)await c?.onRetryFinished?.(!1,y.attempt);return x}if(x.stopReason!=="error"){if(y)await c?.onRetryFinished?.(!0,y.attempt);return x}if(g>=p||!RR(x)){if(y)await c?.onRetryFinished?.(!1,y.attempt,x.errorMessage);return x}g++,y={attempt:g,errorMessage:x.errorMessage||"Unknown error"};let b=TR(n,g);await c?.onRetryScheduled?.(g,p,b,y.errorMessage);try{await Pq(b,i)}catch(S){if(await c?.onRetryFinished?.(!1,g,y.errorMessage),S instanceof Ip){let{errorMessage:T,...A}=x;return{...A,stopReason:"aborted"}}throw S}await c?.onRetryAttemptStart?.()}}function RR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let n=e.errorMessage;if(Aq.test(n))return!1;return Cq.test(n)}function Mq(e,n){return Wr({type:"string",enum:e,...n?.description&&{description:n.description},...n?.default&&{default:n.default}})}function ac(e){return le(e,"~refine")&&Be(e["~refine"])&&on(e["~refine"],0,(n)=>at(n)&&le(n,"check")&&le(n,"error")&&ls(n.check)&&ls(n.error))}function fn(e){return at(e)&&!Be(e)}function Ds(e){return cn(e)}function Ye(e){return fn(e)||Ds(e)}function Wa(e){return le(e,"additionalItems")&&Ye(e.additionalItems)}function Po(e){return le(e,"additionalProperties")&&Ye(e.additionalProperties)}function uc(e){return le(e,"allOf")&&Be(e.allOf)&&e.allOf.every((n)=>Ye(n))}function cc(e){return le(e,"$anchor")&&gt(e.$anchor)}function mc(e){return le(e,"anyOf")&&Be(e.anyOf)&&e.anyOf.every((n)=>Ye(n))}function bp(e){return le(e,"const")}function As(e){return le(e,"contains")&&Ye(e.contains)}function yo(e){return le(e,"default")}function pc(e){return le(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((n)=>Ye(n)||Be(n)&&n.every((i)=>gt(i)))}function lc(e){return le(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((n)=>Be(n)&&n.every((i)=>gt(i)))}function za(e){return le(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((n)=>Ye(n))}function qs(e){return le(e,"$dynamicAnchor")&&gt(e.$dynamicAnchor)}function dc(e){return le(e,"$dynamicRef")&&gt(e.$dynamicRef)}function fc(e){return le(e,"else")&&Ye(e.else)}function Ep(e){return le(e,"enum")&&Be(e.enum)}function hc(e){return le(e,"exclusiveMaximum")&&(_t(e.exclusiveMaximum)||Nr(e.exclusiveMaximum))}function ts(e){return le(e,"exclusiveMinimum")&&(_t(e.exclusiveMinimum)||Nr(e.exclusiveMinimum))}function ca(e){return le(e,"format")&&gt(e.format)}function xo(e){return le(e,"$id")&&gt(e.$id)}function gc(e){return le(e,"if")&&Ye(e.if)}function Fs(e){return le(e,"items")&&(Ye(e.items)||Be(e.items)&&e.items.every((n)=>Ye(n)))}function yc(e){return Fs(e)&&Be(e.items)}function xc(e){return le(e,"maximum")&&(_t(e.maximum)||Nr(e.maximum))}function Ic(e){return le(e,"maxContains")&&_t(e.maxContains)}function Va(e){return le(e,"maxItems")&&_t(e.maxItems)}function bc(e){return le(e,"maxLength")&&_t(e.maxLength)}function Ec(e){return le(e,"maxProperties")&&_t(e.maxProperties)}function rs(e){return le(e,"minimum")&&(_t(e.minimum)||Nr(e.minimum))}function js(e){return le(e,"minContains")&&_t(e.minContains)}function Ii(e){return le(e,"minItems")&&_t(e.minItems)}function ma(e){return le(e,"minLength")&&_t(e.minLength)}function pa(e){return le(e,"minProperties")&&_t(e.minProperties)}function Sc(e){return le(e,"multipleOf")&&(_t(e.multipleOf)||Nr(e.multipleOf))}function wc(e){return le(e,"not")&&Ye(e.not)}function Tc(e){return le(e,"oneOf")&&Be(e.oneOf)&&e.oneOf.every((n)=>Ye(n))}function la(e){return le(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function Us(e){return le(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((n)=>Ye(n))}function ns(e){return le(e,"prefixItems")&&Be(e.prefixItems)&&e.prefixItems.every((n)=>Ye(n))}function Bs(e){return le(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((n)=>Ye(n))}function Ja(e){return le(e,"propertyNames")&&(at(e.propertyNames)||Ye(e.propertyNames))}function vq(e){return le(e,"$recursiveAnchor")&&cn(e.$recursiveAnchor)}function Rc(e){return vq(e)&&_(e.$recursiveAnchor,!0)}function kc(e){return le(e,"$recursiveRef")&&gt(e.$recursiveRef)}function Ac(e){return le(e,"$ref")&&gt(e.$ref)}function os(e){return le(e,"required")&&Be(e.required)&&e.required.every((n)=>gt(n))}function Cc(e){return le(e,"then")&&Ye(e.then)}function Pc(e){return le(e,"type")&&(gt(e.type)||Be(e.type)&&e.type.every((n)=>gt(n)))}function Ai(e){return le(e,"uniqueItems")&&cn(e.uniqueItems)}function $i(e){return le(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function Mi(e){return le(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function Oq(e){return $i(e)||Mi(e)||wa(Se(e),(n)=>Sp(e[n]))}function _q(e){return wa(e,(n)=>Sp(n))}function Sp(e){return Be(e)?_q(e):at(e)?Oq(e):!1}function kR(e,n){return Sp(n)||wa(Se(e),(i)=>Sp(e[i]))}class Mf{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,n=new Set;this.stack=[{indices:e,keys:n}]}Push(){let e=new Set,n=new Set;return this.stack.push({indices:e,keys:n}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let n of e)n.GetIndices().forEach((i)=>this.GetIndices().add(i)),n.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class Dn extends _n{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Qo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var wp={identifier:"External",variables:[]};function vo(e){let n=`External[${wp.variables.length}]`;return wp.variables.push(e),n}function AR(){wp.variables=[]}function CR(){return{...wp}}function PR(e,n,i,c){let p=vo(i["~refine"].map((g)=>g));return fs(p,De(0),["refinement","_"],Ir(bt("refinement","check"),[c]))}function $R(e,n,i,c){return on(i["~refine"],0,(p,g)=>p.check(c))}function MR(e,n,i,c,p,g){return kn(p["~refine"],0,(y,x)=>y.check(g)||n.AddError({keyword:"~refine",schemaPath:i,instancePath:c,params:{index:x,message:y.error(g)}}))}var Lq=0;function Vt(){return`var_${Lq++}`}function vf(e){return Fs(e)&&Be(e.items)}function Nq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Zn(e,n,i.additionalItems,p),x=dd(g,De(i.items.length)),b=n.AddIndex(g);return fs(c,De(0),[p,g],xr(x,En(y,b)))}function Dq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Zn(e,n,i.additionalItems,p),x=dd(g,De(i.items.length));return fs(c,De(0),[p,g],xr(x,y))}function vR(e,n,i,c){if(!vf(i))return De(!0);return n.UseUnevaluated()?Nq(e,n,i,c):Dq(e,n,i,c)}function OR(e,n,i,c){if(!vf(i))return!0;return on(c,0,(g,y)=>Tu(y,i.items.length)||bo(e,n,i.additionalItems,g)&&n.AddIndex(y))}function _R(e,n,i,c,p,g){if(!vf(p))return!0;return on(g,0,(x,b)=>{let S=`${i}/additionalItems`,T=`${c}/${b}`;return Tu(b,p.items.length)||Eo(e,n,S,T,p.additionalItems,x)&&n.AddIndex(b)})}function ss(e){return new RegExp(e,"u")}function qq(e,n){return!e.UseUnevaluated()&&(_(n,!0)||at(n)&&_(Se(n).length,0))}function Fq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Of(e){let n=[];if(Us(e))n.push(...Se(e.patternProperties));if(Bs(e))n.push(...Se(e.properties).map(Fq));return _(n.length,0)?"(?!)":`(${n.join("|")})`}function jq(e,n,i){return os(n)&&Bs(n)&&!Us(n)&&_(n.additionalProperties,!1)&&_(Se(n.properties).length,n.required.length)}function Uq(e,n,i){return io(bt(Ir(bt("Object","getOwnPropertyNames"),[i]),"length"),De(n.required.length))}function Bq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=vo(ss(Of(i))),x=Zn(e,n,i.additionalProperties,`${c}[${p}]`),b=Ir(bt(y,"test"),[p]),S=n.AddKey(p),T=n.UseUnevaluated()?xr(b,En(x,S)):xr(b,x);return fs(zi(c),De(0),[p,g],T)}function LR(e,n,i,c){if(qq(n,i.additionalProperties))return De(!0);return jq(n,i,c)?Uq(n,i,c):Bq(e,n,i,c)}function NR(e,n,i,c){let p=ss(Of(i));return on(Se(c),0,(y,x)=>p.test(y)||bo(e,n,i.additionalProperties,c[y])&&n.AddKey(y))}function DR(e,n,i,c,p,g){let y=ss(Of(p)),x=[];return kn(Se(g),0,(S,T)=>{let A=`${i}/additionalProperties`,C=`${c}/${S}`,P=y.test(S)||Eo(e,n,A,C,p.additionalProperties,g[S])&&n.AddKey(S);if(!P)x.push(S);return P})||n.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:c,params:{additionalProperties:x}})}function Oi(e,n,i,c,p){let g=_s("results","[]"),y=i.map((T,A)=>_s(`context_${A}`,fd("CheckContext",[]))),x=i.map((T,A)=>_s(`condition_${A}`,Ir(Qs(["context"],Nt(e,n,T,c)),[`context_${A}`]))),b=i.map((T,A)=>ky(`condition_${A}`,Ir(bt("results","push"),[`context_${A}`]))),S=cm(En(p,n.Merge("results")));return Ir(Qs([],um([g,...y,...x,...b,S])),[])}function Gq(e,n,i,c){return Oi(e,n,i.allOf,c,io(bt("results","length"),De(i.allOf.length)))}function Kq(e,n,i,c){return An(i.allOf.map((p)=>Nt(e,n,p,c)))}function qR(e,n,i,c){return n.UseUnevaluated()?Gq(e,n,i,c):Kq(e,n,i,c)}function FR(e,n,i,c){let p=i.allOf.reduce((g,y)=>{let x=new _n;return At(e,x,y,c)?[...g,x]:g},[]);return _(p.length,i.allOf.length)&&n.Merge(p)}function jR(e,n,i,c,p,g){let y=[],x=p.allOf.reduce((S,T,A)=>{let C=`${i}/allOf/${A}`,P=new Dn,L=mr(e,P,C,c,T,g);if(!L)y.push(P);return L?[...S,P]:S},[]),b=_(x.length,p.allOf.length)&&n.Merge(x);if(!b)y.forEach((S)=>S.GetErrors().forEach((T)=>n.AddError(T)));return b}function Hq(e,n,i,c){return Oi(e,n,i.anyOf,c,wy(bt("results","length"),De(0)))}function Wq(e,n,i,c){return hd(i.anyOf.map((p)=>Nt(e,n,p,c)))}function UR(e,n,i,c){return n.UseUnevaluated()?Hq(e,n,i,c):Wq(e,n,i,c)}function BR(e,n,i,c){let p=i.anyOf.reduce((g,y)=>{let x=new _n;return At(e,x,y,c)?[...g,x]:g},[]);return Ki(p.length,0)&&n.Merge(p)}function GR(e,n,i,c,p,g){let y=[],x=p.anyOf.reduce((S,T,A)=>{let C=new Dn,P=`${i}/anyOf/${A}`,L=mr(e,C,P,c,T,g);if(!L)y.push(C);return L?[...S,C]:S},[]),b=Ki(x.length,0)&&n.Merge(x);if(!b)y.forEach((S)=>S.GetErrors().forEach((T)=>n.AddError(T)));return b||n.AddError({keyword:"anyOf",schemaPath:i,instancePath:c,params:{}})}function KR(e,n,i,c){return i?De(!0):De(!1)}function _f(e,n,i,c){return i}function HR(e,n,i,c,p,g){return _f(e,n,p,g)||n.AddError({keyword:"boolean",schemaPath:i,instancePath:c,params:{}})}function WR(e,n,i,c){return Hi(i.const)?io(c,De(i.const)):Ry(c,vo(i.const))}function Lf(e,n,i,c){return Hi(i.const)?_(c,i.const):Ta(c,i.const)}function zR(e,n,i,c,p,g){return Lf(e,n,p,g)||n.AddError({keyword:"const",schemaPath:i,instancePath:c,params:{allowedValue:p.const}})}function VR(e){return!(js(e)&&_(e.minContains,0))}function zq(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Un(io(bt(c,"length"),De(0))),x=Av(c,[p,g],En(Nt(e,n,i.contains,p),n.AddIndex(g)));return En(y,x)}function Vq(e,n,i,c){let[p]=[Vt()],g=Un(io(bt(c,"length"),De(0))),y=kv(c,[p,"_"],Nt(e,n,i.contains,p));return En(g,y)}function JR(e,n,i,c){if(!VR(i))return De(!0);return n.UseUnevaluated()?zq(e,n,i,c):Vq(e,n,i,c)}function Nf(e,n,i,c){if(!VR(i))return!0;return!_(c.length,0)&&gy(c,(p,g)=>At(e,n,i.contains,p)&&n.AddIndex(g))}function QR(e,n,i,c,p,g){return Nf(e,n,p,g)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:1}})}function XR(e,n,i,c){let p=io(bt(zi(c),"length"),De(0)),g=An(mn(i.dependencies).map(([y,x])=>{let b=Un(Vi(c,De(y))),S=Nt(e,n,x,c),T=(A)=>An(A.map((C)=>Vi(c,De(C))));return xr(b,Be(x)?T(x):S)}));return xr(p,g)}function YR(e,n,i,c){let p=_(Se(c).length,0),g=on(mn(i.dependencies),0,([y,x])=>!le(c,y)||(Be(x)?x.every((b)=>le(c,b)):At(e,n,x,c)));return p||g}function ZR(e,n,i,c,p,g){let y=_(Se(g).length,0),x=kn(mn(p.dependencies),0,([b,S])=>{let T=`${i}/dependencies/${b}`;return!le(g,b)||(Be(S)?S.every((A)=>le(g,A)||n.AddError({keyword:"dependencies",schemaPath:i,instancePath:c,params:{property:b,dependencies:S}})):mr(e,n,T,c,S,g))});return y||x}function ek(e,n,i,c){let p=io(bt(zi(c),"length"),De(0)),g=An(mn(i.dependentRequired).map(([y,x])=>{let b=Un(Vi(c,De(y))),S=An(x.map((T)=>Vi(c,De(T))));return xr(b,S)}));return xr(p,g)}function tk(e,n,i,c){let p=_(Se(c).length,0),g=on(mn(i.dependentRequired),0,([y,x])=>!le(c,y)||x.every((b)=>le(c,b)));return p||g}function rk(e,n,i,c,p,g){let y=_(Se(g).length,0),x=kn(mn(p.dependentRequired),0,([b,S])=>!le(g,b)||kn(S,0,(T)=>le(g,T)||n.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:c,params:{property:b,dependencies:S}})));return y||x}function nk(e,n,i,c){let p=io(bt(zi(c),"length"),De(0)),g=An(mn(i.dependentSchemas).map(([y,x])=>{let b=Un(Vi(c,De(y))),S=Nt(e,n,x,c);return xr(b,S)}));return xr(p,g)}function ok(e,n,i,c){let p=_(Se(c).length,0),g=on(mn(i.dependentSchemas),0,([y,x])=>!le(c,y)||At(e,n,x,c));return p||g}function sk(e,n,i,c,p,g){let y=_(Se(g).length,0),x=kn(mn(p.dependentSchemas),0,([b,S])=>{let T=`${i}/dependentSchemas/${b}`;return!le(g,b)||mr(e,n,T,c,S,g)});return y||x}function ik(e,n,i,c){let p=e.DynamicRef(i)??!1;return Gs(e,n,p,c)}function ak(e,n,i,c){let p=e.DynamicRef(i)??!1;return Ye(p)&&At(e,n,p,c)}function uk(e,n,i,c,p,g){let y=e.DynamicRef(p)??!1;return Ye(y)&&mr(e,n,"#",c,y,g)}function ck(e,n,i,c){return hd(i.enum.map((p)=>{if(Hi(p))return io(c,De(p));let g=vo(p);return Ry(c,g)}))}function qf(e,n,i,c){return wa(i.enum,(p)=>Hi(p)?_(c,p):Ta(c,p))}function mk(e,n,i,c,p,g){return qf(e,n,p,g)||n.AddError({keyword:"enum",schemaPath:i,instancePath:c,params:{allowedValues:p.enum}})}function pk(e,n,i,c){return dd(c,De(i.exclusiveMaximum))}function Ff(e,n,i,c){return Tu(c,i.exclusiveMaximum)}function lk(e,n,i,c,p,g){return Ff(e,n,p,g)||n.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:c,params:{comparison:"<",limit:p.exclusiveMaximum}})}function dk(e,n,i,c){return wy(c,De(i.exclusiveMinimum))}function jf(e,n,i,c){return Ki(c,i.exclusiveMinimum)}function fk(e,n,i,c,p,g){return jf(e,n,p,g)||n.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:c,params:{comparison:">",limit:p.exclusiveMinimum}})}var Jq=[0,31,28,31,30,31,30,31,31,30,31,30,31],Qq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function Xq(e){return e%4===0&&(e%100!==0||e%400===0)}function Xa(e){let n=Qq.exec(e);if(!n)return!1;let i=+n[1],c=+n[2],p=+n[3];return c>=1&&c<=12&&p>=1&&p<=(c===2&&Xq(i)?29:Jq[c])}var Yq=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Ya(e,n=!0){let i=Yq.exec(e);if(!i)return!1;if(n&&!i[4]&&!i[5])return!1;let c=+i[1],p=+i[2],g=+i[3];if(c>23||p>59||g>60)return!1;if(i[5]){let T=+i[6],A=+i[7];if(T>23||A>59)return!1}if(g<60)return!0;let y=i[5]==="-"?-1:1,x=+(i[6]||0),b=+(i[7]||0);return((c*60+p-y*(x*60+b))%1440+1440)%1440===1439}function Tp(e){let n=e.split(/T/i);return n.length===2&&Xa(n[0])&&Ya(n[1])}var Zq=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Rp(e){return Zq.test(e)}var eF=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function kp(e){return eF.test(e)}var hk=/^(?!-).*(?<!-)$/,gk=/^(?!..--)/,yk=/^[a-zA-Z0-9-]*$/;var Za=/[^\p{ASCII}]/u;var tF=/[0-9]/,xk=/[\u{0660}-\u{0669}]/u,rF=/[\u{06f0}-\u{06f9}]/u,nF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,oF=/[\u{002d}\u{002b}]/u,Uf=/\p{Mn}/u,sF=/\p{Mc}/u;var Ik=/[\p{Mn}\p{Mc}\p{Me}]/u,Bf=/\p{L}/u,iF=/\p{Nd}/u,bk=/\p{Script=Greek}/u,Ap=/\p{Script=Hebrew}/u,Ek=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Sk=/[\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,wk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,aF=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,uF=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,Tk=new RegExp([tF,rF].map((e)=>e.source).join("|"),"u"),Rk=new RegExp([Bf,oF,nF,iF,Uf,sF,aF,uF].map((e)=>e.source).join("|"),"u");function kk(e){return hk.test(e)&&gk.test(e)&&yk.test(e)}var is=36,Mc=1,vc=26,mF=38,pF=700,Ck=72,Pk=128;function Kf(){throw null}function Cp(e){return e.toLowerCase().startsWith("xn--")}function $k(e,n,i){e=i?Math.floor(e/pF):e>>1,e+=Math.floor(e/n);let c=0;while(e>(is-Mc)*vc>>1)e=Math.floor(e/(is-Mc)),c+=is;return c+Math.floor((is-Mc+1)*e/(e+mF))}function Pp(e){let n=[],i=Pk,c=0,p=Ck,g=e.lastIndexOf("-");if(g>0)for(let x=0;x<g;x++){let b=e.charCodeAt(x);if(b>=128)Kf();n.push(b)}let y=g<0?0:g+1;while(y<e.length){let x=c,b=1,S=is;while(!0){if(y>=e.length)Kf();let A=e.charCodeAt(y++),C;if(A>=97&&A<=122)C=A-97;else if(A>=48&&A<=57)C=A-48+26;else Kf();c+=C*b;let P=S<=p?Mc:S>=p+vc?vc:S-p;if(C<P)break;b*=is-P,S+=is}let T=n.length+1;p=$k(c-x,T,x===0),i+=Math.floor(c/T),c%=T,n.splice(c,0,i),c++}return String.fromCodePoint(...n)}function Ak(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var lF=new RegExp(Za.source,"gu");function Mk(e){let n=e.replace(lF,""),i=n.length,c=i>0?[n,"-"]:[],p=Array.from(e,(S)=>S.codePointAt(0)),g=Pk,y=0,x=Ck,b=i;while(b<p.length){let S=1/0;for(let T of p)if(T>=g&&T<S)S=T;y+=(S-g)*(b+1),g=S;for(let T of p){if(T<g)y++;if(T===g){let A=y;for(let C=is;;C+=is){let P=C<=x?Mc:C>=x+vc?vc:C-x;if(A<P)break;let L=P+(A-P)%(is-P);c.push(Ak(L)),A=Math.floor((A-P)/(is-P))}c.push(Ak(A)),x=$k(y,b+1,b===i),y=0,b++}}y++,g++}return c.join("")}var dF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,vk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,fF=/^(?:R|AL|AN)$/;function Ok(e){if(Cp(e))try{return $p(Pp(e.slice(4).toLowerCase()))}catch{return!1}return $p(e)}function _k(e){let n=String.fromCodePoint(e);return Tk.test(n)?"EN":xk.test(n)?"AN":Uf.test(n)?"NSM":Ap.test(n)?"R":Sk.test(n)?"AL":Bf.test(n)?"L":"ON"}function $p(e){for(let n of e)if(fF.test(_k(n.codePointAt(0))))return!0;return!1}function Mp(e){let n=!1,i=vk,c=!1,p=!1,g=!0;for(let y of e){let x=_k(y.codePointAt(0));if(g){if(x!=="L"&&x!=="R"&&x!=="AL")return!1;n=x==="R"||x==="AL",i=n?dF:vk,g=!1}if(!i.test(x))return!1;if(x==="EN")c=!0;else if(x==="AN")p=!0}if(n&&c&&p)return!1;return!0}function hF(e){return Za.test(e)&&Mk(e).length+4>63}function gF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function vp(e){if(hF(e))return!1;if($p(e)&&!Mp(e))return!1;let n=[...e],i=n.map((g)=>g.codePointAt(0)),c=i.length;if(gF(n))return!1;if(Ik.test(n[0]))return!1;let p=!1;for(let g=0;g<c;g++){let y=i[g],x=n[g];if(wk.test(x))return!1;if(!Rk.test(x))return!1;if(Ek.test(x))p=!0;let b=i[g-1],S=i[g+1];switch(y){case 183:if(b!==108||S!==108)return!1;break;case 885:if(!S||!bk.test(n[g+1]))return!1;break;case 1523:case 1524:if(!b||!Ap.test(n[g-1]))return!1;break;case 8204:if(!b||b<128&&!Gf.test(n[g-1]))return!1;break;case 8205:if(!b||!Gf.test(n[g-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function Op(e){if(!Cp(e))return!1;try{let n=e.slice(4).toLowerCase();if(n.lastIndexOf("-")===0)return!1;let i=Pp(n);if(!Za.test(i))return!1;return vp(i)}catch{return!1}}function yF(e){return e.length>0&&e.length<=63}function xF(e){return yF(e)&&(Op(e)||kk(e))}function qk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((n)=>xF(n))}function IF(e){return e.length>0&&e.length<=63}function bF(e){return IF(e)&&(Op(e)||vp(e))}function EF(e){return e.replace(/[\uff01-\uff5e]/g,(n)=>String.fromCharCode(n.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function Fk(e){if(e.length===0||e.includes(" "))return!1;let n=EF(e);if(n.length>253)return!1;let i=n.split("."),c=i.some((p)=>Ok(p));return i.every((p)=>bF(p)&&(!c||Mp(p)))}function _p(e){return qk(e)}var SF=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Lp(e){return SF.test(e.normalize("NFC"))}function Np(e){return Fk(e)}var wF=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Dp(e){return wF.test(e)}var TF=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function qp(e){return TF.test(e)}var RF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,kF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Fp(e){return!RF.test(e)&&!kF.test(e)&&URL.canParse(e,"http://example.com")}var AF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,CF=/[\x00-\x20<>\^`{|}\\]/,PF=/%(?![0-9a-fA-F]{2})/;function $F(e){return e.length<2048?e.replace(AF,"[::1]"):e}function jp(e){if(CF.test(e))return!1;if(PF.test(e))return!1;return URL.canParse($F(e))}var MF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Up(e){return MF.test(e)}var vF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Bp(e){return vF.test(e)}function Gp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var OF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Kp(e){return OF.test(e)}var _F=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Hp(e){return _F.test(e)}var LF=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Wp(e){return LF.test(e)}var NF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function zp(e){return NF.test(e)}function Vp(e){return URL.canParse(e)}var DF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Jp(e){return DF.test(e)}var Er=new Map;function Uk(){Er.clear()}function qF(){return[...Er.entries()]}function FF(e,n){Er.set(e,n)}function jF(e){return Er.has(e)}function UF(e){return Er.get(e)}function Bk(e,n){return Er.get(e)?.(n)??!0}function Gk(){Uk(),Er.set("date-time",Tp),Er.set("date",Xa),Er.set("duration",Rp),Er.set("email",kp),Er.set("hostname",_p),Er.set("idn-email",Lp),Er.set("idn-hostname",Np),Er.set("ipv4",Dp),Er.set("ipv6",qp),Er.set("iri-reference",Fp),Er.set("iri",jp),Er.set("json-pointer-uri-fragment",Up),Er.set("json-pointer",Bp),Er.set("regex",Gp),Er.set("relative-json-pointer",Kp),Er.set("time",Ya),Er.set("uri-reference",Hp),Er.set("uri-template",Wp),Er.set("uri",zp),Er.set("url",Vp),Er.set("uuid",Jp)}Gk();function Kk(e,n,i,c){return Ir(bt("Format","Test"),[De(i.format),c])}function Wf(e,n,i,c){return Bk(i.format,c)}function Hk(e,n,i,c,p,g){return Wf(e,n,p,g)||n.AddError({keyword:"format",schemaPath:i,instancePath:c,params:{format:p.format}})}function Wk(e,n,i,c){let p=Cc(i)?i.then:!0,g=fc(i)?i.else:!0;return Pv(Nt(e,n,i.if,c),Nt(e,n,p,c),Nt(e,n,g,c))}function zk(e,n,i,c){let p=Cc(i)?i.then:!0,g=fc(i)?i.else:!0;return At(e,n,i.if,c)?At(e,n,p,c):At(e,n,g,c)}function Vk(e,n,i,c,p,g){let y=Cc(p)?p.then:!0,x=fc(p)?p.else:!0,b=new Dn,S=mr(e,b,`${i}/if`,c,p.if,g)?mr(e,b,`${i}/then`,c,y,g)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"then"}}):mr(e,n,`${i}/else`,c,x,g)||n.AddError({keyword:"if",schemaPath:i,instancePath:c,params:{failingKeyword:"else"}});if(S)n.Merge([b]);return S}function BF(e,n,i,c){return An(i.items.map((p,g)=>{let y=Wi(bt(c,"length"),De(g)),x=Zn(e,n,p,`${c}[${g}]`),b=n.AddIndex(De(g));return xr(y,En(x,b))}))}function GF(e,n,i,c){return An(i.items.map((p,g)=>{let y=Wi(bt(c,"length"),De(g)),x=Zn(e,n,p,`${c}[${g}]`);return xr(y,x)}))}function KF(e,n,i,c){return n.UseUnevaluated()?BF(e,n,i,c):GF(e,n,i,c)}function HF(e,n,i,c){return on(i.items,0,(p,g)=>ds(c.length,g)||bo(e,n,p,c[g])&&n.AddIndex(g))}function WF(e,n,i,c,p,g){return kn(p.items,0,(y,x)=>{let b=`${i}/items/${x}`,S=`${c}/${x}`;return ds(g.length,x)||Eo(e,n,b,S,y,g[x])&&n.AddIndex(x)})}function zF(e,n,i,c){let p=ns(i)?i.prefixItems.length:0,g=Zn(e,n,i.items,"element"),y=n.AddIndex("index");return fs(c,De(p),["element","index"],En(g,y))}function VF(e,n,i,c){let p=ns(i)?i.prefixItems.length:0,g=Zn(e,n,i.items,"element");return fs(c,De(p),["element","index"],g)}function JF(e,n,i,c){return n.UseUnevaluated()?zF(e,n,i,c):VF(e,n,i,c)}function QF(e,n,i,c){let p=ns(i)?i.prefixItems.length:0;return on(c,p,(g,y)=>bo(e,n,i.items,g)&&n.AddIndex(y))}function XF(e,n,i,c,p,g){let y=ns(p)?p.prefixItems.length:0;return kn(g,y,(x,b)=>{let S=`${i}/items`,T=`${c}/${b}`;return Eo(e,n,S,T,p.items,x)&&n.AddIndex(b)})}function Jk(e,n,i,c){return yc(i)?KF(e,n,i,c):JF(e,n,i,c)}function Qk(e,n,i,c){return yc(i)?HF(e,n,i,c):QF(e,n,i,c)}function Xk(e,n,i,c,p,g){return yc(p)?WF(e,n,i,c,p,g):XF(e,n,i,c,p,g)}function Yk(e){return As(e)}function Zk(e,n,i,c){if(!Yk(i))return De(!0);let[p]=[Vt()],g=am(c,[p,"_"],Nt(e,n,i.contains,p));return Wi(g,De(i.maxContains))}function zf(e,n,i,c){if(!Yk(i))return!0;let p=cd(c,(g)=>At(e,n,i.contains,g));return ds(p,i.maxContains)}function eA(e,n,i,c,p,g){let y=js(p)?p.minContains:1;return zf(e,n,p,g)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:y,maxContains:p.maxContains}})}function tA(e,n,i,c){return Wi(c,De(i.maximum))}function Vf(e,n,i,c){return ds(c,i.maximum)}function rA(e,n,i,c,p,g){return Vf(e,n,p,g)||n.AddError({keyword:"maximum",schemaPath:i,instancePath:c,params:{comparison:"<=",limit:p.maximum}})}function nA(e,n,i,c){return Wi(bt(c,"length"),De(i.maxItems))}function Jf(e,n,i,c){return ds(c.length,i.maxItems)}function oA(e,n,i,c,p,g){return Jf(e,n,p,g)||n.AddError({keyword:"maxItems",schemaPath:i,instancePath:c,params:{limit:p.maxItems}})}function sA(e,n,i,c){return Rv(c,De(i.maxLength))}function Qf(e,n,i,c){return fy(c,i.maxLength)}function iA(e,n,i,c,p,g){return Qf(e,n,p,g)||n.AddError({keyword:"maxLength",schemaPath:i,instancePath:c,params:{limit:p.maxLength}})}function aA(e,n,i,c){return Wi(bt(zi(c),"length"),De(i.maxProperties))}function Xf(e,n,i,c){return ds(Se(c).length,i.maxProperties)}function uA(e,n,i,c,p,g){return Xf(e,n,p,g)||n.AddError({keyword:"maxProperties",schemaPath:i,instancePath:c,params:{limit:p.maxProperties}})}function cA(e){return As(e)}function YF(e,n,i,c){let[p,g]=[Vt(),Vt()],y=am(c,[p,g],En(Nt(e,n,i.contains,p),n.AddIndex(g)));return ku(y,De(i.minContains))}function ZF(e,n,i,c){let[p]=[Vt()],g=am(c,[p,"_"],Nt(e,n,i.contains,p));return ku(g,De(i.minContains))}function mA(e,n,i,c){if(!cA(i))return De(!0);return n.UseUnevaluated()?YF(e,n,i,c):ZF(e,n,i,c)}function Yf(e,n,i,c){if(!cA(i))return!0;let p=cd(c,(g,y)=>At(e,n,i.contains,g)&&n.AddIndex(y));return Sa(p,i.minContains)}function pA(e,n,i,c,p,g){return Yf(e,n,p,g)||n.AddError({keyword:"contains",schemaPath:i,instancePath:c,params:{minContains:p.minContains}})}function lA(e,n,i,c){return ku(c,De(i.minimum))}function Zf(e,n,i,c){return Sa(c,i.minimum)}function dA(e,n,i,c,p,g){return Zf(e,n,p,g)||n.AddError({keyword:"minimum",schemaPath:i,instancePath:c,params:{comparison:">=",limit:p.minimum}})}function fA(e,n,i,c){return ku(bt(c,"length"),De(i.minItems))}function eh(e,n,i,c){return Sa(c.length,i.minItems)}function hA(e,n,i,c,p,g){return eh(e,n,p,g)||n.AddError({keyword:"minItems",schemaPath:i,instancePath:c,params:{limit:p.minItems}})}function gA(e,n,i,c){return Tv(c,De(i.minLength))}function th(e,n,i,c){return hy(c,i.minLength)}function yA(e,n,i,c,p,g){return th(e,n,p,g)||n.AddError({keyword:"minLength",schemaPath:i,instancePath:c,params:{limit:p.minLength}})}function xA(e,n,i,c){return ku(bt(zi(c),"length"),De(i.minProperties))}function rh(e,n,i,c){return Sa(Se(c).length,i.minProperties)}function IA(e,n,i,c,p,g){return rh(e,n,p,g)||n.AddError({keyword:"minProperties",schemaPath:i,instancePath:c,params:{limit:p.minProperties}})}function bA(e,n,i,c){return $v(c,De(i.multipleOf))}function nh(e,n,i,c){return ly(c,i.multipleOf)}function EA(e,n,i,c,p,g){return nh(e,n,p,g)||n.AddError({keyword:"multipleOf",schemaPath:i,instancePath:c,params:{multipleOf:p.multipleOf}})}function e1(e,n,i,c){return Oi(e,n,[i.not],c,Un(io(bt("results","length"),De(1))))}function t1(e,n,i,c){return Un(Nt(e,n,i.not,c))}function SA(e,n,i,c){return n.UseUnevaluated()?e1(e,n,i,c):t1(e,n,i,c)}function oh(e,n,i,c){let p=new _n;return!At(e,p,i.not,c)&&n.Merge([p])}function wA(e,n,i,c,p,g){return oh(e,n,p,g)||n.AddError({keyword:"not",schemaPath:i,instancePath:c,params:{}})}function r1(e,n,i,c){return Oi(e,n,i.oneOf,c,io(bt("results","length"),De(1)))}function n1(e,n,i,c){let[p]=[Vt()],g=Cv(i.oneOf.map((x)=>Nt(e,n,x,c))),y=am(g,[p,"_"],io(p,De(!0)));return io(y,De(1))}function TA(e,n,i,c){return n.UseUnevaluated()?r1(e,n,i,c):n1(e,n,i,c)}function RA(e,n,i,c){let p=i.oneOf.reduce((g,y)=>{let x=new _n;return At(e,x,y,c)?[...g,x]:g},[]);return _(p.length,1)&&n.Merge(p)}function kA(e,n,i,c,p,g){let y=[],x=[],b=p.oneOf.reduce((T,A,C)=>{let P=new Dn,L=`${i}/oneOf/${C}`,q=mr(e,P,L,c,A,g);if(q)x.push(C);if(!q)y.push(P);return q?[...T,P]:T},[]),S=_(b.length,1)&&n.Merge(b);if(!S&&_(x.length,0))y.forEach((T)=>T.GetErrors().forEach((A)=>n.AddError(A)));return S||n.AddError({keyword:"oneOf",schemaPath:i,instancePath:c,params:{passingSchemas:x}})}function AA(e,n,i,c){let p=vo(gt(i.pattern)?ss(i.pattern):i.pattern);return Ir(bt(p,"test"),[c])}function sh(e,n,i,c){return(gt(i.pattern)?ss(i.pattern):i.pattern).test(c)}function CA(e,n,i,c,p,g){return sh(e,n,p,g)||n.AddError({keyword:"pattern",schemaPath:i,instancePath:c,params:{pattern:p.pattern}})}function PA(e,n,i,c){return An(mn(i.patternProperties).map(([p,g])=>{let[y,x]=[Vt(),Vt()],b=vo(ss(p)),S=Un(Ir(bt(b,"test"),[y])),T=Zn(e,n,g,x),A=n.AddKey(y),C=n.UseUnevaluated()?xr(S,En(T,A)):xr(S,T);return fs(Ty(c),De(0),[`[${y}, ${x}]`,"_"],C)}))}function $A(e,n,i,c){return on(mn(i.patternProperties),0,([p,g])=>{let y=ss(p);return on(mn(c),0,([x,b])=>!y.test(x)||bo(e,n,g,b)&&n.AddKey(x))})}function MA(e,n,i,c,p,g){return kn(mn(p.patternProperties),0,([y,x])=>{let b=`${i}/patternProperties/${y}`,S=ss(y);return kn(mn(g),0,([T,A])=>{let C=`${c}/${T}`;return!S.test(T)||Eo(e,n,b,C,x,A)&&n.AddKey(T)})})}function vA(e,n,i,c){return An(i.prefixItems.map((p,g)=>{let y=Wi(bt(c,"length"),De(g)),x=Zn(e,n,p,`${c}[${g}]`),b=n.AddIndex(De(g)),S=n.UseUnevaluated()?En(x,b):x;return xr(y,S)}))}function OA(e,n,i,c){return _(c.length,0)||on(i.prefixItems,0,(p,g)=>ds(c.length,g)||bo(e,n,p,c[g])&&n.AddIndex(g))}function _A(e,n,i,c,p,g){return _(g.length,0)||kn(p.prefixItems,0,(y,x)=>{let b=`${i}/prefixItems/${x}`,S=`${c}/${x}`;return ds(g.length,x)||Eo(e,n,b,S,y,g[x])&&n.AddIndex(x)})}function Qp(e,n){return e.includes(n)||Qo().exactOptionalPropertyTypes}function LA(e,n){return ld(bt(e,n))}function ih(e,n){return Bt(e[n])}function NA(e,n,i,c){let p=os(i)?i.required:[],g=mn(i.properties).map(([y,x])=>{let b=Un(Vi(c,De(y))),S=Zn(e,n,x,bt(c,y)),T=n.AddKey(De(y)),A=n.UseUnevaluated()?En(S,T):S,C=p.includes(y)?A:xr(b,A);return Qp(p,y)?C:xr(LA(c,y),C)});return An(g)}function DA(e,n,i,c){let p=os(i)?i.required:[];return on(mn(i.properties),0,([y,x])=>{let b=!le(c,y)||bo(e,n,x,c[y])&&n.AddKey(y);return Qp(p,y)?b:ih(c,y)||b})}function qA(e,n,i,c,p,g){let y=os(p)?p.required:[];return kn(mn(p.properties),0,([b,S])=>{let T=`${i}/properties/${b}`,A=`${c}/${b}`,C=()=>!le(g,b)||Eo(e,n,T,A,S,g[b])&&n.AddKey(b);return Qp(y,b)?C():ih(g,b)||C()})}function FA(e,n,i,c){let[p,g]=[Vt(),Vt()];return fs(zi(c),De(0),[p,g],Nt(e,n,i.propertyNames,p))}function jA(e,n,i,c){return on(Se(c),0,(p,g)=>At(e,n,i.propertyNames,p))}function UA(e,n,i,c,p,g){let y=[];return kn(Se(g),0,(b,S)=>{let T=`${c}/${b}`,A=`${i}/propertyNames`,C=mr(e,n,A,T,p.propertyNames,b);if(!C)y.push(b);return C})||n.AddError({keyword:"propertyNames",schemaPath:i,instancePath:c,params:{propertyNames:y}})}function BA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Gs(e,n,p,c)}function GA(e,n,i,c){let p=e.RecursiveRef(i)??!1;return Ye(p)&&At(e,n,p,c)}function KA(e,n,i,c,p,g){let y=e.RecursiveRef(p)??!1;return Ye(y)&&mr(e,n,"#",c,y,g)}function o1(e,n,i,c){let p=Qs(["context","value"],Gs(e,n,i,"value")),g=Qs(["context","value"],um([_s("nextContext",fd("CheckContext",[])),_s("result",Ir(p,["nextContext","value"])),ky("result",n.Merge("[nextContext]")),cm("result")]));return Ir(g,["context",c])}function s1(e,n,i,c){return Gs(e,n,i,c)}function HA(e,n,i,c){let p=e.Ref(i)??!1;return n.UseUnevaluated()?o1(e,n,p,c):s1(e,n,p,c)}function WA(e,n,i,c){let p=e.Ref(i)??!1,g=new _n,y=Ye(p)&&At(e,g,p,c);if(y)n.Merge([g]);return y}function zA(e,n,i,c,p,g){let y=e.Ref(p)??!1,x=new Dn,b=Ye(y)&&mr(e,x,"#",c,y,g);if(b)n.Merge([x]);if(!b)x.GetErrors().forEach((S)=>n.AddError(S));return b}function VA(e,n,i,c){return An(i.required.map((p)=>Vi(c,De(p))))}function JA(e,n,i,c){return on(i.required,0,(p)=>le(c,p))}function QA(e,n,i,c,p,g){let y=[];return kn(p.required,0,(b)=>{let S=le(g,b);if(!S)y.push(b);return S})||n.AddError({keyword:"required",schemaPath:i,instancePath:c,params:{requiredProperties:y}})}function XA(e,n,i,c){return _(i,"object")?by(c):_(i,"array")?im(c):_(i,"boolean")?xv(c):_(i,"integer")?Iv(c):_(i,"number")?Iy(c):_(i,"null")?bv(c):_(i,"string")?Sy(c):_(i,"bigint")?xy(c):_(i,"constructor")?wv(c):_(i,"function")?Sv(c):_(i,"symbol")?Ev(c):_(i,"undefined")?ld(c):_(i,"void")?ld(c):De(!0)}function ah(e,n,i,c,p){return _(i,"object")?Jo(p):_(i,"array")?Be(p):_(i,"boolean")?cn(p):_(i,"integer")?sm(p):_(i,"number")?_t(p):_(i,"null")?lo(p):_(i,"string")?gt(p):_(i,"bigint")?Nr(p):_(i,"constructor")?ad(p):_(i,"function")?ls(p):_(i,"symbol")?ud(p):_(i,"undefined")?Bt(p):_(i,"void")?Bt(p):!0}function i1(e,n,i,c){return hd(i.map((p)=>XA(e,n,p,c)))}function YA(e,n,i,c,p){return wa(i,(g)=>ah(e,n,g,c,p))}function ZA(e,n,i,c){return Be(i.type)?i1(e,n,i.type,c):XA(e,n,i.type,c)}function e0(e,n,i,c){return Be(i.type)?YA(e,n,i.type,i,c):ah(e,n,i.type,i,c)}function t0(e,n,i,c,p,g){return(Be(p.type)?YA(e,n,p.type,p,g):ah(e,n,p.type,p,g))||n.AddError({keyword:"type",schemaPath:i,instancePath:c,params:{type:p.type}})}function r0(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetIndices"),[]),x=Ir(bt("indices","has"),[p]),b=Nt(e,n,i.unevaluatedItems,g),S=Ir(bt("context","AddIndex"),[p]),T=fs(c,De(0),[g,p],En(xr(x,b),S));return Ir(Qs(["context"],um([_s("indices",y),cm(T)])),["context"])}function n0(e,n,i,c){let p=n.GetIndices();return on(c,0,(g,y)=>(p.has(y)||At(e,n,i.unevaluatedItems,g))&&n.AddIndex(y))}function o0(e,n,i,c,p,g){let y=n.GetIndices(),x=[];return kn(g,0,(S,T)=>{let A=new Dn,C=(y.has(T)||mr(e,A,i,c,p.unevaluatedItems,S))&&n.AddIndex(T);if(!C)x.push(T);return C})||n.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:c,params:{unevaluatedItems:x}})}function s0(e,n,i,c){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetKeys"),[]),x=Ir(bt("keys","has"),[p]),b=Ir(bt("context","AddKey"),[p]),S=Nt(e,n,i.unevaluatedProperties,g),T=fs(Ty(c),De(0),[`[${p}, ${g}]`,"_"],xr(x,En(S,b)));return Ir(Qs(["context"],um([_s("keys",y),cm(T)])),["context"])}function i0(e,n,i,c){let p=n.GetKeys();return on(mn(c),0,([g,y])=>p.has(g)||At(e,n,i.unevaluatedProperties,y)&&n.AddKey(g))}function a0(e,n,i,c,p,g){let y=n.GetKeys(),x=[];return kn(mn(g),0,([S,T])=>{let A=new Dn,C=y.has(S)||mr(e,A,i,c,p.unevaluatedProperties,T)&&n.AddKey(S);if(!C)x.push(S);return C})||n.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:c,params:{unevaluatedProperties:x}})}function uh(e){return!_(e.uniqueItems,!1)}function u0(e,n,i,c){if(!uh(i))return De(!0);let p=bt(fd("Set",[Ir(bt(c,"map"),[bt("Hashing","Hash")])]),"size"),g=bt(c,"length");return io(p,g)}function c0(e,n,i,c){if(!uh(i))return!0;let p=new Set(c.map(xd)).size,g=c.length;return _(p,g)}function m0(e,n,i,c,p,g){if(!uh(p))return!0;let y=new Set,x=g.reduce((S,T,A)=>{let C=xd(T);if(y.has(C))return[...S,A];return y.add(C),S},[]);return _(x.length,0)||n.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:c,params:{duplicateItems:x}})}function Oc(e,n){return Pc(e)&&(Be(e.type)&&Ki(e.type.length,0)&&on(e.type,0,(i)=>_(i,n))||_(e.type,n))}function a1(e){return Oc(e,"object")}function u1(e){return fn(e)&&(Po(e)||pc(e)||lc(e)||za(e)||Bs(e)||Us(e)||Ja(e)||pa(e)||Ec(e)||os(e)||Mi(e))}function c1(e){return Oc(e,"array")}function m1(e){return fn(e)&&(Wa(e)||Fs(e)||As(e)||Ic(e)||Va(e)||js(e)||Ii(e)||ns(e)||$i(e)||Ai(e))}function p1(e){return Oc(e,"string")}function l1(e){return fn(e)&&(ma(e)||bc(e)||ca(e)||la(e))}function d1(e){return Oc(e,"number")||Oc(e,"bigint")}function f1(e){return fn(e)&&(rs(e)||xc(e)||hc(e)||ts(e)||Sc(e))}function Zn(e,n,i,c){return n.UseUnevaluated()?En(En(n.Push(),Nt(e,n,i,c)),n.Pop()):Nt(e,n,i,c)}function Nt(e,n,i,c){e.Push(i);let p=[];if(Ds(i))return KR(e,n,i,c);if(Pc(i))p.push(ZA(e,n,i,c));if(u1(i)){let y=[];if(os(i))y.push(VA(e,n,i,c));if(Po(i))y.push(LR(e,n,i,c));if(pc(i))y.push(XR(e,n,i,c));if(lc(i))y.push(ek(e,n,i,c));if(za(i))y.push(nk(e,n,i,c));if(Us(i))y.push(PA(e,n,i,c));if(Bs(i))y.push(NA(e,n,i,c));if(Ja(i))y.push(FA(e,n,i,c));if(pa(i))y.push(xA(e,n,i,c));if(Ec(i))y.push(aA(e,n,i,c));let x=An(y),b=xr(Un(by(c)),x);p.push(a1(i)?x:b)}if(m1(i)){let y=[];if(Wa(i))y.push(vR(e,n,i,c));if(As(i))y.push(JR(e,n,i,c));if(Fs(i))y.push(Jk(e,n,i,c));if(Ic(i))y.push(Zk(e,n,i,c));if(Va(i))y.push(nA(e,n,i,c));if(js(i))y.push(mA(e,n,i,c));if(Ii(i))y.push(fA(e,n,i,c));if(ns(i))y.push(vA(e,n,i,c));if(Ai(i))y.push(u0(e,n,i,c));let x=An(y),b=xr(Un(im(c)),x);p.push(c1(i)?x:b)}if(l1(i)){let y=[];if(bc(i))y.push(sA(e,n,i,c));if(ma(i))y.push(gA(e,n,i,c));if(ca(i))y.push(Kk(e,n,i,c));if(la(i))y.push(AA(e,n,i,c));let x=An(y),b=xr(Un(Sy(c)),x);p.push(p1(i)?x:b)}if(f1(i)){let y=[];if(hc(i))y.push(pk(e,n,i,c));if(ts(i))y.push(dk(e,n,i,c));if(xc(i))y.push(tA(e,n,i,c));if(rs(i))y.push(lA(e,n,i,c));if(Sc(i))y.push(bA(e,n,i,c));let x=An(y),b=xr(Un(xr(Iy(c),xy(c))),x);p.push(d1(i)?x:b)}if(Ac(i))p.push(HA(e,n,i,c));if(kc(i))p.push(BA(e,n,i,c));if(dc(i))p.push(ik(e,n,i,c));if(bp(i))p.push(WR(e,n,i,c));if(Ep(i))p.push(ck(e,n,i,c));if(gc(i))p.push(Wk(e,n,i,c));if(wc(i))p.push(SA(e,n,i,c));if(uc(i))p.push(qR(e,n,i,c));if(mc(i))p.push(UR(e,n,i,c));if(Tc(i))p.push(TA(e,n,i,c));if($i(i))p.push(xr(Un(im(c)),r0(e,n,i,c)));if(Mi(i))p.push(xr(Un(Ey(c)),s0(e,n,i,c)));if(ac(i))p.push(PR(e,n,i,c));let g=An(p);return e.Pop(i),g}function bo(e,n,i,c){return n.Push()&&At(e,n,i,c)&&n.Pop()}function At(e,n,i,c){e.Push(i);let p=Ds(i)?_f(e,n,i,c):(!Pc(i)||e0(e,n,i,c))&&(!(at(c)&&!Be(c))||(!os(i)||JA(e,n,i,c))&&(!Po(i)||NR(e,n,i,c))&&(!pc(i)||YR(e,n,i,c))&&(!lc(i)||tk(e,n,i,c))&&(!za(i)||ok(e,n,i,c))&&(!Us(i)||$A(e,n,i,c))&&(!Bs(i)||DA(e,n,i,c))&&(!Ja(i)||jA(e,n,i,c))&&(!pa(i)||rh(e,n,i,c))&&(!Ec(i)||Xf(e,n,i,c)))&&(!Be(c)||(!Wa(i)||OR(e,n,i,c))&&(!As(i)||Nf(e,n,i,c))&&(!Fs(i)||Qk(e,n,i,c))&&(!Ic(i)||zf(e,n,i,c))&&(!Va(i)||Jf(e,n,i,c))&&(!js(i)||Yf(e,n,i,c))&&(!Ii(i)||eh(e,n,i,c))&&(!ns(i)||OA(e,n,i,c))&&(!Ai(i)||c0(e,n,i,c)))&&(!gt(c)||(!bc(i)||Qf(e,n,i,c))&&(!ma(i)||th(e,n,i,c))&&(!ca(i)||Wf(e,n,i,c))&&(!la(i)||sh(e,n,i,c)))&&(!(_t(c)||Nr(c))||(!hc(i)||Ff(e,n,i,c))&&(!ts(i)||jf(e,n,i,c))&&(!xc(i)||Vf(e,n,i,c))&&(!rs(i)||Zf(e,n,i,c))&&(!Sc(i)||nh(e,n,i,c)))&&(!Ac(i)||WA(e,n,i,c))&&(!kc(i)||GA(e,n,i,c))&&(!dc(i)||ak(e,n,i,c))&&(!bp(i)||Lf(e,n,i,c))&&(!Ep(i)||qf(e,n,i,c))&&(!gc(i)||zk(e,n,i,c))&&(!wc(i)||oh(e,n,i,c))&&(!uc(i)||FR(e,n,i,c))&&(!mc(i)||BR(e,n,i,c))&&(!Tc(i)||RA(e,n,i,c))&&(!$i(i)||(!Be(c)||n0(e,n,i,c)))&&(!Mi(i)||(!at(c)||i0(e,n,i,c)))&&(!ac(i)||$R(e,n,i,c));return e.Pop(i),p}function Eo(e,n,i,c,p,g){return n.Push()&&mr(e,n,i,c,p,g)&&n.Pop()}function mr(e,n,i,c,p,g){if(n.AtCapacity())return!1;e.Push(p);let y=Ds(p)?HR(e,n,i,c,p,g):!!(+(!Pc(p)||t0(e,n,i,c,p,g))&+(!(at(g)&&!Be(g))||!!(+(!os(p)||QA(e,n,i,c,p,g))&+(!Po(p)||DR(e,n,i,c,p,g))&+(!pc(p)||ZR(e,n,i,c,p,g))&+(!lc(p)||rk(e,n,i,c,p,g))&+(!za(p)||sk(e,n,i,c,p,g))&+(!Us(p)||MA(e,n,i,c,p,g))&+(!Bs(p)||qA(e,n,i,c,p,g))&+(!Ja(p)||UA(e,n,i,c,p,g))&+(!pa(p)||IA(e,n,i,c,p,g))&+(!Ec(p)||uA(e,n,i,c,p,g))))&+(!Be(g)||!!(+(!Wa(p)||_R(e,n,i,c,p,g))&+(!As(p)||QR(e,n,i,c,p,g))&+(!Fs(p)||Xk(e,n,i,c,p,g))&+(!Ic(p)||eA(e,n,i,c,p,g))&+(!Va(p)||oA(e,n,i,c,p,g))&+(!js(p)||pA(e,n,i,c,p,g))&+(!Ii(p)||hA(e,n,i,c,p,g))&+(!ns(p)||_A(e,n,i,c,p,g))&+(!Ai(p)||m0(e,n,i,c,p,g))))&+(!gt(g)||!!(+(!bc(p)||iA(e,n,i,c,p,g))&+(!ma(p)||yA(e,n,i,c,p,g))&+(!ca(p)||Hk(e,n,i,c,p,g))&+(!la(p)||CA(e,n,i,c,p,g))))&+(!(_t(g)||Nr(g))||!!(+(!hc(p)||lk(e,n,i,c,p,g))&+(!ts(p)||fk(e,n,i,c,p,g))&+(!xc(p)||rA(e,n,i,c,p,g))&+(!rs(p)||dA(e,n,i,c,p,g))&+(!Sc(p)||EA(e,n,i,c,p,g))))&+(!Ac(p)||zA(e,n,i,c,p,g))&+(!kc(p)||KA(e,n,i,c,p,g))&+(!dc(p)||uk(e,n,i,c,p,g))&+(!bp(p)||zR(e,n,i,c,p,g))&+(!Ep(p)||mk(e,n,i,c,p,g))&+(!gc(p)||Vk(e,n,i,c,p,g))&+(!wc(p)||wA(e,n,i,c,p,g))&+(!uc(p)||jR(e,n,i,c,p,g))&+(!mc(p)||GR(e,n,i,c,p,g))&+(!Tc(p)||kA(e,n,i,c,p,g))&+(!$i(p)||(!Be(g)||o0(e,n,i,c,p,g)))&+(!Mi(p)||(!at(g)||a0(e,n,i,c,p,g))))&&(!ac(p)||MR(e,n,i,c,p,g));return e.Pop(p),y}var p0=[0],Xp=new Map,_c=new Map;function h1(){return`${p0[0]++}`}function g1(e,n){if(!Xp.has(e))Xp.set(e,new Map);let i=Xp.get(e);if(i.has(n))return i.get(n);let c=h1();return i.set(n,c),c}function y1(e,n,i,c){return e.UseUnevaluated()?Ir(`check_${i}`,["context",c]):Ir(`check_${i}`,[c])}function x1(e,n,i,c){let p=Nt(e,n,i,"value");return n.UseUnevaluated()?_s(`check_${c}`,Qs(["context","value"],p)):_s(`check_${c}`,Qs(["value"],p))}function l0(){p0[0]=0,Xp.clear(),_c.clear()}function d0(){return[..._c.values()]}function Gs(e,n,i,c){let p=g1(i,e.LexicalBaseURL()),g=y1(n,i,p,c);if(_c.has(p))return g;return _c.set(p,""),_c.set(p,x1(e,n,i,p)),g}function I1(e,n){return at(n)&&!Ru(e)?n[e]:void 0}function b1(e,n){return e.reduce((i,c)=>I1(c,i),n)}function E1(e){if(_(e.length,0))return[];let n=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return n.length>0&&n[0]===""?n.slice(1):n}function S1(e,n){let i=E1(n);return b1(i,e)}var Zp="https://json-schema.org";function h0(e,n){if(at(e)&&qs(e)&&_(e.$dynamicAnchor,n))return e;if(at(e))for(let i of Se(e)){let c=h0(e[i],n);if(c)return c}return}function ch(e,n,i){if(_(e,i))return n.href;let c=fn(e)&&xo(e)?new URL(e.$id,n.href):n;if(Be(e))for(let p of e){let g=ch(p,c,i);if(!Bt(g))return g}else if(at(e))for(let p of Se(e)){let g=ch(e[p],c,i);if(!Bt(g))return g}return}function w1(e,n,i){if(_(e.$id,i.hash))return e;let c=new URL(i.href,n.href);if(_(n.pathname,c.pathname))return i.hash.startsWith("#")?g0(e,i):e;return}function T1(e,n,i){let c=new URL(`#${e.$anchor}`,n.href),p=new URL(i.href,n.href);return _(c.href,p.href)?e:void 0}function R1(e,n,i){let c=new URL(`#${e.$dynamicAnchor}`,n.href),p=new URL(i.href,n.href);return _(c.href,p.href)?e:void 0}function g0(e,n){if(n.href.endsWith("#"))return e;if(!n.hash.startsWith("#"))return;let i=decodeURIComponent(n.hash.slice(1));if(!i.startsWith("/"))return;return S1(e,i)}function k1(e,n,i){if(xo(e)){let c=w1(e,n,i);if(!Bt(c))return c}if(cc(e)){let c=T1(e,n,i);if(!Bt(c))return c}if(qs(e)){let c=R1(e,n,i);if(!Bt(c))return c}return g0(e,i)}function A1(e,n,i){return e.reduce((c,p)=>{let g=el(p,n,i);return!Bt(g)?g:c},void 0)}function C1(e){return _(e,"const")||_(e,"enum")}function P1(e,n,i){return Se(e).reduce((c,p)=>{if(C1(p))return c;let g=el(e[p],n,i);return!Bt(g)?g:c},void 0)}function el(e,n,i){let c=fn(e)&&xo(e)?new URL(e.$id,n.href):n;if(fn(e)){let p=k1(e,c,i);if(!Bt(p))return p}if(Be(e))return A1(e,c,i);if(at(e))return P1(e,c,i);return}function $1(e,n,i){return ch(e,new URL(n||".",Zp),i)}function M1(e,n,i,c){let p=tl(e,n,i,c,!1);return fn(p)&&xo(p)?p:void 0}function f0(e){return e.href.split("#")[0]}function v1(e,n){return le(e,n)?e[n]:void 0}function O1(e,n,i){return el(e,n,i)}function _1(e,n,i){let c=f0(i);if(_(c,f0(n)))return;if(!le(e,c))return;let p=e[c],g=fn(p)&&xo(p)?new URL(p.$id,c):new URL(c);return _(i.hash,"")?p:el(p,g,i)}function L1(e,n,i,c,p){if(!c.$ref.startsWith("#"))return;if(le(e,"$schema"))return;let g=$1(n,i,p);if(Bt(g)||_(g,i))return;return{target:p,base:g,root:n}}function N1(e,n,i){let c=e[n];if(!fn(c))return;return{target:i,base:n,root:c}}function D1(e,n,i,c,p){let g=p?N1(e.context,c,i):void 0;if(!Bt(g))return g;return L1(e.root,e.lexicalSchema,e.referenceBase,n,i)}function q1(e,n,i,c,p,g){if(xo(p))return;let y=M1(e,n,i,c);if(!y||g.includes(y))return;return{target:p,resource:y}}function tl(e,n,i,c,p=!0){let g=new URL(i||".",Zp),y=p&&xo(n)?new URL(n.$id,g):g,x=new URL(c,y.href);return v1(e,c)??O1(n,y,x)??_1(e,y,x)}function F1(e,n,i,c,p,g){let y=new URL(i||".",Zp),x=p.$dynamicRef.startsWith("#")?c:n,b=tl(e,x,i,p.$dynamicRef,!1);if(Bt(b)){let A=new URL(p.$dynamicRef,y).hash;if(!A.startsWith("#/")&&A.startsWith("#")){let C=decodeURIComponent(A.slice(1));return g.find((L)=>_(L.$dynamicAnchor,C))??h0(n,C)}return}if(!fn(b)||!qs(b))return b;if(new URL(p.$dynamicRef,y).hash.startsWith("#/"))return b;return g.find((A)=>_(A.$dynamicAnchor,b.$dynamicAnchor))??b}function j1(e,n){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,c=n.$ref.startsWith("#")?e.lexicalSchema:i,p=tl(e.context,c,e.referenceBase,n.$ref,!1);if(!p||!fn(p))return{schema:p};let g=new URL(n.$ref,e.referenceBase).href.split("#")[0],y=!_(g,e.resourceBase),x=D1(e,n,p,g,y),b=y?q1(e.context,e.root,e.referenceBase,g,p,e.ids):void 0;return{schema:p,retrievedResource:x,resolvedResource:b}}function U1(e,n){let i=Rc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return tl(e.context,i,e.lexicalBase,n.$recursiveRef,!1)}function B1(e,n){return F1(e.context,e.root,e.lexicalBase,e.lexicalSchema,n,e.dynamicAnchors)}var _r=function(e,n,i,c){if(i==="a"&&!c)throw TypeError("Private accessor was defined without a getter");if(typeof n==="function"?e!==n||!c:!n.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?c:i==="a"?c.call(e):c?c.value:n.get(e)},Sr,nl,S0,dh,rl,y0,x0,I0,b0,ph,lh,fh,hh,E0,w0;class Li{constructor(e,n){Sr.add(this),this.context=e,this.schema=n,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return _r(this,Sr,"m",dh).call(this,this.ids)}Push(e){if(!fn(e))return;if(xo(e))_r(this,Sr,"m",fh).call(this,e);if(cc(e))this.anchors.push(e);if(Rc(e))this.recursiveAnchors.push(e);if(qs(e))this.dynamicAnchors.push(e);let n=this.retrievedResources.get(e);if(n)this.retrievedFrames.push({schema:n.root,base:n.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!fn(e))return;if(xo(e))_r(this,Sr,"m",hh).call(this,e);if(cc(e))this.anchors.pop();if(Rc(e))this.recursiveAnchors.pop();if(qs(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();_r(this,Sr,"m",w0).call(this,e)}Ref(e){let n=j1(_r(this,Sr,"m",nl).call(this),e);return _r(this,Sr,"m",S0).call(this,n),n.schema}RecursiveRef(e){let n=U1(_r(this,Sr,"m",nl).call(this),e);if(n)this.pendingResource=!0;return n}DynamicRef(e){let n=B1(_r(this,Sr,"m",nl).call(this),e);if(n)this.pendingResource=!0;return n}}Sr=new WeakSet,nl=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:_r(this,Sr,"m",x0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:_r(this,Sr,"m",y0).call(this),resourceBase:_r(this,Sr,"m",rl).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},S0=function(n){if(!Bt(n.schema))this.pendingResource=!0;if(!Bt(n.resolvedResource))_r(this,Sr,"m",E0).call(this,n.resolvedResource.target,n.resolvedResource.resource);if(!Bt(n.retrievedResource))this.retrievedResources.set(n.retrievedResource.target,{base:n.retrievedResource.base,root:n.retrievedResource.root})},dh=function(n){let i=this.retrievedFrames[this.retrievedFrames.length-1],c=i?new URL(i.base):new URL(Zp);return(i?n.slice(i.idDepth):n).reduce((g,y)=>new URL(y.$id,g),c).href},rl=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(!n)return _r(this,Sr,"m",dh).call(this,this.resourceIds);return this.resourceIds.slice(n.resourceDepth).reduce((i,c)=>new URL(c.$id,i),new URL(n.base)).href},y0=function(){if(this.retrievedFrames.length>0)return _r(this,Sr,"m",rl).call(this);let n=this.ids[this.ids.length-1];if(n&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(n.$id))return this.LexicalBaseURL();return _r(this,Sr,"m",rl).call(this)},x0=function(){let n=this.retrievedFrames[this.retrievedFrames.length-1];if(n)return this.ids.length>n.idDepth?this.ids[this.ids.length-1]:n.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},I0=function(n){n.forEach((i)=>_r(this,Sr,"m",ph).call(this,i,!1))},b0=function(n){n.forEach((i)=>_r(this,Sr,"m",lh).call(this,i,!1))},ph=function e(n,i=!0){if(Ds(n))return;if(Be(n))return _r(this,Sr,"m",I0).call(this,n);if(!fn(n))return;let c=n;if(!i&&xo(c))return;if(!i&&qs(c))this.dynamicAnchors.push(c);for(let p of Se(c))_r(this,Sr,"m",e).call(this,c[p],!1)},lh=function e(n,i=!0){if(Ds(n))return;if(Be(n))return _r(this,Sr,"m",b0).call(this,n);if(!fn(n))return;let c=n;if(!i&&xo(c))return;if(!i&&qs(c))this.dynamicAnchors.pop();for(let p of Se(c))_r(this,Sr,"m",e).call(this,c[p],!1)},fh=function(n){this.ids.push(n);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(n);_r(this,Sr,"m",ph).call(this,n,!0)},hh=function(n){if(this.ids.pop(),this.resourceIds.length>0&&_(this.resourceIds[this.resourceIds.length-1],n))this.resourceIds.pop();_r(this,Sr,"m",lh).call(this,n,!0)},E0=function(n,i){_r(this,Sr,"m",fh).call(this,i),this.resolvedResources.set(n,i)},w0=function(n){if(!this.resolvedResources.has(n))return;let i=this.resolvedResources.get(n);_r(this,Sr,"m",hh).call(this,i),this.resolvedResources.delete(n)};function G1(e){let n=e.Functions().join(`;
29
+ `),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${n}; return (value) => { ${i.join("; ")} }`}function K1(e,n){return Ky("CheckContext","Guard","Format","Hashing",e.External().identifier,n)(_n,z,eu,Yi,e.External().variables)}function H1(e){let n=new Li(e.Context(),e.Schema()),i=new _n;return(c)=>At(n,i,e.Schema(),c)}function W1(e,n){return Gy()?K1(e,n):H1(e)}class T0{constructor(e,n,i){this.isAccelerated=e,this.code=n,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class R0{constructor(e,n,i,c,p,g){this.context=e,this.schema=n,this.external=i,this.functions=c,this.entry=p,this.useUnevaluated=g}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=G1(this),n=W1(this,e);return new T0(Gy(),e,n)}}function ol(...e){let[n,i]=Sn(e,{2:(b,S)=>[b,S],1:(b)=>[{},b]});AR(),l0();let c=new Li(n,i),p=new Mf(kR(n,i)),g=Gs(c,p,i,"value"),y=d0(),x=CR();return new R0(n,i,x,y,g,p.UseUnevaluated())}function sl(...e){let[n,i,c]=Sn(e,{3:(T,A,C)=>[T,A,C],2:(T,A)=>[{},T,A]}),p=new Li(n,i),g=new Dn,y=mr(p,g,"#","",i,c),x=g.GetErrors(),b=Zy(),S=x.map((T)=>({...T,message:b(T)}));return[y,S]}function yh(...e){let[n,i,c]=Sn(e,{3:(y,x,b)=>[y,x,b],2:(y,x)=>[{},y,x]}),p=new Li(n,i),g=new _n;return At(p,g,i,c)}function Xt(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return yh(n,i,c)}function Cs(...e){let[n,i,c]=Sn(e,{3:(y,x,b)=>[y,x,b],2:(y,x)=>[{},y,x]}),[p,g]=sl(n,i,c);return g}class da extends Error{constructor(e,n,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:n},writable:!1,configurable:!1,enumerable:!1})}}function k0(e,n,i){if(!Be(i))return i;return i.map((c)=>hn(e,n.items,c))}function A0(e,n,i){return hn({...e,...n.$defs},sn(n.$ref),i)}function J1(e,n){let i=le(n,"unevaluatedProperties")?{additionalProperties:n.unevaluatedProperties}:{},c=Ao(e,n),p=Tn(c);return Qe(p)?hp(p,i):p}function C0(e,n,i){let c=J1(e,n);return hn(e,c,i)}function il(e){return le(e,"additionalProperties")?e.additionalProperties:void 0}function P0(e,n,i){if(!at(i)||Be(i))return i;let c=il(n);for(let p of Se(i)){if(le(n.properties,p)){i[p]=hn(e,n.properties[p],i[p]);continue}if(cn(c)&&_(c,!0)||Pr(c)&&Xt(e,c,i[p])){i[p]=hn(e,c,i[p]);continue}delete i[p]}return i}function $0(e,n,i){if(!at(i))return i;let c=il(n),[p,g]=[new RegExp(dn(n)),fr(n)];for(let y of Se(i)){if(p.test(y)){i[y]=hn(e,g,i[y]);continue}if(cn(c)&&_(c,!0)||Pr(c)&&Xt(e,c,i[y])){i[y]=hn(e,c,i[y]);continue}delete i[y]}return i}function M0(e,n,i){return le(e,n.$ref)?hn(e,e[n.$ref],i):i}function v0(e,n,i){if(!Be(i))return i;let c=Math.min(i.length,n.items.length);for(let p=0;p<c;p++)i[p]=hn(e,n.items[p],i[p]);return Ki(i.length,c)?i.slice(0,c):i}function Gr(e){return Ra(e)}function O0(e,n,i){for(let c of n.anyOf){let p=hn(e,c,Gr(i));if(Xt(e,c,p))return p}return i}function hn(e,n,i){return wt(n)?k0(e,n,i):Qt(n)?A0(e,n,i):He(n)?C0(e,n,i):Qe(n)?P0(e,n,i):Gt(n)?$0(e,n,i):jt(n)?M0(e,n,i):lt(n)?v0(e,n,i):xe(n)?O0(e,n,i):i}function Q1(e,n){for(let i of Se(e)){if(le(n,i))continue;n[i]=e[i]}return n}function X1(e){let n={};for(let i of Se(e))n[i]=Lc(e[i]);return n}function Y1(e){return xh(aR(e))}function xh(e){return e.map((n)=>Lc(n))}function Lc(e){let n=wt(e)?B(Lc(e.items),ka(e)):He(e)?Cn(xh(e.allOf)):xe(e)?m(Y1(e.anyOf)):Qe(e)?s(X1(e.properties)):Gt(e)?Ss(oi(e),Lc(fr(e))):lt(e)?Ur(xh(e.items)):e;return Q1(e,n)}function tu(e){return Lc(e)}function _o(...e){let[n,i,c]=Sn(e,{3:(g,y,x)=>[g,y,x],2:(g,y)=>[{},g,y]}),p=Qo().unionPrioritySort?tu(i):i;return hn(n,p,c)}function po(e){return at(e)&&le(e,"value")}function Ge(e){return{value:e}}function wr(){return}function Z1(e){return Be(e)?Ge(e):Ge([e])}function ej(e){return _(e,!0)?Ge(BigInt(1)):Ge(BigInt(0))}var tj=/^-?(0|[1-9]\d*)n$/,rj=/^-?(0|[1-9]\d*)\.\d+$/,nj=/^-?(0|[1-9]\d*)$/;function oj(e){return tj.test(e)}function sj(e){return rj.test(e)}function ij(e){return nj.test(e)}function aj(e){let n=e.toLowerCase();return oj(e)?Ge(BigInt(e.slice(0,e.length-1))):sj(e)?Ge(BigInt(e.split(".")[0])):ij(e)?Ge(BigInt(e)):_(n,"false")?Ge(BigInt(0)):_(n,"true")?Ge(BigInt(1)):wr()}function al(e){return Nr(e)?Ge(e):cn(e)?ej(e):_t(e)?Ge(BigInt(Math.trunc(e))):lo(e)?Ge(BigInt(0)):gt(e)?aj(e):Bt(e)?Ge(BigInt(0)):wr()}function uj(e){return _(e,BigInt(0))?Ge(!1):_(e,BigInt(1))?Ge(!0):wr()}function cj(e){return _(e,0)?Ge(!1):_(e,1)?Ge(!0):wr()}function mj(e){return _(e.toLowerCase(),"false")?Ge(!1):_(e.toLowerCase(),"true")?Ge(!0):_(e,"0")?Ge(!1):_(e,"1")?Ge(!0):wr()}function _0(e){return Nr(e)?uj(e):cn(e)?Ge(e):_t(e)?cj(e):lo(e)?Ge(!1):gt(e)?mj(e):Bt(e)?Ge(!1):wr()}function pj(e){return _(e,BigInt(0))?Ge(null):wr()}function lj(e){return _(e,!1)?Ge(null):wr()}function dj(e){return _(e,0)?Ge(null):wr()}function fj(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(null):wr()}function hj(e){return Nr(e)?pj(e):cn(e)?lj(e):_t(e)?dj(e):lo(e)?Ge(null):gt(e)?fj(e):Bt(e)?Ge(null):wr()}var L0=BigInt(Number.MAX_SAFE_INTEGER),N0=BigInt(Number.MIN_SAFE_INTEGER);function gj(e){return e<=L0&&e>=N0?Ge(Number(e)):wr()}function yj(e){return Ge(e?1:0)}function xj(e){let n=+e;if(_t(n))return Ge(n);let i=e.toLowerCase();if(_(i,"false"))return Ge(0);if(_(i,"true"))return Ge(1);let c=al(e);if(po(c))return c.value<=L0&&c.value>=N0?Ge(Number(c.value)):wr();return wr()}function Ih(e){return Nr(e)?gj(e):cn(e)?yj(e):_t(e)?Ge(e):lo(e)?Ge(0):gt(e)?xj(e):Bt(e)?Ge(0):wr()}function D0(e){return Nr(e)?Ge(e.toString()):cn(e)?Ge(e.toString()):_t(e)?Ge(e.toString()):lo(e)?Ge("null"):gt(e)?Ge(e):Bt(e)?Ge(""):wr()}function Ij(e){return _(e,BigInt(0))?Ge(void 0):wr()}function bj(e){return _(e,!1)?Ge(void 0):wr()}function Ej(e){return _(e,0)?Ge(void 0):wr()}function Sj(e){let n=e.toLowerCase();return _(n,"undefined")||_(n,"null")||_(e,"")||_(e,"0")?Ge(void 0):wr()}function q0(e){return Nr(e)?Ij(e):cn(e)?bj(e):_t(e)?Ej(e):lo(e)?Ge(void 0):gt(e)?Sj(e):Bt(e)?Ge(e):wr()}function F0(e,n,i){return Z1(i).value.map((p)=>Jr(e,n.items,p))}function j0(e,n,i){let c=al(i);return po(c)?c.value:i}function U0(e,n,i){let c=_0(i);return po(c)?c.value:i}function B0(e,n,i){return Jr({...e,...n.$defs},sn(n.$ref),i)}function G0(e,n,i){return Jr(e,Tn(n),i)}function K0(e,n,i){let c=Ih(i);return po(c)?Math.trunc(c.value):i}function H0(e,n,i){let c=Ao(e,n),p=Tn(c);return Jr(e,p,i)}function wj(e,n,i){let c=al(i);return po(c)&&_(n.const,c.value)?c.value:i}function Tj(e,n,i){let c=_0(i);return po(c)&&_(n.const,c.value)?c.value:i}function Rj(e,n,i){let c=Ih(i);return po(c)&&_(n.const,c.value)?c.value:i}function kj(e,n,i){let c=D0(i);return po(c)&&_(n.const,c.value)?c.value:i}function W0(e,n,i){if(_(n.const,i))return i;return cx(n)?wj(e,n,i):mx(n)?Tj(e,n,i):Im(n)?Rj(e,n,i):bm(n)?kj(e,n,i):qr()}function z0(e,n,i){let c=hj(i);return po(c)?c.value:i}function V0(e,n,i){let c=Ih(i);return po(c)?c.value:i}function ul(e,n,i,c){let p=Se(c);for(let[g,y]of n)for(let x of p)if(!g.test(x))c[x]=Jr(e,i,c[x]);return c}function Nc(e,n,i){return an(e)&&Bt(i[n])}function Aj(e,n,i){let c=md(n.properties),p=Se(i);for(let[g,y]of c)for(let x of p){if(!g.test(x)||Nc(y,x,i))continue;i[x]=Jr(e,y,i[x])}return le(n,"additionalProperties")&&at(n.additionalProperties)?ul(e,c,n.additionalProperties,i):i}function J0(e,n,i){return Jo(i)?Aj(e,n,i):i}function Cj(e,n,i){let c=md(n.patternProperties),p=Se(i);for(let[g,y]of c)for(let x of p)if(g.test(x))i[x]=Jr(e,y,i[x]);return le(n,"additionalProperties")&&at(n.additionalProperties)?ul(e,c,n.additionalProperties,i):i}function Q0(e,n,i){return Jo(i)?Cj(e,n,i):i}function X0(e,n,i){return le(e,n.$ref)?Jr(e,e[n.$ref],i):i}function Y0(e,n,i){let c=D0(i);return po(c)?c.value:i}function Z0(e,n,i){return Jr(e,Tn(n),i)}function eC(e,n,i){if(!Be(i))return i;for(let c=0;c<Math.min(n.items.length,i.length);c++)i[c]=Jr(e,n.items[c],i[c]);return i}function tC(e,n,i){let c=q0(i);return po(c)?c.value:i}function rC(e,n,i){if(n.anyOf.some((y)=>Xt(e,y,i)))return i;let g=n.anyOf.map((y)=>Jr(e,y,Gr(i))).find((y)=>Xt(e,n,y));return Bt(g)?i:g}function nC(e,n,i){let c=q0(i);return po(c)?void 0:i}function Jr(e,n,i){return wt(n)?F0(e,n,i):uo(n)?j0(e,n,i):Wn(n)?U0(e,n,i):Qt(n)?B0(e,n,i):rn(n)?G0(e,n,i):ln(n)?K0(e,n,i):He(n)?H0(e,n,i):yt(n)?W0(e,n,i):bs(n)?z0(e,n,i):kr(n)?V0(e,n,i):Qe(n)?J0(e,n,i):Gt(n)?Q0(e,n,i):jt(n)?X0(e,n,i):nn(n)?Y0(e,n,i):ur(n)?Z0(e,n,i):lt(n)?eC(e,n,i):es(n)?tC(e,n,i):xe(n)?rC(e,n,i):co(n)?nC(e,n,i):i}function us(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Jr(n,i,c)}function oC(e,n,i){if(!Be(i))return i;for(let c=0;c<i.length;c++)i[c]=gn(e,n.items,i[c]);return i}function sC(e,n,i){return gn({...e,...n.$defs},sn(n.$ref),i)}function iC(e,n){if(!Bt(n))return n;return ls(e.default)?e.default():Gr(e.default)}function aC(e,n,i){let c=Ao(e,n),p=Tn(c);return gn(e,p,i)}function uC(e,n,i){if(!at(i))return i;let c=Se(n.properties);for(let p of c){let g=gn(e,n.properties[p],i[p]);if(Bt(g)&&(an(n.properties[p])||!le(n.properties[p],"default")))continue;i[p]=g}if(!Po(n)||cn(n.additionalProperties))return i;for(let p of Se(i)){if(c.includes(p))continue;i[p]=gn(e,n.additionalProperties,i[p])}return i}function cC(e,n,i){if(!at(i))return i;let[c,p]=[new RegExp(dn(n)),fr(n)];for(let g of Se(i)){if(!(c.test(g)&&yo(p)))continue;i[g]=gn(e,p,i[g])}if(!Po(n))return i;for(let g of Se(i)){if(c.test(g))continue;i[g]=gn(e,n.additionalProperties,i[g])}return i}function mC(e,n,i){return le(e,n.$ref)?gn(e,e[n.$ref],i):i}function pC(e,n,i){if(!Be(i))return i;let[c,p]=[n.items,Math.max(n.items.length,i.length)];for(let g=0;g<p;g++)if(g<c.length)i[g]=gn(e,c[g],i[g]);return i}function lC(e,n,i){for(let c of n.anyOf){let p=gn(e,c,Gr(i));if(Xt(e,c,p))return p}return i}function gn(e,n,i){let c=yo(n)?iC(n,i):i;return wt(n)?oC(e,n,c):Qt(n)?sC(e,n,c):He(n)?aC(e,n,c):Qe(n)?uC(e,n,c):Gt(n)?cC(e,n,c):jt(n)?mC(e,n,c):lt(n)?pC(e,n,c):xe(n)?lC(e,n,c):c}function Ks(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return gn(n,i,c)}function ru(e){return(...n)=>{let[i,c,p]=Sn(n,{3:(g,y,x)=>[g,y,x],2:(g,y)=>[{},g,y]});return e.reduce((g,y)=>y(i,c,g),p)}}function Pj(e,n,i){return n["~codec"].decode(i)}function $j(e,n,i){return n["~codec"].encode(i)}function Tr(e,n,i,c){if(!Hn(i))return c;return _(e,"Decode")?Pj(n,i,c):$j(n,i,c)}function Mj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<c.length;p++)c[p]=Cr(e,n,i.items,c[p]);return Tr(e,n,i,c)}function vj(e,n,i,c){let p=Tr(e,n,i,c);if(!Be(p))return p;for(let g=0;g<p.length;g++)p[g]=Cr(e,n,i.items,p[g]);return p}function dC(e,n,i,c){return _(e,"Decode")?Mj(e,n,i,c):vj(e,n,i,c)}function fC(e,n,i,c){return c=Cr(e,{...n,...i.$defs},sn(i.$ref),c),Tr(e,n,i,c)}function hC(e){return e.reduce((n,i)=>({...n,...i}),{})}function gC(e,n){for(let i of n)if(!Ta(e,i))return i;return e}function Oj(e,n,i,c){if(_(i.allOf.length,0))return Tr(e,n,i,c);let p=i.allOf.map((x)=>Cr(e,n,x,_o(x,Gr(c)))),y=p.every((x)=>at(x))?hC(p):gC(c,p);return Tr(e,n,i,y)}function _j(e,n,i,c){if(_(i.allOf.length,0))return Tr(e,n,i,c);let p=Tr(e,n,i,c),g=i.allOf.map((x)=>Cr(e,n,x,_o(x,Gr(p))));if(g.every((x)=>at(x)))return hC(g);return gC(p,g)}function yC(e,n,i,c){return _(e,"Decode")?Oj(e,n,i,c):_j(e,n,i,c)}function Lj(e,n,i,c){if(!Jo(c))return c;for(let p of Se(i.properties)){if(!le(c,p)||Nc(i.properties[p],p,c))continue;c[p]=Cr(e,n,i.properties[p],c[p])}return Tr(e,n,i,c)}function Nj(e,n,i,c){let p=Tr(e,n,i,c);if(!Jo(p))return p;for(let g of Se(i.properties)){if(!le(p,g)||Nc(i.properties[g],g,p))continue;p[g]=Cr(e,n,i.properties[g],p[g])}return p}function xC(e,n,i,c){return _(e,"Decode")?Lj(e,n,i,c):Nj(e,n,i,c)}function Dj(e,n,i,c){if(!Jo(c))return c;let p=new RegExp(dn(i));for(let g of Se(c)){if(!p.test(g))continue;c[g]=Cr(e,n,fr(i),c[g])}return Tr(e,n,i,c)}function qj(e,n,i,c){let p=Tr(e,n,i,c);if(!Jo(p))return p;let g=new RegExp(dn(i));for(let y of Se(p)){if(!g.test(y))continue;p[y]=Cr(e,n,fr(i),p[y])}return p}function IC(e,n,i,c){return _(e,"Decode")?Dj(e,n,i,c):qj(e,n,i,c)}function bC(e,n,i,c){return le(n,i.$ref)?Cr(e,n,n[i.$ref],c):c}function EC(e,n,i,c){return _(e,"Decode")?Tr(e,n,i,bC(e,n,i,c)):bC(e,n,i,Tr(e,n,i,c))}function Fj(e,n,i,c){if(!Be(c))return c;for(let p=0;p<Math.min(i.items.length,c.length);p++)c[p]=Cr(e,n,i.items[p],c[p]);return Tr(e,n,i,c)}function jj(e,n,i,c){let p=Tr(e,n,i,c);if(!Be(p))return c;for(let g=0;g<Math.min(i.items.length,p.length);g++)p[g]=Cr(e,n,i.items[g],p[g]);return p}function SC(e,n,i,c){return _(e,"Decode")?Fj(e,n,i,c):jj(e,n,i,c)}function Uj(e,n,i,c){for(let p of i.anyOf){if(!Xt(n,p,c))continue;let g=Cr(e,n,p,c);return Tr(e,n,i,g)}return c}function Bj(e,n,i,c){let p=Tr(e,n,i,c);for(let g of i.anyOf){let y=Cr(e,n,g,Gr(p));if(!Xt(n,g,y))continue;return y}return p}function wC(e,n,i,c){return _(e,"Decode")?Uj(e,n,i,c):Bj(e,n,i,c)}function Cr(e,n,i,c){return wt(i)?dC(e,n,i,c):Qt(i)?fC(e,n,i,c):He(i)?yC(e,n,i,c):Qe(i)?xC(e,n,i,c):Gt(i)?IC(e,n,i,c):jt(i)?EC(e,n,i,c):lt(i)?SC(e,n,i,c):xe(i)?wC(e,n,i,c):Tr(e,n,i,c)}class TC extends da{constructor(e,n){super("Decode",e,n)}}function Gj(e,n,i){if(!Xt(e,n,i))throw new TC(i,Cs(e,n,i));return i}function Kj(e,n,i){let c=Qo().unionPrioritySort?tu(n):n;return Cr("Decode",e,c,i)}var Hj=ru([(e,n,i)=>Gr(i),(e,n,i)=>Ks(e,n,i),(e,n,i)=>us(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>Gj(e,n,i),(e,n,i)=>Kj(e,n,i)]);function bh(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Hj(n,i,c)}class RC extends da{constructor(e,n){super("Encode",e,n)}}function Wj(e,n,i){if(!Xt(e,n,i))throw new RC(i,Cs(e,n,i));return i}function zj(e,n,i){let c=Qo().unionPrioritySort?tu(n):n;return Cr("Encode",e,c,i)}var Vj=ru([(e,n,i)=>Gr(i),(e,n,i)=>zj(e,n,i),(e,n,i)=>Ks(e,n,i),(e,n,i)=>us(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>Wj(e,n,i)]);function Eh(...e){let[n,i,c]=Sn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Vj(n,i,c)}function Jj(e,n){return Hn(n)||Ni(e,n.items)}function Qj(e,n){return Hn(n)||kC({...e,...n.$defs},sn(n.$ref))}function Xj(e,n){return Hn(n)||n.allOf.some((i)=>Ni(e,i))}function Yj(e,n){return Hn(n)||Se(n.properties).some((i)=>Ni(e,n.properties[i]))}function Zj(e,n){return Hn(n)||Ni(e,fr(n))}function kC(e,n){if(Sh.has(n.$ref))return!1;return Sh.add(n.$ref),Hn(n)||le(e,n.$ref)&&Ni(e,e[n.$ref])}function eU(e,n){return Hn(n)||n.items.some((i)=>Ni(e,i))}function tU(e,n){return Hn(n)||n.anyOf.some((i)=>Ni(e,i))}function Ni(e,n){return wt(n)?Jj(e,n):Qt(n)?Qj(e,n):He(n)?Xj(e,n):Qe(n)?Yj(e,n):Gt(n)?Zj(e,n):jt(n)?kC(e,n):lt(n)?eU(e,n):xe(n)?tU(e,n):Hn(n)}var Sh=new Set;function wh(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return Sh.clear(),Ni(n,i)}class cs extends Error{constructor(e,n){super(n);this.type=e}}function AC(e,n){return ls(n.default)?n.default(n):at(n.default)?Gr(n.default):n.default}function CC(e,n){if(Ai(n)&&!yo(n))throw new cs(n,"Arrays with uniqueItems constraints must specify a default annotation");let i=Ii(n)?n.minItems:0;return Array.from({length:i},()=>Qr(e,n.items))}function PC(e,n){return ts(n)?BigInt(n.exclusiveMinimum)+BigInt(1):rs(n)?BigInt(n.minimum):BigInt(0)}function $C(e,n){return!1}function MC(e,n){let i=Qr(e,n.instanceType);return class{constructor(){Object.assign(this,i)}}}function vC(e,n){return Qr({...e,...n.$defs},sn(n.$ref))}function OC(e,n){return Qr(e,Tn(n))}function _C(e,n){let i=Qr(e,n.returnType);return()=>i}function LC(e,n){return ts(n)&&_t(n.exclusiveMinimum)?n.exclusiveMinimum+1:rs(n)?n.minimum:0}function NC(e,n){let i=Ao(e,n),c=Tn(i);return Qr(e,c)}function DC(e,n){return n.const}function qC(e,n){throw new cs(n,"Cannot create TNever types")}function FC(e,n){return null}function jC(e,n){return ts(n)&&_t(n.exclusiveMinimum)?n.exclusiveMinimum+1:rs(n)?n.minimum:0}function UC(e,n){return(Bt(n.required)?[]:n.required).reduce((c,p)=>({...c,[p]:Qr(e,n.properties[p])}),{})}function BC(e,n){if(pa(n)&&!yo(n))throw new cs(n,"Record with the minProperties constraint must have a default annotation");return{}}function GC(e,n){return le(e,n.$ref)?Qr(e,e[n.$ref]):(()=>{throw new cs(n,"Unable to deref Ref")})()}function KC(e,n){if((la(n)||ca(n))&&!yo(n))throw Error("Strings with format or pattern constraints must specify default");let c=ma(n)?n.minLength:0;return"".padEnd(c)}function HC(e,n){return Symbol()}function WC(e,n){let i=_u(n.pattern);if(nn(i))throw new cs(n,"Unable to create TemplateLiteral due to infinite type expansion");return Qr(e,i)}function zC(e,n){return Array.from({length:n.minItems},(i,c)=>Qr(e,n.items[c]))}function VC(e,n){return}function JC(e,n){if(_(n.anyOf.length,0))throw Error("Unable to create Union with no variants");return Qr(e,n.anyOf[0])}function QC(e,n){return}function Qr(e,n){return yo(n)?AC(e,n):wt(n)?CC(e,n):uo(n)?PC(e,n):Wn(n)?$C(e,n):Yr(n)?MC(e,n):Qt(n)?vC(e,n):rn(n)?OC(e,n):Zr(n)?_C(e,n):ln(n)?LC(e,n):He(n)?NC(e,n):yt(n)?DC(e,n):ao(n)?qC(e,n):bs(n)?FC(e,n):kr(n)?jC(e,n):Qe(n)?UC(e,n):Gt(n)?BC(e,n):jt(n)?GC(e,n):nn(n)?KC(e,n):Es(n)?HC(e,n):ur(n)?WC(e,n):lt(n)?zC(e,n):es(n)?VC(e,n):xe(n)?JC(e,n):co(n)?QC(e,n):void 0}function Ps(...e){let[n,i]=Sn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return Qr(n,i)}class cl extends da{constructor(e,n){super("Parse",e,n)}}function rU(e,n,i){if(!Xt(e,n,i))throw new cl(i,Cs(e,n,i));return i}var XC=ru([(e,n,i)=>Gr(i),(e,n,i)=>Ks(e,n,i),(e,n,i)=>us(e,n,i),(e,n,i)=>_o(e,n,i),(e,n,i)=>rU(e,n,i)]);var oU=s({type:a("insert"),path:l(),value:Rr()}),sU=Object({type:a("update"),path:l(),value:Rr()}),iU=s({type:a("delete"),path:l()}),bOe=m([oU,sU,iU]);class ml{constructor(e,n){this.hasCodec=wh(e,n),this.buildResult=ol(e,n),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(Qo().correctiveParse)return XC(this.Context(),this.Type(),e);throw new cl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Cs(this.Context(),this.Type(),e)}Clean(e){return _o(this.Context(),this.Type(),e)}Convert(e){return us(this.Context(),this.Type(),e)}Create(){return Ps(this.Context(),this.Type())}Default(e){return Ks(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?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[n,i]=Sn(e,{2:(c,p)=>[c,p],1:(c)=>[{},c]});return new ml(n,i)}var ZC=new WeakMap,cU=Symbol.for("TypeBox.Kind");function mU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((n)=>typeof n==="string");return[]}function pU(e,n){switch(n){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function kh(e){try{return tP(e)}catch{return}}function lU(e,n){switch(n){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isFinite(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let i=Number(e);if(Number.isInteger(i))return i}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function dU(e,n){let i=n.properties,c=new Set(i?Object.keys(i):[]);if(i)for(let[p,g]of Object.entries(i)){if(!(p in e))continue;e[p]=ha(e[p],g)}if(n.additionalProperties&&typeof n.additionalProperties==="object")for(let[p,g]of Object.entries(e)){if(c.has(p))continue;e[p]=ha(g,n.additionalProperties)}}function fU(e,n){if(Array.isArray(n.items)){for(let i=0;i<e.length;i++){let c=n.items[i];if(!c)continue;e[i]=ha(e[i],c)}return}if(n.items&&typeof n.items==="object")for(let i=0;i<e.length;i++)e[i]=ha(e[i],n.items)}function eP(e,n){for(let i of n)if(kh(i)?.Check(e))return e;for(let i of n){let c=structuredClone(e),p=ha(c,i);if(kh(i)?.Check(p))return p}return e}function ha(e,n){let i=e;if(Array.isArray(n.allOf))for(let g of n.allOf)i=ha(i,g);if(Array.isArray(n.anyOf))i=eP(i,n.anyOf);if(Array.isArray(n.oneOf))i=eP(i,n.oneOf);let c=mU(n),p=c.length>1&&c.some((g)=>pU(i,g));if(c.length>0&&!p)for(let g of c){let y=lU(i,g);if(y!==i){i=y;break}}if(c.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))dU(i,n);if(c.includes("array")&&Array.isArray(i))fU(i,n);return i}function pl(e,n){if(Array.isArray(e)){if(Array.isArray(n.items))for(let p=0;p<e.length;p++){let g=n.items[p];if(g)pl(e[p],g)}else if(n.items)for(let p of e)pl(p,n.items);return}if(typeof e!=="object"||e===null||!n.properties)return;let i=e,c=new Set(n.required??[]);for(let[p,g]of Object.entries(n.properties)){if(!(p in i))continue;if(i[p]===null&&!c.has(p)&&typeof g.$ref!=="string"&&kh(g)?.Check(null)===!1)delete i[p];else pl(i[p],g)}}function tP(e){let n=e,i=ZC.get(n);if(i)return i;let c=Rh(e);return ZC.set(n,c),c}function hU(e){if(e.keyword==="required"){let c=e.params.requiredProperties?.[0];if(c){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${c}`:c}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function gU(e,n){let i=e.find((c)=>c.name===n.name);if(!i)throw Error(`Tool "${n.name}" not found`);return nu(i,n)}function nu(e,n){let i=structuredClone(n.arguments);pl(i,e.parameters),us(e.parameters,i);let c=tP(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(cU)){let y=ha(i,e.parameters);if(y!==i)if(typeof i==="object"&&i!==null&&typeof y==="object"&&y!==null){for(let x of Object.keys(i))delete i[x];Object.assign(i,y)}else return c.Check(y)?y:i}if(c.Check(i))return i;let p=c.Errors(i).map((y)=>` - ${hU(y)}: ${y.message}`).join(`
30
+ `)||"Unknown validation error",g=`Validation failed for tool "${n.name}":
31
+ ${p}
32
+
33
+ Received arguments:
34
+ ${JSON.stringify(n.arguments,null,2)}`;throw Error(g)}var rP;function Dc(){if(!rP)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return rP}async function nP(e,n,i,c,p,g){let y=iP(n,e),x=[...y],b={...n,messages:[...n.messages,...y]};await c({type:"agent_start"}),await c({type:"turn_start"});for(let S of y)await c({type:"message_start",message:S}),await c({type:"message_end",message:S});return await sP(b,x,i,p,c,g??Dc()),x}async function oP(e,n,i,c,p){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let g=[],y={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await sP(y,g,n,c,i,p??Dc()),g}async function sP(e,n,i,c,p,g){let y=e,x=i,b,S=!1,T=await x.getSteeringMessages?.()||[];while(!0){let A=!0;while(A||T.length>0){let P=[];if(b){let J=await x.prepareNextTurn?.(b);if(J)y=J.context??y,P=J.messages??[],x={...x,model:J.model??x.model,reasoning:J.thinkingLevel===void 0?x.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(T.length===0)T=await x.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let J of iP(y,[...P,...T]))await p({type:"message_start",message:J}),await p({type:"message_end",message:J}),y.messages.push(J),n.push(J);T=[];let L=await x.prepareRequest?.({context:y,model:x.model,thinkingLevel:x.reasoning??"off"},c);if(L)y=L.context??y,x={...x,model:L.model??x.model,reasoning:L.thinkingLevel===void 0?x.reasoning:L.thinkingLevel==="off"?void 0:L.thinkingLevel};let q=await xU(y,x,c,p,g);if(n.push(q),q.stopReason==="error"||q.stopReason==="aborted"){b={message:q,toolResults:[],context:y,newMessages:n},await x.finishTurn?.(b,c),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:n});return}let X=q.content.filter((J)=>J.type==="toolCall"),j=[];if(A=!1,X.length>0){let J=q.stopReason==="length"?await IU(X,p):await bU(y,q,x,c,p);j.push(...J.messages),A=!J.terminate;for(let ee of j)y.messages.push(ee),n.push(ee)}b={message:q,toolResults:j,context:y,newMessages:n};let V=await x.finishTurn?.(b,c);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:n});return}if(S=V?.action==="continue",T=await x.getSteeringMessages?.()||[],A||T.length>0)S=!1}let C=await x.getFollowUpMessages?.()||[];if(C.length>0){S=!1,T=C;continue}if(S){S=!1;continue}break}await p({type:"agent_end",messages:n})}function iP(e,n){let i=-1;for(let T=n.length-1;T>=0;T--)if(n[T].role==="system"){i=T;break}let c=n[i],p=c?n.map((T,A)=>A===i?Ah(c,yU):T):n,g=$o(ne([...e.messages,...p]),(e.tools??[]).map(nt)),y=g.toolsAdded.length===0&&g.toolsRemoved.length===0;if(c){if(y&&!c.toolsAdded?.length&&!c.toolsRemoved?.length)return n;return p.map((T,A)=>A===i?Ah(c,g):T)}if(y)return n;let x=Ah({role:"system",content:"",timestamp:Date.now()},g),b=n.findIndex((T)=>T.role!=="system"),S=b===-1?n.length:b;return[...n.slice(0,S),x,...n.slice(S)]}var yU={toolsAdded:[],toolsRemoved:[]};function Ah(e,{toolsAdded:n,toolsRemoved:i}){let{toolsAdded:c,toolsRemoved:p,...g}=e;return{...g,...n.length>0?{toolsAdded:n}:{},...i.length>0?{toolsRemoved:i}:{}}}async function xU(e,n,i,c,p){let g=e.messages;if(n.transformContext)g=await n.transformContext(g,i);let y=await n.convertToLlm(g),x=ht({messages:y}),b=(n.getApiKey?await n.getApiKey(n.model.provider):void 0)||n.apiKey,S=await p(n.model,x,{...n,apiKey:b,signal:i}),T=async()=>Object.assign(await S.result(),{thinkingLevel:n.reasoning??"off"}),A=null,C=!1;for await(let L of S)switch(L.type){case"start":A=L.partial,e.messages.push(A),C=!0,await c({type:"message_start",message:{...A}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(A)A=L.partial,e.messages[e.messages.length-1]=A,await c({type:"message_update",assistantMessageEvent:L,message:{...A}});break;case"done":case"error":{let q=await T();if(C)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!C)await c({type:"message_start",message:{...q}});return await c({type:"message_end",message:q}),q}}let P=await T();if(C)e.messages[e.messages.length-1]=P;else e.messages.push(P),await c({type:"message_start",message:{...P}});return await c({type:"message_end",message:P}),P}async function IU(e,n){let i=[];for(let c of e){await n({type:"tool_execution_start",toolCallId:c.id,toolName:c.name,args:c.arguments});let p={toolCall:c,result:Ws(`Tool call "${c.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await qc(p,n);let g=Ch(p);await Ph(g,n),i.push(g)}return{messages:i,terminate:!1}}async function bU(e,n,i,c,p){let g=n.content.filter((x)=>x.type==="toolCall"),y=g.some((x)=>e.tools?.find((b)=>b.name===x.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||y)return EU(e,n,g,i,c,p);return SU(e,n,g,i,c,p)}async function EU(e,n,i,c,p,g){let y=[],x=[];for(let b of i){await g({type:"tool_execution_start",toolCallId:b.id,toolName:b.name,args:b.arguments});let S=await uP(e,n,b,c,p),T;if(S.kind==="immediate")T={toolCall:b,result:S.result,isError:S.isError};else{let C=await mP(S,p,cP(b,g));T=await pP(e,n,S,C,c,p)}await qc(T,g);let A=Ch(T);if(await Ph(A,g),y.push(T),x.push(A),p?.aborted)break}return{messages:x,terminate:aP(y)}}async function SU(e,n,i,c,p,g){let y=[];for(let S of i){await g({type:"tool_execution_start",toolCallId:S.id,toolName:S.name,args:S.arguments});let T=await uP(e,n,S,c,p);if(T.kind==="immediate"){let A={toolCall:S,result:T.result,isError:T.isError};if(await qc(A,g),y.push(A),p?.aborted)break;continue}if(y.push(async()=>{if(p?.aborted){let P={toolCall:S,result:Ws("Operation aborted"),isError:!0};return await qc(P,g),P}let A=await mP(T,p,cP(S,g)),C=await pP(e,n,T,A,c,p);return await qc(C,g),C}),p?.aborted)break}let x=await Promise.all(y.map((S)=>typeof S==="function"?S():Promise.resolve(S))),b=[];for(let S of x){let T=Ch(S);await Ph(T,g),b.push(T)}return{messages:b,terminate:aP(x)}}function aP(e){return e.length>0&&e.every((n)=>n.result.terminate===!0)}function wU(e,n){if(!e.prepareArguments)return n;let i=e.prepareArguments(n.arguments);if(i===n.arguments)return n;return{...n,arguments:i}}async function uP(e,n,i,c,p,g=e.tools??[]){let y=g.find((x)=>x.name===i.name);if(!y)return{kind:"immediate",result:Ws(`Tool ${i.name} not found`),isError:!0};try{let x=wU(y,i),b=nu(y,x);if(c.beforeToolCall){let S=await c.beforeToolCall({assistantMessage:n,toolCall:i,args:b,context:e},p);if(p?.aborted)return{kind:"immediate",result:Ws("Operation aborted"),isError:!0};if(S?.block){let T=Ws(S.reason||"Tool execution was blocked");if(S.terminate===!0)T.terminate=!0;return{kind:"immediate",result:T,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Ws("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:y,args:b}}catch(x){return{kind:"immediate",result:Ws(x instanceof Error?x.message:String(x)),isError:!0}}}function cP(e,n){return(i)=>n({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function mP(e,n,i){let c=[],p=!0,g=performance.now(),y=()=>Math.round(performance.now()-g);try{let x=await e.tool.execute(e.toolCall.id,e.args,n,(S)=>{if(!p)return;c.push(Promise.resolve(i(S)))}),b=y();return p=!1,await Promise.all(c),{result:x,isError:x.isError===!0,durationMs:b}}catch(x){let b=y();return p=!1,await Promise.all(c),{result:Ws(x instanceof Error?x.message:String(x)),isError:!0,durationMs:b}}finally{p=!1}}async function pP(e,n,i,c,p,g){let{result:y,isError:x}=c;if(p.afterToolCall)try{let b=await p.afterToolCall({assistantMessage:n,toolCall:i.toolCall,args:i.args,result:y,isError:x,context:e},g);if(b){let S=b.structuredContent??(b.content?void 0:y.structuredContent);if(y={...y,content:b.content??y.content,details:b.details??y.details,usage:b.usage??y.usage,terminate:b.terminate??y.terminate},S===void 0)delete y.structuredContent;else y.structuredContent=S;x=b.isError??x}}catch(b){y=Ws(b instanceof Error?b.message:String(b)),x=!0}return{toolCall:i.toolCall,result:y,isError:x,durationMs:c.durationMs}}function Ws(e){return{content:[{type:"text",text:e}],details:{}}}async function qc(e,n){await n({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function Ch(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 Ph(e,n){await n({type:"message_start",message:e}),await n({type:"message_end",message:e})}function TU(e){return e.filter((n)=>n.role==="system"||n.role==="user"||n.role==="assistant"||n.role==="toolResult")}var RU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},kU={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 AU(e){let n=e?.tools?.slice()??[],i=e?.messages?.slice()??[],c=jn(e?.systemPrompt,n.map(nt));if(i[0]?.role!=="system"&&c)i.unshift(c);return{get systemPrompt(){return Wo(i)},model:e?.model??kU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return n},set tools(p){n=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class $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 Mh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let n=e??{};this._state=AU(n.initialState),this.convertToLlm=n.convertToLlm??TU,this.transformContext=n.transformContext,this.streamFunction=n.streamFn??Dc(),this.getApiKey=n.getApiKey,this.onPayload=n.onPayload,this.onResponse=n.onResponse,this.onProviderStreamEvent=n.onProviderStreamEvent,this.beforeToolCall=n.beforeToolCall,this.afterToolCall=n.afterToolCall,this.finishTurn=n.finishTurn,this.prepareRequest=n.prepareRequest,this.prepareNextTurn=n.prepareNextTurn,this.prepareNextTurnWithContext=n.prepareNextTurnWithContext,this.steeringQueue=new $h(n.steeringMode??"one-at-a-time"),this.followUpQueue=new $h(n.followUpMode??"one-at-a-time"),this.sessionId=n.sessionId,this.thinkingBudgets=n.thinkingBudgets,this.transport=n.transport??"auto",this.maxRetryDelayMs=n.maxRetryDelayMs,this.toolExecution=n.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=Vr(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,n){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let i=this.normalizePromptInput(e,n);await this.runPromptMessages(i)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((n)=>n.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let n=this.steeringQueue.drain();if(n.length>0){await this.runPromptMessages(n,{skipInitialSteeringPoll:!0});return}let i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,n){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(n&&n.length>0)i.push(...n);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,n={}){await this.runWithLifecycle(async(i)=>{await nP(e,this.createContextSnapshot(),this.createLoopConfig(n),(c)=>this.processEvents(c),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await oP(this.createContextSnapshot(),this.createLoopConfig(),(n)=>this.processEvents(n),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let n=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(n)return n=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let n=new AbortController,i=()=>{},c=new Promise((p)=>{i=p});this.activeRun={promise:c,resolve:i,abortController:n},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(n.signal)}catch(p){await this.handleRunFailure(p,n.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,n){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:RU,stopReason:n?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let n=this.activeRun?.abortController.signal;if(!n)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,n)}}function we(e,...n){return Object.assign(e,{aliases:n})}function ga(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function CU(e){let n=[],i="";for(let c of e){if(!/[a-zA-Z0-9]/.test(c)){if(i)n.push(i);i="";continue}if(c>="A"&&c<="Z"&&i&&!/[A-Z]$/.test(i))n.push(i),i="";i+=c}if(i)n.push(i);return n}function lP(e,n){if(e.some((L)=>L.name===n))return n;let i=e.map((L)=>L.name),c=(L)=>i.filter((q)=>ga(q)===L),p=c(ga(n));if(p.length===1&&p[0])return p[0];if(p.length>1)return n;let g=n.split(/[.:/]/).pop()??n,y=g===n?[]:c(ga(g));if(y.length===1&&y[0])return y[0];let x=new Map;for(let L of e)for(let q of L.aliases??[]){let X=ga(q);x.set(X,(x.get(X)??new Set).add(L.name))}let b=(L)=>[...new Set([...c(L),...x.get(L)??[]])],S=b(ga(g));if(S.length===1&&S[0])return S[0];if(S.length>1)return n;let T=CU(g),A=new Set;T.forEach((L,q)=>{A.add(ga(L));let X=T[q+1];if(X)A.add(ga(L+X))});let C=new Set;for(let L of A)for(let q of b(L))C.add(q);let P=[...C];return P.length===1&&P[0]?P[0]:n}function v(e){return e}function bn(e,n){let i=n.indexOf("/");if(i<=0)return;return e.getModel(n.slice(0,i),n.slice(i+1))}function tt(e){return`${e.provider}/${e.id}`}function PU(e,n,i){let c=async(g,y)=>{try{if(n){let b=g instanceof Request?g:void 0;n({at:Date.now(),method:y?.method??b?.method??"GET",url:typeof g==="string"?g:g instanceof URL?g.toString():g.url,headers:dP(y?.headers??b?.headers),body:$U(y?.body!==void 0?y.body:b?.body??void 0)})}}catch{}let x=await e(g,y);if(i)try{let b=Date.now(),{status:S,statusText:T}=x,A=dP(x.headers);if(!x.body)return i({at:b,status:S,statusText:T,headers:A,body:""}),x;let C="",P=new TextDecoder,L=new TransformStream({transform(j,V){V.enqueue(j),C+=P.decode(j,{stream:!0}),i({at:b,status:S,statusText:T,headers:A,body:C})},flush(){C+=P.decode(),i({at:b,status:S,statusText:T,headers:A,body:C})}}),q=x.body.pipeThrough(L),X=new Response(q,x);try{Object.defineProperty(X,"url",{value:x.url})}catch{}return X}catch{}return x},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(c,{preconnect:p})}function dP(e){if(!e||typeof e!=="object")return{};let n={};if(e instanceof Headers)return e.forEach((c,p)=>{n[p]=c}),n;let i=Array.isArray(e)?e:Object.entries(e);for(let c of i)if(Array.isArray(c)&&typeof c[0]==="string"&&typeof c[1]==="string")n[c[0]]=c[1];return n}function $U(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 MU(e,n){return lP(e,n)}function vU(e,n,i){let c=Date.now(),p=new WeakSet,g=(b)=>{if(!b||typeof b!=="object"||!("role"in b)||b.role!=="assistant")return;let S=Date.now(),T=Math.max(10,S-c);b.generationMs=T},y=async(b)=>{if(!i||!b||typeof b!=="object"||!("role"in b)||b.role!=="assistant")return;if(g(b),p.has(b))return;p.add(b),Object.assign(b,await i(b))},x=(b)=>{let S=b?.content;if(!Array.isArray(S))return;for(let T of S)if(T&&T.type==="toolCall"&&typeof T.name==="string")T.name=MU(n(),T.name)};return{async*[Symbol.asyncIterator](){for await(let b of e){let{partial:S,message:T}=b;x(S),await y(T),x(T),yield b}},result:async()=>{let b=await e.result();return g(b),await y(b),x(b),b}}}function Fc(e,n){let i=(n??[]).filter((x)=>x.kind==="path").map((x)=>`<file path=${JSON.stringify(x.data)} />`),c=(n??[]).filter((x)=>x.kind==="text").map((x)=>`<file name=${JSON.stringify(x.name)}>
35
+ ${x.data}
36
+ </file>`),p=(n??[]).filter((x)=>x.kind==="image").map((x)=>({type:"image",data:x.data,mimeType:x.mimeType})),g=(n??[]).filter((x)=>x.kind==="image"&&x.id).map((x)=>`<image id=${JSON.stringify(x.id)} name=${JSON.stringify(x.name)} />`);return{merged:[...i,...c,...g,...e.trim()?[e]:[]].join(`
37
+
38
+ `),images:p}}function vh(e,n){let{merged:i,images:c}=Fc(e,n);return{role:"user",content:c.length>0?[{type:"text",text:i},...c]:i,timestamp:Date.now()}}function fP(e){let n=new Set;for(let x of e.tools){let b=x.name.toLowerCase();if(n.has(b))throw Error(`Tool names collide ignoring case: ${x.name}`);n.add(b)}let i=new Mh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(x,b,S)=>{let{captureRequest:T,captureResponse:A}=e,C=T||A?{...S,fetch:PU(S?.fetch??globalThis.fetch,T?(L)=>T({...L,model:tt(x)}):void 0,A?(L)=>A({...L,model:tt(x)}):void 0)}:S,P=x.api==="openai-completions"||x.api==="openai-responses"?{...x,compat:{...x.compat,supportsDeveloperRole:!1}}:x;return vU(e.models.streamSimple(P,b,C),()=>i.state.tools,e.hooks.response)},convertToLlm:(x)=>x,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:x,model:b})=>{let S=x.messages.findIndex((P)=>P.role!=="system"),T=x.messages.slice(0,S===-1?x.messages.length:S),A=e.hooks.prepare,C=e.hooks.tools?.()??x.tools;if(C){i.state.tools=C;let P=T[0];if(P?.role==="system")T[0]={...P,toolsAdded:C.map(nt),toolsRemoved:void 0}}return{context:{...x,tools:C,messages:await A(T,C,b)}}}:void 0}),c=new Map,p=new Map,g=new WeakSet,y;return i.subscribe((x)=>{if(x.type==="message_update"&&x.message.role==="assistant"){p.clear(),e.hooks.draft(gP(x.message));return}if(x.type==="tool_execution_update"){let S=c.get(x.toolCallId)??Ee(x.toolName,x.args),T=Array.isArray(x.partialResult?.content)?x.partialResult.content.map((A)=>A.type==="text"&&typeof A.text==="string"?A.text:"").join(""):"";p.set(x.toolCallId,{type:"tool_call",id:x.toolCallId,name:S.name,input:S.input,...S.source?{source:S.source}:{},output:T}),e.hooks.draft([...p.values()]);return}if(x.type==="tool_execution_end"){if(p.delete(x.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(x.type!=="message_end")return;if(g.has(x.message)){e.steerConsumed?.(x.message);return}let b=x.message.role==="user"&&y?{type:"user",text:y.text,...y.attachments?.length?{attachments:y.attachments}:{}}:OU(x.message);if(x.message.role==="user")y=void 0;if(b?.type==="assistant"){for(let S of b.parts)if(S.type==="tool_call")c.set(S.id,S)}if(b?.type==="tool_result"){let S=c.get(b.callID);if(S?.source)Object.assign(b,{name:S.name,source:S.source})}if(b)e.hooks.message(b,x.message);if(x.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(x,b)=>{y={text:x,attachments:b};let{merged:S,images:T}=Fc(x,b);return i.prompt(S,T.length>0?T:void 0)},retry:async()=>{let x=i.state.messages;if(x.at(-1)?.role==="assistant")i.state.messages=x.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(x)=>{g.add(x),i.steer(x)},unsteer:(x)=>{let S=i.steeringQueue?.messages;if(!S)return!1;let T=S.indexOf(x);if(T<0){let C=JSON.stringify(x);T=S.findIndex((P)=>JSON.stringify(P)===C)}if(T<0)return!1;let[A]=S.splice(T,1);if(A)g.delete(A);return!0},abort:()=>i.abort()}}function 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 hP(e){let{name:i,source:c}=Ee(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:i,...c?{source:c}:{},output:"\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002",isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:"\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"}],isError:!0,timestamp:Date.now()}}}function gP(e){return e.content.map((n)=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="thinking")return{type:"thinking",text:n.thinking};return{type:"tool_call",id:n.id,...Ee(n.name,n.arguments)}})}function OU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((n)=>n.type==="text"?n.text:"").join("")};case"assistant":return{type:"assistant",parts:gP(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let n=e.content.filter((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...n.length>0?{images:n}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class ut extends Error{errors;constructor(e){super(e.map((n)=>n.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function R(e){return e}import{createHash as yP}from"crypto";import{existsSync as _U}from"fs";import{readFile as xP,realpath as ll}from"fs/promises";import{dirname as LU,isAbsolute as IP,relative as bP,resolve as EP,sep as SP}from"path";var wP=[...Dg];class dl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((n)=>n.message).join("; ")}`);this.errors=e}}class fl{cache=new Map;pending=new Map;async entry(e,n){if(!e){if(n)throw Error("Plugin web entry requires a plugin source path");return}let i=LU(EP(e)),c=EP(i,n??"web.tsx");if(!n&&!_U(c))return;let p=bP(await ll(i),await ll(c));if(IP(p)||p===".."||p.startsWith(`..${SP}`))throw Error("Plugin web entry must stay inside its plugin directory");return c}async build(e,n){let i=this.pending.get(e);if(i)return i;let c=this.compile(e,n);this.pending.set(e,c);try{return await c}finally{this.pending.delete(e)}}async compile(e,n){let i=this.cache.get(e);if(i){let S=!0;for(let[T,A]of i.inputs){let C=await xP(T).catch(()=>{return});if(!C||yP("sha256").update(C).digest("hex")!==A){S=!1;break}}if(S)return i.source;this.cache.delete(e)}let c=await ll(n),p=new Map,g=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:wP,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(S){S.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(T)=>{if(!wP.includes(T.path))throw Error(`Unsupported shared web import: ${T.path}`);return{path:T.path,external:!0}}),S.onLoad({filter:/.*/},async(T)=>{let A=bP(c,await ll(T.path));if(IP(A)||A===".."||A.startsWith(`..${SP}`))throw Error("Plugin web imports must stay inside its plugin directory");let C=await xP(T.path);p.set(T.path,yP("sha256").update(C).digest("hex"));return})}}]}).catch((S)=>{let A=(S instanceof AggregateError?S.errors:[S]).map((C)=>C instanceof Error?C.message:String(C));throw Error(`Plugin web build failed: ${A.join("; ")}`,{cause:S})});if(!g.success)throw new dl(g.logs.filter((S)=>S.level==="error").map((S)=>({file:S.position?.file??null,line:S.position?.line??null,message:S.message})));let y=g.outputs.find((S)=>S.kind==="entry-point"&&S.path.endsWith(".js")),x=g.outputs.find((S)=>S.path.endsWith(".css"));if(!y||g.outputs.some((S)=>S!==y&&S!==x))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let b=await y.text();return this.cache.set(e,{source:b,css:await x?.text(),inputs:p}),b}}function jo(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function $s(e){let n=e;if(typeof n.content==="string")return n.content;return n.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function hl(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
39
+
40
+ `)}function ou(e){return e.content.map((n)=>n.type==="text"?n.text:"[image]").join("")}function su(e){return e.role==="assistant"&&e.content.length>0}function ms(e){let n=[],i=new Map,c=0;for(let p of e){let g=p.raw;if(g.role==="assistant"){if(su(g))c++;for(let y of g.content){if(y.type!=="toolCall")continue;let x={call:y,step:c,message:g};n.push(x),i.set(y.id,x)}}else if(g.role==="toolResult"){let y=i.get(g.toolCallId);if(y)y.result=g}}return n}var gl=new Set(["edit","write"]),TP=new Set(["grep","glob"]);function so(e,n){let i=Ee(e.name,e.arguments).input?.[n];return typeof i==="string"?i:void 0}function RP(e){return[...new Set(ms(e).flatMap((n)=>gl.has(Ee(n.call.name,n.call.arguments).name)&&n.result&&!n.result.isError&&so(n.call,"path")?[so(n.call,"path")]:[]))]}function _h(e){return!e.result?"pending":e.result.isError?"error":"completed"}function yl(e){let n=[{source:"ASSISTANT_TOOL",text:`${Ee(e.call.name,e.call.arguments).name}(${jo(Ee(e.call.name,e.call.arguments).input)}) [${_h(e)}, call=${e.call.id}]`}];if(e.result)n.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:ou(e.result)});return n}function O(e){let n=0,i=0,c=0;for(let p of e){let g=p.codePointAt(0);if(g<=127)n++;else if(g>=19968&&g<=40959||g>=12288&&g<=12351||g>=65280&&g<=65519||g>=131072&&g<=173791)i++;else c++}return Math.max(0,Math.ceil(n/4+i+c/2))}var Lh=8192;function F(e){let n=e,i=0,c="";if(n.role==="system")c=typeof n.content==="string"?n.content:JSON.stringify(n.content);else if(n.role==="user")if(typeof n.content==="string")c=n.content;else for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else if(n.role==="assistant")for(let p of n.content)if(p.type==="text")c+=p.text;else if(p.type==="thinking")c+=p.thinking;else c+=`${p.name}${jo(p.arguments)}`;else if(n.role==="toolResult")for(let p of n.content)if(p.type==="text")c+=p.text;else i++;else c=jo(e);return O(c)+16+i*Lh}function Di(e=[]){return e.reduce((n,i)=>n+O(i.name+i.description+jo(i.parameters))+16,0)}function Fn(e,n){let i=e.replace(/\s+/g," ").trim();if(O(i)<=n)return i;let c=Math.min(i.length,n*4);while(c>0&&O(i.slice(0,c))>n-1)c=Math.floor(c*0.8);return`${i.slice(0,c).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function So(e,n,i=Number.POSITIVE_INFINITY){if(O(e)<=n&&e.length<=i)return e;let c=`
41
+ [... omitted; use history tools for the full text ...]
42
+ `,p=Math.floor((n-O(c))/2);if(p<=0)return"";let g=(y)=>{let x=0,b=Math.max(0,Math.min(e.length,p*4,Math.floor((i-c.length)/2)));while(x<b){let S=Math.ceil((x+b)/2),T=y?e.slice(-S):e.slice(0,S);if(O(T)<=p)x=S;else b=S-1}if(!x)return"";return y?e.slice(-x).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,x).replace(/[\uD800-\uDBFF]$/,"")};return`${g(!1)}${c}${g(!0)}`}function xl(e,n){if(O(e.join(`
43
+ `))<=n)return e;let i=(T)=>`- [... ${T} steps omitted; use history tools for the full text ...]`,c=n-O(i(e.length)),p=[],g=[],y=0,x=0,b=e.length-1;while(x<=b){let T=p.length<=g.length,A=T?e[x]:e[b],C=O(`${A}
44
+ `);if(y+C>c)break;if(y+=C,T)p.push(e[x++]);else g.unshift(e[b--])}let S=b-x+1;return[...p,...S>0?[i(S)]:[],...g]}function Ms(e){let n=[],i;for(let c of e){let p=c.entry;if(p.type==="run"&&p.state==="start"){i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},n.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=NU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!c.raw)continue;if(!i&&p.type==="user"&&p.notices&&n.length){n.at(-1)?.records.push(c);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},n.push(i);i.records.push(c)}for(let c of n)c.records=Nh(c.records);return n}function Nh(e){if(e.length<=1)return[...e];let n=[],i=[],c=new Set;for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;let y=g.raw?.role;if(y==="assistant"){let b=g.raw.content?.filter((S)=>S.type==="toolCall")??[];if(b.length>0)for(let S of b)c.add(S.id);if(n.push(g),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(y==="toolResult"){let x=g.raw;if(x.toolCallId)c.delete(x.toolCallId);if(n.push(g),c.size===0&&i.length>0)n.push(...i),i=[];continue}if(y==="user"){if(n.length===0){n.push(g);continue}let x=e.slice(p+1).some((b)=>b.raw?.role==="assistant");if(c.size>0||x){i.push(g);continue}n.push(g);continue}n.push(g)}if(i.length>0)n.push(...i);return n}function NU(e,n){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=n.findLast((c)=>c.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&li(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return li(i)?"interrupted":"failed";default:return"interrupted"}}function ya(e){for(let n=e.length-1;n>=0;n--){let i=e[n]?.entry;if(i?.type==="compaction")return i.through}return 0}function Il(e,n){return e.end!==void 0&&e.end<=n&&e.records.every((i)=>i.entry.seq<=n)}function Dh(e,n){return e.find((i)=>i.start<n&&!Il(i,n)&&i.records.some((c)=>c.entry.seq<=n))}function iu(e){let n=ya(e),c=Ms(e).findLast((p)=>p.end!==void 0);if(!c?.end||c.end<=n)return;return c.end}function bl(e){let n=ya(e);return Dh(Ms(e),n)?.end}function jc(e,n){let i=ya(e),c=Ms(e).at(-1);if(!c||c.end!==void 0)return;let p=c.records.filter((T)=>T.entry.seq>i),g=[],y=new Set;for(let T of p){let A=T.raw,C=F(T.raw);if(A.role==="assistant"){for(let P of A.content)if(P.type==="toolCall")y.add(P.id)}else if(A.role==="toolResult")y.delete(A.toolCallId);if(su(A)||!g.length||A.role==="user"&&g.at(-1)?.assistant)g.push({end:T.entry.seq,tokens:C,assistant:su(A),pending:y.size});else{let P=g.at(-1);P.end=T.entry.seq,P.tokens+=C,P.pending=y.size}}let x=g.findLastIndex((T)=>T.assistant),b=0,S;for(let T=g.length-1;T>=0;T--){let A=g[T];if(T<x&&A.assistant&&A.pending===0&&(b<=n||S===void 0))S=A.end;if(b+=A.tokens,b>n&&S!==void 0)break}if(b<=n)return;return S}var kP=2000;function qi(e,n){let i=O(n);if(i<=kP)return n;let c=new TextEncoder().encode(n).length,p=n.split(`
45
+ `).length,g=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${c} bytes, ${p} lines, approximately ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
46
+ `),y="</user-text-reference>",x=kP-O(`${g}
47
+
48
+ ${y}`);if(x<=0)return n;let b=`${g}
49
+ ${So(n,x,n.length-g.length-y.length-3)}
50
+ ${y}`;return b.length<n.length&&O(b)<i?b:n}function AP(e){let n=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return n;if(typeof n.content==="string"){let p=qi(e.entry.seq,n.content);return p===n.content?n:{...n,content:p}}let i=!1,c=n.content.map((p)=>{if(p.type!=="text")return p;let g=qi(e.entry.seq,p.text);if(g!==p.text)i=!0;return g===p.text?p:{...p,text:g}});return i?{...n,content:c}:n}function qh(e,n=!1){let i=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),c=i.flatMap((P)=>{let L=P.raw.content;return typeof L==="string"?[]:L.filter((q)=>q.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,g=e.status==="open"?"interrupted":e.status,y="";if(i.length){let P=n?So(i.map((L)=>$s(L.raw)).join(`
51
+
52
+ `),600):i.map((L,q)=>`<user-message sequence="${q+1}">
53
+ ${qi(L.entry.seq,$s(L.raw))}
54
+ </user-message>`).join(`
55
+
56
+ `);y=[`<chunk-input id="${e.id}" status="${g}"${n?' excerpt="true"':""}>`,P,...n?[p]:[],"</chunk-input>"].join(`
57
+ `)}let b=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,S=b?hl(b):"",T=[];if(g!=="completed"){let P=ms(e.records),L=new Map(P.map((J)=>[J.call,J])),q=P.slice(-3),X=new Set(q.map((J)=>J.message)),j=[],V=[];for(let J of e.records){let ee=J.raw;if(ee.role!=="assistant")continue;let ie=X.has(ee);for(let H of ee.content)if(H.type==="text"&&ee!==b&&H.text.trim())if(ie)V.push(`ASSISTANT: ${Fn(H.text,50)}`);else j.push(`- ASSISTANT: ${Fn(H.text,50)}`);else if(H.type==="toolCall"){let ce=L.get(H);if(!ce)continue;if(ie){if(q.includes(ce))for(let fe of yl(ce))V.push(`${fe.source}: ${So(fe.text,fe.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${H.name}(${Fn(jo(H.arguments),40)}) [${_h(ce)}]`)}}T.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...j.length?[`Earlier steps, oldest first:
58
+ ${xl(j,n?300:800).join(`
59
+ `)}`]:[],...V)}let A=RP(e.records),C=[`<chunk-summary id="${e.id}" status="${g}" folded-messages="${e.records.length}"${n?' excerpt="true"':""}>`,S?n?So(S,600):S:"No final assistant response was recorded.",...T,...A.length?[`Recorded file changes:
60
+ ${So(A.join(`
61
+ `),250)}`]:[],...n&&g==="completed"?[p]:[],"</chunk-summary>"].join(`
62
+ `);return{input:y,images:c,summary:C,tokens:DU(y,C,c.length)}}function DU(e,n,i){return(e?O(e)+16:0)+O(n)+16+i*Lh}var qU=["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."],FU="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,UU=80,BU=240;function CP(e,n,i){let c=[],p=0,g=Math.min(n.target,n.hard);for(let x=e.length-1;x>=0;x--){let b=e[x],S=qh(b),T=p+S.tokens>g?qh(b,!0):void 0,A=T&&T.tokens<S.tokens?T:S;if(!(!i&&x===e.length-1&&b.status!=="completed")&&p+A.tokens>n.hard)break;p+=A.tokens,c.push({run:b,content:A})}c.reverse();let y=e.slice(0,e.length-c.length);return{visible:c,archived:y,tokens:p}}function PP(e){let{runs:n,visible:i,archived:c,partial:p}=e,g=c.flatMap((b)=>{let S=b.records.filter((A)=>A.raw.role==="user"&&!(A.entry.type==="user"&&A.entry.notices)).map((A)=>$s(A.raw));if(!S.length)return[];let T=b===n[0]?BU:UU;return[`- ${b.id} [${b.status}]: ${Fn(S.join(" / "),T)}`]}),y=new Map(n.map((b,S)=>[b,S+1])),x=[...i.map((b)=>y.get(b)??0),...p?[n.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...qU,...p?[FU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${c.length}`,`archived chunk IDs: ${c.length?c.map((b)=>b.id).join(", "):"none"}`,`visible sequences: ${x.length?`${x[0]}..${x.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...g.length?["archived requests, oldest first:",So(g.join(`
63
+ `),jU)]:[],"</conversation-checkpoint>"].join(`
64
+ `)}function $P(e,n){let i=e.split(`
65
+ `),c=n.split(`
66
+ `),p=new Set(i),g=new Set(c),y=[...i.filter((b)=>b.trim()&&!g.has(b)).map((b)=>`- ${Fn(b,40)}`),...c.filter((b)=>b.trim()&&!p.has(b)).map((b)=>`+ ${Fn(b,40)}`)],x=i.find((b)=>b.trim()&&g.has(b));return[...y.slice(0,6),...y.length>6?[`\u2026 ${y.length-6} more changed lines`]:[],...x&&y.every((b)=>b.startsWith("+"))?[`@ ${Fn(x,40)}`]:[]]}function El(e,n){if(!n)return e;let i=n.endsWith("/")?n:`${n}/`;return e.startsWith(i)?e.slice(i.length):e}function GU(e){let n=e.arguments?.paths;if(!Array.isArray(n))return[];return n.flatMap((i)=>{let c=i&&typeof i==="object"?i.path:void 0;return typeof c==="string"?[c]:[]})}function KU(e,n){let i=so(e,"path");if(gl.has(e.name)&&i)return`file:${El(i,n)}`;let c=so(e,"command");if(c)return`command:${c}`;return`${e.name}:${jo(e.arguments)}`}function HU(e,n){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},c=new Map;for(let g of ms(e)){let y=c.get(g.step)??[];y.push(g),c.set(g.step,y)}let p=new Map;for(let g of e){let y=g.raw;if(!su(y))continue;let x=++i.steps,b=hl(y);if(b)i.narration.push({step:x,text:Fn(b,60)});for(let{call:S,result:T}of c.get(x)??[]){if(!T)continue;let A=Ee(S.name,S.arguments),C={...S,name:A.name,arguments:A.input},P=KU(C,n),L=ou(T);if(T.isError){let ee=so(C,"command"),ie=ee?`${C.name} \`${Fn(ee,40)}\``:`${C.name} ${P.startsWith("file:")?P.slice(5):Fn(jo(C.arguments),40)}`,H={step:x,key:P,what:ie,detail:So(L.trim().split(`
67
+ `).slice(0,8).join(`
68
+ `),200)};i.errors.push(H);let ce=p.get(P)??[];ce.push(H),p.set(P,ce);continue}for(let ee of p.get(P)??[])ee.resolved=x;p.delete(P);let q=so(C,"path");if(gl.has(C.name)&&q){let ee=El(q,n),ie=i.files.get(ee)??{count:0,first:x,last:x,diffs:[]};if(ie.count++,ie.last=x,ie.diffs.push({step:x,lines:C.name==="edit"?so(C,"old_string")!==void 0?$P(so(C,"old_string")??"",so(C,"new_string")??""):[]:$P("",so(C,"content")??"")}),ie.diffs.length>3)ie.diffs.shift();i.files.set(ee,ie);continue}let X=C.name==="read"?[...q?[q]:[],...GU(C)]:[];if(X.length){for(let ee of X){let ie=El(ee,n),H=i.reads.get(ie)??[];H.push(x),i.reads.set(ie,H)}continue}if(TP.has(C.name)){let ee=q?` in ${El(q,n)}`:"",ie=C.name==="grep"&&so(C,"glob")?` (${so(C,"glob")})`:"",H=`${C.name} ${so(C,"pattern")??""}${ee}${ie}`.replace(/\s+/g," "),ce=i.searches.get(H)??{steps:[],head:""};ce.steps.push(x),ce.head=Fn(L.trim().split(`
69
+ `)[0]??"",25),i.searches.set(H,ce);continue}let j=so(C,"command");if(j){let ee=L.trim().split(`
70
+ `);i.commands.push({step:x,command:Fn(j,40),exit:"0",lines:ee.length,tail:ee.slice(-3).map((ie)=>Fn(ie,40))});continue}let V=`${C.name} ${Fn(jo(C.arguments),40)}`,J=i.other.get(V)??[];J.push(x),i.other.set(V,J)}}return i}function MP(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Uc(e,n,i){let c=(S,T)=>T===void 0||!S.length?S:xl(S,T),p=[`<work-state chunk="${n.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${n.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],g=[...e.files];p.push("",`## Modified files (${g.length})`),g.forEach(([S,T],A)=>{if(p.push(`- ${S}: ${T.count} change${T.count>1?"s":""} (step ${T.first}${T.last!==T.first?`-${T.last}`:""})`),A<g.length-i.diffFiles)return;for(let C of T.diffs)p.push(` step ${C.step}:`,...C.lines.map((P)=>` ${P}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((S)=>S.resolved?`- step ${S.step} ${S.what} (resolved at step ${S.resolved})${i.lists===void 0?`: ${S.detail.replace(/\n/g,`
71
+ `)}`:""}`:`- step ${S.step} ${S.what} (UNRESOLVED): ${S.detail.replace(/\n/g,`
72
+ `)}`)),p.push("","## Steps",...c(e.narration.map((S)=>`- ${S.step}. ${S.text}`),i.narration));let y=[...e.reads].map(([S,T])=>`- ${S} @ ${T.join(",")}`);p.push("",`## Files read (${y.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...c(y,i.lists));let x=[...e.searches].map(([S,T])=>`- ${S} \u2192 ${T.head||"(no output)"} (${MP(T.steps)})`);p.push("",`## Searches (${x.length})`,...c(x,i.lists));let b=e.commands.map((S)=>[`- ${S.step}. \`${S.command}\` exit=${S.exit}, ${S.lines} output lines, last ${S.tail.length}:`,...S.tail.map((T)=>` ${T}`)].join(`
73
+ `));if(p.push("",`## Commands (${b.length})`,...c(b,i.lists)),e.other.size){let S=[...e.other].map(([T,A])=>`- ${T} (${MP(A)})`);p.push("",`## Other tool calls (${S.length})`,...c(S,i.lists))}return p.push("</work-state>"),p.join(`
74
+ `)}function Sl(e,n,i,c){let p=HU(e,c),g=Uc(p,n,{diffFiles:Number.POSITIVE_INFINITY});if(O(g)<=i)return g;let y={...p,narration:[]};for(let S of[Number.POSITIVE_INFINITY,20,10,5]){let T=O(Uc(y,n,{diffFiles:S}));if(T>i*0.7)continue;return Uc(p,n,{narration:Math.max(500,i-T),diffFiles:S})}let x=Math.max(300,Math.floor(i*0.1)),b=O(Uc(y,n,{diffFiles:0,lists:x}));return Uc(p,n,{narration:Math.max(500,i-b),diffFiles:0,lists:x})}function wl(e){return{role:"user",content:e,timestamp:0}}function Fh(e,n){return{role:"assistant",content:[{type:"text",text:e}],api:n.api,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function vP(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:wl(e.input)}function au(e){let n=[];for(let i of e){let c=n.at(-1),p=i;if(c?.role==="user"&&p.role==="user"){let g=(y)=>typeof y.content==="string"?[{type:"text",text:y.content}]:y.content;n[n.length-1]={...p,content:[...g(c),{type:"text",text:`
75
+
76
+ `},...g(p)]};continue}n.push(i)}return n}function WU(e,n){if(typeof n!=="string")return n;if(e==="data"&&n.length>160)return`${n.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(n.length-96).toLocaleString()} \u5B57\u7B26]`;if(n.length>2400)return`${n.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(n.length-1600).toLocaleString()} \u5B57\u7B26]`;return n}function ke(e,n,i,c={}){let p=ya(e),g=Ms(e),y=g.filter((be)=>Il(be,p)),x=Dh(g,p),b=[],S=[],T=0;for(let be of g){if(Il(be,p))continue;let se=[];for(let me of be.records){if(be===x&&me.entry.seq<=p)continue;let qe=me.raw.role==="user"?AP(me):me.raw;T+=F(qe),b.push(qe),se.push(qe)}if(c.inspect&&se.length)S.push({id:`recent-${be.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${be.id}`,tokens:se.reduce((me,qe)=>me+F(qe),0),detail:JSON.stringify(se,WU,2)})}if(!y.length&&!x)return{items:S,messages:au(b),visible:0,archived:0,open:T,tokens:T,untrimmed:T};let A=CP(y,i,!!x),{visible:C,archived:P}=A,L=A.tokens,q=[],X="",j="";if(x){let be=x.records.filter((me)=>me.entry.seq<=p),se=be.filter((me)=>me.entry.type==="user"&&!me.entry.notices&&me.raw.role==="user");if(se.length){X=[`<chunk-input id="${x.id}" status="partial">`,...se.map((qe,xt)=>`<user-message sequence="${xt+1}">
77
+ ${qi(qe.entry.seq,$s(qe.raw))}
78
+ </user-message>`),"</chunk-input>"].join(`
79
+ `);let me=se.flatMap((qe)=>{let xt=qe.raw.content;return typeof xt==="string"?[]:xt.filter((Je)=>Je.type==="image")});q.push(me.length?{role:"user",content:[{type:"text",text:X},...me],timestamp:0}:wl(X))}j=Sl(be,x,i.index,c.cwd),q.push(Fh(j,n))}let V=e.flatMap((be)=>{let se=be.raw;if(be.entry.seq>p||se?.role!=="toolResult"||se.toolName!=="skill")return[];return[wl(se.content.filter((me)=>me.type==="text").map((me)=>me.text).join(`
80
+ `))]}),J="",ee=()=>{J=PP({runs:y,visible:C.map((se)=>se.run),archived:P,partial:!!x,tokens:L,budget:i});let be=[wl(J)];for(let{content:se}of C){if(se.input)be.push(vP(se));be.push(Fh(se.summary,n))}return[...be,...V,...q]},ie=(be)=>be.reduce((se,me)=>se+F(me),0),H=ee(),ce=ie(H)+T,fe=ce,{trim:_e}=c;while(_e&&_e.fixed+ce>_e.limit){let be=x||C.at(-1)?.run.status==="completed"?C:C.slice(0,-1);if(!be.length)break;let se=0,me=0;for(let qe of be)if(me++,se+=qe.content.tokens,se>=_e.fixed+ce-_e.limit)break;P=[...P,...C.slice(0,me).map((qe)=>qe.run)],C=C.slice(me),L-=se,H=ee(),ce=ie(H)+T}return{items:c.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:F(H[0]),detail:J},...C.map(({run:be,content:se})=>({id:be.id,label:`Chunk ${be.id}`,state:"sealed",tokens:(se.input?F(vP(se)):0)+F(Fh(se.summary,n)),detail:[se.input,se.summary].filter(Boolean).join(`
81
+
82
+ `)})),...P.map((be)=>({id:be.id,label:`Chunk ${be.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...x?[{id:x.id,label:`Chunk ${x.id}`,state:"folded",tokens:ie(q),detail:[X,j].filter(Boolean).join(`
83
+
84
+ `)}]:[],...S]:[],messages:au([...H,...b]),visible:C.length,archived:P.length,open:T,tokens:ce,untrimmed:fe}}function uu(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var jh=0.97,zU=0.97,OP=0.5,VU=0.05,JU=20000,QU=24000;function Bc(e){return{target:JU,hard:QU,index:Math.floor(uu(e)*VU)}}function Uh(e){let n=e.usage;return n.totalTokens||n.input+n.output+n.cacheRead+n.cacheWrite}class Gc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,n,i=()=>{return}){this.records=e;this.fold=n;this.cwd=i}budget(e){return Bc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let n=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(n>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,n/this.lastEstimate))}previewLimit(e){return Math.floor(uu(e)*jh/this.ratio)}prepare(e,n,i,c){let p=uu(i),g=Bc(i),y=e.reduce((H,ce)=>H+F(ce),0)+Di(n),x=this.records().at(-1)?.entry.seq??0,b=()=>c?[...c,...this.records().filter((H)=>H.entry.seq>x)]:this.records(),S=()=>ke(b(),i,g,{cwd:this.cwd(),trim:{fixed:y,limit:Math.floor(p*jh/this.ratio)}}),T=b().findLast((H)=>H.raw?.role==="assistant"),A=T?b().filter((H)=>H.entry.seq>T.entry.seq&&H.raw):[],C=T?.raw,P=()=>T!==void 0&&(T.entry.seq===this.reshapedAfter||b().some((H)=>H.entry.type==="compaction"&&H.entry.seq>T.entry.seq)),L=this.dueSeal(i);if(L!==void 0)this.fold(L,!1),this.reshapedAfter=T?.entry.seq??-1;let q=S(),X=A.reduce((H,ce)=>H+F(ce.raw),0);if(this.lastEstimate===0&&T&&C&&!P()){let H=C.usage.input+C.usage.cacheRead+C.usage.cacheWrite,ce=y+q.untrimmed-F(C)-X;if(H>0&&ce>0)this.ratio=Math.min(2,Math.max(0.5,H/ce))}let V=((H)=>{let ce=y+H.untrimmed,fe=y+H.tokens;return((T&&C&&!P()&&Uh(C)>0?Uh(C)+Math.round(this.ratio*X):void 0)??Math.round(ce*this.ratio))-Math.round((ce-fe)*this.ratio)})(q);if(V>p*zU){let H=V-q.open*this.ratio,ce=Math.max(1000,Math.floor((p*OP-H-g.index)/this.ratio)),fe=T?.entry.seq??-1,_e=b().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,be=Math.max(this.lastFoldSeq,_e),me=(be>0?b().filter((qe)=>qe.entry.seq>be&&qe.raw?.role==="assistant").length:999)<=1;if(!me||this.consecutivePartialFolds<2){let qe=jc(b(),ce);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=fe,this.lastFoldSeq=fe,this.consecutivePartialFolds=me?this.consecutivePartialFolds+1:1,q=S()}}else this.consecutivePartialFolds=0;this.lastEstimate=y+q.tokens;let J=q.messages,ee=y+q.tokens;if(Math.round(ee*this.ratio)>p)J=XU(J,Math.floor((p-y)/this.ratio)),ee=y+J.reduce((H,ce)=>H+F(ce),0);return this.lastEstimate=ee,{messages:au([...e,...J]),estimate:ee}}settle(e){let n=this.dueSeal(e);if(n===void 0)return;this.fold(n,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let n=this.records();if(bl(n)===void 0){let i=n.findLast((x)=>x.raw?.role==="assistant"),c=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||n.some((x)=>x.entry.type==="compaction"&&x.entry.seq>i.entry.seq)),y=(i?n.filter((x)=>x.entry.seq>i.entry.seq&&x.raw):[]).reduce((x,b)=>x+F(b.raw),0);if(p||!c||Uh(c)+y<Math.floor(uu(e)*jh))return}return iu(n)}recover(e){let n=uu(e),i=Bc(e),c=ke(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((n*OP-(n-c.open*this.ratio)-i.index)/this.ratio),g=jc(this.records(),p);if(g===void 0)return!1;return this.fold(g,!0),this.reshapedAfter=this.records().findLast((y)=>y.raw?.role==="assistant")?.entry.seq??-1,!0}}function XU(e,n){let i=e.reduce((p,g)=>p+F(g),0);if(i<=n)return e;let c=[];for(let p of e){let g=p;if(g.role!=="toolResult"||i<=n){c.push(p);continue}let y=F(p);if(y<=1500){c.push(p);continue}let x=Math.max(500,Math.floor(y/2)),b=g.content.map((A)=>{if(A.type!=="text")return A;return{...A,text:So(A.text,x)}}),S={...g,content:b},T=F(S);i-=y-T,c.push(S)}return c}var YU=2000;function cu(e,n){let i=[];for(let c of n.replace(/\r\n/g,`
85
+ `).split(`
86
+ `))for(let p=0;p<Math.max(c.length,1);){let g=Math.min(c.length,p+YU);if(g<c.length&&/[\uD800-\uDBFF]/.test(c.charAt(g-1)))g--;i.push({source:e,text:c.slice(p,g)}),p=g>p?g:p+1}return i}function mu(e){let n=[],i=ms(e.records),c=new Map(i.map((g)=>[g.call,g])),p=new Set(i.flatMap((g)=>g.result?[g.result]:[]));for(let g of e.records){let y=g.raw;if(y.role==="user")n.push(...cu(g.entry.type==="user"&&g.entry.notices?"NOTICE":"USER",$s(y)));else if(y.role==="assistant"){for(let x of y.content)if(x.type==="text"&&x.text.trim())n.push(...cu("ASSISTANT",x.text));else if(x.type==="toolCall"){let b=c.get(x);if(b)for(let S of yl(b))n.push(...cu(S.source,S.text))}}else if(y.role==="toolResult"&&!p.has(y))n.push(...cu(y.isError?"TOOL_ERROR":"TOOL_OUTPUT",ou(y)))}return n.map((g,y)=>({chunk:e.id,line:y,...g}))}function Kc(e,n){let i=e.find((c)=>c.entry.seq===n);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return cu("USER",$s(i.raw)).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Hc(e,n){let i=e.find((c)=>c.entry.seq===n)?.entry;if(i?.type!=="extension"||!i.display)return;return cu("EXTENSION",i.display.text).map((c,p)=>({chunk:`seq ${n}`,line:p,...c}))}function Wc(e,n=""){return e.map((i,c)=>{let p=e[c-1],g=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${n}${g?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
87
+ `)}import{join as Cg}from"path";import{existsSync as YP}from"fs";import{realpath as ZP}from"fs/promises";import{dirname as e$,isAbsolute as hB,join as t$,relative as gB,resolve as Vh,sep as yB}from"path";import{existsSync as ZU,watch as eB}from"fs";import{readdir as tB,stat as rB}from"fs/promises";import{basename as Bh,dirname as nB,join as _P,resolve as oB}from"path";class Gh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,n,i,c=150){this.host=e;this.slots=n;this.watching=i;this.debounceMs=c}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,n=[]){let i=[],c=[];for(let x of[...new Set(e)]){let b;try{b=await tB(x)}catch(S){if(S instanceof Error&&"code"in S&&S.code==="ENOENT")continue;throw S}for(let S of b.sort()){let T=_P(x,S),A=(await rB(T)).isDirectory()?_P(T,"index.ts"):T;if(!A.endsWith(".ts")||A.endsWith(".d.ts"))continue;try{c.push({definition:await this.read(A),path:A})}catch(C){let P=Bh(A)==="index.ts"?Bh(nB(A)):Bh(A,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let L={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};i.push({definition:L,path:A}),this.slots.set(P,{definition:L,path:A,enabled:!0,discoveryFailed:!0,error:C instanceof Error?C.message:String(C)})}}}let p=n.filter((x)=>![...c,...i].some((b)=>b.definition.id===x.definition.id)),g=[...p,...c],y=this.order(g.map(({definition:x})=>x));for(let x of y){let b=g.find((T)=>T.definition===x)?.path,S=p.some((T)=>T.definition===x);try{await this.host.install(x,b,S)}catch(T){this.slots.set(x.id,{definition:x,path:b,builtin:S,enabled:!0,error:T instanceof Error?T.message:String(T)})}}if(this.watching())for(let x of[...g,...i]){if(!ZU(x.path))continue;let b=eB(x.path,()=>{let S=x.definition.id,T=this.debounceTimers.get(S);if(T)clearTimeout(T);let A=setTimeout(()=>{this.debounceTimers.delete(S),this.host.reload(S).catch((C)=>{let P=this.slots.get(S);if(P)P.error=C instanceof Error?C.message:String(C)})},this.debounceMs);A.unref?.(),this.debounceTimers.set(S,A)});b.on("error",(S)=>{let T=this.slots.get(x.definition.id);if(T)T.error=S.message,this.host.changed()}),this.watchers.push(b)}}order(e,n=!1){let i=new Map;for(let x of e){if(this.validate(x),i.has(x.id)||!n&&this.slots.has(x.id))throw Error(`Duplicate plugin: ${x.id}`);i.set(x.id,x)}let c=[],p=new Set,g=new Set,y=(x)=>{if(g.has(x.id))return;if(p.has(x.id))throw Error(`Plugin dependency cycle: ${x.id}`);p.add(x.id);for(let b of x.deps??[]){let S=i.get(b);if(S)y(S);else if(!this.slots.has(b))throw Error(`Missing plugin dependency: ${b}`)}p.delete(x.id),g.add(x.id),c.push(x)};for(let x of e)y(x);return c}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((n)=>typeof n!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let n=await import(`${oB(e)}?v=${++this.revision}`);if(!n.default)throw Error("Plugin module must export a default definition");return this.validate(n.default),n.default}}async function LP(e,n,i=!1){if(!Number.isSafeInteger(n)||n<1||n>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let c=new AbortController,p;try{return await Promise.race([i?Promise.resolve(e(c.signal)):Promise.resolve().then(()=>e(c.signal)),new Promise((g,y)=>{p=setTimeout(()=>{c.abort(),y(Error(`Plugin callback timed out after ${n}ms`))},n)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as sB}from"async_hooks";import{isDeepStrictEqual as NP}from"util";var xa=new sB;function vs(){let e=xa.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function pu(e){let n=structuredClone(e),i=(c)=>{if(!c||typeof c!=="object"||Object.isFrozen(c))return;Object.freeze(c);for(let p of Object.values(c))i(p)};return i(n),n}function DP(e,n){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Entry replacement must be a body");for(let b of["seq","time","session_id","raw"])if(b in n)throw Error(`Entry replacement contains protected field: ${b}`);let i=JSON.parse(JSON.stringify(n,(b,S)=>{if(typeof S==="function"||typeof S==="symbol"||typeof S==="number"&&!Number.isFinite(S))throw Error("Entry replacement must contain JSON values");return S}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let c=i,p=[];switch(e.type){case"user":p.push("text","attachments");break;case"assistant":p.push("parts","error");break;case"tool_result":p.push("output","images");break;case"extension":p.push("payload","display");break;case"notice_pending":p.push("notice");break;case"run":if(e.state==="end")p.push("error");break;case"compaction":break}let g={...e};for(let b of new Set([...Object.keys(e),...Object.keys(c)])){if(!p.includes(b)&&!NP(g[b],c[b]))throw Error(`Entry replacement changed protected field: ${b}`);if(["seq","time","session_id","raw"].includes(b))throw Error(`Entry replacement contains protected field: ${b}`)}let y=(b)=>b===void 0||typeof b==="string",x=!0;switch(e.type){case"user":x=typeof c.text==="string"&&(c.attachments===void 0||Array.isArray(c.attachments)&&c.attachments.every((b)=>b&&typeof b.name==="string"&&typeof b.mimeType==="string"&&em.includes(b.kind)&&typeof b.data==="string"));break;case"assistant":x=y(c.error)&&Array.isArray(c.parts)&&c.parts.every((b)=>b&&(["text","thinking"].includes(b.type)&&typeof b.text==="string"||b.type==="tool_call"&&typeof b.id==="string"&&typeof b.name==="string"&&("input"in b)));break;case"tool_result":x=typeof c.output==="string"&&(c.images===void 0||Array.isArray(c.images)&&c.images.every((b)=>b&&typeof b.mimeType==="string"&&typeof b.data==="string"));break;case"extension":{let b=c.display;x="payload"in c&&(b===void 0||b!==null&&typeof b==="object"&&("text"in b)&&typeof b.text==="string"&&(!("title"in b)||y(b.title)));break}case"notice_pending":{let S=["text"],T=g.notice,A=c.notice;if(x=!!A&&typeof A==="object"&&!Array.isArray(A),!x)break;let C=A;for(let P of new Set([...Object.keys(T),...Object.keys(C)]))if(S.includes(P)){if(typeof C[P]!=="string")x=!1}else if(!NP(T[P],C[P]))x=!1;break}case"run":x=y(c.error);break;case"compaction":break}if(!x)throw Error("Invalid entry replacement content");return i}function qP(e,n,i,c,p,g){let y=c;for(let x of i.generations)for(let b of x.hooks.get("entry.before_append")??[]){if(x.disabled)break;let S={phase:"before",violated:!1};try{let T=xa.run(S,()=>{let A=pu(y),C=performance.now(),P=b(A,{sessionID:p,seq:g});if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")throw Promise.resolve(P).catch(()=>{}),Error("entry.before_append must be synchronous");let L=P===void 0?void 0:DP(y,P);if(S.violated)throw Error("entry.before_append attempted a database write");if(performance.now()-C>e)throw Error("entry.before_append exceeded budget");return L});if(T&&JSON.stringify(T)!==JSON.stringify(y))y=T;x.beforeFailures=0,x.failures=0}catch(T){x.failures=x.beforeFailures++,n(x,T)}}return y}function iB(e,n){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return n;if(e==="entry.after_append")return pu(n);return structuredClone(n)}async function FP(e,n,i,c,p,g,y,x,b="end"){let S=g;for(let T of c){if(T.disabled)continue;let A=T.hooks.get(p)??[];for(let C of A){if(T.disabled)break;let P=T.hookOptions.get(C);if(p==="prompt.fragments"&&(P?.promptPosition??"end")!==b)continue;let L=p==="prompt.fragments"?JSON.stringify([y?.id,S]):void 0,q=L===void 0?void 0:T.promptCache.get(C)?.get(L);try{let X=iB(p,S),j=P?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:y,connection:x}):j,J=await n((ee)=>C(X,{runtime:e.runtime,session:y,connection:x,signal:ee}),V);if(L!==void 0){let ee=J===void 0?S:J;if(!Array.isArray(ee)||ee.some((H)=>typeof H!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(ee))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let ie=T.promptCache.get(C)??new Map;ie.set(L,[...ee]),T.promptCache.set(C,ie)}if(T.failures=0,J!==void 0&&p!=="entry.after_append")S=J}catch(X){if(q)S=structuredClone(q);if(i(T,X),P?.errorMode==="propagate")throw X}}}return S}class zc{host;generations;released=!1;constructor(e,n){this.host=e;this.generations=n}async invoke(e,n,i,c,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,n,i,c,p)}has(e,n){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((c)=>n===void 0||(i.hookOptions.get(c)?.promptPosition??"end")===n))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((n)=>({...n,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${n.name}`);return n.execute(...i)}})))}waiting(e){return this.generations.some((n)=>!n.disabled&&n.gates.some((i)=>i(e)))}resolveHistory(e,n){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let c of i.historyResolvers){let p=c(e,n);if(p)return p}}}policy(e){return this.generations.findLast((n)=>!n.disabled&&n.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as aB}from"fs";import{dirname as uB,resolve as jP}from"path";var Kh=new WeakMap;function UP(e){return[...e].map((n)=>{let i=Boolean(n.path&&(Boolean(n.definition.webEntry)||aB(jP(uB(jP(n.path)),"web.tsx"))));if(n.current&&!Kh.has(n.current))Kh.set(n.current,crypto.randomUUID());return{id:n.definition.id,description:n.definition.description,builtin:n.builtin??!1,web:n.enabled&&!n.current?.disabled?n.current?.web??[]:[],webBundle:i,webRevision:n.current?Kh.get(n.current):void 0,version:n.definition.version,deps:n.definition.deps??[],status:!n.enabled?"disabled":n.current?.disabled||!n.current?"error":"enabled",error:n.error??n.current?.error,registrations:n.current?[...[...n.current.hooks.keys()].map((c)=>({kind:"hook",name:c})),...n.current.tools.map((c)=>({kind:"tool",name:c.name})),...n.current.routes.map((c)=>({kind:"route",method:c.method,path:c.path})),...n.current.websockets.map((c)=>({kind:"websocket",path:c.path})),...n.current.commands.map((c)=>({kind:"command",id:c.id})),...n.current.web.map((c)=>({kind:"web",id:c.id})),...[...n.current.policies.keys()].map((c)=>({kind:"policy",id:c})),...n.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class Hh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,n,i){this.host=e;this.deadline=n;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,n,i){let c=this.host.pin(),p=(async()=>{try{let g=[];for(let y of c.generations){if(y.disabled)continue;for(let x of y.hooks.get(e)??[]){let b=y.hookOptions.get(x)?.timeoutMs,S=typeof b==="function"?b({runtime:this.host.runtime,session:n,connection:i}):b;g.push(this.deadline((T)=>x(n,{runtime:this.host.runtime,session:n,connection:i,signal:T}),S,!0).catch((T)=>this.fail(y,T)))}}await Promise.all(g)}finally{await c.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,n,i){let c=i===void 0?void 0:pu(i),p=(this.entryQueues.get(n)??Promise.resolve()).then(async()=>{try{if(c)await xa.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",c,this.host.runtime.get(n)))}finally{await e.release()}});this.entryQueues.set(n,p),this.pending.add(p);let g=()=>{if(this.pending.delete(p),this.entryQueues.get(n)===p)this.entryQueues.delete(n)};p.then(g,g)}}function BP(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 cB(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 mB(e,n){let i=n.sessionID?e.get(n.sessionID):void 0;if(n.sessionID&&!i)throw Error("Completion session not found");let c=n.model??i?.model??e.options.defaultModel;if(typeof c!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=bn(e.options.models,c);if(!p&&n.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(n.model===void 0||!p){let g=(await e.models()).models.filter((x)=>x.available===!0),y=p?tt(p):c;if(!g.some((x)=>x.id===y)){let x=g[0];if(x)p=bn(e.options.models,x.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function GP(e,n){cB(n);let i=await mB(e,n),c=n.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(c)||c<=0||c>i.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(n.signal?.aborted)throw Error("Completion cancelled");let p="",g=!1;try{let y=[...n.system?[{role:"system",content:n.system,timestamp:Date.now()}]:[],{role:"user",content:n.prompt,timestamp:Date.now()}],x=e.options.models.streamSimple(i,{messages:y},{maxTokens:c,signal:n.signal});for await(let b of x){if(n.signal?.aborted)throw Error("cancelled");if(b.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${BP(b.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(b.type==="text_delta")p+=b.delta;if(b.type==="done"){if(b.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(b.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${b.reason}\uFF09`);g=!0}}}catch(y){if(n.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${BP(y instanceof Error?y.message:String(y))}`)}if(n.signal?.aborted)throw Error("Completion cancelled");if(!g)throw Error("Model completion ended without a stop response; retry");return{text:p,model:tt(i)}}var pB=["active","archived","all"];function KP(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function lB(e){let{projectID:n,children:i,archive:c,since:p}=e;if(n!==void 0&&n!==null&&typeof n!=="string")throw Error("sessions projectID must be a string or null");if(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(c!==void 0&&!pB.includes(c))throw Error("sessions archive must be active, archived or all");if(p!==void 0&&!Number.isFinite(p))throw Error("sessions since must be a finite timestamp in milliseconds")}function dB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function HP(e){function n(i,c={}){let{types:p,bodies:g}=c;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let y=KP(c.limit),x=c.after??0;if(!Number.isSafeInteger(x)||x<0)throw Error("sessions after must be a non-negative integer");let b=(e.get(i)?.entries(x)??[]).filter((S)=>p===void 0||p.includes(S.type)).slice(0,y);return structuredClone(g===!1?b.map(dB):b)}return{list(i={}){lB(i);let c=i.limit===void 0?void 0:KP(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((g)=>i.projectID===void 0||g.projectID===i.projectID).filter((g)=>i.since===void 0||g.created>=i.since);return structuredClone(c===void 0?p:p.slice(0,c))},get(i){return structuredClone(e.get(i)?.info())},entries:n}}async function WP(e,n,i,c,p,g){let y={definition:n,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},x=e.runtime.store.db,b=new Map,S=!1,T=!0,A=()=>{if(!T||y.disposed)throw Error("Plugin registration scope is closed")},C=(j,V)=>{if(A(),!S){b.set(j,V);return}if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,j);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,j,V)},P={get:(j)=>{A();let V=b.has(j)?b.get(j):x.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(n.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");C(j,J)},delete:(j)=>C(j,null)},L=()=>{if(A(),S)throw Error("Register resources during setup only")},q=[...n.migrations??[]].sort((j,V)=>j.version-V.version),X=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||X.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(X.add(j.version),x.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(n.id,j.version))continue;x.transaction(()=>{if(j.sql!==void 0)x.run(j.sql);else j.up({...P,db:x});for(let[V,J]of b)if(J===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,V);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,V,J);x.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(n.id,j.version)})(),b.clear()}return await c(async()=>n.setup({runtime:e.runtime,sessions:HP(e.runtime),complete:(j)=>GP(e.runtime,j),kv:P,database:x,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{L(),y.gates.push(j)},registerNoticeSource:(j,V)=>{if(L(),!j||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");y.noticeSources.set(j,{...V})},provide:(j,V)=>{if(L(),j.pluginID!==n.id)throw Error("Service key must belong to the providing plugin");if(y.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);y.services.set(j.name,V)},on:(j,V,J)=>{if(L(),J?.promptPosition&&j!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let ee=y.hooks.get(j)??[];if(ee.push(V),y.hooks.set(j,ee),J)y.hookOptions.set(V,J)},registerHistoryResolver:(j)=>{L(),y.historyResolvers.push(j)},registerTool:(j,V)=>{if(L(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||fB(e,p,n.id).has(j.name.toLowerCase())||y.tools.some((ee)=>ee.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let J=i?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;y.tools.push({...j,defer:J,source:`plugin:${n.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(L(),!(j.path.startsWith(`/api/plugins/${n.id}/`)||(n.routePrefixes??[]).some((V)=>j.path===V||j.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(j.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(y.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");y.routes.push(j)},registerWebSocket:(j)=>{if(L(),!j.path.startsWith(`/api/plugins/${n.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(y.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");y.websockets.push(j)},registerCommand:(j)=>{L(),y.commands.push(j)},registerWebContribution:(j)=>{L(),y.web.push(j)},registerToolPolicy:(j,V)=>{L(),y.policies.set(j,V)},appendExtension:(j,V)=>{if(vs(),A(),!S)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{L(),y.deactivators.push(j)},onDispose:(j)=>{L(),y.disposers.push(j)}})),x.transaction(()=>{for(let[j,V]of b)if(V===null)x.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(n.id,j);else x.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(n.id,j,V)})(),b.clear(),S=!0,y}catch(j){throw T=!1,await g(y),j}}function fB(e,n,i){let c=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,g]of n){if(p===i)continue;for(let y of g.current?.tools??[])c.add(y.name.toLowerCase())}return c}class Wh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let n of e.connections)n.close(1012,"Plugin changed");this.retired.add(e);for(let n of e.deactivators.splice(0).reverse())try{await this.deadline(n)}catch(i){e.error=i instanceof Error?i.message:String(i)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let n of e.disposers.reverse())try{await this.deadline(n)}catch(i){e.error=i instanceof Error?i.message:String(i)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function zP(e,n,i,c){for(let p of n){let g=p.current;if(!g||g.disabled||g.retired)continue;let y=g.websockets.find((x)=>x.path===c);if(!y)continue;return{connect:(x)=>{let b=!1;g.references++,g.connections.add(x);let S={send:(A)=>{if(b||g.retired||g.disabled)return;x.send(A)},close:(A,C)=>x.close(A,C)},T=async(A)=>{if(b||g.retired||g.disabled){x.close(1012,"Plugin unavailable");return}try{await i(A),g.failures=0}catch(C){if(g.failures++,g.error=C instanceof Error?C.message:String(C),x.close(1011,"Plugin callback failed"),g.failures>=e.failureThreshold){g.disabled=!0;for(let P of g.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>T(()=>y.open?.(S)),message:(A)=>T(()=>y.message(S,A)),close:async()=>{if(b)return;b=!0,g.connections.delete(x);try{await i(()=>y.close?.(S))}catch(A){g.error=A instanceof Error?A.message:String(A)}finally{g.references--,await e.collect(g)}}}}}}return}function zh(e,n){let i=e.split("/"),c=new URL(n.url).pathname.split("/");if(i.length!==c.length)return;let p={};return i.every((y,x)=>{let b=c[x];if(b===void 0)return!1;if(!y.startsWith(":"))return b===y;try{p[y.slice(1)]=decodeURIComponent(b)}catch{return!1}return b.length>0})?p:void 0}async function VP(e,n,i,c,p){let g=e.pin();try{let y=g.generations.find((x)=>x.definition.id===i)?.commands.find((x)=>x.id===c);if(!y)throw new f("Plugin command is unavailable");return await n(()=>y.execute(p))}finally{await g.release()}}function JP(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.method===n.method&&zh(p.path,n)!==void 0))}finally{i.release()}}function QP(e,n){let i=e.pin();try{return i.generations.some((c)=>c.routes.some((p)=>p.public===!0&&p.method===n.method&&zh(p.path,n)!==void 0))}finally{i.release()}}async function XP(e,n,i){let c=e.pin(),p=!0;try{for(let g of c.generations)for(let y of g.routes){if(y.method!==i.method)continue;let x=zh(y.path,i);if(x){let b=await n(()=>y.handler(i,x),y.timeoutMs);if(!b)return;if(b.body&&b.body instanceof ReadableStream){p=!1;let S=!1,T=()=>{if(S)return;S=!0,c.release()},A=b.body.getReader(),C=new ReadableStream({async pull(P){try{let{done:L,value:q}=await A.read();if(L)P.close(),T();else P.enqueue(q)}catch(L){P.error(L),T()}},async cancel(P){try{await A.cancel(P)}finally{T()}}});return new Response(C,{status:b.status,statusText:b.statusText,headers:b.headers})}return b}}return}finally{if(p)await c.release()}}class 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 fl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,n={}){this.runtime=e;this.options=n;if(n.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(n.beforeAppendBudgetMs)||n.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new Gh(this,this.slots,()=>n.watch===!0,n.watchDebounceMs??150),this.timeoutMs=n.timeoutMs??5000,this.failureThreshold=n.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let n=this.slots.get(e.pluginID);if(!n?.enabled||!n.current||n.current.disabled||n.current.retired)throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=n.current.services.get(e.name);if(!e.validate(i))throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((n)=>n.enabled&&n.current&&!n.current.disabled&&n.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let n=this.pin();try{await n.invoke("project.delete",e)}finally{await n.release()}}exclusive(e){let n=this.serial.then(async()=>{let i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=n.then(()=>{},()=>{}),n}discover(e,n=[]){for(let i of e)this.directories.add(Vh(i));return this.catalog.discover(e,n).finally(()=>this.changed())}async pluginPath(e){let n=await ZP(e),i=[...this.directories,t$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((c)=>t$(c.directory,".basalt","plugins"))];for(let c of i){if(!YP(c))continue;let p=gB(await ZP(c),n);if(p&&p!==".."&&!p.startsWith(`..${yB}`)&&!hB(p)){if(!n.endsWith(".ts")||n.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return n}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let n=await this.pluginPath(e),i=await this.checkEntry(n);if(!i.ok)throw new ut(i.errors);let c=await this.catalog.read(n);return await this.installDefinition(c,n,!1),c.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let n=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:n.success,errors:n.logs.filter((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,n=!1){return this.catalog.order(e,n)}install(e,n,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,n,i)})}async installDefinition(e,n,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let c=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:n,builtin:i,enabled:c?.enabled!==0};if(p.enabled)p.current=await this.stage(e,i);this.slots.set(e.id,p)}reload(e){return this.exclusive(async()=>{let n=this.require(e);if(!n.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!n.builtin){let x=await this.checkEntry(n.path);if(!x.ok)throw new ut(x.errors)}let i=n.builtin&&!YP(n.path)?n.definition:await this.catalog.read(n.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!n.enabled)throw Error("Enable the plugin before reloading");let c=this.order([...this.slots.values()].map((x)=>x.definition.id===e?i:x.definition),!0),p=await this.stage(i),g=n.current;n.definition=i,n.current=p,n.error=void 0,n.discoveryFailed=!1;let y=new Map(this.slots);this.slots.clear();for(let x of c){let b=y.get(x.id);if(b)this.slots.set(x.id,b)}if(g)await this.retirement.retire(g)}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,n){return this.exclusive(async()=>{let i=this.require(e);if(n===i.enabled&&(!n||i.current&&!i.current.disabled))return;if(!n){for(let y of this.slots.values())if(y.enabled&&y.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${y.definition.id}`)}let c=n&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.definition;if(c.id!==e)throw Error("Enable cannot change plugin id");let p=n?await this.stage(c):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(n));let g=i.current;if(i.definition=c,n)i.discoveryFailed=!1;if(i.enabled=n,i.current=p,i.error=void 0,g)await this.retirement.retire(g)})}require(e){if(this.closed)throw Error("Plugin host is closed");let n=this.slots.get(e);if(!n)throw Error(`Plugin not found: ${e}`);return n}async stage(e,n=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let i of e.deps??[])if(i===e.id||!this.slots.get(i)?.current||this.slots.get(i)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${i}`);return WP(this,e,n,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,n,i){this.observers.notify(e,n,i)}resolveHistory(e,n){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let c of i.current.historyResolvers){let p=c(e,n);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((n)=>n.enabled&&n.current&&!n.current.disabled&&n.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((n)=>n.enabled&&n.current&&!n.current.disabled?[n.current]:[]);for(let n of e)n.references++;return new zc(this,e)}async invoke(e,n,i,c,p,g="end"){return FP(this,this.deadline.bind(this),this.fail.bind(this),e,n,i,c,p,g)}pinEntry(e){if(xa.getStore()?.phase==="after")return;let n;for(let i of this.slots.values()){let c=i.current;if(!i.enabled||!c||c.disabled||e.type==="extension"&&e.namespace===c.definition.id)continue;if(!c.hooks.has("entry.before_append")&&!c.hooks.has("entry.after_append"))continue;n??=[],n.push(c),c.references++}if(!n)return;return new zc(this,n)}beforeEntry(e,n,i,c){return qP(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,n,i,c)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,n){if(e.failures++,e.error=n instanceof Error?n.message:String(n),e.failures>=this.failureThreshold){e.disabled=!0;for(let i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,n,i){this.observers.finishEntry(e,n,i)}deadline(e,n=this.timeoutMs,i=!1){return LP(e,n,i)}appendExtension(e,n){return vs(),new Promise((i)=>{let c=this.runtime.get(e);if(!c)throw Error("Extension target session does not exist");if(!n.namespace||!n.kind||!Number.isSafeInteger(n.schemaVersion)||n.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...n});c.refreshEntries(),i(p)})}list(){return UP(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let n=this.require(e),i=await this.webBuilder.entry(n.path,n.definition.webEntry);if(i&&n.path)await this.webBuilder.build(i,e$(Vh(n.path)));return{ok:!0}}catch(n){if(n instanceof dl)return{ok:!1,errors:n.errors};return{ok:!1,errors:[{file:null,line:null,message:n instanceof Error?n.message:String(n)}]}}}async webBundle(e){let n=this.slots.get(e);if(!n?.enabled||!n.path||n.current?.disabled)return;let i=await this.webBuilder.entry(n.path,n.definition.webEntry);if(!i)return;return this.webBuilder.build(i,e$(Vh(n.path)))}async webCSS(e){await this.webBundle(e);let n=this.slots.get(e);if(!n?.enabled||!n.path||n.current?.disabled)return;let i=await this.webBuilder.entry(n.path,n.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,n,i){return VP(this,this.deadline.bind(this),e,n,i)}hasRoute(e){return JP(this,e)}isPublicRoute(e){return QP(this,e)}route(e){return XP(this,this.deadline.bind(this),e)}websocket(e){return zP(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 r$}from"fs";import{join as xB}from"path";var IB=500,bB=1000,EB=3600000,SB=5000,wB=2000,TB=3,RB=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=xB(e.dataDir,Ho),this.features={...qo(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let n=this.engineStatus,i=n?.backfill;if(!n||!i)return{...e,state:"backfilling"};if(i.state==="done"){let c=n.entries;return{...e,state:"ready",lag:n.lag,total:c,indexed:Math.max(0,c-n.lag)}}return{...e,lag:n.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...n.etaSec!==void 0?{etaSec:n.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let n of["","-wal"])try{e+=r$(this.indexPath+n).size}catch{}return e}budget(){let e=0;try{e=r$(this.options.store.path).size}catch{}return Math.max(RB,Math.round(e*0.6))}async setEnabled(e){if(this.closed||e===this.enabledFlag)return;if(this.enabledFlag=e,this.failure=void 0,this.restarts=0,e){if(this.clearTimer)clearInterval(this.clearTimer);if(this.clearTimer=void 0,this.usable)this.start();else this.idleMaintenance()}else await this.stopWorker(),this.idleMaintenance();this.pushStatus()}async rebuild(){if(!this.usable)return;await this.stopWorker(),Jn(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((n)=>{this.flushes.set(e,()=>n(this.status())),this.post({type:"flush",id:e})})}pause(e){let n=this.worker;if(!n)return e();Atomics.store(this.flags,$e,1),n.postMessage({type:"pause"}),Atomics.wait(this.flags,Tt,0,SB);try{return e()}finally{Atomics.store(this.flags,$e,0),Atomics.notify(this.flags,$e)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=Go(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,$e,0),Atomics.store(this.flags,Tt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(n)=>this.receive(e,n.data),e.onerror=(n)=>this.crashed(e,n.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,n){if(e!==this.worker){if(n.type==="stopped")this.stopped?.();return}switch(n.type){case"status":this.update(n.status);break;case"flushed":{this.update(n.status),this.flushes.get(n.id)?.(),this.flushes.delete(n.id);break}case"error":if(n.fatal)this.crashed(e,n.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,n,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<TB&&this.usable)this.restarts++,this.start();else this.failure=n,console.error("search index unavailable:",n),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,$e,0),Atomics.notify(this.flags,$e);let n=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([n,Bun.sleep(wB)]),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,IB-(performance.now()-this.lastPrune));this.pruneTimer=setTimeout(()=>{this.pruneTimer=void 0,this.prune()},e),this.pruneTimer.unref?.()}prune(){let e=this.engineStatus?.queueDone??0;if(e<=this.pruned)return;this.lastPrune=performance.now();try{this.options.store.db.query("DELETE FROM search_queue WHERE id <= ?").run(e),this.pruned=e}catch{}}idleMaintenance(){if(this.engineStatus=void 0,!this.enabledFlag)Jn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),EB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let n=Math.max(0,bB-(performance.now()-this.lastPush)),i=()=>{if(this.statusTimer=void 0,this.closed)return;let c=this.status(),p=JSON.stringify({...c,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(c)};if(n===0)i();else this.statusTimer=setTimeout(i,n),this.statusTimer.unref?.()}}import{existsSync as fu,mkdirSync as MB,readdirSync as m$,readFileSync as i$,realpathSync as Xh,statSync as Cl,writeFileSync as Yh}from"fs";import{dirname as Al,isAbsolute as Zh,relative as p$,resolve as vB}from"path";import{existsSync as Vc}from"fs";import{dirname as $B,join as du}from"path";import{mkdirSync as kB,writeFileSync as AB}from"fs";import{tmpdir as CB}from"os";import{join as n$}from"path";var Tl=2000,Pe=30000;function u(e){return{content:[{type:"text",text:e}],details:void 0}}function lu(e,n){return e.map((i,c)=>{let p=i.length>Tl?`${i.slice(0,Tl)}\u2026 [line truncated]`:i;return`${String(n+c).padStart(6)} ${p}`}).join(`
88
+ `)}function je(e,n){if(e.length<=n)return e;let i=Math.floor(n*0.4),c=n-i,p=e.length-i-c,g=e.slice(i,e.length-c).split(`
89
+ `).length-1;return`${e.slice(0,i)}
90
+
91
+ \u2026 [${p} characters, ~${g} lines omitted] \u2026
92
+
93
+ ${e.slice(-c)}`}var PB=0;function rt(e,n){if(e.length<=n)return e;let i=je(e,n);try{let c=n$(CB(),"basalt-output");kB(c,{recursive:!0});let p=n$(c,`${process.pid}-${Date.now().toString(36)}-${PB++}.txt`);return AB(p,e),`${i}
94
+ [Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return i}}var o$=120000,s$=600000,Ia;function tr(){if(Ia!==void 0)return Ia||void 0;let n=(process.env.PATH??"").split(";").map((c)=>c.trim()).filter(Boolean);for(let c of n){let p=du(c,"bash.exe");if(Vc(p))return Ia=p,p}for(let c of n){let p=du(c,"git.exe");if(Vc(p)){let g=$B(c),y=du(g,"bin","bash.exe");if(Vc(y))return Ia=y,y;let x=du(g,"usr","bin","bash.exe");if(Vc(x))return Ia=x,x}}let i=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?du(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?du(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let c of i)if(Vc(c))return Ia=c,c;Ia="";return}class Rl{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let n=new Uint8Array(this.gbkPending.length+e.length);n.set(this.gbkPending),n.set(e,this.gbkPending.length);let i=0;while(i<n.length){if(n[i]<128){i+=1;continue}let p=n[i+1];if(p===void 0)break;let g=p>=48&&p<=57?4:2;if(i+g>n.length)break;i+=g}return this.gbkPending=n.slice(i),this.gbk.decode(n.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});if(this.isGbk)return this.decodeGbk(e);try{return this.utf8.decode(e,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(e)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(!this.isGbk)return this.utf8.decode();let e=this.gbkPending;return this.gbkPending=new Uint8Array(0),e.length>0?this.gbk.decode(e):""}}function ba(e,n){let i=process.platform==="win32",c=n??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(c==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(c==="bash")return{argv:[tr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(c==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=tr();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,n){let i=await ze(e,n.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:c,isWindows:p}=ba(e,n.shell),g=Bun.spawn(c,{cwd:n.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...n.extraPath?{[Object.keys(process.env).find((ee)=>ee.toLowerCase()==="path")??"PATH"]:n.extraPath}:{}}}),y=!1,x=()=>{try{if(p)g.kill();else process.kill(-g.pid,"SIGKILL")}catch{}},b=setTimeout(()=>{y=!0,x()},n.timeout);n.signal?.addEventListener("abort",x,{once:!0});let S=Pe*2,T="",A="",C=0,P=0,L="",q=(ee=!1)=>{let ie=C-T.length-A.length,H=ie>0?`${T}
95
+ \u2026 [${ie} characters omitted] \u2026
96
+ ${A}`:T+A;if(!ee)return je(H,Pe);return rt(L.length===C?L:H,Pe)},X=()=>{let ee=new Rl;return async(ie)=>{for await(let ce of ie){let fe=ee.decode(ce);if(C+=fe.length,L.length<4000000)L+=fe;if(T.length<S)T+=fe;else A=(A+fe).slice(-S);if(n.onOutput){let _e=performance.now();if(_e-P>=80)P=_e,n.onOutput(q())}}let H=ee.flush();if(H){if(C+=H.length,L.length<4000000)L+=H;if(T.length<S)T+=H;else A=(A+H).slice(-S)}}},j=Promise.all([X()(g.stdout),X()(g.stderr)]),V=await g.exited;if(clearTimeout(b),n.signal?.removeEventListener("abort",x),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))A+=`
97
+ [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,n=Cl(e).mtimeMs){this.seen.set(e,n)}check(e){let n=this.seen.get(e);if(n===void 0)return"unread";return Cl(e).mtimeMs!==n?"changed":void 0}}var a$=2000,OB=500,_B=10485760,kl=20,LB=6,NB=40000,DB=80000;function qB(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 l$(e,n,i=[],c){let p=(L)=>Zh(L)?L:vB(e,L),g=(L)=>{let q=p$(e,L);return q&&!q.startsWith("..")&&!Zh(q)?q:L},y=(L)=>{let q=L;while(!fu(q)&&Al(q)!==q)q=Al(q);let X=Xh(q);if(i.some((j)=>fu(j)&&c$(Xh(j),X))&&!c$(Xh(e),X))throw Error("External directories are read-only")},x=(L,q,X)=>{let j=p(L);if(!fu(j))throw Error(`No such file or directory: ${j}${BB(j)}`);let V=Cl(j);if(V.isDirectory()){let me=m$(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),qe=me.slice(0,OB),xt=me.length-qe.length;return u(`${qe.join(`
98
+ `)}${xt>0?`
99
+ \u2026 and ${xt} more entries`:""}`||"(empty directory)").content}let J=i$(j),ee=qB(J);if(ee){if(V.size>_B)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return n.mark(j),[{type:"text",text:`Read image ${g(j)} (${ee}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:ee}]}if(J.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);n.mark(j);let ie=J.toString("utf8");if(!ie)return u("(empty file)").content;let H=ie.replace(/\r?\n$/,"").split(/\r?\n/),ce=(q??1)-1;if(ce>=H.length)throw Error(`offset ${q} is past the end of the file (${H.length} lines)`);let fe=Math.min(H.length,ce+(X??a$)),_e=0,be=ce;while(be<fe){let me=H[be]?.length??0;if(be>ce&&_e+me>NB)break;_e+=me,be++}let se=lu(H.slice(ce,be),ce+1);if(be<fe)se+=`
100
+
101
+ (Showing lines ${ce+1}-${be} of ${H.length} (truncated at line ${be} due to safety budget). Use offset/limit to read specific windows.)`;else if(ce>0||be<H.length)se+=`
102
+
103
+ (Showing lines ${ce+1}-${be} of ${H.length}. Use offset/limit to read other parts.)`;return u(se).content},b=v({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
104
+ - path may be absolute or relative to the working directory.
105
+ - By default reads up to ${a$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
106
+ - Lines longer than ${Tl} characters are truncated.
107
+ - Reading a directory lists its entries (directories end with /).
108
+ - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
109
+ - To read several files at once, give paths instead of path (up to ${kl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
110
+ - Always read a file before editing or overwriting it.`,parameters:s({path:o(l({description:"File or directory path"})),offset:o(w({minimum:1,description:"1-based line number to start from"})),limit:o(w({minimum:1,description:"Maximum number of lines to return"})),paths:o(B(s({path:l({description:"File or directory path"}),offset:o(w({minimum:1,description:"1-based line number to start from"})),limit:o(w({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:kl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(L,q){let X=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(X.length===0)throw Error("Give path, or paths to read several files");if(X.length===1){let ie=X[0];return{content:x(ie.path,ie.offset,ie.limit),details:void 0}}if(X.length>kl)throw Error(`Read at most ${kl} paths per call`);let j=[],V=[],J=0,ee=(ie)=>{let H=j.at(-1);if(ie.type==="text"&&H?.type==="text")H.text+=`
111
+
112
+ ${ie.text}`;else j.push(ie)};for(let ie of X){let H=`==> ${g(p(ie.path))} <==`;if(J>=DB){ee({type:"text",text:`${H}
113
+ (Skipped due to total read safety budget; read in separate calls)`});continue}try{let ce=x(ie.path,ie.offset,ie.limit);for(let fe=0;fe<ce.length;fe++){let _e=ce[fe];if(!_e)continue;if(_e.type==="text")J+=_e.text.length,ee(fe===0?{..._e,text:`${H}
114
+ ${_e.text}`}:_e);else ee(_e)}}catch(ce){let fe=ce instanceof Error?ce.message:String(ce);V.push(fe),ee({type:"text",text:`${H}
115
+ Error: ${fe}`})}}if(V.length===X.length)throw Error(V.join(`
116
+ `));return{content:j,details:void 0}}}),S=async(L,q,X,j)=>{let V=j?.update,J=await rr(L,{cwd:e,timeout:120000,signal:X,extraPath:c?.extraPath,shell:typeof c?.shell==="function"?c.shell():c?.shell,onOutput:V?(fe)=>V(u(`${j.prefix}
117
+
118
+ $ ${L}
119
+ ${fe.trimEnd()}`)):void 0}),ee=J.output.trimEnd()||"(no output)",ie=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,H=J.timedOut||J.code!==0,ce=H?`
120
+ ${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
121
+
122
+ $ ${L}
123
+ ${ee}
124
+ [${ie}]${ce}`,failed:H}},T=(L,q=!1)=>{let X=n.check(L);if(X==="changed")return`Note: ${g(L)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(X==="unread"&&q)return`Note: ${g(L)} existed and had not been read; it was replaced whole.`;return},A=v({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
125
+ - An existing file is replaced whole, including changes made since you last read it.
126
+ - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
127
+ - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
128
+ - Do not create documentation or README files unless asked.`,parameters:s({path:l({description:"File path"}),content:l({description:"The full file content"}),then_run:o(l({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(L,q,X,j){let V=p(q.path);y(V);let J=fu(V),ee;if(J){if(Cl(V).isDirectory())throw Error(`${V} is a directory`);ee=T(V,!0)}MB(Al(V),{recursive:!0}),Yh(V,q.content),n.mark(V);let ie=q.content?q.content.split(`
129
+ `).length:0,H=`${J?"Overwrote":"Created"} ${g(V)} (${ie} lines)${ee?`
130
+ ${ee}`:""}`;if(q.then_run){let ce=await S(q.then_run,`${g(V)} was written as given`,X,{prefix:H,update:j});if(H+=ce.out,ce.failed)return{...u(H),isError:!0}}return u(H)}}),C=(L,q,X,j)=>{let V=p(L);if(!fu(V))throw Error(`File not found: ${V} (use write to create it)`);y(V);let J=T(V),ee=i$(V,"utf8"),ie=ee,H=ie.includes(`\r
131
+ `),ce=[],fe=[],_e=0,be=0;return q.forEach((se,me)=>{let qe=j?`edits[${X+me}]: `:"";try{if(se.old_string===se.new_string)throw Error(`${qe}old_string and new_string are identical`);if(!se.old_string)throw Error(`${qe}old_string is empty (use write to create or replace a whole file)`);let xt=H&&!se.old_string.includes(`\r
132
+ `),Je=xt?se.old_string.replace(/\n/g,`\r
133
+ `):se.old_string,Yt=xt?se.new_string.replace(/\n/g,`\r
134
+ `):se.new_string,Fe=FB(ie,Je).map((Ct)=>[Ct,Ct+Je.length]);if(Fe.length===0)Fe=jB(ie,Je);if(Fe.length===0)throw Error(`${qe}old_string not found in ${g(V)}; read the relevant lines and copy the exact text.${UB(ie,Je)}`);if(Fe.length>1&&!se.replace_all){let Ct=Fe.map(([st])=>u$(ie,st)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${Ct}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=u$(ie,Fe[0][0]),qt=se.replace_all?Fe:[Fe[0]],dt="",Ot=0;for(let[Ct,st]of qt)dt+=ie.slice(Ot,Ct)+Yt,Ot=st;ie=dt+ie.slice(Ot),_e++,be+=qt.length;let yr=ie.split(/\r?\n/),pr=Ue+Yt.split(/\r?\n/).length-1,Ut=Math.max(1,Ue-1),ot=Math.min(yr.length,pr+1);if(ot-Ut+1<=LB+2)ce.push(lu(yr.slice(Ut-1,ot),Ut));else ce.push(`${lu(yr.slice(Ut-1,Ue+1),Ut)}
135
+ \u2026 (${pr-Ue-3} lines as given)
136
+ ${lu(yr.slice(pr-2,ot),pr-1)}`)}catch(xt){fe.push(xt instanceof Error?xt.message:String(xt))}}),{path:V,original:ee,content:ie,echoes:ce,applied:_e,total:be,count:q.length,note:J,failed:fe}},P=v({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
137
+ - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
138
+ - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
139
+ - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
140
+ - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
141
+ - To create a file use write; to delete or move files use bash.
142
+ - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
143
+ - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:s({path:o(l({description:"File path (the default for edits items without their own path)"})),old_string:o(l({description:"The exact text to replace (only when edits is absent)"})),new_string:o(l({description:"The replacement text (only when edits is absent)"})),replace_all:o(D({description:"Replace every occurrence (default false)"})),edits:o(B(s({path:o(l({description:"The file of this replacement, when it is not path"})),old_string:l({description:"The exact text to replace"}),new_string:l({description:"The replacement text"}),replace_all:o(D({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:o(l({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(L,q,X,j){let V=q.edits&&q.edits.length>0?q.edits.map((se)=>({path:se.path??q.path,step:se})):q.old_string!==void 0&&q.new_string!==void 0?[{path:q.path,step:{old_string:q.old_string,new_string:q.new_string,replace_all:q.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,ee=new Map;V.forEach((se,me)=>{if(!se.path)throw Error(`${J?`edits[${me}]: `:""}path is required`);let qe=p(se.path),xt=ee.get(qe)??{raw:se.path,steps:[],offset:me};xt.steps.push(se.step),ee.set(qe,xt)});let ie=[],H=[];for(let se of ee.values())try{let me=C(se.raw,se.steps,se.offset,J);if(me.applied>0)ie.push(me);H.push(...me.failed)}catch(me){let qe=me instanceof Error?me.message:String(me);H.push(`${J?`edits[${se.offset}]: `:""}${qe}`)}if(ie.length===0)throw Error(H.join(`
144
+ `));let ce=[];try{for(let se of ie)Yh(se.path,se.content),ce.push(se)}catch(se){for(let me of ce)Yh(me.path,me.original);throw se}for(let se of ie)n.mark(se.path);let _e=ie.map((se)=>{let me=se.total===1?"1 occurrence":`${se.total} occurrences`,qe=se.note?`
145
+ ${se.note}`:"";if(!J)return`Edited ${g(se.path)} (${me}).${qe}
146
+ ${se.echoes[0]}`;let xt=se.failed.length>0?`, ${se.failed.length} failed`:"";return`Edited ${g(se.path)} (${se.applied} edits${xt}, ${me}). Regions are shown as they were right after each edit; later edits may shift line numbers.${qe}
147
+ ${se.echoes.map((Je,Yt)=>`--- edit ${Yt+1}
148
+ ${Je}`).join(`
149
+ `)}`}).join(`
150
+
151
+ `),be=!1;if(q.then_run){let se=await S(q.then_run,"The edits above were applied",X,{prefix:_e,update:j});if(_e+=se.out,se.failed)be=!0}if(H.length>0)_e+=`
152
+
153
+ ${H.length===1?"1 edit":`${H.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
154
+ - ${H.join(`
155
+ - `)}`,be=!0;return be?{...u(_e),isError:!0}:u(_e)}});return[we(b,"cat","view","read_file","view_file","open_file","open"),we(A,"write_file","create_file","new_file","save_file"),we(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function FB(e,n){let i=[];for(let c=e.indexOf(n);c!==-1;c=e.indexOf(n,c+n.length))i.push(c);return i}function u$(e,n){let i=1;for(let c=0;c<n;c++)if(e.charCodeAt(c)===10)i++;return i}function jB(e,n){let i=n.replace(/\r?\n$/,"").split(/\r?\n/).map((b)=>b.trimEnd()),c=[],p=e.split(`
156
+ `),g=0;for(let b of p)c.push(g),g+=b.length+1;let y=p.map((b)=>b.replace(/\r$/,"").trimEnd()),x=[];for(let b=0;b+i.length<=y.length;b++)if(i.every((S,T)=>y[b+T]===S)){let S=b+i.length-1,T=c[S]+p[S].replace(/\r$/,"").length,A=n.endsWith(`
157
+ `)&&T<e.length?e[T]==="\r"?2:1:0;x.push([c[b],T+A]),b+=i.length-1}return x}function UB(e,n){let i=(x)=>x.replace(/\s+/g," ").trim(),c=i(n);if(!c)return"";let p=e.split(/\r?\n/),g=n.split(/\r?\n/).length;for(let x=0;x+g<=p.length;x++)if(i(p.slice(x,x+g).join(`
158
+ `))===c)return` A match ignoring whitespace exists at line ${x+1}; copy the exact indentation and line breaks from the read output:
159
+ ${je(lu(p.slice(x,x+g),x+1),4000)}`;let y=n.split(/\r?\n/).find((x)=>x.trim())?.trim();if(y){let x=p.findIndex((b)=>b.includes(y));if(x!==-1)return` Its first line appears at line ${x+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function BB(e){let n=Al(e);if(!fu(n))return"";let c=e.slice(n.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!c)return"";let p=m$(n).filter((g)=>{let y=g.toLowerCase().replace(/\.[^.]*$/,"");return y&&(y.includes(c)||c.includes(y))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function c$(e,n){let i=p$(e,n);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!Zh(i)}var tg=20,rg=80,GB=5,d$=(e)=>e!==void 0&&e>0?e:void 0;function Pl(e,n){let i=(g)=>{if(n)return n(g);if(g.source&&g.source!=="self"||g.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},c=v({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
160
+ - Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
161
+ - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),pattern:l({minLength:1,description:"Text to search for"}),also:o(B(l({minLength:1}),{maxItems:GB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:o(l({description:"Only search this chunk"})),seq:o(w({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:o(D({description:"Default false"})),head_limit:o(w({minimum:1,maximum:tg,description:`Hits to return (default ${tg})`})),offset:o(w({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(g,y){let x=i(y),b=d$(y.seq),S=()=>Ms(x.records),T=`session_id=${x.sessionID}`,A=b!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
162
+ `:"",C;if(b!==void 0){let H=Kc(x.records,b)??Hc(x.records,b);if(!H)throw Error(`No user message with seq ${b}`);C=[H]}else{let H=S(),ce=y.chunk_id?H.filter((fe)=>fe.id===y.chunk_id):H;if(y.chunk_id&&!ce.length)throw Error(`No chunk ${y.chunk_id}. Chunk IDs look like r12.`);C=ce.map(mu)}let P=(H)=>y.case_sensitive?H:H.toLowerCase(),L=[y.pattern,...(y.also??[]).filter(Boolean)].map(P),q=y.head_limit??tg,X=y.offset??0,j=[],V=new Map,J=0;for(let H of C)H.forEach((ce,fe)=>{let _e=P(ce.text);if(!L.every((se)=>_e.includes(se)))return;if(V.set(ce.chunk,(V.get(ce.chunk)??0)+1),J++,J<=X||j.length>=q)return;let be=H.slice(Math.max(0,fe-2),fe+3);j.push(`${T} chunk ${ce.chunk} line ${ce.line}:
163
+ ${Wc(be," ")}`)});if(!J)return u(`${A}No matches`);if(!j.length)return u(`${A}No matches at offset ${X} (total ${J})`);let ee=J-X-j.length,ie=V.size>1?` (all matches by chunk: ${[...V].map(([H,ce])=>`${H} ${ce}`).join(", ")})`:"";return u(`${A}${j.join(`
164
+
165
+ `)}${ee>0?`
166
+
167
+ \u2026 ${ee} more matches${ie}; continue with offset=${X+j.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=v({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:s({source:o(l()),session_id:o(l({description:"Source session ID from the reference"})),chunk_id:o(l({description:"Chunk to read"})),seq:o(w({description:"User message to read (from a user-text-reference)"})),offset:o(w({minimum:0,description:"First line (default 0)"})),limit:o(w({minimum:1,maximum:rg,description:`Lines to return (default ${rg})`}))}),async execute(g,y){let x=i(y),b=d$(y.seq),S=()=>Ms(x.records),T=`session_id=${x.sessionID}`,A=b!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
168
+ `:"",C;if(b!==void 0){if(C=Kc(x.records,b)??Hc(x.records,b),!C)throw Error(`No user message with seq ${b}`)}else if(y.chunk_id){let X=S().find((j)=>j.id===y.chunk_id);if(!X)throw Error(`No chunk ${y.chunk_id}. Chunk IDs look like r12.`);C=mu(X)}else{let X=S().map((j)=>`${T} ${j.id} (${j.status}, ${mu(j).length} lines)`);return u(X.length?`Pass chunk_id or seq. Chunks in this session:
169
+ ${X.join(`
170
+ `)}`:"This session has no history yet")}let P=y.offset??0,L=C.slice(P,P+(y.limit??rg));if(!L.length)return u(`No lines at offset ${P} (total ${C.length})`);let q=C.length-P-L.length;return u(`${A}${T} ${b!==void 0?`seq=${b}`:y.chunk_id}
171
+ ${Wc(L)}${q>0?`
172
+
173
+ \u2026 ${q} more lines; continue with offset=${P+L.length}`:""}`)}});return[c,p]}import{statSync as KB}from"fs";import{isAbsolute as f$,relative as HB,resolve as h$}from"path";var $l=200,WB=30000,Ml=Bun.which("rg");async function ng(e,n,i){let c=Bun.spawn(e,{cwd:n,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,g,y]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(y>1)throw Error(g.trim()||`${e[0]} exited with ${y}`);return p}function g$(e){let n=(g)=>g?f$(g)?g:h$(e,g):e,i=(g)=>{let y=HB(e,g);return y&&!y.startsWith("..")&&!f$(y)?y:g},c=v({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
174
+ - Respects .gitignore and skips .git. Use it instead of find or ls -R.
175
+ - To search file contents, use grep.`,parameters:s({pattern:l({description:"Glob pattern, matched relative to path"}),path:o(l({description:"Directory to search (default: working directory)"}))}),async execute(g,y,x){let b=n(y.path),S;if(Ml)S=(await ng([Ml,"--files","--hidden","--glob","!.git","--glob",y.pattern],b,x)).split(`
176
+ `).filter(Boolean);else{S=[];for await(let P of new Bun.Glob(y.pattern).scan({cwd:b,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(P))S.push(P)}if(!S.length)return u("No files found");let T=S.map((P)=>{let L=h$(b,P);try{return{path:L,time:KB(L).mtimeMs}}catch{return{path:L,time:0}}});T.sort((P,L)=>L.time-P.time);let A=T.slice(0,$l).map((P)=>i(P.path)),C=S.length-A.length;return u(`${A.join(`
177
+ `)}${C>0?`
178
+ \u2026 ${C} more files; narrow the pattern`:""}`)}}),p=v({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
179
+ - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
180
+ - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
181
+ - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
182
+ - Use this instead of running grep or rg through bash.`,parameters:s({pattern:l({description:"Regular expression"}),path:o(l({description:"File or directory to search (default: working directory)"})),glob:o(l({description:"Only search files matching this glob"})),output:o(m([a("files"),a("content"),a("count")],{description:"Output mode (default files)"})),ignore_case:o(D()),context:o(w({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(g,y,x){let b=n(y.path),S=y.output??"files",T;if(Ml){let P=[Ml,"--hidden","--glob","!.git","--max-columns","400","--max-columns-preview"];if(y.ignore_case)P.push("-i");if(y.glob)P.push("--glob",y.glob);if(S==="files")P.push("-l");else if(S==="count")P.push("-c");else if(P.push("-n","--no-heading"),y.context)P.push("-C",String(y.context));P.push("--",y.pattern,b),T=await ng(P,e,x)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(y.ignore_case)P.push("-i");if(y.glob)P.push(`--include=${y.glob}`);if(S==="files")P.push("-l");else if(S==="count")P.push("-c");else if(P.push("-n"),y.context)P.push(`-C${y.context}`);P.push("--",y.pattern,b),T=await ng(P,e,x)}let A=`${e}/`,C=T.split(`
183
+ `).filter(Boolean).map((P)=>P.startsWith(A)?P.slice(A.length):P).filter((P)=>S!=="count"||!P.endsWith(":0"));if(!C.length)return u("No matches");if(S==="files"&&C.length>$l)return u(`${C.slice(0,$l).join(`
184
+ `)}
185
+ \u2026 ${C.length-$l} more files; narrow the search`);return u(rt(C.join(`
186
+ `),WB))}});return[we(c,"find","find_files","list_files","file_search","ls","list","list_dir"),we(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function y$(e){return we(v({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
187
+ Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
188
+ - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
189
+ - Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
190
+ - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:s({todos:B(s({content:l({minLength:1,description:"What to do, in imperative form"}),status:m(qg.map((n)=>a(n)))}))}),async execute(n,i){let c=i.todos.map((y)=>({content:y.content,status:y.status}));e(c);let p=c.filter((y)=>y.status==="completed").length,g=c.find((y)=>y.status==="in_progress");return u(`Todo list updated (${p}/${c.length} completed${g?`; in progress: ${g.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function We(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}function x$(e){let n=We(e);return{target:n,hard:n,index:n}}class vl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,n=()=>{return},i){this.records=e;this.cwd=n;if(i)this.defaultPolicy=new Gc(e,i,n)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??x$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??We(e)}prepare(e,n,i,c,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,n,i,c);let g=e.reduce((S,T)=>S+F(T),0)+Di(n),y=Math.max(0,We(i)*this.recoveryRatio-g),x=ke(c??this.records(),i,x$(i),{cwd:this.cwd()}).messages,b=x.reduce((S,T)=>S+F(T),0);if(p&&b>y)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(b>y&&x.length>1){let S=x.shift();if(S)b-=F(S);while(x[0]?.role==="toolResult"){let T=x.shift();if(T)b-=F(T)}}if(b>y){let S=x.at(-1),T=S&&"content"in S&&typeof S.content==="string"?S.content:"[Context omitted: use history tools to retrieve earlier messages.]";x.length=0;let A=T;while(A&&F({role:"user",content:A,timestamp:0})>y)A=A.slice(Math.ceil(A.length/2));if(A)x.push({role:"user",content:A,timestamp:0});b=x.reduce((C,P)=>C+F(P),0)}return this.lastMessageCount=x.length,{messages:[...e,...x],estimate:g+b}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as I$,readFileSync as zB}from"fs";import{homedir as VB}from"os";import{dirname as JB,join as b$}from"path";var QB=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
191
+
192
+ # How to work
193
+
194
+ - Complete the task end to end. Keep going until the user's request is fully resolved before ending your turn: investigate, make the change, verify it. Do not stop halfway to report a plan or ask "should I continue?" when the next step is clear.
195
+ - Ask the user only when you are genuinely blocked: the request is ambiguous in a way that changes the outcome, or the action is destructive or irreversible. Otherwise make a reasonable choice, state the assumption briefly, and proceed.
196
+ - If the user only asks a question or asks for a plan or review, answer it; do not start changing files. For a review, lead with findings: bugs, risks, behavior regressions and missing tests, ordered by severity with file:line. Keep any summary short and after the findings.
197
+ - Do not use the todo tool for a single deliverable, even a complex one (implementing a feature, fixing a bug, writing a module and its tests): work through it directly with a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later. Never make reading, environment checks or the final summary into items, and update it only together with your next action, never as a turn of its own.
198
+
199
+ # Making changes
200
+
201
+ - Investigate before changing anything. Find the relevant code with grep/glob, read it, and understand how it is used. Edit from what you have actually seen: a read, or grep output with enough context to copy the text exactly.
202
+ - Verify unfamiliar technical entities instead of recalling them. When a task involves a library, API, tool or version you do not confidently recognize, check the project first: package manifests and lockfiles, \`--version\`, or the installed sources. A fluent answer built on an outdated memory looks right and is wrong. Never guess URLs; use only ones the user or the project gave you.
203
+ - Follow the conventions of the existing code: style, naming, structure, libraries, error handling, comment density, test layout. Before using a library, confirm the project already depends on it.
204
+ - Fix the root cause, not the symptom. Keep changes minimal and focused on the task; do not refactor, rename or "clean up" unrelated code, and do not add features that were not requested. Between two correct approaches, prefer the smaller one. Do not add backward-compatibility code unless something concrete needs it (persisted data, shipped behavior, external consumers, an explicit requirement).
205
+ - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
206
+ - Do not add comments that narrate the change ("added this", "fixed bug"). Comment only where the code is not self-explanatory, in the style of the surrounding code.
207
+
208
+ # Verifying
209
+
210
+ - Verify behaviour the way the user would see it. When asked to test a feature, or after a change with user-visible effects, run the real thing first: start the app or server with bash background=true, exercise the changed path (curl an endpoint, run the CLI with real input, or drive a web UI with the browser tools: open, act, then browser_screenshot and look at the image), and confirm the result matches the requirement. Unit tests complement this; they do not replace it, and "the tests pass" is not evidence the feature works.
211
+ - For code with no runnable surface (a library, a refactor, types, build config), or when the app cannot be started here, run the most specific tests, type checker, linter or build instead \u2014 find how in the project's README, package scripts, Makefile or CI config \u2014 and say what you could not exercise.
212
+ - Once the change is verified, stop: re-verify only after new changes, failures or a concrete unresolved concern. Do not re-run a check that already passed when nothing it covers has changed. Kill servers and close pages you started.
213
+ - Do not re-read a file after your own edit or re-check mkdir/delete/move results: an edit result already shows the new content, and a failing call reports an error. Re-read only if someone else changed the file.
214
+ - When a step fails, read the error and diagnose why before retrying. Do not loop on the same failing approach; after two failed attempts, step back and reconsider. If a tool call is blocked, do not retry it unchanged; follow the stated reason or ask the user.
215
+
216
+ # Tools
217
+
218
+ - Tool calls are the only way to act; describing an action does not perform it.
219
+ - Use the dedicated tools for files: read to view (paths reads several files in one call), edit for replacements (give edits for several changes, even across files), write to create or rewrite a file, grep to search contents, glob to find files. A quick read-only look (ls, cat, sed -n) may share a bash command with other work, such as listing a directory while checking tool versions; to only view or edit a file, use read and edit.
220
+ - Create files you will keep or edit later with write, passing then_run to run them or their tests in the same step. A file written by a bash heredoc has not been read through the tools, so a later edit of it costs an extra step; a heredoc is fine for a throwaway script that the same command runs.
221
+ - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
222
+ - In bash, search with rg / rg --files when it exists (much faster than grep/find). Do not join commands with echo or printf separators such as an echo '====' line; the output gets noisy. Do not use python or other scripts just to print or edit file contents when read, edit will do. Backticks and $() inside a command still execute, so escape text carefully.
223
+ - Put every tool call you already know into one response. Independent reads and searches run in parallel; calls that change things (edit, write, bash) run one after another in the order you give them, so you can edit a file and run its tests in the same response. Put all replacements of one logical change (for example an import, a helper and its call sites, plus the matching test) into one edit call's edits and pass then_run with the test command, instead of one edit per spot followed by a separate test run. Pass then_run to write as well. When probing behaviour, batch the checks into one script instead of one command each.
224
+ - Use bash for builds, tests, git, package managers and running programs. Each bash call starts in the project directory; use absolute or project-relative paths and chain dependent steps with &&.
225
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished, including dev servers you start to verify a change. Do not busy-wait or poll repeatedly.
226
+
227
+ # Honesty
228
+
229
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
230
+ - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
231
+ - When the user asks you to run something, run it, even when you can predict the result.
232
+ - If a step failed, was skipped or could not be verified, say which one and why.
233
+
234
+ # Safety
235
+
236
+ - Do not run destructive or irreversible commands (rm -rf on broad paths, git reset --hard, git push --force, dropping databases, killing unrelated processes) unless the user explicitly asked for exactly that.
237
+ - Never commit, push, create branches or rewrite git history unless the user asks. If asked to commit, write a concise message that explains why, matching the repository's existing style.
238
+ - Do not revert or overwrite changes you did not make; the user may be editing files at the same time. If a file changed unexpectedly, read it again and work with the new content.
239
+ - Never print, log or commit secrets such as API keys, tokens or passwords.
240
+
241
+ # Communication
242
+
243
+ - Reply in the same language the user writes in.
244
+ - Be concise and direct. No filler, no flattery, no restating the request. Do not narrate every tool call: a short sentence before a batch of related actions, and in a long run a brief progress note every few calls, is enough.
245
+ - Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
246
+ - Do not use emojis unless the user does or asks for them.
247
+ - When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
248
+ - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,XB=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
249
+
250
+ # Tools
251
+
252
+ - Use read to view files, edit to change them and write to create them; use grep/glob to search contents and find files in the working directory.
253
+ - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
254
+ - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
255
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
256
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
257
+
258
+ # Communication
259
+
260
+ - Reply in the same language the user writes in.
261
+ - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
262
+ - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,YB=["AGENTS.md","CLAUDE.md"],ZB=20000;function E$(e){let n=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?QB:XB}],i=[];if(e.globalInstructions?.trim())i.push(og("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let c of eG(e.project.directory))i.push(og(c.path,c.content));if(e.project.instructions.trim())i.push(og(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)n.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
263
+
264
+ # Instructions from the user and project
265
+
266
+ The following instructions were written by the user or the project maintainers. Follow them; they override the defaults above when they conflict. More specific (deeper directory) instructions take precedence over general ones.
267
+
268
+ ${i.join(`
269
+
270
+ `)}`});return n.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
271
+
272
+ ${tG(e)}`}),n}function og(e,n){return`<instructions source="${e}">
273
+ ${je(n.trim(),ZB)}
274
+ </instructions>`}function eG(e){let n=[],i=e;for(let c=0;c<20;c++){for(let g of YB){let y=b$(i,g);if(I$(y)){try{n.unshift({path:y,content:zB(y,"utf8")})}catch{}break}}if(I$(b$(i,".git"))||i===VB())break;let p=JB(i);if(p===i)break;i=p}return n}function tG(e){let n=e.now??new Date,i=n.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),c=n.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:g}=ba("",e.shell),y=[`Working directory: ${p}`,`Shell: ${g}`,`Date: ${i} (${c})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project){let x=rG(e.project.directory);y.push(x??"Git: not a git repository")}return`<environment>
275
+ ${y.join(`
276
+ `)}
277
+ </environment>`}function rG(e){let n=(...x)=>{try{let b=Bun.spawnSync(["git",...x],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0});return b.exitCode===0?b.stdout.toString().trim():void 0}catch{return}},i=n("rev-parse","--abbrev-ref","HEAD");if(i===void 0)return;let c=n("status","--short")??"",p=c?c.split(`
278
+ `):[],g=p.length>30?[...p.slice(0,30),`\u2026 ${p.length-30} more`]:p,y=n("log","--oneline","-5")??"";return[`Git branch: ${i}`,`Git status at session start:${g.length?`
279
+ ${g.join(`
280
+ `)}`:" clean"}`,y?`Recent commits:
281
+ ${y}`:"Recent commits: none"].join(`
282
+ `)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Pl(e.records,e.history):[],c=e.directory??process.cwd();return[...l$(c,new eg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...g$(c),y$(e.onTodos),...i]}class Fi{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||!jg.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Fg.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let n=this.settings();if(e.scope==="global")if(e.mode===null)delete n.global;else n.global=e.mode;else{let i=e.scope==="tool"?n.tools:n.sources,c=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[c];else i[c]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(n)),n}partition(e){let n=this.settings();return e.map((c)=>{let p=c,g=p.source??"core",y=c.name.toLowerCase(),x=p.defer??"always",b="suggestion";if(n.global)x=n.global,b="global";if(Object.hasOwn(n.sources,g))x=n.sources[g]??x,b="source";if(Object.hasOwn(n.tools,y))x=n.tools[y]??x,b="tool";if(g==="core"||p.builtin&&p.defer!=="defer")x="always",b="suggestion";return{name:c.name,source:g,mode:x,origin:b,deferred:x==="defer"}})}}function sg(e){return{name:e.name,description:e.description,parameters:e.parameters}}function ig(e,n){if(!n)return e;let i=Array.isArray(n.type)?n.type:[n.type],c=e;if(i.includes("number")||i.includes("integer")){let p=typeof c==="string"&&c.trim()?Number(c):c;if(typeof p!=="number"||!Number.isFinite(p))return c;let g=p;if(typeof n.maximum==="number"&&g>n.maximum)g=n.maximum;if(typeof n.minimum==="number"&&g<n.minimum)g=n.minimum;return g===p?c:g}if(typeof c==="string"&&(i.includes("object")||i.includes("array")))try{let p=JSON.parse(c),g=Array.isArray(p);if(typeof p==="object"&&p!==null&&!g&&i.includes("object")||g&&i.includes("array"))c=p}catch{}if(Array.isArray(c)){let p=n.items;if(!p||typeof p!=="object"||Array.isArray(p))return c;return c.map((g)=>ig(g,p))}if(typeof c==="object"&&c!==null&&n.properties){let p={...c};for(let[g,y]of Object.entries(n.properties))if(g in p)p[g]=ig(p[g],y);return p}return c}function nG(e){let n=e.prepareArguments;return{...e,prepareArguments:(i)=>{let c=ig(i,e.parameters);return n?n(c):c}}}function oG(e,n,i){let c=e.prepareArguments?e.prepareArguments(i):i;return nu(e,{type:"toolCall",id:n,name:e.name,arguments:c})}class ag{retrieved=new Map;stub(e){let n=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${n}
283
+ (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:s({},{additionalProperties:!0}),execute:async(i,c,p,g)=>{let y=JSON.stringify(sg(e)),x;try{x=oG(e,i,c??{})}catch(T){return{...u(`Invalid arguments for ${e.name}: ${String(T)}
284
+ Schema: ${y}`),isError:!0}}let b=await e.execute(i,x,p,g),S=b.content.map((T)=>T.type==="text"?{...T,text:rt(T.text,Pe)}:T);return{...b,content:S}}}}assemble(e,n,i){let c=e.map(nG),p=new Set(n.filter((y)=>y.deferred).map((y)=>y.name));if(!p.size)return c;let g=c.filter((y)=>p.has(y.name)&&i(y.name)).sort((y,x)=>y.name<x.name?-1:y.name>x.name?1:0);return[...c.filter((y)=>!p.has(y.name)),...g.map((y)=>this.stub(y)),we(v({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:s({query:l(),max_results:o(w({minimum:1,maximum:100}))}),execute:async(y,x)=>{let b=x.query.trim().toLowerCase(),S=b.startsWith("select:")?b.slice(7).split(",").map((A)=>A.trim()):void 0,T=g.filter((A)=>i(A.name)&&(S?S.includes(A.name.toLowerCase()):`${A.name} ${A.description}`.toLowerCase().includes(b))).slice(0,x.max_results??5);return u(JSON.stringify(T.map((A)=>{let C=JSON.stringify(sg(A)),P=this.retrieved.get(A.name);if(P?.schema===C)return{name:A.name,status:"\u5DF2\u53D6\u56DE",callID:P.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(A.name,{schema:C,callID:y}),sg(A)})))}}),"tool_search")]}}async function Ol(e,n,i){let c=await n.setup(e),p=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!i)return c;if(i.has("session.setup"))c=await i.invoke("session.setup",c,e);if(i.has("tools.configure"))c=await i.invoke("tools.configure",c,e);let g=c.systemPrompt,y=c.systemParts?.at(-1);if(y?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let T=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),A=g.length-y.detail.length;g=g.slice(0,A)+T.join("")+y.detail}let x=await i.invoke("prompt.fragments",[],e),b=[...c.tools,...i.tools()],S=i.has("tools.visible")?await i.invoke("tools.visible",b,e):b;return{...c,systemPrompt:g+x.join(""),tools:S}}var sG=3,S$={attempts:1/0,delayMs:2000},iG=/\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 aG(e,n){if(e.stopReason!=="error")return!1;if(li(e,n))return!1;return!iG.test(e.errorMessage??"")}function uG(e,n){return new Promise((i,c)=>{if(n.aborted)return c(n.reason);let p=setTimeout(()=>{n.removeEventListener("abort",g),i()},e),g=()=>{clearTimeout(p),c(n.reason)};n.addEventListener("abort",g,{once:!0})})}async function w$(e,n,i,c,p,g,y,x,b=!1){let S=b?void 0:await n?.invoke("run.start",{text:g},e);if(S)g=S.text;if(x.throwIfAborted(),g===void 0)await c.resume();else await c.prompt(g,y);let T=0,A=0;while(T<sG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!li(q,p.contextWindow)){if(!aG(q,p.contextWindow)||A>=S$.attempts)return;A++,await uG(S$.delayMs,x),await c.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}x.throwIfAborted(),T++,await c.retry()}let P=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&P?.stopReason==="error"&&li(P,p.contextWindow))throw Error(i.overflowError??"Context exceeds the request budget")}async function T$(e,n,i,c,p,g){g.throwIfAborted();let y,x;try{x=await Promise.race([Ol(e,n,i()),new Promise((C,P)=>{y=()=>P(g.reason),g.addEventListener("abort",y,{once:!0})})])}finally{if(y)g.removeEventListener("abort",y)}g.throwIfAborted();let b=i(),S=(C)=>{if(!b)return C;return{...C,execute:async(P,L,q,X)=>{let j=c()??x.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?b.policy(j):void 0;if(j&&!V?.(C.name,e))throw Error(`Tool ${C.name} is unavailable under tool policy ${j}`);let J=await b.invoke("tool.before_call",{name:C.name,callID:P,args:L},e);if(J.block)throw Error(J.block);let ee=await K.run(e,()=>C.execute(P,J.args,q,X));return b.invoke("tool.after_result",ee,e)}}};if(b)x.tools=x.tools.map(S);let T=x.tools,A=()=>{if(!T.some((P)=>P.name==="history_grep")){if(e.records.some((L)=>L.entry.type==="compaction")){let q=Pl(()=>e.records,(X)=>n.runtime?.resolveHistory?.(e.id,X)).map(S);for(let X of q)if(!T.some((j)=>j.name===X.name))T.push(X)}}let C=new Fi(n.store).partition(T);return x.tools=p.assemble(T,C,(P)=>e.permitsTool(P)),x.tools};return x.tools=A(),{setup:x,executionTools:T,assemble:A}}function R$(e,n,i,c,p,g,y){return{response:async(x)=>{let b=await n()?.invoke("model.after_response",x,e)??x;if(b.role==="assistant")for(let S of b.content){if(S.type!=="toolCall"||S.name.toLowerCase()!=="tool_call")continue;let T=S.arguments.name;if(typeof T==="string"){let A=y.find((C)=>C.name.toLowerCase()===T.toLowerCase());S.arguments.name=A?.name??T}}return b},payload:(x)=>n()?.invoke("model.before_request",x,e)??Promise.resolve(x),transformContext:(x)=>n()?.invoke("transformContext",x,e)??Promise.resolve(x),boundary:async()=>{if(c())return!0;let x=await n()?.invoke("step.after",{notices:[]},e);for(let S of x?.notices??[])e.notice(S);await g.work;let b=await g.flushNotices();if(b&&!p())e.agent?.steer(b)},prepare:async(x,b,S)=>{if(c())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let T=await n()?.invoke("model.check",{},e);if(T?.error)throw Error(T.error);let A=await n()?.invoke("step.before",{notices:[]},e);for(let j of A?.notices??[])e.notice(j);await g.work,await g.flushNotices();let C=await n()?.invoke("projection.before",e.records,e),P=await n()?.invoke("projection.prefix",[],e)??[],L=e.context.prepare([...x,...P],b,S,C,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&L.estimate>We(S))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=L.messages,X=await n()?.invoke("projection.after",q,e)??q;return au(X)}}}async function k$(e,n,i){let c=n.store.pendingNotices(e.id);if(!c.length)return;let p=c,g=n.plugins?.pin();try{if(g){let P=await g.invoke("notice.deliver",c,e);p=c.map((L,q)=>({...L,text:P[q]?.text??L.text}))}}finally{await g?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let y=p.map((P)=>P.text).join(`
285
+ `),x=p.map((P)=>n.plugins?.noticeSource(P.sourceKind)),b=Math.max(800,...x.map((P)=>P?.summaryLimit??800)),S=y.length>b?`
286
+ [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",A=`${x.find((P)=>P?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
287
+ ${y.slice(0,b)}${S}`,C={role:"user",content:A,timestamp:Date.now()};return i({type:"user",text:A,notices:c.map(({text:P,...L})=>L)},C),C}class ug{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,n,i,c,p,g,y,x){this.session=e;this.context=n;this.isStopped=i;this.isRunning=c;this.waiting=p;this.start=g;this.invalidateAgent=y;this.append=x}recover(){for(let e of this.context.store.pendingNotices(this.session.id)){if(e.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:e.dedupeKey,sourceKind:e.sourceKind,sourceID:e.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if(this.context.store.pendingNotices(this.session.id).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let n={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,n)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((i)=>{this.failure=i}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=k$(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((n)=>n.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var cG=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 n={};for(let[i,c]of Object.entries(e)){if(!cG.has(i.toLowerCase())){n[i]=c;continue}let p=/^bearer\s+/i.exec(c)?.[0];n[i]=p?`${p}***`:"***"}return n}function A$(e,n,i,c){let g=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((H,ce)=>({id:`system-${ce}`,label:H.label,detail:H.detail,tokens:O(H.detail)+(ce===0?16:0)})),y=i.tools.map((H)=>{let ce=H,fe=ce.defer==="defer"||H.description.includes("(Parameters not inlined: use toolsearch");return{name:H.name,description:H.description,group:ce.group??"\u5185\u7F6E",schema:H.parameters,deferred:fe}});g.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Di(i.tools),detail:JSON.stringify(y,null,2)});let x=g.reduce((H,ce)=>H+ce.tokens,0),b=c!==void 0?e.records.filter((H)=>H.entry.seq<=c):e.records,S=ke(b,n,e.context.budget(n),{inspect:!0,cwd:i.cwd,trim:{fixed:x,limit:e.context.previewLimit(n)}}),T,A=0,C=0;for(let H of b){if(H.raw?.role!=="assistant")continue;let ce=H.raw.usage;T??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},T.input+=ce.input,T.output+=ce.output,T.cacheRead+=ce.cacheRead,T.cacheWrite+=ce.cacheWrite,T.cost+=ce.cost.total;let fe=H.entry.generationMs??H.raw.generationMs;if(typeof fe==="number"&&fe>0&&ce.output>0)A+=fe,C+=ce.output}if(T){let H=T.input+T.cacheRead+T.cacheWrite;if(H>0)T.cacheHitRate=T.cacheRead/H}if(T&&A>0&&C>0)T.generationMs=A,T.tps=Number((C/(A/1000)).toFixed(1));let P=x+S.tokens,L=e.context.calibrationRatio??1,q=Math.round(P*L),X=b.findLast((H)=>H.raw?.role==="assistant"),j=X?.raw,J=(X?b.filter((H)=>H.entry.seq>X.entry.seq&&H.raw):b.filter((H)=>H.raw)).length>0,ee,ie;if(j){let H=j.usage,ce=H.input+H.cacheRead+H.cacheWrite;if(ce>0)ee=ce,ie=H.cacheRead/ce}return{contextWindow:n.contextWindow,usableWindow:We(n),items:[...g,...S.items],calibratedTokens:q,calibrationRatio:L,lastInputTokens:ee,lastCacheHitRate:ie,hasPendingOutput:J,tools:y,usage:T}}class pt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class oe extends Error{constructor(e="session"){super(`${e} is busy`)}}var mg="medium";class _l{row;ctx;events;notices;lease;policyID;discovery=new ag;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let n=await Ol(this,this.ctx,e);return new Fi(this.ctx.store).partition(n.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new oe;this.policyID=e,this.reset()}historyScope(e){if(this.lease)return this.lease.resolveHistory(this,e);return this.ctx.plugins?.resolveHistory(this,e)}permitsTool(e){let n=this.policyID??this.setup?.toolPolicy;if(!n)return this.info().parentID===null;return(this.lease?.policy(n)??this.ctx.plugins?.toolPolicy(n))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,n,i){this.row=e;this.ctx=n;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new ug(this,n,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=n.store.lastSeq(e.id);let c=n.store.lastEntry(e.id,"run");this.stopped=c?.type==="run"&&c.state==="end"&&c.reason==="aborted";let p=this.entries().findLast((y)=>y.type==="extension"&&y.namespace==="session"&&y.kind==="stop_requested"),g=this.entries().findLast((y)=>y.type==="run"&&y.state==="start");if(p&&p.seq>(g?.seq??0))this.stopped=!0;if(c?.type==="run"&&c.state==="start"){let y=this.records.some((b)=>b.entry.seq>c.seq&&b.entry.type==="user"),x=n.store.pendingNotices(e.id).some((b)=>b.wake&&b.recovery!=="discard");if(!this.stopped&&(y||x))this.recoveryStart=c.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new vl(()=>this.records,()=>this.cwd,(y,x)=>this.appendCompaction(y,x)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=bn(this.ctx.models,this.row.model);if(!e)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");return e}lastModelRequest(){let e=this.lastRequestSnapshot;return e?{...e,headers: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:n,projectID:i,model:c,thinking:p,metadata:g,created:y,updated:x,todos:b}=this.row;return{id:e,title:n,projectID:i,model:c,thinking:p??mg,metadata:g,created:y,updated:x,archivedAt:this.row.archivedAt,status:this.status,todos:b,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let n=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,n)}entriesBefore(e,n){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-n));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,n,i){return this.ctx.store.entriesAround(this.row.id,e,n,i)}entriesFrom(e,n){return this.ctx.store.entriesFrom(this.row.id,e,n)}entries(e=0){return this.ctx.store.entries(this.row.id).filter((n)=>n.seq>e)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let n=(async()=>{let i=bn(this.ctx.models,this.row.model);if(!i)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let c=this.ctx.plugins?.pin(),p;try{p=this.setup??await Ol(this,this.ctx,c)}finally{await c?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new Fi(this.ctx.store).partition(p.tools),(y)=>this.permitsTool(y));let g=A$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:g};return g})();if(e!==void 0)return n;this.snapshotInFlight=n;try{return await n}finally{if(this.snapshotInFlight===n)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new pt}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!bn(this.ctx.models,e))throw new t(`unknown model ${e}`);let n=this.row.model;if(n===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:n,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let n=e?.trim()?e.trim():null;if(this.row.thinking===n)return;this.save({thinking:n}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,n){this.startRun(e,Yl(n))}steer(e,n){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,n);return}this.stopped=!1;let i=Yl(n),c=vh(e,i),p=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},c);if(this.recallableSteers.set(p.seq,c),this.events.changed(),this.agent)this.agent.steer(c);else this.pendingSteers.push(c)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let n=this.records.find((g)=>g.entry.seq===e);if(n?.entry.type!=="user"||n.raw===void 0)return!1;if("notices"in n.entry&&n.entry.notices)return!1;let i=n.raw,c=this.pendingSteers.indexOf(i);if(c<0){let g=JSON.stringify(i);c=this.pendingSteers.findIndex((y)=>JSON.stringify(y)===g)}let p=!1;if(c>=0)this.pendingSteers.splice(c,1),p=!0;else p=this.agent?.unsteer(i)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[n,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(n),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,n,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new oe;if(e!==void 0)this.stopped=!1;let c=bn(this.ctx.models,this.row.model);if(!c&&i===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let p=new AbortController;if(this.starting=p,!this.row.title&&e!==void 0)this.row={...this.row,title:mG(e,n)},this.ctx.store.updateSession(this.row);let g=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let y=this.append({type:"user",text:e,...n?.length?{attachments:n}:{}});this.pendingUserSeq=y.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let x=this.records.filter((A)=>A.entry.seq>g),b=x.filter((A)=>A.entry.type==="user"&&!A.raw);if(b.length>1)return{reason:"interrupted"};let S=b[0];if(S?.entry.type==="user"){if(x.some((A)=>A.entry.seq>S.entry.seq&&A.raw?.role==="assistant"))return{reason:"interrupted"};e=S.entry.text,n=S.entry.attachments,this.pendingUserSeq=S.entry.seq}for(let A of ms(x.filter((C)=>C.raw))){if(A.result)continue;let{body:C,raw:P}=hP(A.call);this.append(C,P)}if(!S&&this.waitingForInput())return{reason:"waiting_user"};let T=this.records.findLast((A)=>A.entry.seq>g&&A.raw)?.raw;if(!S&&T?.role==="assistant")return Oh(T);if(!S&&!T&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!c)throw Error(`unknown model ${this.row.model}`);let y=await this.prepareAgent(c,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let x=this.pendingSteers.shift();if(x)y.steer(x)}return await w$(this,this.lease,this.setup,y,c,e,n,p.signal,i!==void 0&&e===void 0),Oh(this.records.findLast((x)=>x.entry.seq>g&&x.raw?.role==="assistant")?.raw)}).then((y)=>p.signal.aborted?{reason:"aborted"}:y,(y)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(y)}).then(async(y)=>{try{if(!this.suspended&&y.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())y={reason:"waiting_user"};if(y.reason!=="interrupted")y=await this.lease?.invoke("run.end",{reason:y.reason,error:y.error},this)??y}}catch(x){y={reason:"error",error:String(x)}}finally{try{await this.lease?.release()}catch(x){y={reason:"error",error:String(x)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...y});let x=bn(this.ctx.models,this.row.model);if(x)this.context.settle(x)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,n){if(!this.agent){let{setup:i,executionTools:c,assemble:p}=await T$(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,n);if(this.setup=i,this.row.parentID&&(!i.toolPolicy||!this.lease?.policy(i.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=i.cwd,this.agent=fP({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,...R$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,c),message:(g,y)=>{if(this.suspended&&y.role==="assistant"&&(y.stopReason==="aborted"||y.stopReason==="error"))return;if(y.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,y);let x=this.loaded?.find((b)=>b.entry.seq===this.pendingUserSeq);if(x)x.raw=y;this.pendingUserSeq=void 0;return}if(y.role==="assistant")this.context.calibrate(y);this.append(g,y)},draft:(g)=>{this.draftParts=g,this.events.draft(g)}}})}return this.agent}notice(e,n=!1){if(this.closed)return;if(n)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let n of e)this.loaded?.push(n);for(let{entry:n}of e)this.events.entry(n)}appendCompaction(e,n){this.assertWritable();let i=this.measureCompactionSavings(e,n);this.append({type:"compaction",through:e,partial:n,...i?{saved:i}:{}})}measureCompactionSavings(e,n){let i=bn(this.ctx.models,this.row.model);if(!i)return;let c=this.context.budget(i),p=ke(this.records,i,c,{cwd:this.cwd}).tokens,g={entry:{type:"compaction",through:e,partial:n,seq:this.seq+1,time:0}},y=ke([...this.records,g],i,c,{cwd:this.cwd}).tokens;return{before:p,after:y}}compact(){this.assertWritable();let e=iu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,n){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,n);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function mG(e,n){let c=(e.trim()||n?.map((p)=>p.name).join(" ")||"").split(`
288
+ `)[0]?.trim()??"";return c.length>40?`${c.slice(0,40)}\u2026`:c}var P$=new Set(["user","assistant","tool_result","run","compaction"]),pG=new Set(["user","assistant","toolResult"]);function $$(e,n,i){return{format:Xl,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...i?{project:i}:{},records:n.filter((c)=>P$.has(c.entry.type)).map((c)=>c.raw===void 0?{entry:c.entry}:{entry:c.entry,raw:c.raw})}}function No(e){if(!gr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Xl)return lG(e);if(gr(e.info)&&Array.isArray(e.messages))return fG(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 lG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let n=e.session;if(!gr(n))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let i=0,c=e.records.flatMap((p,g)=>{let y=`records[${g}]`;if(!gr(p)||!gr(p.entry))throw new t(`${y} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let x=p.entry;if(x.type==="notice_pending"||x.type==="extension")return[];if(typeof x.type!=="string"||!P$.has(x.type))throw new t(`${y} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(x.type)}`);let{seq:b,time:S}=x;if(typeof b!=="number"||!Number.isSafeInteger(b)||b<=i)throw new t(`${y} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof S!=="number"||!Number.isFinite(S))throw new t(`${y} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=b,dG(x,y);let T=p.raw;if(T!==void 0&&!(gr(T)&&typeof T.role==="string"&&pG.has(T.role)))throw new t(`${y} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:x,...T===void 0?{}:{raw:T}}]});return{title:Lr(n.title),model:typeof n.model==="string"?n.model:void 0,thinking:typeof n.thinking==="string"?n.thinking:null,todos:Array.isArray(n.todos)?n.todos.flatMap(v$):[],created:zs(n.created)??Date.now(),updated:zs(n.updated)??Date.now(),needsRaw:!1,records:c}}function dG(e,n){let i=(c)=>new t(`${n}\uFF08${String(e.type)}\uFF09${c}`);switch(e.type){case"user":if(typeof e.text!=="string")throw i("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw i("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw i("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&Og.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 fG(e){let n=e.info,i=gr(n.time)?n.time:{},c=gr(n.model)?n.model:void 0,p=e.messages.filter(gr).sort(hG),g=[],y=0,x=0,b=(X,j)=>{x=Math.max(x,j??x),y+=1,g.push({entry:{...X,seq:y,time:x}})},S=!1,T=(X,j)=>{if(!S)return;S=!1,b({type:"run",state:"end",reason:X,...j?{error:j}:{}},void 0)};for(let X of p){let j=gr(X.info)?X.info:{},V=Array.isArray(X.parts)?X.parts.filter(gr):[],J=zs(gr(j.time)?j.time.created:void 0);if(j.role==="user"){T("done");let ee=gG(V);if(!ee)continue;b({type:"run",state:"start"},J),b(ee,J),S=!0}else if(j.role==="assistant"){if(!S)b({type:"run",state:"start"},J),S=!0;IG(j,V,b);let ee=M$(j.error);if(ee)T(ee.aborted?"aborted":"error",ee.aborted?void 0:ee.message)}}T("done");let A=p.findLast((X)=>gr(X.info)&&X.info.role==="assistant"),C=gr(A?.info)?A.info:void 0,P=Lr(c?.providerID)||Lr(C?.providerID),L=Lr(c?.id)||Lr(C?.modelID),q=P&&L?`${P}/${L}`:void 0;return{title:Lr(n.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(v$):[],created:zs(i.created)??g[0]?.entry.time??Date.now(),updated:zs(i.updated)??g.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:g}}function hG(e,n){let i=(p)=>(gr(p.info)&&gr(p.info.time)?zs(p.info.time.created):void 0)??0,c=(p)=>gr(p.info)?Lr(p.info.id):"";return i(e)-i(n)||c(e).localeCompare(c(n))}function gG(e){let n=e.filter((c)=>c.type==="text"&&c.synthetic!==!0&&c.ignored!==!0).map((c)=>Lr(c.text)).join(`
289
+
290
+ `),i=e.flatMap((c)=>c.type==="file"?yG(c):[]);if(!n.trim()&&i.length===0)return;return{type:"user",text:n,...i.length?{attachments:i}:{}}}function yG(e){let n=Lr(e.mime)||"application/octet-stream",i=Lr(e.filename)||"file",c=Lr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(c);if(p){let g=p[3]??"";if(n.startsWith("image/"))return[{name:i,mimeType:n,kind:"image",data:p[2]?g:btoa(g)}];if(n.startsWith("text/")||n==="application/json"){let y=p[2]?new TextDecoder().decode(Uint8Array.from(atob(g),(x)=>x.charCodeAt(0))):g;return[{name:i,mimeType:n,kind:"text",data:y}]}return[]}if(c.startsWith("file://"))try{return[{name:i,mimeType:n,kind:"path",data:decodeURIComponent(new URL(c).pathname)}]}catch{return[]}return[]}function xG(e){let n=[[]];for(let i of e){if(i.type==="step-start"){if(n.at(-1)?.length)n.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")n.at(-1)?.push(i)}return n.filter((i)=>i.length>0)}function IG(e,n,i){let c=`${Lr(e.providerID)}/${Lr(e.modelID)}`,p=M$(e.error),g=xG(n);g.forEach((y,x)=>{let b=y.flatMap((A)=>{if(A.type==="reasoning")return Lr(A.text).trim()?[{type:"thinking",text:Lr(A.text)}]:[];if(A.type==="text")return A.ignored!==!0&&Lr(A.text).trim()?[{type:"text",text:Lr(A.text)}]:[];return[{type:"tool_call",id:C$(A.callID),name:Lr(A.tool),input:gr(A.state)&&gr(A.state.input)?A.state.input:{}}]}),S=x===g.length-1,T=bG(y);i({type:"assistant",parts:b,model:c,...S&&p&&!p.aborted?{error:p.message}:{}},T);for(let A of y){if(A.type!=="tool")continue;let C=gr(A.state)?A.state:{},P=C.status==="error",L=C.status==="pending"||C.status==="running",q=P?[Lr(C.output),Lr(C.error)].filter(Boolean).join(`
291
+ `):L?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Lr(C.output);i({type:"tool_result",callID:C$(A.callID),name:Lr(A.tool),output:q,isError:P||L},zs(gr(C.time)?C.time.end:void 0))}})}function C$(e){return Lr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function M$(e){if(!gr(e))return;let n=gr(e.data)?e.data:{};return{message:Lr(n.message)||Lr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function bG(e){for(let n of e){let i=gr(n.time)?zs(n.time.start):gr(n.state)?EG(n.state):void 0;if(i!==void 0)return i}return}function EG(e){return gr(e.time)?zs(e.time.start):void 0}function v$(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 O$(e,n){let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:c})=>{let p=c.time;switch(c.type){case"user":return{entry:c,raw:SG(c,p)};case"assistant":{let g=c.parts.flatMap((x)=>{if(x.type==="text")return[{type:"text",text:x.text}];if(x.type==="thinking")return[];return[{type:"toolCall",id:x.id,name:x.name,arguments:wG(x.input)}]}),y=g.some((x)=>x.type==="toolCall");return{entry:c,raw:{role:"assistant",content:g,api:n.api,provider:n.provider,model:n.id,usage:i,stopReason:c.error?"error":y?"toolUse":"stop",...c.error?{errorMessage:c.error}:{},timestamp:p}}}case"tool_result":return{entry:c,raw:{role:"toolResult",toolCallId:c.callID,toolName:c.name,content:[{type:"text",text:c.output}],isError:c.isError,timestamp:p}};default:return{entry:c}}})}function SG(e,n){let i=(e.attachments??[]).flatMap((g)=>g.kind==="path"?[`<file path=${JSON.stringify(g.data)} />`]:g.kind==="text"?[`<file name=${JSON.stringify(g.name)}>
292
+ ${g.data}
293
+ </file>`]:[]),c=(e.attachments??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),p=[...i,...e.text.trim()?[e.text]:[]].join(`
294
+
295
+ `);return{role:"user",content:c.length?[{type:"text",text:p},...c]:p,timestamp:n}}function gr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e==="string"?e:""}function zs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function wG(e){return gr(e)?e:{}}function or(e,n){let i=e.at(-1)?.entry.seq??0,c,p,g;for(let{entry:S}of e){if(S.type==="run"&&S.state==="start")c=S.seq;if(S.seq===n)if(S.type==="user"&&!S.notices)i=(c??S.seq)-1;else p=c;if(S.type==="run"&&S.state==="end"){if(p!==void 0&&c===p)g=S.seq;c=void 0}}let y=e.find((S)=>S.entry.seq===n)?.entry;if(n!==void 0&&!y)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(y&&!(y.type==="user"&&!y.notices)){if(p!==void 0&&g===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=g??y.seq}else if(n===void 0&&c!==void 0)i=e.findLast(({entry:S})=>S.type==="run"&&S.state==="end")?.entry.seq??0;let x=e.filter(({entry:S})=>S.seq<=i&&(S.type!=="compaction"||S.through<=i)),b=new Map(x.map(({entry:S},T)=>[S.seq,T+1]));return x.map((S,T)=>{let A=structuredClone(S);if(A.entry.seq=T+1,A.entry.type==="compaction"){let C=A.entry.through,P=x.findLast(({entry:L})=>L.seq<=C);A.entry.through=P?b.get(P.entry.seq)??0:0}return A})}function ir(e){let n=new Map,i=[];for(let c of e){if(c.type==="assistant"){for(let y of c.parts)if(y.type==="tool_call"&&y.name==="todo")n.set(y.id,y.input)}if(c.type!=="tool_result"||c.name!=="todo"||c.isError)continue;let p=n.get(c.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let g=[];for(let y of p.todos){if(!y||typeof y!=="object"||!("content"in y)||typeof y.content!=="string"||!("status"in y)||y.status!=="pending"&&y.status!=="in_progress"&&y.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");g.push({content:y.content,status:y.status})}i=g}return i}import{Buffer as Nl}from"buffer";import{createHash as _$}from"crypto";import{isDeepStrictEqual as Ll}from"util";var ji="@blob:";function hu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Dl(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(ji)){let g=Nl.from(p.data,"base64");if(g.byteLength>0&&g.toString("base64")===p.data){let y=_$("sha256").update(g).digest("hex");return n.put(y,p.mimeType,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),i=!0,{...p,data:`${ji}${y}`}}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.length>=256&&!p.data.startsWith(ji)){let g=Nl.from(p.data,"base64");if(g.byteLength>0&&g.toString("base64")===p.data){let y=_$("sha256").update(g).digest("hex");return n.put(y,p.mimeType,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),i=!0,{...p,data:`${ji}${y}`}}}return p});if(!i)return e;return{...e,images:c}}return e}function Ea(e,n){if(!n)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,c=e.attachments.map((p)=>{if(p.kind==="image"&&typeof p.data==="string"&&p.data.startsWith(ji)){let g=p.data.slice(ji.length),y=n.get(g);if(y!==void 0)return i=!0,{...p,data:Nl.from(y.buffer,y.byteOffset,y.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,attachments:c}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,c=e.images.map((p)=>{if(typeof p.data==="string"&&p.data.startsWith(ji)){let g=p.data.slice(ji.length),y=n.get(g);if(y!==void 0)return i=!0,{...p,data:Nl.from(y.buffer,y.byteOffset,y.byteLength).toString("base64")}}return p});if(!i)return e;return{...e,images:c}}return e}function Jc(e,n){if(!hu(n))return n;if(e.type==="user"){let{merged:i,images:c}=Fc(e.text,e.attachments),p=c.length>0?[{type:"text",text:i},...c]:i,g=Object.keys(n),{role:y,timestamp:x,content:b}=n;if(g.length===3&&y==="user"&&typeof x==="number"&&"content"in n&&Ll(b,p))return{role:"user",timestamp:x};return n}if(e.type==="tool_result"){let{role:i,toolCallId:c,toolName:p,isError:g,timestamp:y,content:x}=n;if(i!=="toolResult"||c!==e.callID||typeof p!=="string"||g!==e.isError||typeof y!=="number")return n;let b=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in n?!Ll(n.details,e.meta):e.meta!==void 0)return n;let{role:T,toolCallId:A,toolName:C,content:P,details:L,isError:q,timestamp:X,...j}=n;if(Ll(x,b))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:y};if(Array.isArray(x)){let V=e.images??[],J=0,ee=!0,ie=x.map((H)=>{if(hu(H)&&H.type==="image"){let ce=V[J++],fe=Object.keys(H);if(ce&&fe.length===3&&H.mimeType===ce.mimeType&&H.data===ce.data)return{type:"image",mimeType:H.mimeType};ee=!1}return H});if(ee&&J===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:ie,...j,timestamp:y}}return n}if(e.type==="assistant"){let{role:i,content:c}=n;if(i!=="assistant"||!Array.isArray(c)||c.length!==e.parts.length)return n;let p=!1,g=c.map((y,x)=>{let b=e.parts[x];if(hu(y)){if(y.type==="text"&&b?.type==="text"&&y.text===b.text){p=!0;let S={...y};return delete S.text,S}if(y.type==="thinking"&&b?.type==="thinking"&&y.thinking===b.text){p=!0;let S={...y};return delete S.thinking,S}if(y.type==="toolCall"&&b?.type==="tool_call"&&y.id===b.id&&y.name===b.name&&"arguments"in y&&Ll(y.arguments,b.input)){p=!0;let S={...y};return delete S.id,delete S.name,delete S.arguments,S}}return y});if(!p)return n;return{...n,content:g}}return n}function pg(e,n){if(!hu(n))return n;if(e.type==="user"){let{role:i,timestamp:c}=n;if(i==="user"&&!("content"in n)&&typeof c==="number"&&Object.keys(n).length===2){let{merged:p,images:g}=Fc(e.text,e.attachments);return{role:"user",content:g.length>0?[{type:"text",text:p},...g]:p,timestamp:c}}return n}if(e.type==="tool_result"){let{role:i,timestamp:c}=n;if(i==="toolResult"&&(!("content"in n)||!("toolCallId"in n))&&typeof c==="number"){let{role:g,toolName:y,content:x,timestamp:b,...S}=n,T;if(Array.isArray(x)){let A=e.images??[],C=0;T=x.map((P)=>{if(hu(P)&&P.type==="image"&&!("data"in P)){let L=A[C++];if(L)return{type:"image",mimeType:P.mimeType,data:L.data}}return P})}else T=[{type:"text",text:e.output},...(e.images??[]).map((A)=>({type:"image",mimeType:A.mimeType,data:A.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof y==="string"?y:e.name,content:T,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...S,timestamp:c}}return n}if(e.type==="assistant"){let{role:i,content:c}=n;if(i!=="assistant"||!Array.isArray(c))return n;let p=!1,g=c.map((y,x)=>{let b=e.parts[x];if(hu(y)){if(y.type==="text"&&!("text"in y)&&b?.type==="text"){p=!0;let{type:S,...T}=y;return{type:S,text:b.text,...T}}if(y.type==="thinking"&&!("thinking"in y)&&b?.type==="thinking"){p=!0;let{type:S,...T}=y;return{type:S,thinking:b.text,...T}}if(y.type==="toolCall"&&!("arguments"in y)&&b?.type==="tool_call"){p=!0;let{type:S,...T}=y;return{type:S,id:b.id,name:b.name,arguments:structuredClone(b.input),...T}}}return y});if(!p)return n;return{...n,content:g}}return n}function L$(e){let n=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),c={put(b,S,T){n.run(b,S,T)},get(b){return i.get(b)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),g=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),y=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),x=0;return e.transaction(()=>{for(let b of p){let S;try{S=JSON.parse(b.body)}catch{continue}let T=Ea(S,c),A=Dl(T,c),C=A===S?b.body:JSON.stringify(A),P=b.raw;if(b.raw!==null)try{let L=JSON.parse(b.raw),q=pg(T,L),X=Jc(T,q);P=JSON.stringify(X)}catch{P=b.raw}if(C!==b.body)g.run(C,P,b.session_id,b.seq),x++;else if(P!==b.raw)y.run(P,b.session_id,b.seq),x++}})(),x}import{Database as TG}from"bun:sqlite";import{chmodSync as N$,existsSync as RG,mkdirSync as kG}from"fs";import{dirname as AG}from"path";var lg=[`
296
+ CREATE TABLE projects (
297
+ id TEXT PRIMARY KEY,
298
+ name TEXT NOT NULL,
299
+ directory TEXT NOT NULL UNIQUE,
300
+ instructions TEXT NOT NULL DEFAULT '',
301
+ created INTEGER NOT NULL,
302
+ updated INTEGER NOT NULL
303
+ );
304
+ CREATE TABLE automations (
305
+ id TEXT PRIMARY KEY,
306
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
307
+ name TEXT NOT NULL,
308
+ prompt TEXT NOT NULL,
309
+ schedule TEXT NOT NULL,
310
+ model TEXT NOT NULL,
311
+ enabled INTEGER NOT NULL,
312
+ created INTEGER NOT NULL,
313
+ updated INTEGER NOT NULL,
314
+ next_run INTEGER,
315
+ last_run INTEGER,
316
+ last_session_id TEXT
317
+ );
318
+ CREATE TABLE sessions (
319
+ id TEXT PRIMARY KEY,
320
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
321
+ automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
322
+ title TEXT NOT NULL DEFAULT '',
323
+ model TEXT NOT NULL,
324
+ todos TEXT NOT NULL DEFAULT '[]',
325
+ created INTEGER NOT NULL,
326
+ updated INTEGER NOT NULL
327
+ );
328
+ CREATE INDEX sessions_project ON sessions(project_id);
329
+ CREATE TABLE entries (
330
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
331
+ seq INTEGER NOT NULL,
332
+ time INTEGER NOT NULL,
333
+ body TEXT NOT NULL,
334
+ raw TEXT,
335
+ PRIMARY KEY (session_id, seq)
336
+ ) WITHOUT ROWID;
337
+ `,"","","",`
338
+ ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
339
+ ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
340
+ ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
341
+ CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
342
+ ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
343
+ 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,
344
+ PRIMARY KEY (namespace, key));
345
+ CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
346
+ PRIMARY KEY (namespace, version));
347
+ 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);
348
+ CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
349
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
350
+ END;
351
+ CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
352
+ INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
353
+ END;
354
+ CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
355
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
356
+ END;
357
+ CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
358
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
359
+ END;
360
+ CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
361
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
362
+ END;
363
+ CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
364
+ INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
365
+ END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
366
+ WHERE json_extract(body,'$.type')='compaction';
367
+ CREATE TABLE IF NOT EXISTS blobs (
368
+ hash TEXT PRIMARY KEY,
369
+ mime TEXT NOT NULL,
370
+ data BLOB NOT NULL
371
+ ) WITHOUT ROWID;
372
+ 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 CG=[20,50,100,200,400,800];function PG(e){if(!e||typeof e!=="object")return!1;let n="code"in e&&typeof e.code==="string"?e.code:"";if(n==="SQLITE_BUSY"||n.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let c="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(c)}function dg(e){let n=0;while(!0)try{return e()}catch(i){let c=CG[n];if(c===void 0||!PG(i))throw i;n++,Bun.sleepSync(c)}}function D$(e,n){if(e!==":memory:")kG(AG(e),{recursive:!0});let i=new TG(e,{create:!0,strict:!0}),c=(g,y=!0)=>new Proxy(function(...x){return Reflect.apply(g,this,x)},{apply(x,b,S){vs();let T=n.length===0&&!i.inTransaction,A=y?Reflect.get(g,"immediate"):void 0,C=()=>{let P=[];n.push(P);let L=!1;try{let q=typeof A==="function"?Reflect.apply(A,g,S):Reflect.apply(x,b,S);return L=!0,q}finally{n.pop();let q=n.at(-1);if(L&&q)q.push(...P);else for(let X of P)if(L)X.commit();else X.rollback()}};return T?dg(C):C()},get(x,b){let S=Reflect.get(g,b);if(["deferred","immediate","exclusive"].includes(String(b))&&typeof S==="function")return c(S,!1);return S}}),p=new Proxy(i,{get(g,y){let x=Reflect.get(g,y,g);if(typeof x!=="function")return x;return(...b)=>{vs();let A=(y==="run"||y==="exec")&&n.length===0&&!i.inTransaction?dg(()=>Reflect.apply(x,g,b)):Reflect.apply(x,g,b);if(y==="transaction"&&typeof A==="function")return c(A,!0);if(y!=="query"&&y!=="prepare")return A;if(!A||typeof A!=="object")throw Error("Invalid SQL statement");return new Proxy(A,{get(C,P,L){let q=Reflect.get(C,P,C);if(typeof q!=="function")return q;return(...X)=>{vs();let J=(P==="run"||P==="get"||P==="all"||P==="values")&&n.length===0&&!i.inTransaction?dg(()=>Reflect.apply(q,C,X)):Reflect.apply(q,C,X);return J===C?L:J}}})}}});if(e!==":memory:")N$(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"),$G(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(RG(y))N$(y,384)}return p}function $G(e,n=lg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>n.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${n.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let c=i;c<n.length;c++)e.transaction(()=>{let p=n[c]??"",g=Array.isArray(p)?p:c>=4?MG(p):[p];for(let y of g)try{if(y.trim())e.run(y)}catch(x){if(!(x instanceof Error)||!/already exists|duplicate column name/i.test(x.message))throw x}e.run(`PRAGMA user_version = ${c+1}`)})()}function MG(e){let n=[],i=0,c=0,p=[],g=!1,y=0,x=(b)=>{let S=e.slice(i,b).trim();if(S)n.push(S);i=b+1,p=[],g=!1,y=0};while(c<e.length){let b=e[c];if(b==="'"||b==='"'||b==="`"||b==="["){let S=b==="["?"]":b;c++;while(c<e.length)if(e[c]===S)if(S!=="]"&&e[c+1]===S)c+=2;else break;else c++;c++;continue}if(b==="-"&&e[c+1]==="-"){let S=e.indexOf(`
373
+ `,c);c=S===-1?e.length:S+1;continue}if(b==="/"&&e[c+1]==="*"){let S=e.indexOf("*/",c+2);c=S===-1?e.length:S+2;continue}if(/[A-Za-z_]/.test(b)){let S=c+1;while(S<e.length&&/[A-Za-z0-9_$]/.test(e[S]))S++;let T=e.slice(c,S).toUpperCase();if(p.length<3)p.push(T),g=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(g){if(T==="BEGIN"||T==="CASE"&&y>0)y++;else if(T==="END"&&y>0)y--}c=S;continue}if(b===";"&&y===0)x(c);c++}return x(e.length),n}var ql=({position:e,closed_at:n,...i})=>({...i,closedAt:n??null}),Fl=(e)=>{let n;if(e.metadata)try{n=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!n?.["automations.id"])n={...n,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:n,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};class jl{path;plugins;entryTransactions=[];db;blobs;constructor(e){this.path=e;this.db=D$(e,this.entryTransactions),this.blobs={put:(n,i,c)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(n,i,c)},get:(n)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(n)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(ql)}project(e){let n=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return n?ql(n):void 0}projectByDirectory(e){let n=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return n?ql(n):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let n=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[i,c]of e.entries())n.run(i,c)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){this.db.query("DELETE FROM projects WHERE id = ?").run(e)}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(Fl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(Fl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(Fl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((n)=>n.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,n,i){this.insertSessionWithRecords(n,or(this.records(e),i))}insertSessionWithRecords(e,n){this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(n.at(-1)?.entry.seq??0,e.id);let i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:c,raw:p}of n){let{seq:g,time:y,...x}=c,b=x,S=Dl(b,this.blobs),T=p===void 0?null:JSON.stringify(Jc(b,p));i.run(e.id,g,y,JSON.stringify(S),T)}})()}truncationEpoch(e){let n=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!n)throw Error("Session no longer exists");return n.truncation_epoch}truncateSession(e,n){this.db.transaction(()=>{this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,n,n),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(n-1,e.id),this.updateSession(e)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,n){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let c of e)i.run(n,c)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.db.query("DELETE FROM sessions WHERE id = ?").run(e)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,n,i,c){vs();let p=this.plugins,g=p?.pinEntry(i),y;try{return y=this.db.transaction(()=>{let x=Math.max(n??0,this.lastSeq(e)+1),S=(g&&p?p.beforeEntry(g,i,e,x):void 0)??i,T=JSON.stringify(S),A=g?JSON.parse(T):S,C={...A,seq:x,time:Date.now()},P=Dl(A,this.blobs),L=P===A&&!g?T:JSON.stringify(P),q=c===void 0?null:JSON.stringify(Jc(A,c));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,x,C.time,L,q),C.type==="user"&&!(("notices"in C)&&C.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(C.time,e);return C})(),y}finally{if(g&&p){let x={commit:()=>p.finishEntry(g,e,y),rollback:()=>p.finishEntry(g,e)},b=this.entryTransactions.at(-1);if(b)b.push(x);else x.commit()}}}setEntryRaw(e,n,i){let c=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,n);if(!c)throw Error("pending message entry is missing or already completed");let p=Ea(JSON.parse(c.body),this.blobs),g=Jc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(g),e,n).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,n=0){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,n).map((i)=>({...Ea(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}))}deleteEntry(e,n){this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,n)}entriesRange(e,n,i=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,n,i).map((c)=>({...Ea(JSON.parse(c.body),this.blobs),seq:c.seq,time:c.time}))}alignToUser(e,n){if(n<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,n)?.seq??1}alignToTurnEnd(e,n){let i=this.lastSeq(e),c=(b)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,b),p=c(n),g=p?.type==="run"&&p.state==="start"?n+1:n;if(g>=i)return i;let y=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,g,g);if(!y)return i;if(y.end)return y.seq;let x=c(y.seq-1);return x?.type==="run"&&x.state==="start"&&y.seq-1>g?y.seq-2:y.seq-1}entriesAround(e,n,i,c){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let g=Math.min(Math.max(1,n),p),y=this.alignToUser(e,Math.max(1,g-i)),x=this.alignToTurnEnd(e,Math.min(p,g+c));return this.window(e,y,x,p)}entriesFrom(e,n,i){let c=this.lastSeq(e),p=Math.max(1,n);if(p>c)return{entries:[],from:p,to:c,hasBefore:c>0,hasAfter:!1};let g=this.alignToTurnEnd(e,Math.min(c,p+i-1));return this.window(e,p,g,c)}window(e,n,i,c){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,n);return{entries:this.entriesRange(e,n,i+1),from:n,to:i,hasBefore:p!==null,hasAfter:i<c}}replayStart(e,n,i){let c=this.lastSeq(e),p=this.lastEntry(e,"compaction"),g=p?.type==="compaction"?p.through+1:1,y=Math.max(1,c-i+1,Math.min(g,c-n+1));return this.alignToUser(e,y)}records(e,n=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,n).map((i)=>{let c=Ea(JSON.parse(i.body),this.blobs);return{entry:{...c,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:pg(c,JSON.parse(i.raw))}}})}lastEntry(e,n){let i=this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,n);return i?{...Ea(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,n){let i=this.truncationEpoch(e),c=n;if(this.plugins){let p=this.plugins.pin();try{let g=await p.invoke("notice.enqueue",n,this.plugins.runtime.get(e));if(g===null)return!1;n={...g,dedupeKey:c.dedupeKey,wake:c.wake&&g.wake,recovery:c.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==i)return!1;if(this.entries(e).some((x)=>x.type==="notice_pending"&&x.notice.dedupeKey===n.dedupeKey||x.type==="user"&&x.notices?.some((b)=>b.dedupeKey===n.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:n}),!0})()}pendingNotices(e){let n=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,n),c=new Set;for(let g of i)if(g.type==="user"&&g.notices)for(let y of g.notices)c.add(y.dedupeKey);else if(g.type==="extension"&&g.namespace==="basalt.notice"&&g.kind==="discarded"&&g.payload&&typeof g.payload==="object"&&"dedupeKey"in g.payload&&typeof g.payload.dedupeKey==="string")c.add(g.payload.dedupeKey);let p=[];for(let g of i)if(g.type==="notice_pending"&&!c.has(g.notice.dedupeKey))p.push(g.notice);return p}}function ue(e){let n=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(n).toString("base64url")}`}import{existsSync as vG,readdirSync as F$,statSync as j$}from"fs";import{join as U$}from"path";function Qc(e){try{return j$(e).size}catch{return 0}}function B$(e){try{return Math.round(j$(e).mtimeMs)}catch{return}}function G$(e){let n=0,i=0;try{let c=F$(e,{withFileTypes:!0});for(let p of c){let g=U$(e,p.name);if(p.isDirectory()){let y=G$(g);n+=y.bytes,i+=y.files}else if(p.isFile())n+=Qc(g),i+=1}}catch{return{bytes:0,files:0}}return{bytes:n,files:i}}function OG(e){if(!vG(e))return[];try{return F$(e,{withFileTypes:!0}).flatMap((n)=>{let i=U$(_G(e),n.name),c=B$(i);if(n.isDirectory()){let p=G$(i);return[{name:n.name,kind:"directory",bytes:p.bytes,files:p.files,...c!==void 0?{modified:c}:{}}]}if(n.isFile())return[{name:n.name,kind:"file",bytes:Qc(i),...c!==void 0?{modified:c}:{}}];return[]}).sort((n,i)=>i.bytes-n.bytes||n.name.localeCompare(i.name))}catch{return[]}}function _G(e){return e}function Vs(e,n){let i=e.db.query(`PRAGMA ${n}`).get();if(!i)return 0;let c=Object.values(i)[0];return typeof c==="number"?c:0}function q$(e,n){try{let i=e.db.query(`PRAGMA ${n}`).get();if(!i)return;let c=Object.values(i)[0];return c!==void 0&&c!==null?String(c):void 0}catch{return}}var LG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},NG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function DG(e){let n=new Map;try{let i=new Map,c=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let g of c)i.set(g.name,g.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let g of p){let y=i.get(g.name)??g.name;if(y.startsWith("sqlite_autoindex_")){let b=y.slice(17),S=b.lastIndexOf("_");if(S>0)y=b.slice(0,S)}let x=n.get(y)??{bytes:0,pages:0};n.set(y,{bytes:x.bytes+(Number(g.bytes)||0),pages:x.pages+(Number(g.pages)||0)})}}catch{}return n}function qG(e){let n=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
374
+ count(*) AS total,
375
+ sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
376
+ sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
377
+ sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
378
+ sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
379
+ FROM sessions`).get(),c=e.db.query(`SELECT
380
+ count(*) AS total,
381
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
382
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
383
+ min(time) AS oldest_time,
384
+ max(time) AS newest_time
385
+ FROM entries`).get(),g=e.db.query(`SELECT
386
+ coalesce(json_extract(body, '$.type'), 'unknown') AS type,
387
+ count(*) AS count,
388
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
389
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes
390
+ FROM entries
391
+ GROUP BY type
392
+ ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((b)=>({type:String(b.type||"unknown"),count:Number(b.count)||0,bodyBytes:Number(b.body_bytes)||0,rawBytes:Number(b.raw_bytes)||0})),y=g.find((b)=>b.type==="compaction")?.count??0,x=[];try{let b=new Map,S=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let C of S)b.set(C.namespace,Number(C.max_ver)||0);let T=e.db.query(`SELECT
393
+ namespace,
394
+ count(*) AS keys,
395
+ coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
396
+ FROM plugin_kv
397
+ GROUP BY namespace
398
+ ORDER BY bytes DESC, keys DESC`).all(),A=new Set;for(let C of T){A.add(C.namespace);let P=b.get(C.namespace);x.push({namespace:C.namespace,keys:Number(C.keys)||0,bytes:Number(C.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[C,P]of b.entries())if(!A.has(C))x.push({namespace:C,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:n,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(c?.total)||0,totalBodyBytes:Number(c?.body_bytes)||0,totalRawBytes:Number(c?.raw_bytes)||0,compactionCount:y,...c?.oldest_time?{oldestEntryTime:Number(c.oldest_time)}:{},...c?.newest_time?{newestEntryTime:Number(c.newest_time)}:{},entryTypes:g,pluginNamespaces:x}}function Ul(e,n){let i=Vs(e,"page_size"),c=Vs(e,"page_count"),p=Vs(e,"freelist_count"),g=e.db.query("PRAGMA journal_mode").get(),y=e.db.query("SELECT sqlite_version() AS v").get(),x=Vs(e,"synchronous"),b=Vs(e,"auto_vacuum"),S=Vs(e,"cache_size"),T=S<0?Math.abs(S)*1024:S*i,A=Vs(e,"foreign_keys")===1,C=Vs(e,"busy_timeout"),P=q$(e,"encoding")??"UTF-8",L=q$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?B$(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=DG(e),V=OG(n);return{dataDir:n,databasePath:e.path,dataBytes:V.reduce((J,ee)=>J+ee.bytes,0),database:{size:Qc(e.path),walSize:Qc(`${e.path}-wal`),shmSize:Qc(`${e.path}-shm`),sqliteVersion:y?.v??"unknown",journalMode:g?.journal_mode??"unknown",synchronous:LG[x]??String(x),foreignKeys:A,busyTimeout:C,encoding:P,autoVacuum:NG[b]??String(b),cacheSizeBytes:T,pageSize:i,pageCount:c,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Vs(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:L},analytics:qG(e),entries:V,tables:X.map(({name:J,sql:ee})=>{let ie=J.replaceAll('"','""'),H=e.db.query(`SELECT count(*) AS count FROM "${ie}"`).get().count,ce=e.db.query(`PRAGMA table_info("${ie}")`).all().map((se)=>se.name),fe=e.db.query(`PRAGMA index_list("${ie}")`).all().length,_e=Boolean(ee&&/WITHOUT\s+ROWID/i.test(ee)),be=j.get(J);return{name:J,rows:H,...be?{bytes:be.bytes,pages:be.pages}:{},indexes:fe,columns:ce,withoutRowid:_e}})}}function FG(e){let n;try{n=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(n.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),c=new Set;for(let g of i)for(let y of g.body.matchAll(/@blob:([0-9a-f]{64})/g)){let x=y[1];if(x)c.add(x)}let p=[];for(let g of n)if(!c.has(g.hash))p.push(g.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let g=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let y of p)g.run(y)})()}catch{return 0}return p.length}function K$(e,n,i){let c=Ul(e,n);if(i.vacuum)L$(e.db),FG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:c,after:Ul(e,n)}}var jG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Bl{plugins;builtinNames;registered=new Map;constructor(e,n){this.plugins=e;this.builtinNames=n}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let n=e.name.trim().toLowerCase();if(!n)throw Error("Tool name cannot be empty");if(jG.has(n))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((c)=>c.toLowerCase()),...this.list().map((c)=>c.name.toLowerCase())]).has(n))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(n,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function H$(e,n){let i=Kr(n);return{id:e,name:n.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:n.contextWindow,maxTokens:n.maxTokens}}async function W$(e,n){let c=(await e.options.models.getAvailable().catch(()=>[])).map((g)=>({...H$(tt(g),g),available:!0})),p=new Set(c.map((g)=>g.id));for(let g of[n,...e.list(!0,{archive:"all"}).map((y)=>y.model)]){if(p.has(g))continue;let y=bn(e.options.models,g);if(!y)continue;p.add(g),c.push({...H$(g,y),available:!1})}return{models:c}}function z$(e,n){if(typeof n!=="string"||!bn(e.options.models,n))throw new t(`unknown model ${n}`);return n}import{existsSync as UG,statSync as BG}from"fs";import{basename as GG,resolve as KG}from"path";class fg{runtime;sessions;emit;arm;constructor(e,n,i,c){this.runtime=e;this.sessions=n;this.emit=i;this.arm=c}requireProject(e){let n=this.runtime.store.project(e);if(!n)throw new f("no such project");return n}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let n=KG(e.directory.trim());if(!UG(n)||!BG(n).isDirectory())throw new t(`${n} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(n);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let c=Date.now(),p={id:ue("p"),name:e.name?.trim()||GG(n)||n,directory:n,instructions:e.instructions??"",created:c,updated:c,closedAt:null};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,n){let c={...this.requireProject(e),...typeof n.name==="string"&&n.name.trim()?{name:n.name.trim()}:{},...typeof n.instructions==="string"?{instructions:n.instructions}:{},...typeof n.closed==="boolean"?{closedAt:n.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(c);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:c}),c}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let n=new Set(this.runtime.store.projects().map((p)=>p.id)),i=new Set(e);if(!(i.size===e.length&&i.size===n.size&&e.every((p)=>n.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let n=this.requireProject(e),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new oe("a session in this project");await this.runtime.plugins.invokeProjectDelete(n),this.runtime.store.deleteProject(e);for(let p of i)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as pK,readFileSync as lK}from"fs";import{homedir as dK}from"os";import{join as gu}from"path";var eM=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),HG={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"]},WG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),yg={'"':['"'],"\u201C":["\u201D",'"']},hg=(e)=>e!==void 0&&/\s/.test(e),tM=(e)=>[...new Set(e)],Xc=(e)=>[...e].length;var zG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function VG(e,n){let i=e.trim().toLowerCase(),c=new Date(n),p=c.getFullYear(),g=c.getMonth(),y=c.getDate();if(i==="today")return{start:new Date(p,g,y).getTime(),end:new Date(p,g,y+1).getTime()};if(i==="yesterday")return{start:new Date(p,g,y-1).getTime(),end:new Date(p,g,y).getTime()};let x=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(x)return{start:n-Number(x[1])*zG[x[2]]};if(/^\d{4}$/.test(i))return{start:new Date(Number(i),0,1).getTime(),end:new Date(Number(i)+1,0,1).getTime()};let b=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!b)return null;let S=Number(b[1]),T=Number(b[3]);if(T<1||T>12)return null;if(b[4]===void 0){if(b[5]!==void 0)return null;return{start:new Date(S,T-1,1).getTime(),end:new Date(S,T,1).getTime()}}let A=Number(b[4]),C=Number(b[5]??0),P=Number(b[6]??0),L=Number(b[7]??0);if(C>23||P>59||L>59)return null;let q=new Date(S,T-1,A,C,P,L);if(q.getMonth()!==T-1||q.getDate()!==A)return null;if(b[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(S,T-1,A+1).getTime()}}var JG=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),xg=(e,n)=>e===void 0?n:n===void 0?e:Math.max(e,n),Ig=(e,n)=>e===void 0?n:n===void 0?e:Math.min(e,n);function gg(e,n,i,c,p,g){let y=i.trim(),x=(S,T)=>e.diagnostics.push({code:S,message:T,filter:n});if(!y)return x("empty_filter",`${n}: \u7F3A\u5C11\u53D6\u503C`);if(c&&n!=="is")return x("unsupported_negation",`-${n}: \u4E0D\u652F\u6301\u53D6\u53CD`);let b=p?[y]:y.split(",").map((S)=>S.trim()).filter(Boolean);switch(n){case"in":case"project":for(let S of b){let T=S.toLowerCase();if(n==="in"&&T==="this")e.currentSession=!0;else if(n==="in"&&T==="title")e.fields.push("title");else e.projectID.push(S)}return;case"session":for(let S of b)if(S.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(S);return;case"from":case"role":for(let S of b){let T=HG[S.toLowerCase()];if(T)e.fields.push(...T);else x("bad_filter_value",`${n}:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...b);return;case"model":e.model.push(...b);return;case"is":for(let S of b){let T=S.toLowerCase();if(T==="error")e.isError=!c;else if(T==="archived")e.archived=!c;else if(T==="compacted")e.compacted=!c;else x("bad_filter_value",`is:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let S=VG(y,g);if(!S)return x("bad_filter_value",`${n}:${y} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(n==="after")e.after=xg(e.after,S.start);else if(n==="before")e.before=Ig(e.before,S.start);else if(e.after=xg(e.after,S.start),S.end!==void 0)e.before=Ig(e.before,S.end)}}}function QG(e,n){let i={},c=(L,q)=>{let X=tM([...L??[],...q]);return X.length?X:void 0},p=c(e?.projectID,n.projectID),g=c(e?.sessionID,n.sessionID),y=c(e?.fields,n.fields),x=c(e?.tools,n.tools),b=c(e?.model,n.model);if(p)i.projectID=p;if(g)i.sessionID=g;if(y)i.fields=y;if(x)i.tools=x;if(b)i.model=b;let S=n.isError??e?.isError,T=n.archived??e?.archived,A=n.compacted??e?.compacted;if(S!==void 0)i.isError=S;if(T!==void 0)i.archived=T;if(A!==void 0)i.compacted=A;let C=xg(e?.after,n.after),P=Ig(e?.before,n.before);if(C!==void 0)i.after=C;if(P!==void 0)i.before=P;if(C!==void 0&&P!==void 0&&C>=P)n.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function V$(e,n){let i=yg[e[n]]??['"'],c="",p=n+1;while(p<e.length){let g=e[p],y=e[p+1];if(g==="\\"&&y!==void 0&&(y==="\\"||y==='"'||y==="\u201C"||y==="\u201D")){c+=y,p+=2;continue}if(i.includes(g))return{text:c,next:p+1,closed:!0};c+=g,p++}return{text:c,next:p,closed:!1}}function J$(e){let n=e[e.length-1];if(e.length<2||!n||n.esc||n.c!==":"&&n.c!=="\uFF1A")return;let i=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(i.length!==e.length-1)return;let c=i.toLowerCase();return eM.has(c)?c:void 0}function Q$(e,n,i){let c=e==="word"&&!i&&Xc(n)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(n)&&!/^\p{N}+$/u.test(n);return{kind:e,text:n,prefix:i,fuzzy:c}}function XG(e,n){let i=[],c=e.length,p=0;while(p<c){if(hg(e[p])){p++;continue}let g=!1;if(e[p]==="-"){if(p+1>=c||hg(e[p+1])){p++;continue}g=!0,p++}if(yg[e[p]]){let P=V$(e,p);if(p=P.next,!P.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let L=P.text.trim();if(L)i.push({kind:"term",negated:g,term:Q$("phrase",L,!1)});continue}let y=[],x;while(p<c&&!hg(e[p])){let P=e[p],L=e[p+1];if(P==="\\"&&L!==void 0&&WG.has(L)){y.push({c:L,esc:!0}),p+=2;continue}let q=yg[P]?J$(y):void 0;if(q){let X=V$(e,p);if(p=X.next,!X.closed)n.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});x={key:q,value:X.text,quoted:!0};break}y.push({c:P,esc:!1}),p++}if(x){i.push({kind:"filter",negated:g,...x});continue}let b=y.findIndex((P,L)=>L>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),S=b>0?J$(y.slice(0,b+1)):void 0;if(S){i.push({kind:"filter",negated:g,key:S,value:y.slice(b+1).map((P)=>P.c).join(""),quoted:!1});continue}if(!g&&y.length===2&&y.every((P)=>!P.esc)&&y[0]?.c==="O"&&y[1]?.c==="R"){i.push({kind:"or"});continue}let T=y[y.length-1],A=y.length>1&&T!==void 0&&!T.esc&&T.c==="*",C=(A?y.slice(0,-1):y).map((P)=>P.c).join("");if(C)i.push({kind:"term",negated:g,term:Q$("word",C,A)})}return i}var YG=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function X$(e){let n=[];return{rest:e.replace(YG,(c,p,g,y,x)=>{let b=y.toLowerCase();if(!eM.has(b))return c;let S=x.startsWith('"')&&x.length>=2;return n.push({key:b,value:S?x.slice(1,-1).replace(/\\(["\\])/g,"$1"):x,negated:g==="-",quoted:S}),p}).trim(),filters:n}}var Y$={n:`
399
+ `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function ZG(e){let n=[...e],i=0,c=(T)=>{let A=n.slice(i,i+T).join("");if(A.length!==T||!/^[0-9a-fA-F]+$/.test(A))return;return i+=T,String.fromCodePoint(Number.parseInt(A,16))},p=()=>{let T=n[i++];if(T===void 0)return{kind:"lit",ch:"\\"};if(T in Y$)return{kind:"lit",ch:Y$[T]};if("dDwWsS".includes(T))return{kind:"any"};if(T==="b"||T==="B")return{kind:"zero"};if(T>="1"&&T<="9"){while(n[i]!==void 0&&/\d/.test(n[i]))i++;return{kind:"any"}}if(T==="k"||T==="p"||T==="P"){let A=n[i];if(A==="<"||A==="{"){let C=A==="<"?">":"}",P=n.indexOf(C,i);i=P<0?n.length:P+1}return{kind:"any"}}if(T==="c")return i++,{kind:"any"};if(T==="x"){let A=c(2);return A===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:A}}if(T==="u"){if(n[i]==="{"){let C=n.indexOf("}",i),P=C<0?"":n.slice(i+1,C).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return i=C+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let A=c(4);return A===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:A}}return{kind:"lit",ch:T}},g=()=>{if(n[i]==="^")i++;while(i<n.length&&n[i]!=="]")i+=n[i]==="\\"?2:1;return i++,{kind:"any"}},y=()=>{let T="capture";if(n[i]==="?"){let C=n[i+1],P=n[i+2];if(C===":")T="plain",i+=2;else if(C==="="||C==="!")T="look",i+=2;else if(C==="<"&&(P==="="||P==="!"))T="look",i+=3;else if(C==="<"){let L=n.indexOf(">",i);i=L<0?n.length:L+1}else{T="opaque";while(i<n.length&&n[i]!==":"&&n[i]!==")")i++;if(n[i]===":")i++}}let A=S();if(n[i]===")")i++;if(T==="look")return{kind:"zero"};return{kind:"group",alts:A,opaque:T==="opaque"}},x=()=>{let T=n[i],A=1,C=!0;if(T==="*"||T==="?")A=0,i++;else if(T==="+")i++;else if(T==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(n.slice(i,i+24).join(""));if(!P)return{quantified:!1,min:1};A=Number(P[1]),i+=P[0].length}else return{quantified:!1,min:1};if(n[i]==="?")i++;return{quantified:C,min:A}},b=()=>{let T=[];while(i<n.length){let A=n[i];if(A==="|"||A===")")break;i++;let C;if(A==="(")C=y();else if(A==="[")C=g();else if(A==="\\")C=p();else if(A===".")C={kind:"any"};else if(A==="^"||A==="$")C={kind:"zero"};else if(A==="*"||A==="+"||A==="?")C={kind:"zero"};else C={kind:"lit",ch:A};T.push({atom:C,...x()})}return T};function S(){let T=[b()];while(n[i]==="|")i++,T.push(b());return T}return S()}function Z$(e){let n=[],i="",c=()=>{if(i)n.push([i]);i=""},p=(g)=>{for(let y of g){let x=y.atom;if(x.kind==="lit")if(y.min>=1){if(i+=x.ch,y.quantified)c()}else c();else if(x.kind==="group"&&!x.opaque&&y.min>=1)if(x.alts.length===1&&!y.quantified)p(x.alts[0]);else c(),n.push(...rM(x.alts));else c()}};return p(e),c(),n}function rM(e){if(e.length===1)return Z$(e[0]);let n=[];for(let i of e){let c=Z$(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!c.length)return[];n.push(c.reduce((p,g)=>Xc(g)>Xc(p)?g:p))}return[tM(n)]}var eK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function tK(e){return!/^\s*$/.test(e)&&(Xc(e)>=2||eK.test(e))}function rK(e){let n;try{n=rM(ZG(e))}catch{return[]}let i=n.filter((b)=>b.every(tK)),c=i.filter((b)=>b.length===1).map((b)=>b[0]),p=i.filter((b)=>{if(b.length!==1)return!0;let S=b[0];return!c.some((T)=>T!==S&&T.includes(S))}),g=new Set,y=p.filter((b)=>{let S=JSON.stringify(b);if(g.has(S))return!1;return g.add(S),!0}),x=(b)=>Math.min(...b.map(Xc));return y.sort((b,S)=>x(S)-x(b))}function nK(e){let n=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(n)}function oK(e,n){let i=`m${n?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(c){let p=c instanceof Error?c.message:String(c),g="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))g="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))g="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))g="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))g="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${g}`}}}function Gl(e,n={}){let i=n.now??Date.now(),c=e.q??"",p=JG(),g=p.diagnostics,y,x=[];if(e.mode==="regex"){let q=X$(c);for(let X of q.filters)gg(p,X.key,X.value,X.negated,X.quoted,i);y=q.rest}else{let q=X$(c),X=/^\/([\s\S]+)\/$/.exec(q.rest);if(X){for(let j of q.filters)gg(p,j.key,j.value,j.negated,j.quoted,i);y=X[1]}else{x=[{include:[],exclude:[]}];for(let j of XG(c,g)){let V=x[x.length-1];if(j.kind==="or")x.push({include:[],exclude:[]});else if(j.kind==="filter")gg(p,j.key,j.value,j.negated,j.quoted,i);else(j.negated?V.exclude:V.include).push(j.term)}x=x.filter((j)=>j.include.length||j.exclude.length)}}let b=x.flatMap((q)=>[...q.include,...q.exclude]),S=y!==void 0?nK(y):b.some((q)=>/\p{Lu}/u.test(q.text)),T=e.caseSensitive??S,A=e.caseSensitive===void 0&&S,C,P;if(y){let q=oK(y,T);if("message"in q)P={code:"bad_regex",message:q.message};else{let X=rK(y);C={source:y,flags:q.flags,literals:X,deepScan:X.length===0}}}let L=QG(e.filters,p);return{mode:y!==void 0?"regex":"text",branches:x,...C?{regex:C}:{},filters:L,currentSession:p.currentSession,caseSensitive:T,smartCase:A,wholeWord:e.wholeWord??!1,fuzzy:x.some((q)=>q.include.some((X)=>X.fuzzy)),hasPositive:C!==void 0||x.some((q)=>q.include.length>0),hasFilters:Object.keys(L).length>0||p.currentSession,...P?{error:P}:{},diagnostics:g}}var Eg={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},nM=new WeakMap;function oM(e){let n=e.query("PRAGMA data_version").get()?.data_version??0,i=nM.get(e);if(i?.version===n)return i.terms;let c=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return nM.set(e,{version:n,terms:c}),c}var bg=32,sK=1024,Yc=(e)=>`"${e.replaceAll('"','""')}"`;function iK(e,n){let i=Array.from({length:n.length+1},(c,p)=>p);for(let c=0;c<e.length;c++){let p=[c+1];for(let g=0;g<n.length;g++)p.push(Math.min((p[g]??0)+1,(i[g+1]??0)+1,(i[g]??0)+Number(e[c]!==n[g])));i=p}return i[n.length]??e.length}function Sg(e,n){let i=ft(n.trim());if(!i||i.length>64)return[];let c=oM(e),p=c.filter((x)=>x.t.startsWith(i)).slice(0,8).map((x)=>x.t);if(p.length>=8||i.length<4)return p;let g=i.length>=8?2:1,y=[];for(let x of c){if(Math.abs(x.t.length-i.length)>g)continue;if(iK(i,x.t)<=g)y.push(x.t);if(y.length>=8)break}return[...new Set([...p,...y])].slice(0,8)}function sM(e,n){let i=!1,c=[],p=[],g=n.filters,y=(X,j)=>{if(!j?.length)return;p.push(`${X} IN (${j.map(()=>"?").join(",")})`),c.push(...j)};if(y("s.project_id",g.projectID),g.sessionID?.length){p.push(`(${g.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let X of g.sessionID)c.push(X,X)}if(g.archived!==void 0)p.push(`s.archived_at IS ${g.archived?"NOT ":""}NULL`);let x=p.length?p.join(" AND "):"1",b=[...c];if(y("r.kind",g.fields?.map((X)=>Oe[X])),y("r.tool",g.tools),g.model?.length){p.push(`(${g.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let X of g.model)c.push(X,X)}if(g.isError!==void 0)p.push("r.err = ?"),c.push(Number(g.isError));if(g.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
400
+ SELECT max(json_extract(body,'$.through')) FROM store.entries
401
+ WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
402
+ ),0)) = ?`),c.push(Number(g.compacted));if(g.after!==void 0)p.push("r.time >= ?"),c.push(g.after);if(g.before!==void 0)p.push("r.time < ?"),c.push(g.before);let S=e.query("SELECT v FROM meta WHERE k='layout'").get(),T=S&&JSON.parse(S.v).msg==="trigram",A=!n.hasPositive||Boolean(n.regex?.deepScan),C=(X)=>{let j=(ee)=>{let ie=ft(ee);if(!X&&T){if([...ie].length<3){let se=[...ie].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ie,`${ie}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ie);if([...ie].length===1&&se.length>bg)se.length=bg,i=!0;if(!se.length)return Yc("__basalt_no_short_match__");return`(${se.map((me)=>Yc(me.term)).join(" OR ")})`}return Yc(ie)}let H=/^[\p{Script=Latin}\p{N}]+$/u.test(ee)?[ie]:zo(ee),ce=H.filter((se)=>!/^[a-z0-9]{1,2}$/.test(se)),fe=ce.length?ce:H;if(!fe.length){A=!0;return}let _e=fe.map((se,me)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(se),xt=fe.length>2&&me>0&&me<fe.length-1;if(qe||xt){let Fe=e.query("SELECT n FROM term WHERE t=?").get(se)?.n??0;return{expression:Yc(se),frequency:Fe}}let Je=[se],Yt=0;for(let Fe of oM(e)){if(!Fe.t.includes(se))continue;if(Yt+=Fe.n,Fe.t!==se)Je.push(Fe.t);if(Je.length>=bg){i=!0;break}}return{expression:`(${Je.map(Yc).join(" OR ")})`,frequency:Yt}});return _e.sort((se,me)=>se.frequency-me.frequency),`(${_e.slice(0,(_e[0]?.frequency??1/0)<=sK?1:2).map((se)=>se.expression).join(" AND ")})`},V=n.regex?n.regex.literals:n.branches.map((ee)=>ee.include.map((ie)=>ie.text));if(n.regex){let ee=V.map((ie)=>ie.map(j));if(ee.some((ie)=>ie.some((H)=>!H)))return;return ee.map((ie)=>`(${ie.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((ee)=>{let ie=ee.filter((H)=>!/^[a-z0-9]{1,2}$/i.test(H));return(ie.length?ie:ee).map(j)});if(J.some((ee)=>!ee.length||ee.some((ie)=>!ie)))return;return J.map((ee)=>`(${ee.join(" AND ")})`).join(" OR ")||void 0},P=C(!1),L=C(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:L,scan:A,where:p.length?p.join(" AND "):"1",bindings:c,forks:q,sessionWhere:x,sessionBindings:b,partial:i,candidateLimit:n.branches.some((X)=>X.include.length>0&&X.include.every((j)=>[...j.text].length<2))?512:void 0}}function iM(e){let n=1/0,i=-1/0;for(let c of e)n=Math.min(n,c.relevance),i=Math.max(i,c.relevance);return e.map((c)=>({...c,relevance:n===i?-1:-(0.5+0.5*(i-c.relevance)/(i-n))}))}function Kl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(Eg).map(([i,c])=>`WHEN ${Oe[i]} THEN ${c}`).join(" ")} ELSE 1 END) *
403
+ (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function aM(e,n,i,c){let p=Math.max(0,c-i)/86400000;return Math.max(0.000000001,-e)*Eg[n]*(0.3+0.7/(1+p/30))}function wg(e,n){return e.sort((i,c)=>(n==="best"?c.score-i.score:0)||(n==="recent"?c.time-i.time:0)||(i.sessionID<c.sessionID?-1:Number(i.sessionID>c.sessionID))||c.seq-i.seq||i.field.localeCompare(c.field))}var Rg=512;function uM(e,n,i){let c=performance.now(),p=n.partial;kg(e,n),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[g,y]of[["fts",n.msg],["fts_out",n.out]]){if(!y)continue;let x=n.candidateLimit??2000,b=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
404
+ ORDER BY ${n.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(y,n.candidateLimit?x+1:x);if(n.candidateLimit&&b.length>x)b.length=x,p=!0;else if(!n.candidateLimit&&b.length===x){let T=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
405
+ AND rowid NOT IN (SELECT value FROM json_each(?))`).all(y,JSON.stringify(b.map((A)=>A.doc)));for(let A of T)b.push(A)}let S=iM(b);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
406
+ FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(S))}return i?.("match",performance.now()-c),p}function cM(e,n,i,c,p){let g=performance.now();if(n.candidateLimit){let x=e.query(`
407
+ SELECT r.session_id,r.seq,${Kl(c)} AS score
408
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
409
+ ${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
410
+ WHERE ${n.where} LIMIT ${n.candidateLimit+1}
411
+ `).all(...n.bindings);if(x.length>n.candidateLimit)x.length=n.candidateLimit,n.partial=!0;let b=new Map;for(let S of x){let T=i?S.seq:0,A=JSON.stringify([S.session_id,T]),C=b.get(A);if(!C||S.score>C.score)b.set(A,{...S,seq:T})}return p?.("filter",performance.now()-g),[...b.values()].sort((S,T)=>T.score-S.score||(S.session_id<T.session_id?-1:Number(S.session_id>T.session_id))||T.seq-S.seq)}let y=e.query(`
412
+ SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Kl(c)}) AS score
413
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
414
+ ${n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
415
+ WHERE ${n.where}
416
+ GROUP BY r.session_id${i?",r.seq":""}
417
+ ORDER BY score DESC,r.session_id,seq DESC LIMIT ${n.candidateLimit?n.candidateLimit+1:-1}
418
+ `).all(...n.bindings);return p?.("filter",performance.now()-g),y}var mM=new WeakMap,aK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
419
+ SELECT id,forked_from_id,forked_from_seq FROM store.sessions
420
+ WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
421
+ UNION
422
+ SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
423
+ FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
424
+ WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
425
+ )`;function kg(e,n){if(!n.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${aK} 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();mM.set(e,new Map(i.map((c)=>[c.ancestor,c.through])))}function Tg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
426
+ SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
427
+ JOIN store.sessions ps ON ps.id=pr.session_id
428
+ WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
429
+ AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
430
+ AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
431
+ SELECT 1 FROM store.entries original JOIN store.entries copied
432
+ ON copied.session_id=r.session_id AND copied.seq=r.seq
433
+ WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
434
+ ))
435
+ ))`}function pM(e,n,i,c,p){let g=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let y=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,x=n.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
436
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${y>4000?"INDEXED BY ref_time":""}
437
+ ${x} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${n.where} AND ${Tg(n)}
438
+ ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${c} OFFSET ?`).run(...n.bindings,...n.forks?n.bindings:[],i);let b=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(b===c){let S=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(S)e.query(`
439
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${x}
440
+ WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
441
+ AND ${n.where} AND ${Tg(n)} AND NOT EXISTS (
442
+ SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
443
+ )`).run(S.session_id,S.seq,...n.bindings,...n.forks?n.bindings:[]),b=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-g),b}function lM(e,n,i,c,p,g,y){let x=performance.now(),b=n.group==="none",S=n.sort==="recent"?"time DESC":"relevance DESC,time DESC",T=e.query(`
444
+ SELECT r.session_id,${b?"r.seq":"0"} AS seq,
445
+ max(${Kl(p)}) AS relevance,max(r.time) AS time
446
+ FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
447
+ WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
448
+ GROUP BY r.session_id${b?",r.seq":""}
449
+ ORDER BY ${S},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(g),c,i);return y?.("group",performance.now()-x),T}function dM(e,n,i,c,p,g){let y=performance.now(),x=p?n:{...n,forks:!1},b=e.query(`
450
+ SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
451
+ ${x.forks||n.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
452
+ WHERE r.session_id=? ${c?"AND r.seq=?":""}
453
+ AND ${n.where} AND ${Tg(x)}
454
+ ${n.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${n.candidateLimit+1}`:""}`).all(i.session_id,...c?[i.seq]:[],...n.bindings,...x.forks?n.bindings:[]);return g?.("filter",performance.now()-y),b}function Ag(e,n,i,c){if(!n.forks)return[];let p=mM.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
455
+ SELECT DISTINCT r.session_id,s.title,e.body
456
+ FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
457
+ CROSS JOIN ref r ON r.session_id=l.child
458
+ JOIN store.sessions s ON s.id=r.session_id
459
+ LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
460
+ WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${n.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...n.bindings).filter((g)=>{if(i.seq===0)return g.title===c;if(!g.body)return!1;let y=JSON.parse(g.body);return Ke(y,!0).some((x)=>x.part===i.part&&x.kind===Xr[i.kind]&&x.text===c)}).map((g)=>g.session_id)}function uK(e,n){let i=n?e:ft(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let c="",p=[],g=[],y=0;for(let x of e){let b=n?x:ft(x);c+=b;for(let S=0;S<b.length;S++)p.push(y),g.push(y+x.length);y+=x.length}return{normalized:c,starts:p,ends:g}}function Hl(e,n){if(n.regex){let b=new RegExp(n.regex.source,`${n.regex.flags}g`),S=[];for(let T of e.matchAll(b)){if(n.wholeWord&&!fM(e,T.index,T.index+T[0].length))continue;S.push([T.index,T.index+T[0].length])}return S.length?S:void 0}let{normalized:i,starts:c,ends:p}=uK(e,n.caseSensitive),g=(b)=>{let S=n.caseSensitive?b.text:ft(b.text),T=[],A=i.indexOf(S);while(A>=0&&S){let C=c?c[A]:A,P=p?p[A+S.length-1]:A+S.length,L=C===0||C!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(C-1,C))||/[a-z0-9][A-Z]/.test(e.slice(C-1,C+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(b.text));if(C!==void 0&&P!==void 0&&(!b.prefix||L)&&(!n.wholeWord||fM(e,C,P)))T.push([C,P]);A=i.indexOf(S,A+Math.max(1,S.length))}return T};if(!n.branches.length)return[];let y=[],x=!1;for(let b of n.branches){if(b.exclude.some((T)=>g(T).length))continue;let S=b.include.map(g);if(S.some((T)=>!T.length))continue;x=!0,y.push(...S.flat())}return x?y:void 0}function fM(e,n,i){let c=/[\p{L}\p{N}_]/u;return(n===0||!c.test(e.slice(n-1,n)))&&(i===e.length||!c.test(e.slice(i,i+1)))}function Wl(e,n){let i=e.split(`
461
+ `),c=new Set,p=0,g=i.map((y,x)=>{let b=p;if(n.some(([S,T])=>S<=b+y.length&&T>=b))for(let S=Math.max(0,x-1);S<=Math.min(i.length-1,x+1);S++)c.add(S);return p+=y.length+1,b});if(!c.size)c.add(0);return[...c].sort((y,x)=>y-x).slice(0,5).map((y)=>{let x=i[y]??"",b=g[y]??0,S=n.filter(([P,L])=>L>b&&P<b+x.length),T=Math.max(0,(S[0]?.[0]??b)-b-100),A=x.slice(T,T+300),C=S.map(([P,L])=>[Math.max(0,P-b-T),Math.min(A.length,L-b-T)]);return{text:A,line:y+1,ranges:C.filter(([P,L])=>P<L)}})}var hM=3;function cK(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 gM(e,n){return n.score-e.score||(e.sessionID<n.sessionID?-1:Number(e.sessionID>n.sessionID))||n.seq-e.seq}function mK(e,n){if(!e)return{offset:0,key:n,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===n&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let c="window"in i?i.window:0,p="seen"in i?i.seen:[],g="emitted"in i?i.emitted:[],y="after"in i?i.after:void 0;if(y!==void 0&&!cK(y))throw Error("invalid best cursor");let x=(b)=>Array.isArray(b)&&b.every((S)=>typeof S==="string"&&S.length<=1024);if(typeof c==="number"&&Number.isSafeInteger(c)&&c>=0&&x(p)&&x(g))return{offset:i.offset,key:n,now:i.now,window:c,seen:p,emitted:g,after:y}}}catch{}throw Error("invalid search cursor")}function On(e,n){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:n})).toString();return mK(e.cursor,i)}async function $r(e,n,i){let c="search"in e?e.search:e,p=performance.now(),g=(Fe)=>{if(!i.signal?.aborted)i.onEvent(Fe)};if(i.signal?.aborted)return;let y=On(n,i.sessionID);if(n.filters?.sessionID?.length===1)n={...n,group:"none"};let x=Gl(n,{now:y.now});if(x.error){g({type:"error",...x.error});return}if(x.currentSession){if(!i.sessionID){g({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}x.filters.sessionID=[i.sessionID]}if(!n.deep&&x.regex?.deepScan){g({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let b=performance.now(),S=c.withIndex((Fe)=>sM(Fe,x));if(!S){g({type:"error",code:"unavailable",message:c.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}i.onTiming?.("plan",performance.now()-b);let T=S.partial,A=y.after,C=new Map,P=new Map,L=[],q=!1,X=new Map,j=new WeakMap,V=new Map,J=new Map,{offset:ee,window:ie}=y,H=[...y.seen],ce=[...y.emitted],fe=!1,_e=Math.max(1,Math.min(200,n.limit??30)),be=Math.min(S.candidateLimit??2000,n.group==="none"?Rg:Math.min(2000,Math.max(Rg,_e*32))),se=(Fe,Ue)=>{let qt=C.get(Ue);if(qt)return qt;let dt=Fe.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Ue);if(dt)C.set(Ue,dt);return dt??void 0},me=(Fe,Ue,qt)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(Ue.session_id))return;if(i.excludeEntry?.sessionID===Ue.session_id&&i.excludeEntry.seq===Ue.seq)return;let dt=se(Fe,Ue.session_id);if(!dt)return;let Ot=Xr[Ue.kind];if(!Ot)return;let yr=dt.title;if(Ue.seq!==0){let st=`${Ue.session_id}:${Ue.seq}`,Jt=J.get(st);if(!Jt){let un=qt?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!qt&&!un)return;let Kt=qt??JSON.parse(un?.body??"null");Jt=Ke(Kt,!0),J.set(st,Jt)}let Zt=Jt.find((un)=>un.part===Ue.part&&un.kind===Ot);if(!Zt)return;yr=Zt.text}let pr=Hl(yr,x);if(!pr)return;let Ut=P.get(dt.id);if(Ut===void 0)Ut=Fe.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(dt.id)?.through??0,P.set(dt.id,Ut);let ot=Ue.seq>0&&Ue.seq<=Ut;if(x.filters.compacted!==void 0&&ot!==x.filters.compacted)return;let Ct={sessionID:dt.id,seq:Ue.seq,time:Ue.time,field:Ot,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:aM(Ue.relevance,Ot,Ue.time,y.now),flags:{archived:dt.archived_at!==null,compacted:ot,partial:yr.length>Ei+Pi}};return X.set(Ct,{text:yr,ranges:pr}),L.push(Ct),q=!0,V.set(Ct,{doc:Ue.doc,part:Ue.part}),Ct},qe=(Fe)=>{let Ue=performance.now(),qt=[...Fe].sort((ot,Ct)=>ot.time-Ct.time||ot.sessionID.localeCompare(Ct.sessionID)),dt=[],Ot=new Map;for(let ot of qt){let Ct=V.get(ot),Jt=C.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=C.get(Jt.forked_from_id)??c.withIndex((wo)=>se(wo,Jt?.forked_from_id??""));let un=`${Jt?.id??ot.sessionID}:${ot.seq}:${Ct?.part}:${Ct?.doc}`,Kt=Ot.get(un);if(Kt){if(Kt.sessionID!==ot.sessionID)Kt.forks=[...new Set([...Kt.forks??[],ot.sessionID])]}else Ot.set(un,ot),dt.push(ot)}let yr=[],pr=new Map,Ut=new Map;for(let ot of dt){let Ct=`${ot.sessionID}:${ot.seq}`,st=Ut.get(Ct);if(!st){Ut.set(Ct,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},Ut.set(Ct,Zt),j.set(Zt,Jt)}for(let ot of wg([...Ut.values()],n.sort??"best")){let Ct=C.get(ot.sessionID);if(!Ct)continue;let st=n.group==="none"?void 0:pr.get(Ct.id);if(!st)st={session:{id:Ct.id,title:Ct.title,projectID:Ct.project_id,updated:Ct.updated},hits:[],more:0,...T&&n.group!=="none"?{moreIsLowerBound:!0}:{}},yr.push(st),pr.set(Ct.id,st);if(st.hits.length<hM||n.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 qt of Ue.hits){if(i.allowedSessionIDs&&qt.forks)qt.forks=qt.forks.filter((yr)=>i.allowedSessionIDs?.has(yr));let dt=performance.now(),Ot=new Map;for(let yr of j.get(qt)??[qt]){let pr=X.get(yr);if(!pr)continue;for(let Ut of Wl(pr.text,pr.ranges)){let ot=`${Ut.line}:${Ut.text}`,Ct=Ot.get(ot);if(!Ct)Ot.set(ot,Ut);else Ct.ranges=[...new Map([...Ct.ranges,...Ut.ranges].map((st)=>[st.join(":"),st])).values()]}}qt.snippet=[...Ot.values()],i.onTiming?.("snippet",performance.now()-dt)}},Je=n.deep||S.scan,Yt=(Fe,Ue)=>{let qt=se(Fe,Ue.session_id);if(!qt)return[];let dt=dM(Fe,S,Ue,n.group==="none",qt.forked_from_id!==null,i.onTiming);if(S.candidateLimit&&dt.length>S.candidateLimit)dt.length=S.candidateLimit,T=!0;let Ot=L.length,yr=performance.now();for(let pr of dt){if(i.signal?.aborted)break;let Ut=me(Fe,pr);if(!Ut)continue;let ot=Ag(Fe,S,pr,X.get(Ut)?.text??"");if(ot.length)Ut.forks=ot}return i.onTiming?.("body",performance.now()-yr),L.slice(Ot)};if(Je){T=!1;let Fe=[],Ue=new Set,qt=c.withIndex((st)=>{kg(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())C.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 wo=Kt.forked_from_id?C.get(Kt.forked_from_id):void 0;if(wo)Zt(wo);if(Jt.has(Kt.id))Fe.push(Kt)};for(let Kt of C.values())Zt(Kt);return(st.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
462
+ SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}
463
+ )`).get(...S.sessionBindings)?.n??0)+Jt.size})??0,dt=0,Ot=0,yr=0;if(x.regex?.deepScan)g({type:"groups",groups:[]});let pr=new Set,Ut=new Set,ot=new Map,Ct=()=>{let st=qe(L),Jt=[];for(let Zt of st){let un=Zt.session.id,Kt=n.group==="none"?void 0:ot.get(un);if(n.group!=="none"&&Ut.has(un)&&!Kt)continue;if(!Kt){if(Ut.add(un),Ot<y.offset){Ot++;continue}if(yr>=_e){fe=!0;break}yr++,ee++}if(n.group!=="none"){let wo=(Kt?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,hM-(Kt?.shown??0));let yu=(Kt?.shown??0)+Zt.hits.length;Zt.more=wo-yu,ot.set(un,{shown:yu,count:wo})}Jt.push(Zt)}if(Jt.length)xt(Jt),g({type:"groups",groups:Jt});L.length=0,X.clear(),V.clear(),J.clear()};for(let st of Fe){if(i.signal?.aborted||fe)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||fe)break;let un=c.withIndex((Kt)=>{let wo=Kt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(st.id,Math.max(0,Jt));if(Jt<0)wo.unshift({seq:0,time:st.updated,body:null});for(let Ui of wo){if(i.signal?.aborted)break;let xu=Ui.body?JSON.parse(Ui.body):void 0;if(xu?.type==="assistant")Zt=xu.model;let SM=xu?Ke(xu,!0):[{part:0,kind:"title",text:st.title}];for(let Ko of SM){if(i.signal?.aborted)break;let Os={session_id:st.id,seq:Ui.seq,part:Ko.part,doc:Number(BigInt(Bun.hash(Ko.text))&0x1fffffffffffffn),kind:Oe[Ko.kind],tool:Ko.tool??null,err:Number(Ko.err??!1),model:Ko.model??(Ko.tool?Zt:void 0)??null,time:Ui.time,relevance:-1};if(!Kt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
464
+ JOIN store.sessions s ON s.id=r.session_id WHERE ${S.where}`).get(Os.session_id,Os.seq,Os.kind,Os.tool,Os.err,Os.model,Os.time,...S.bindings))continue;let Js=st,Pg=new Set;while(Js.forked_from_id&&Js.forked_from_seq!==null&&Ui.seq<=Js.forked_from_seq&&!Pg.has(Js.id)){Pg.add(Js.id);let Iu=C.get(Js.forked_from_id);if(!Iu)break;Js=Iu}let $g=`${Js.id}:${Ui.seq}:${Ko.part}:${Bun.hash(Ko.text)}`;if(pr.has($g))continue;let Mg=me(Kt,Os,xu);if(Mg){if(pr.add($g),S.forks){let Iu=Kt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(st.id,Ui.seq,Ko.part);if(Iu){let vg=Ag(Kt,S,{...Os,doc:Iu.doc},Ko.text);if(vg.length)Mg.forks=vg}}}}}let yu=wo.at(-1);if(yu)Jt=yu.seq;return wo.length});if(un===void 0){g({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(dt+=un,g({type:"progress",scanned:dt,total:qt}),i.signal?.aborted)return;if(Ct(),!un||fe)break;await Bun.sleep(0)}}}else c.withIndex((Fe)=>{if(T=uM(Fe,S,i.onTiming)||T,x.regex?x.regex.literals.every((dt)=>dt.some((Ot)=>[...Ot].length<3)):x.branches.some((dt)=>dt.include.length>0&&dt.include.every((Ot)=>[...Ot.text].length<3)))Fe.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(n.sort!=="recent"){let dt=cM(Fe,S,n.group==="none",y.now,i.onTiming);if(T||=S.partial,S.candidateLimit&&dt.length>S.candidateLimit)dt.length=S.candidateLimit,T=!0;let Ot=[];for(let pr of dt){if(i.signal?.aborted)return;let Ut=Ot[_e]?.key.score;if(Ut!==void 0&&pr.score+0.000000000001<Ut)break;let ot=L.length,Ct=Yt(Fe,pr);L.splice(ot);let st=wg([...Ct],"best")[0];if(!st)continue;let Jt={score:st.score,sessionID:st.sessionID,seq:n.group==="none"?st.seq:0};if(y.after&&gM(Jt,y.after)<=0)continue;if(Ot.push({key:Jt,hits:Ct}),Ot.sort((Zt,un)=>gM(Zt.key,un.key)),Ot.length>_e+1)Ot.length=_e+1}fe=Ot.length>_e;let yr=Ot.slice(0,_e);for(let pr of yr)L.push(...pr.hits);A=yr.at(-1)?.key;return}let qt=0;for(;;){if(i.signal?.aborted)return;let dt=pM(Fe,S,ie,be,i.onTiming),Ot=S.candidateLimit!==void 0&&ie+dt>=S.candidateLimit;T||=Ot;let yr=lM(Fe,n,ee,_e-qt+1,y.now,H,i.onTiming);fe=yr.length>_e-qt;let pr=yr.slice(0,_e-qt);if(!pr.length){if(dt<be||Ot){fe=!1;break}ie+=dt,ee=0,H=[...new Set([...H,...ce])],ce=[];continue}for(let Ut of pr)if(ee++,Yt(Fe,Ut).length){if(qt++,n.group!=="none")ce.push(Ut.session_id)}if(qt>=_e){fe||=!Ot&&dt>=be;break}if(!fe){if(dt<be||Ot)break;ie+=dt,ee=0,H=[...new Set([...H,...ce])],ce=[]}}});if(i.signal?.aborted)return;if(!Je){let Fe=qe(L);xt(Fe),g({type:"groups",groups:Fe})}if(!q){let Fe=x.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)g({type:"suggest",terms:c.withIndex((Ue)=>Sg(Ue,Fe))??[]})}g({type:"done",cursor:fe?Buffer.from(JSON.stringify(!Je&&n.sort!=="recent"?{...y,offset:0,window:0,seen:[],emitted:[],after:A}:{...y,offset:ee,window:ie,seen:H,emitted:ce})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:T,index:c.status()})}function Do(e,n){return e.withIndex((i)=>Sg(i,n))??[]}function yM(e,n,i){let c=v({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:s({query:o(m([l({maxLength:2000}),Pn()])),scope:o(m([a("session"),a("project"),a("all"),a(""),Pn()])),fields:o(m([B(Wr({type:"string",enum:[...In]})),Pn()])),tool:o(m([l(),Pn()])),isError:o(m([D(),Pn()])),after:o(m([l(),Y(),Pn()])),before:o(m([l(),Y(),Pn()])),limit:o(m([w(),Pn()])),session:o(m([l(),Pn()])),seq:o(m([w(),Pn()])),around:o(m([w(),Pn()]))}),async execute(p,g,y){let x={query:g.query?.trim(),scope:g.scope||void 0,fields:g.fields?.length?g.fields:void 0,tool:g.tool?.trim(),isError:g.isError??void 0,after:g.after??void 0,before:g.before??void 0,limit:g.limit||void 0,session:g.session?.trim(),seq:g.seq??void 0,around:g.around??void 0},b=x.query?.trim(),S=!b&&Boolean(x.session?.trim())&&Number.isSafeInteger(x.seq)&&(x.seq??0)>=1;if(S&&x.around!==void 0&&(!Number.isInteger(x.around)||x.around<0||x.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(x.scope&&!["session","project","all"].includes(x.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(y?.aborted)throw Error("History search cancelled");let T=e.sessions().find((se)=>se.id===i);if(!T)throw Error("History session is unavailable");let A=(se)=>{if(se===void 0||se===0||typeof se==="string"&&!se.trim())return;if(typeof se==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(se))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let me=typeof se==="number"?se:Date.parse(se);if(!Number.isFinite(me)||Math.abs(me)>8640000000000000){if(typeof se==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return me},C=S?void 0:A(x.after),P=S?void 0:A(x.before);if(C!==void 0&&P!==void 0&&C>=P)throw Error("after must precede before");let L=[];if(S&&x.session&&x.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===x.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let me=x.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(x.session,Math.max(1,x.seq-me),x.seq+me);if(!qe.some((Je)=>Je.seq===x.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:qe.map((Je)=>{let Yt={...JSON.parse(Je.body),seq:Je.seq,time:Je.time};return`[seq=${Je.seq}]
465
+ ${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
466
+ `).slice(0,4000)}`}).join(`
467
+
468
+ `)||"No history content"}],details:{groups:L,count:qe.length}}}if(!b)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(x.limit)?Math.max(1,Math.min(30,Math.trunc(x.limit??10))):10,X=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,j=new Set(e.sessions().filter((se)=>{if(x.scope==="session")return se.id===i;if((x.scope??"project")==="project"&&T.projectID)return se.projectID===T.projectID;return!0}).map((se)=>se.id)),V={q:b,filters:{tools:x.tool?.trim()?[x.tool.trim()]:void 0,isError:x.isError,after:C,before:P},group:"none",limit:q},J=Gl(V);if(J.error)throw Error(J.error.message);if(x.fields?.length){if(J.filters.fields=x.fields.filter((se)=>(se in Oe)),J.filters.fields.length!==x.fields.length)throw Error("Unknown search field")}if((x.scope??"project")==="session")J.filters.sessionID=[i];else if((x.scope??"project")==="project"&&T.projectID)J.filters.projectID=[T.projectID];let ee=n.status().state!=="ready",ie=!1;if(!ee){let se=J.filters.fields??Object.keys(Oe).filter((xt)=>(xt in Oe)),me=se.filter((xt)=>xt!=="title"),qe=me.length?[me]:[];if(se.includes("title"))qe.push(["title"]);for(let xt of qe){if(L.length>=q&&ie)break;if(await $r(n,{...V,limit:Math.max(1,q-L.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")L.push(...Je.groups);if(Je.type==="done")ie||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")ee=!0;else throw Error(Je.message)}}),ee)break}}let H=[],ce=0;if(ee){L.length=0;let se=performance.now()+2000;e:for(let me of e.sessions()){if(!j.has(me.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(me.id))continue;if(J.filters.projectID&&(!me.projectID||!J.filters.projectID.includes(me.projectID)))continue;let qe=Number.MAX_SAFE_INTEGER,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(me.id,qe);if(xt)Je.push({body:"null",seq:0,time:me.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(ce>=1e4||performance.now()>se){ie=!0;break e}if(ce++,me.id===i&&Yt.seq===X)continue;if(J.filters.after!==void 0&&Yt.time<J.filters.after||J.filters.before!==void 0&&Yt.time>=J.filters.before)continue;let Fe=Yt.seq===0?[{part:0,kind:"title",text:me.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Ue of Fe){if(J.filters.fields&&!J.filters.fields.includes(Ue.kind))continue;if(J.filters.tools&&(!Ue.tool||!J.filters.tools.includes(Ue.tool)))continue;if(J.filters.isError!==void 0&&Boolean(Ue.err)!==J.filters.isError)continue;let qt=Hl(Ue.text,J);if(!qt)continue;if(L.length>=q&&Ue.kind!=="title"){ie=!0;break e}(Ue.kind==="title"?H:L).push({session:{id:me.id,title:me.title,projectID:me.projectID,updated:me.updated},more:0,hits:[{sessionID:me.id,seq:Yt.seq,time:Yt.time,field:Ue.kind,tool:Ue.tool,isError:Boolean(Ue.err),snippet:Wl(Ue.text,qt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(y?.aborted)throw Error("History search cancelled");if(H.length>Math.max(0,q-L.length))ie=!0;if(L.push(...H.slice(0,q)),L.sort((se,me)=>Number(se.hits[0]?.field==="title")-Number(me.hits[0]?.field==="title")),L.length>q)ie=!0;L.length=Math.min(L.length,q);let fe=new Map;for(let se of L)for(let me of se.hits){let qe=fe.get(se.session.id)??[];qe.push(`[${se.session.title.replace(/[\r\n]/g," ")} \xB7 ${me.sessionID} \xB7 ${me.seq} \xB7 ${new Date(me.time).toISOString()} \xB7 ${me.field}${me.tool?`/${me.tool}`:""}]
469
+ ${me.snippet.slice(0,3).map((xt)=>{let Je=xt.text;for(let[Yt,Fe]of[...xt.ranges].sort((Ue,qt)=>qt[0]-Ue[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Fe)}\u3011${Je.slice(Fe)}`;return Je}).join(`
470
+ `)}`),fe.set(se.session.id,qe)}let _e="";if(ee){if(_e="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",n.status().state==="disabled")_e="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let be=L.reduce((se,me)=>se+me.hits.length,0);return{content:[{type:"text",text:[_e,ee&&ie?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ce} \u6761`:"",[...fe.values()].map((se)=>se.join(`
471
+
472
+ `)).join(`
473
+
474
+ `),be===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${be} \u6761\uFF1B${ie?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
475
+ `)}],details:{groups:L,count:be}}}});return Object.assign(c,{source:"history",builtin:!0,defer:"defer"})}async function xM(e,n){let i=n.projectID?e.store.project(n.projectID):void 0,c=i?.directory??process.cwd(),g=n.info().kind==="sub",y=()=>g||n.records.some((S)=>S.entry.type==="compaction"),x=e.options.tools??nr({directory:i?.directory,records:()=>n.records,history:(S)=>e.resolveHistory(n.id,S),onTodos:(S)=>n.setTodos(S),shell:()=>e.serverShell(),hasCompacted:y});if(e.options.tools===void 0)x.push(yM(e.store,e.search,n.id));let b=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:E$({project:i,globalInstructions:hK(e),shell:e.serverShell()});return{systemPrompt:b.map((S)=>S.detail).join(""),systemParts:b,tools:[...x,...e.tools.snapshot()],cwd:c}}var fK=[gu(".basalt","AGENTS.md"),gu(".agents","AGENTS.md"),gu(".opencode","AGENTS.md"),gu(".claude","CLAUDE.md"),gu(".codex","AGENTS.md")];function hK(e){let n=e.options.homeDir??dK();for(let i of fK){let c=gu(n,i);try{if(pK(c))return lK(c,"utf8")}catch{return}}return}class Hr{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new fg(this,this.sessions,(n)=>this.emit(n)),this.defaultModel=e.defaultModel,this.store=new jl(Cg(e.dataDir,"basalt.db")),this.plugins=new Jh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Bl(this.plugins,()=>this.builtinToolNames()),this.search=new Qh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(n)=>this.emit({type:"search_status",status:n})});for(let n of this.store.allSessions()){let i=this.open(n,"restore");this.sessions.set(n.id,i),this.restored.add(i)}}static async create(e){let n=new Hr(e);try{return await n.initialize(),n}catch(i){throw await n.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[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 W$(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((c)=>c.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let n=[...this.sessions.values()];if(await Promise.all(n.map((c)=>c.noticesIdle())),n.some((c)=>c.status==="busy"||!e.includes(c)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Ul(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>K$(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,n){return this.projectOperations.updateProject(e,n)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,n={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let c=n.archive??"active";return c==="all"||i.archivedAt!==null===(c==="archived")}).sort((i,c)=>c.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((n)=>n.info().parentID===e).map((n)=>n.info())}resolveHistory(e,n){let i=this.get(e);if(!i)throw new t("History session is unavailable");let c=i.historyScope(n);if(c)return c;if(n.source&&n.source!=="self"||n.session_id&&n.session_id!==i.id)throw new t("History source is unavailable");return{sessionID:i.id,records:i.records}}openStoredSession(e,n="restore"){let i=this.open(e,n);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let n=e.model??this.defaultModel;if(!bn(this.options.models,n))throw new t(`unknown model ${n}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),c={id:ue("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:n,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(c);let p=this.open(c);return this.sessions.set(c.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,n,i){n={...n,archivedAt:null},this.store.copySession(e,n,i);let c=this.open(n);return this.sessions.set(n.id,c),this.plugins.notify("session.fork",c),this.emit({type:"session",session:c.info()}),c}exportSession(e){let n=this.get(e);if(!n)throw new f("no such session");let i=n.info(),c=i.projectID?this.store.project(i.projectID):void 0;return $$(i,this.store.records(e),c?{name:c.name,directory:c.directory}:void 0)}importSession(e,n={}){if(n.model!==void 0)this.checkModel(n.model);if(n.projectID)this.projectOperations.requireProject(n.projectID);let i=[n.model,e.model,this.defaultModel].find((y)=>y!==void 0&&bn(this.options.models,y)!==void 0),c=i?bn(this.options.models,i):void 0;if(!i||!c)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:ue("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:n.projectID??null,model:i,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?O$(e.records,c):e.records);let g=this.open(p);return this.sessions.set(p.id,g),this.emit({type:"session",session:g.info()}),g}truncateHistory(e,n){let i=this.sessions.get(e.id);if(!i)throw new f("no such session");if(i.assertWritable(),i.status==="busy")throw new oe;if(!bn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);i.close();for(let p of this.sessions.values()){if(p.info().parentID!==e.id)continue;if(p.status==="busy")p.abort();p.close()}this.store.truncateSession(e,n);let c=this.open(e,"replay");return this.sessions.set(e.id,c),this.emit({type:"truncated",sessionID:e.id,after:n-1,truncationEpoch:this.store.truncationEpoch(e.id)}),c}setArchived(e,n){let i=this.sessions.get(e);if(!i)throw new f("no such session");if(i.info().parentID)throw new t("\u8BF7\u5F52\u6863\u6216\u6062\u590D\u6240\u5C5E\u4F1A\u8BDD\uFF08\u542B\u5B50\u4F1A\u8BDD\uFF09");let c=this.sessionTree(i);if(c.some((p)=>p.status==="busy"))throw new oe;if(i.isArchived===n)return i.info();this.store.setArchived(c.map((p)=>p.id),n?Date.now():null);for(let p of c)p.refreshArchive();for(let p of c)p.archiveChanged();return i.info()}sessionTree(e){let n=[e];for(let i=0;i<n.length;i++){let c=n[i];if(!c)continue;for(let p of this.sessions.values())if(p.info().parentID===c.id)n.push(p)}return n}deleteSession(e){let n=this.sessions.get(e);if(!n)throw new f("no such session");if(n.status==="busy")throw new oe;let i=this.sessionTree(n).slice(1),c=()=>{for(let p of i)p.close(),this.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});n.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",n),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return c();n.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(c)}open(e,n="create"){let i=e.id,c=new _l(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>xM(this,p)},{entry:(p)=>{this.emit({type:"entry",sessionID:i,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:i,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(p)=>this.emit({type:"draft",sessionID:i,parts:p}),changed:()=>{let p=this.sessions.get(i);if(p)this.emit({type:"session",session:p.info()})}});if(n!=="restore")this.plugins.notify(n==="create"?"session.create":"session.open",c);return c}get toolLoading(){return new Fi(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!Ql.includes(e))throw new t(`Invalid shell type; must be ${Ql.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return z$(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let n of this.listeners)try{n(e)}catch(i){console.error("runtime listener failed",i)}}}var Re={now:()=>Date.now(),after(e,n){let i=setTimeout(n,e);return()=>clearTimeout(i)}};var IM=1048576,bM=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,n=30000,i,c){this.cwd=e;this.outputLimit=n;this.terminal=i;this.shellPreference=c}setTerminalObserver(e){this.terminal=e}start(e,n,i){let c=i?.observer,p=i?.clock??Re;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let X=od(e);if(X.length>0)throw Error(sd(X))}if(this.list().filter((X)=>X.state==="running").length>=bM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${bM}\uFF09`);let y=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:x,isWindows:b}=ba(e,y),S=Bun.spawn(x,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!b,windowsHide:!0}),T={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:S,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(T.id,T);let A=()=>{for(let X of T.waiters.splice(0))X()},C=async(X,j)=>{let V=new Rl;for await(let ee of X){let ie=V.decode(ee);T.output+=ie,c?.output(ie,j);let H=Buffer.from(T.output);if(H.length>IM){let ce=H.length-IM;while(ce<H.length&&(H[ce]??0)>>6===2)ce++;let fe=H.subarray(ce).toString(),_e=T.output.length-fe.length;T.unreadDroppedBytes+=Buffer.byteLength(T.output.slice(Math.max(0,T.readAt-T.dropped),_e)),T.output=fe,T.dropped+=_e}A()}let J=V.flush();if(T.output+=J,J)c?.output(J,j)},P,L=Promise.all([C(S.stdout,"stdout"),C(S.stderr,"stderr")]).catch((X)=>{P=X,this.kill(T)}),q=!1;if(T.done=(async()=>{if(T.code=await S.exited,T.timer?.(),this.kill(T),await L,P)throw P;if(T.state==="running")T.state="exited";if(q=!0,c?.end(T.state,T.code),!c&&T.state!=="killed")this.terminal?.(T);A()})().catch((X)=>{if(T.state="exited",T.output+=`
476
+ [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(X)}]`,!q)c?.end(T.state,T.code);if(c)throw X;if(!c)this.terminal?.(T,X);A()}),n!==void 0)T.timer=p.after(n,()=>{if(T.state==="running")T.state="timeout",this.kill(T)});return T}find(e){let n=this.jobs.get(e);if(!n)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return n}kill(e){try{if(process.platform==="win32"){let n=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(n.exitCode!==0&&n.exitCode!==128&&e.proc.exitCode===null)throw Error("\u65E0\u6CD5\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B\u6811\uFF0C\u8BF7\u68C0\u67E5\u8FDB\u7A0B\u6743\u9650")}else process.kill(-e.proc.pid,"SIGKILL")}catch(n){if(!(n instanceof Error&&("code"in n)&&n.code==="ESRCH"))throw n}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,n,i=0,c=!1,p){let g=this.find(e),y=n?new RegExp(n):void 0,x=Date.now()+i;p?.throwIfAborted();while(g.state==="running"){p?.throwIfAborted();let C=g.output.slice(Math.max(0,g.readAt-g.dropped));if((y?y.test(C):!c)||Date.now()>=x)break;await new Promise((P,L)=>{let q=()=>{clearTimeout(j);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);L(p?.reason)},X=()=>{clearTimeout(j),p?.removeEventListener("abort",q);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);P()},j=setTimeout(X,Math.max(0,x-Date.now()));g.waiters.push(X),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let b=g.unreadDroppedBytes;g.unreadDroppedBytes=0;let S=g.output.slice(Math.max(0,g.readAt-g.dropped));g.readAt=g.dropped+g.output.length;let T=S.slice(-this.outputLimit),A=b+Buffer.byteLength(S.slice(0,S.length-T.length));return{job:g,output:`${A?`[truncated ${A} bytes]
477
+ `:""}${T}`}}async write(e,n,i=!1,c){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let g=p.proc.stdin;if(!g||typeof g==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(n){let y=await ze(n,c);if(y)throw Error(y);g.write(n)}if(i)await g.end();else await g.flush()}async stop(e){let n=this.find(e);if(n.state==="running")n.state="killed",this.kill(n);return await n.done,{id:n.id,state:n.state,code:n.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var zl=new WeakMap,Vl=new WeakMap;function sr(e,n){let i=zl.get(e);if(!i)i=n(),zl.set(e,i);return i}function ar(e){Vl.set(e,(Vl.get(e)??0)+1)}function lr(e,n){let i=(Vl.get(n)??1)-1;if(Vl.set(n,i),i>0)return!1;if(n.close(),zl.get(e)===n)zl.delete(e);return!0}async function U(e){let n=await e.json();if(!n||typeof n!=="object"||Array.isArray(n))throw new t("expected a JSON object");return n}function E(e,n){let i=e[n];if(!i)throw new t(`${n} is required`);return i}var Nn=100,cr=1e4,gK=60000,yK=200,Rn=()=>l(),EM=()=>o(w({minimum:1,maximum:cr})),Zc=()=>o(l({minLength:1,maxLength:128})),xK=m([s({click:m([Rn(),s({selector:Rn()})])}),s({type:s({label:Rn(),text:Rn()})}),s({waitText:Rn(),timeoutMs:EM()}),s({expectText:Rn(),within:o(Rn())}),s({waitSelector:Rn(),timeoutMs:EM()}),s({expectCount:s({selector:Rn(),n:w({minimum:0})})}),s({snapshot:s({selector:Rn(),depth:o(w({minimum:0,maximum:yK}))})}),s({expectCalls:s({onOpen:o(B(Rn())),onClose:o(w({minimum:0}))})}),s({expectValue:s({label:Rn(),value:Rn()})})]),IK=s({status:w({minimum:100,maximum:599}),body:Rr(),delayMs:o(w({minimum:0,maximum:cr}))}),bK=m([a("paths"),a("request"),a("verify"),a("ui_test"),a("list"),a("docs"),a("check"),a("load"),a("reload"),a("enable"),a("disable")]),EK=m([a("page"),a("tab"),a("card"),a("sidebar")]),wi=s({action:bK,path:o(l({minLength:1,maxLength:4096})),method:o(Rn()),body:o(Ss(Rn(),Rr())),importTimeoutMs:o(w({minimum:1,maximum:cr})),timeoutMs:o(w({minimum:1,maximum:gK})),sessionID:Zc(),scope:o(m([a("user"),a("all")])),id:Zc(),slot:Zc(),view:Zc(),codeBlock:Zc(),kind:o(EK),props:o(Ss(Rn(),Rr())),context:o(Ss(Rn(),Rr())),steps:o(B(xK,{maxItems:Nn})),mockRoutes:o(Ss(Rn(),IK)),topic:o(l({maxLength:100})),grep:o(l({minLength:1,maxLength:200}))});
478
+ export{t,f,pi,di,mi,Fr,er,ko,In,hi,fi,gi,Ft,yi,bi,Mn,Si,Ro,Ee,xi,et,Et,K,Co,ze,Pt,B,o,s,Wr,D,w,a,Y,l,m,h,ae,Ln,Io,Mo,Lo,Oo,we,v,tt,ut,R,O,F,ke,Pe,u,je,rt,tr,rr,We,nr,pt,oe,No,or,ir,ue,On,$r,Do,Hr,Re,Wt,sr,ar,lr,U,E,Uo,Nn,cr,wi};