@bkm016/basalt 0.1.12 → 0.1.13

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 (271) hide show
  1. package/{chunk-7jezts2n.js → chunk-06s9pr82.js} +2 -2
  2. package/{chunk-jpnf71q7.js → chunk-095adzn5.js} +2 -2
  3. package/chunk-0a7ft50x.js +18 -0
  4. package/{chunk-vjne04dp.js → chunk-0nedq669.js} +4 -4
  5. package/chunk-0x9netvr.js +5 -0
  6. package/{chunk-9as0p561.js → chunk-15ve3nmv.js} +11 -11
  7. package/chunk-1dbfmejf.js +2 -0
  8. package/{chunk-hbnmymaq.js → chunk-1q6e3mj7.js} +2 -2
  9. package/{chunk-85v69h91.js → chunk-22az84sh.js} +2 -2
  10. package/{chunk-w0rr66z7.js → chunk-2q56egb8.js} +1 -1
  11. package/{chunk-fhxy6y34.js → chunk-2tf7qfbx.js} +2 -2
  12. package/{chunk-nw1xpt3s.js → chunk-2zbj8ny6.js} +2 -2
  13. package/chunk-302n9g7p.js +2 -0
  14. package/{chunk-bk4rpnm8.js → chunk-37ndxehw.js} +2 -2
  15. package/chunk-41das1ty.js +2 -0
  16. package/{chunk-6mges89p.js → chunk-44a7f5ta.js} +5 -5
  17. package/{chunk-jn5pqy5v.js → chunk-46vy2m29.js} +1 -1
  18. package/{chunk-1zj3zvw5.js → chunk-4k9t9jvx.js} +4 -4
  19. package/{chunk-eq4wqxzt.js → chunk-4rnmxtpx.js} +2 -2
  20. package/{chunk-1xfv4bd7.js → chunk-4w9zqv0k.js} +1 -1
  21. package/chunk-6d9r9p91.js +20 -0
  22. package/chunk-6f4ht2hw.js +2 -0
  23. package/{chunk-jj4hqbrx.js → chunk-6sea12mw.js} +3 -3
  24. package/chunk-74wwdx3y.js +3 -0
  25. package/{chunk-w6f2r052.js → chunk-77c2cqp2.js} +1 -1
  26. package/chunk-7chv3knf.js +2 -0
  27. package/chunk-86yr2c0r.js +3 -0
  28. package/{chunk-6sz5q3df.js → chunk-8cgz8xv7.js} +2 -2
  29. package/{chunk-tvm4zmgj.js → chunk-959z9efn.js} +2 -2
  30. package/{chunk-eyrtbbdd.js → chunk-9e8vhzy7.js} +1 -1
  31. package/chunk-b516bp7n.js +3 -0
  32. package/chunk-bja7p3em.js +25 -0
  33. package/chunk-bng72094.js +2 -0
  34. package/{chunk-ksk49hv0.js → chunk-bp61xdsc.js} +1 -1
  35. package/chunk-bq54argx.js +2 -0
  36. package/chunk-ct77cdg7.js +2 -0
  37. package/{chunk-02d3x4mj.js → chunk-dk6fgprw.js} +3 -3
  38. package/chunk-drett6hb.js +2 -0
  39. package/{chunk-4gtgqcct.js → chunk-edbq461k.js} +3 -3
  40. package/{chunk-p2pmdbt2.js → chunk-f0h2bv11.js} +12 -12
  41. package/{chunk-8mezk0cb.js → chunk-g2etemv5.js} +2 -2
  42. package/{chunk-n0ybj4h9.js → chunk-g5p9mj1r.js} +2 -2
  43. package/{chunk-fy82qxa1.js → chunk-gpnqmtbk.js} +1 -1
  44. package/{chunk-kpe7pnhy.js → chunk-h9zxqeqr.js} +4 -4
  45. package/{chunk-qfcr5g35.js → chunk-jjtt9aq8.js} +3 -3
  46. package/{chunk-5wnmbc1b.js → chunk-kbpbrr11.js} +2 -2
  47. package/chunk-m71pj3g1.js +2 -0
  48. package/chunk-mdkfm1ak.js +7 -0
  49. package/chunk-mf04h0yy.js +7 -0
  50. package/chunk-n22vd4at.js +2 -0
  51. package/{chunk-v7wcchy2.js → chunk-nbjnwd54.js} +1 -1
  52. package/{chunk-1h34mzh7.js → chunk-pryvvs96.js} +22 -22
  53. package/{chunk-2kxnw7vs.js → chunk-r1jn77q6.js} +2 -2
  54. package/{chunk-ypqjfv3a.js → chunk-rn3jwyh1.js} +2 -2
  55. package/chunk-sgrrxsnz.js +482 -0
  56. package/chunk-sgz87ht5.js +2 -0
  57. package/{chunk-stj493dn.js → chunk-snz19yc2.js} +2 -2
  58. package/{chunk-qs8zzg50.js → chunk-szj85dqe.js} +2 -2
  59. package/{chunk-nrsd810j.js → chunk-tfhp09nj.js} +2 -2
  60. package/{chunk-hc300148.js → chunk-tfhze1vq.js} +2 -2
  61. package/{chunk-01nve4qy.js → chunk-tjg0gcks.js} +1 -1
  62. package/{chunk-cbgpymt4.js → chunk-tnj2kqb8.js} +1 -1
  63. package/{chunk-3pf1d62g.js → chunk-vqm94hz2.js} +2 -2
  64. package/{chunk-82v8jh1h.js → chunk-xvm0y99b.js} +2 -2
  65. package/{chunk-rwks9zaw.js → chunk-y23dpz5e.js} +2 -2
  66. package/{chunk-ejjem0tc.js → chunk-y4pvhes1.js} +6 -6
  67. package/{chunk-bwawt15q.js → chunk-ydzag81d.js} +2 -2
  68. package/chunk-ymg7mtcx.js +3 -0
  69. package/chunk-yy1f9jxc.js +4044 -0
  70. package/{chunk-ntks40jd.js → chunk-z0c8ek0j.js} +5 -5
  71. package/chunk-zk91579b.js +3 -0
  72. package/{chunk-0fc9apfn.js → chunk-zx75vnw8.js} +18 -18
  73. package/compiled.js +85 -12
  74. package/package.json +1 -1
  75. package/ui-test-worker.js +53 -53
  76. package/web/{chunk-aeymdtm1.js → chunk-0jbf73pr.js} +3 -3
  77. package/web/{chunk-7vgh17es.js → chunk-0rhx7qb8.js} +1 -1
  78. package/web/{chunk-7adsmqv6.js → chunk-0rvwj2wh.js} +2 -2
  79. package/web/chunk-12qf1r6m.js +1 -0
  80. package/web/{chunk-dndd757x.js → chunk-14vmr99v.js} +3 -3
  81. package/web/{chunk-4f6a8dsk.js → chunk-16jc5m0f.js} +1 -1
  82. package/web/{chunk-bra33pt0.js → chunk-1m6fx2h7.js} +2 -2
  83. package/web/{chunk-hva7xyne.js → chunk-1xm9x7d6.js} +1 -1
  84. package/web/{chunk-8539865x.js → chunk-20jxvmbw.js} +1 -1
  85. package/web/chunk-2n5xbnrt.js +1 -0
  86. package/web/{chunk-bygwbpvq.js → chunk-2sef2wft.js} +2 -2
  87. package/web/{chunk-w9gnqkez.js → chunk-2x7vmhm0.js} +2 -2
  88. package/web/{chunk-19zd0tye.js → chunk-2y1avvqj.js} +8 -8
  89. package/web/chunk-36s08nye.js +1 -0
  90. package/web/chunk-3ctmehg4.js +1 -0
  91. package/web/{chunk-ncfzmf2g.js → chunk-3jjksgze.js} +1 -1
  92. package/web/{chunk-aebrw6cv.js → chunk-3p9w8sg5.js} +2 -2
  93. package/web/{chunk-sdr5wa4z.js → chunk-3wpxymxa.js} +3 -3
  94. package/web/{chunk-v34mr9ky.js → chunk-4py9sndw.js} +3 -3
  95. package/web/chunk-4swea9sn.js +1 -0
  96. package/web/chunk-4zz5a483.js +1 -0
  97. package/web/{chunk-3rkkp6ed.js → chunk-5cwxhhae.js} +5 -5
  98. package/web/{chunk-d57fm7k0.js → chunk-5ym5ffd5.js} +2 -2
  99. package/web/{chunk-gten0rpx.js → chunk-6e87m0nm.js} +2 -2
  100. package/web/{chunk-b99k8q22.js → chunk-6rsr2cyw.js} +8 -8
  101. package/web/chunk-6y55gk1n.js +1 -0
  102. package/web/chunk-7aep7k4v.js +1 -0
  103. package/web/{chunk-yf8ykk4v.js → chunk-8j4tzff5.js} +3 -3
  104. package/web/{chunk-ny436sqg.js → chunk-8tgavnwx.js} +1 -1
  105. package/web/{chunk-xvfeq8v2.js → chunk-97t3ngqf.js} +12 -12
  106. package/web/{chunk-gkmaryr4.js → chunk-980zhtht.js} +1 -1
  107. package/web/chunk-9k7fkx80.js +1 -0
  108. package/web/{chunk-hxbfkdjd.js → chunk-9wz8jne3.js} +1 -1
  109. package/web/chunk-a00vg115.js +1 -0
  110. package/web/chunk-a4gbxnm3.js +1 -0
  111. package/web/{chunk-6f2sz84q.js → chunk-a6g3nqp0.js} +1 -1
  112. package/web/{chunk-n9v14vyd.js → chunk-a9er7a7c.js} +22 -22
  113. package/web/chunk-atppv8fk.js +1 -0
  114. package/web/{chunk-xbyrgyy0.js → chunk-awkdw9rw.js} +2 -2
  115. package/web/{chunk-hqxc9m07.js → chunk-b4gcpsbg.js} +10 -10
  116. package/web/{chunk-qdd3bx8q.js → chunk-b9jry5a3.js} +1 -1
  117. package/web/{chunk-jyf7a7yp.js → chunk-ba9qy65y.js} +1 -1
  118. package/web/chunk-bq6mep6p.js +2 -0
  119. package/web/chunk-bwy3e58v.js +1 -0
  120. package/web/{chunk-aa46mrgh.js → chunk-c57f714b.js} +2 -2
  121. package/web/{chunk-b5zf1hs3.js → chunk-c6m4vfn5.js} +101 -101
  122. package/web/{chunk-5np514v5.js → chunk-cr04125j.js} +4 -4
  123. package/web/{chunk-ym7kv2hs.js → chunk-cr05dttm.js} +1 -1
  124. package/web/{chunk-2cyzaqjy.js → chunk-ct7z7bea.js} +3 -3
  125. package/web/{chunk-y2rzeb4v.js → chunk-ct90yf8z.js} +2 -2
  126. package/web/{chunk-yjs6jmdb.js → chunk-ddg8rz82.js} +3 -3
  127. package/web/{chunk-8cnjd0f2.js → chunk-dmha2y9c.js} +18 -18
  128. package/web/{chunk-jeafmjsm.js → chunk-e57h40qa.js} +6 -6
  129. package/web/chunk-eeesa5q1.js +1 -0
  130. package/web/{chunk-4wwd3pfz.js → chunk-eqndhs21.js} +2 -2
  131. package/web/{chunk-td83xf12.js → chunk-eqxy6535.js} +2 -2
  132. package/web/{chunk-wvrs986a.js → chunk-et1rsgmp.js} +3 -3
  133. package/web/chunk-f7jpakwh.js +1 -0
  134. package/web/{chunk-v1hfbjz9.js → chunk-fnvgdvrg.js} +4 -4
  135. package/web/chunk-fp62avjh.js +1 -0
  136. package/web/{chunk-6jb2zyp6.js → chunk-frnh4zqf.js} +2 -2
  137. package/web/chunk-g0be12na.js +1 -0
  138. package/web/{chunk-60mym60n.js → chunk-g7hqafb8.js} +1 -1
  139. package/web/{chunk-wqzbxzk3.js → chunk-ga07tv37.js} +1 -1
  140. package/web/chunk-gr163fex.js +1 -0
  141. package/web/chunk-gxtz10wf.js +1 -0
  142. package/web/{chunk-pjpre6de.js → chunk-h1k2kqbs.js} +6 -6
  143. package/web/{chunk-7tkgbbf9.js → chunk-h6k1x096.js} +2 -2
  144. package/web/{chunk-885kpj14.js → chunk-jccz14ye.js} +2 -2
  145. package/web/{chunk-d73zkc4q.js → chunk-jh33m2mq.js} +2 -2
  146. package/web/{chunk-g488hxx0.js → chunk-jh3k7xex.js} +3 -3
  147. package/web/{chunk-3qxxrwsp.js → chunk-jpem3qvs.js} +10 -10
  148. package/web/chunk-k9qnvx86.js +2 -0
  149. package/web/chunk-kcnj0gan.js +1 -0
  150. package/web/{chunk-2jfesv7m.js → chunk-ke8dffnk.js} +2 -2
  151. package/web/chunk-kpp5xqsb.js +1 -0
  152. package/web/chunk-m33yted6.js +1 -0
  153. package/web/chunk-me5jqqn6.js +1 -0
  154. package/web/{chunk-7v85yvb2.js → chunk-mkxeenph.js} +1 -1
  155. package/web/{chunk-mxkbmgcv.js → chunk-mnf4ngj9.js} +1 -1
  156. package/web/{chunk-30aeb767.js → chunk-mykrm8ba.js} +2 -2
  157. package/web/chunk-mzqqwbmr.js +1 -0
  158. package/web/chunk-npyrdsf8.css +1 -0
  159. package/web/chunk-p6e2vr51.js +34 -0
  160. package/web/{chunk-3n9ypydh.js → chunk-p7pa02k9.js} +2 -2
  161. package/web/chunk-q34as3v6.js +1 -0
  162. package/web/{chunk-7ksg3ccg.js → chunk-q4vy3dkk.js} +2 -2
  163. package/web/chunk-q6c8p73w.js +1 -0
  164. package/web/{chunk-h754ntg7.js → chunk-qb8mbptk.js} +1 -1
  165. package/web/{chunk-g4zm0crw.js → chunk-qbmtah1x.js} +1 -1
  166. package/web/chunk-qn93we3a.js +1 -0
  167. package/web/{chunk-c3fty2c2.js → chunk-qq06x2ce.js} +7 -7
  168. package/web/{chunk-fj753yzt.js → chunk-qq6m2my8.js} +2 -2
  169. package/web/chunk-r1f1egve.js +1 -0
  170. package/web/{chunk-80z8s8zb.js → chunk-s935z8er.js} +1 -1
  171. package/web/{chunk-3psgr0q8.js → chunk-sq75q603.js} +20 -20
  172. package/web/{chunk-qp3tjhaq.js → chunk-ss96cz1f.js} +1 -1
  173. package/web/{chunk-hn8m1vsg.js → chunk-t82sngk9.js} +7 -7
  174. package/web/chunk-tt9410zw.js +8 -0
  175. package/web/{chunk-act3rr85.js → chunk-v4cqc9f9.js} +1 -1
  176. package/web/chunk-ve8gy05p.js +1142 -0
  177. package/web/chunk-vg1ebkce.js +1 -0
  178. package/web/{chunk-k4dnjf8n.js → chunk-vk7ch6fh.js} +3 -3
  179. package/web/chunk-vnt34mkb.js +1 -0
  180. package/web/{chunk-kerfb21g.js → chunk-w28dn4dw.js} +1 -1
  181. package/web/{chunk-rdr6wt22.js → chunk-w4tfad6c.js} +4 -4
  182. package/web/{chunk-81s15c2e.js → chunk-wpxtkxjt.js} +2 -2
  183. package/web/{chunk-h24ybwp6.js → chunk-xcyqd7cn.js} +1 -1
  184. package/web/chunk-xe121vg7.js +1 -0
  185. package/web/chunk-xh4xn1az.js +1 -0
  186. package/web/{chunk-e94pd9rr.js → chunk-xk1vkcj4.js} +9 -9
  187. package/web/chunk-xrk5ewsn.js +1 -0
  188. package/web/{chunk-5g8md2wg.js → chunk-xvm66b7v.js} +4 -4
  189. package/web/{chunk-q1zxvjhs.js → chunk-xxmaqj1m.js} +2 -2
  190. package/web/chunk-xzwxcxb4.js +1 -0
  191. package/web/{chunk-xpecre7w.js → chunk-y9waq403.js} +4 -4
  192. package/web/chunk-ydhnkws0.js +1 -0
  193. package/web/{chunk-ar6jnhm5.js → chunk-yn4t5s9r.js} +1 -1
  194. package/web/chunk-ys2tns0p.js +1 -0
  195. package/web/chunk-zb61mf0a.js +1 -0
  196. package/web/{chunk-r6kk4vp1.js → chunk-ze6azq7z.js} +4 -4
  197. package/web/chunk-zh7193nq.js +2 -0
  198. package/web/chunk-zqcg6frm.js +1 -0
  199. package/web/{chunk-enwfd8d5.js → chunk-zxrbbbtp.js} +2 -2
  200. package/web/index.html +1 -1
  201. package/worker.js +1 -1
  202. package/chunk-2fyjph3f.js +0 -2
  203. package/chunk-37zystxb.js +0 -25
  204. package/chunk-3k627vf2.js +0 -3
  205. package/chunk-7er5pz7s.js +0 -479
  206. package/chunk-7g5smgjj.js +0 -2
  207. package/chunk-7m3jagqn.js +0 -2
  208. package/chunk-9c4gdg1q.js +0 -3
  209. package/chunk-b2bxqeb4.js +0 -2
  210. package/chunk-bpw6q7g0.js +0 -3
  211. package/chunk-cdw03j4t.js +0 -20
  212. package/chunk-ch1r3ted.js +0 -2
  213. package/chunk-cmwdjes8.js +0 -18
  214. package/chunk-db7ws33a.js +0 -7
  215. package/chunk-e1x629v0.js +0 -5
  216. package/chunk-j64dc767.js +0 -3
  217. package/chunk-m4bg1apa.js +0 -7
  218. package/chunk-nhm9z3d8.js +0 -2
  219. package/chunk-pnspvnyd.js +0 -2
  220. package/chunk-qnkrrwmg.js +0 -2
  221. package/chunk-r4gm8ngh.js +0 -2
  222. package/chunk-rks90mh1.js +0 -2
  223. package/chunk-t7te60m7.js +0 -2
  224. package/chunk-tv52xajf.js +0 -2
  225. package/chunk-wqqjzsjt.js +0 -3983
  226. package/chunk-xef4642x.js +0 -3
  227. package/web/chunk-04drx71p.js +0 -1
  228. package/web/chunk-0mdf1qja.js +0 -1
  229. package/web/chunk-0rdgt4jb.css +0 -1
  230. package/web/chunk-1m0kp0g3.js +0 -8
  231. package/web/chunk-3j2tcphs.js +0 -1
  232. package/web/chunk-3k9h7a73.js +0 -1142
  233. package/web/chunk-3m1bb2fw.js +0 -1
  234. package/web/chunk-55nvm2mj.js +0 -1
  235. package/web/chunk-5dkqfnh7.js +0 -2
  236. package/web/chunk-7ky5nrrr.js +0 -1
  237. package/web/chunk-8sdjgv3k.js +0 -1
  238. package/web/chunk-9bxtzwtc.js +0 -1
  239. package/web/chunk-9jy8nc4r.js +0 -1
  240. package/web/chunk-bcjgzwef.js +0 -1
  241. package/web/chunk-cxpnj495.js +0 -2
  242. package/web/chunk-d1btrqmw.js +0 -1
  243. package/web/chunk-d94t9z70.js +0 -1
  244. package/web/chunk-e68jw0bg.js +0 -1
  245. package/web/chunk-fr4fft89.js +0 -1
  246. package/web/chunk-gckmcef6.js +0 -1
  247. package/web/chunk-gnb09wmx.js +0 -1
  248. package/web/chunk-hrgqc1vr.js +0 -1
  249. package/web/chunk-j9c8fa82.js +0 -1
  250. package/web/chunk-jz5mmp64.js +0 -1
  251. package/web/chunk-kxeaj44h.js +0 -1
  252. package/web/chunk-m0136xav.js +0 -1
  253. package/web/chunk-m1rdyvb5.js +0 -1
  254. package/web/chunk-m6vyvgm5.js +0 -1
  255. package/web/chunk-my0ec787.js +0 -1
  256. package/web/chunk-nkpdd9hw.js +0 -1
  257. package/web/chunk-pbp1p5ex.js +0 -1
  258. package/web/chunk-ph75hddv.js +0 -1
  259. package/web/chunk-phdfyqaa.js +0 -1
  260. package/web/chunk-phxa5krt.js +0 -1
  261. package/web/chunk-r4zbw4zj.js +0 -2
  262. package/web/chunk-ry4ycah9.js +0 -1
  263. package/web/chunk-sqm16fat.js +0 -1
  264. package/web/chunk-tj1fn8v2.js +0 -1
  265. package/web/chunk-v0wtk059.js +0 -34
  266. package/web/chunk-v1qt3gq4.js +0 -1
  267. package/web/chunk-v854w9yn.js +0 -1
  268. package/web/chunk-ve56gxq0.js +0 -1
  269. package/web/chunk-w573ym17.js +0 -1
  270. package/web/chunk-x0mjydtp.js +0 -1
  271. package/web/chunk-zhybh04p.js +0 -1
@@ -0,0 +1,482 @@
1
+ // @bun
2
+ import{ei,nn,G}from"./chunk-edbq461k.js";import{Gi,ze,Rt,zi,lo,Vi,Ki,Qi,Ct,Yi,Be,uo,Je}from"./chunk-44a7f5ta.js";import{eo,ts,rn}from"./chunk-g5p9mj1r.js";import{Oe,oe,ti,to,N,ro,yt,Ne,br,W,De,no,bt,ge,zt,ae,on,ri,Ue,ie,st,oo,ni,xe,rs,Hi,ve,io,d,ns,Y,sn,V,os}from"./chunk-y4pvhes1.js";import{so,D,ao,Xe,qi,jt,Ie}from"./chunk-szj85dqe.js";import{r,Ze}from"./chunk-ydzag81d.js";var xy=r(function(d2,yy){var IM=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],pd=/[\n\r\u2028\u2029]/,bM=/[\s#!"$&'():;<=>@\\^`|~]/g;yy.exports=function(o){var i=!1;return o.map(function(u){if(i&&typeof u==="string"&&pd.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(pd.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(bM,"\\$&")}if("op"in u&&typeof u.op==="string"){if(IM.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(pd.test(u.comment))throw TypeError("`comment` must not contain line terminators");return i=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var ky=r(function(f2,Ry){var wy="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Iy=new RegExp("^"+wy+"$"),by="|&;()<> \\t",EM="'([^']*?)'",Ty="(?:\\\\[\\s\\S]|[^\\\\'])*?",Ey="\\$'"+Ty+"'",sm=new RegExp("\\$'"+Ty+"(?:(')|\\\\?$)","g"),SM="abeEfnrtv",wM=`\x07\b\x1B\x1B\f
3
+ \r \v`,TM=/^#$/,ld="'",Sy='"',ku="$",vi="",RM=4294967296;for(om=0;om<4;om++)vi+=(RM*Math.random()).toString(16);var om,kM=new RegExp("^"+vi);function AM(e,o){var i=o.lastIndex,u=[],m;while(m=o.exec(e))if(u[u.length]=m,o.lastIndex===m.index)o.lastIndex+=1;return o.lastIndex=i,u}function PM(e,o,i){var u=typeof e==="function"?e(i):e[i];if(typeof u>"u"&&i!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+vi+JSON.stringify(u)+vi;return o+u}var CM=/\\([0-7]{1,3}|x[\dA-Fa-f]{1,2}|u[\dA-Fa-f]{1,4}|U[\dA-Fa-f]{1,8}|c(?:\\\\|[\s\S])|[abeEfnrtv\\'"?])/g;function $M(e,o){var i=o.charAt(0);if(i==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var m=parseInt(o.slice(1),16);if(m>1114111)return e;return String.fromCharCode.apply(null,m>65535?[55232+(m>>10),56320+(m&1023)]:[m])}if(i>="0"&&i<="7")return String.fromCharCode(parseInt(o,8)&255);var p=SM.indexOf(o);return p<0?o:wM.charAt(p)}function vM(e){return e.replace(CM,$M).split("\x00")[0]}function MM(e,o){return sm.lastIndex=o,!!sm.exec(e)[1]}function OM(e,o,i){if(!i)i={};var u=i.escape||"\\",m=i.splitUnquoted===!0?`
4
+ `:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",p="(\\"+u+`['"$\\`+u+by+"]|\\$\\$|\\$(?!"+Ey.slice(2)+`)|[^\\s'"$`+by+"])+",f='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',h=new RegExp(["("+wy+")","("+Ey+"|"+p+"|"+f+"|"+EM+")+"].join("|"),"g"),x=AM(e,h);if(x.length===0)return[];if(!o)o={};var I=!1;return x.map(function(S){var R=S[0];if(!R||I)return;if(Iy.test(R))return{op:R};var k=!1,A=!1,v="",_=[],Q=!1,L=null,z=!1,J;function Z(){J+=1;var ue,$e,gt=R.charAt(J);if(gt==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var Ke=1;ue=J;while(Ke>0&&ue<R.length){if(R.charAt(ue)==="{"&&R.charAt(ue-1)==="$")Ke+=1;else if(R.charAt(ue)==="}")Ke-=1;ue+=1}if(Ke!==0)throw Error("Bad substitution: "+R.slice(J));ue-=1,$e=R.slice(J,ue),J=ue}else if(/[*@#?$!-]/.test(gt))$e=gt;else{var Zt=R.slice(J);if(ue=Zt.match(/[^\w\d_]/),!ue)$e=Zt,J=R.length;else $e=Zt.slice(0,ue.index),J+=ue.index-1}return PM(o,"",$e)}function re(){if(L===null)return;if(L===0){if(v!=="")_[_.length]=v,v=""}else{_[_.length]=v,v="";for(var ue=1;ue<L;ue+=1)_[_.length]=""}L=null}for(J=0;J<R.length;J++){var U=R.charAt(J);if(m&&U!==ku)re();if(z=z||!k&&(U==="*"||U==="?"),A)v+=U,A=!1;else if(k)if(U===k)k=!1;else if(k==ld)v+=U;else if(U===u)if(J+=1,U=R.charAt(J),U===Sy||U===u||U===ku)v+=U;else v+=u+U;else if(U===ku)v+=Z();else v+=U;else if(U===Sy||U===ld)k=U,Q=!0;else if(Iy.test(U))return{op:R};else if(TM.test(U)){I=!0;var ne={comment:e.slice(S.index+J+1)};if(v.length)return[v,ne];return[ne]}else if(U===u)A=!0;else if(U===ku&&R.charAt(J+1)===ld&&MM(R,J))re(),Q=!0,v+=vM(R.slice(J+2,sm.lastIndex-1)),J=sm.lastIndex-1;else if(U===ku){var fe=Z();if(!m)v+=fe;else for(var Re=0;Re<fe.length;Re+=1){var Ee=fe.charAt(Re);if(m.indexOf(Ee)<0)re(),v+=Ee;else if(L===null)L=Ee===" "||Ee==="\t"||Ee===`
5
+ `?0:1;else if(Ee!==" "&&Ee!=="\t"&&Ee!==`
6
+ `)L+=1}}else v+=U}if(z)return{op:"glob",pattern:v};if(m){if(L!==null&&L>0){_[_.length]=v,v="";for(var ee=1;ee<L;ee+=1)_[_.length]=""}if(v!==""||Q&&_.length===0)_[_.length]=v;return _}return v}).reduce(function(S,R){if(typeof R>"u")return S;return[].concat(R).forEach(function(k){S[S.length]=k}),S},[])}Ry.exports=function(o,i,u){var m=OM(o,i,u);if(typeof i!=="function")return m;return m.reduce(function(p,f){if(typeof f==="object")return p[p.length]=f,p;var h=f.split(RegExp("("+vi+".*?"+vi+")","g"));if(h.length===1)return p[p.length]=h[0],p;return h.filter(Boolean).forEach(function(x){p[p.length]=kM.test(x)?JSON.parse(x.split(vi)[1]):x}),p},[])}});var Zo={};Ze(Zo,{ArchivedError:()=>ft,BadRequestError:()=>t,BusyError:()=>ce,DEFAULT_TIMEOUT:()=>B$,FoldingPolicy:()=>zc,MAX_ATTACHMENTS:()=>mt,MAX_TIMEOUT:()=>G$,MAX_TOOL_OUTPUT:()=>Ce,NotFoundError:()=>b,PluginCheckError:()=>ht,ProcessRegistry:()=>Gt,Type:()=>mo,aliased:()=>Pe,budget:()=>Wc,calls:()=>Po,clip:()=>le,clipSaved:()=>it,dataDir:()=>nt,definePlugin:()=>C,estimateMessage:()=>q,estimateTokens:()=>F,estimateTools:()=>ki,extensionTranscript:()=>vl,findWindowsBash:()=>ar,foldPoint:()=>Kc,foldedThrough:()=>Ta,formatLines:()=>Vc,gateShellCommand:()=>Qe,groupRuns:()=>Qs,historyTodos:()=>pr,newID:()=>se,normalizeRunRecords:()=>Jh,processRegistry:()=>dr,project:()=>Me,projectUserText:()=>Ai,releaseProcesses:()=>hr,requestBody:()=>O,resolveShellCommand:()=>Aa,retainProcesses:()=>mr,routeParam:()=>P,runShell:()=>lr,sealPoint:()=>lu,selectHistory:()=>ur,sessionTools:()=>cr,staleFold:()=>kl,text:()=>c,timerClock:()=>Le,tool:()=>E,toolSession:()=>K,transcript:()=>hu,usable:()=>me,userTranscript:()=>$l,validAttachment:()=>qt,workState:()=>Pl});var Qo={};Ze(Qo,{AssistantMessageEventStream:()=>D,AssistantMessageFrameEncoder:()=>QR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>ZR,EventStream:()=>so,InMemoryCredentialStore:()=>to,InMemoryModelsStore:()=>ro,ModelsError:()=>N,StringEnum:()=>AF,Type:()=>mo,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>Y,clampThinkingLevel:()=>V,cleanupSessionResources:()=>ts,collapseSystemMessages:()=>Ue,contentText:()=>br,createAssistantMessageDiagnostic:()=>jt,createAssistantMessageEventStream:()=>ao,createFauxCore:()=>JR,createInitialSystemMessage:()=>no,createModels:()=>io,createProvider:()=>d,declarationsEqual:()=>oo,defaultProviderAuthContext:()=>ti,envApiKeyAuth:()=>y,extractDiagnosticError:()=>qi,fauxAssistantMessage:()=>Vo,fauxProvider:()=>Ko,fauxText:()=>qn,fauxThinking:()=>jo,fauxToolCall:()=>iF,formatThrownValue:()=>Xe,getCurrentSystemMessage:()=>on,getCurrentSystemPrompt:()=>ri,getCurrentTools:()=>ae,getDeclaredTools:()=>xe,getInitialSystemMessage:()=>ge,getModelType:()=>yt,getOverflowPatterns:()=>SF,getSupportedThinkingLevels:()=>sn,getSystemMessageText:()=>W,getToolStateChanges:()=>ni,hasApi:()=>ns,hasNonAdditiveToolChanges:()=>Hi,hasToolRedefinitions:()=>rs,isContextOverflow:()=>ha,isModelType:()=>Ne,isRecoverableLength:()=>EF,isRetryableAssistantError:()=>tk,lazyApi:()=>oe,lazyOAuth:()=>de,lazyStream:()=>Oe,modelsAreEqual:()=>os,normalizeContext:()=>bt,parseJsonWithRepair:()=>nn,parseStreamingJson:()=>G,reduceAssistantMessageFrames:()=>xF,registerSessionResourceCleanup:()=>eo,renderSystemMessageUpdate:()=>De,repairJson:()=>ei,resolveTranscript:()=>ie,resolveTranscriptTools:()=>ve,retryAssistantCall:()=>kF,retryDelayMs:()=>ek,toToolDeclaration:()=>st,uuidv7:()=>rn,validateToolArguments:()=>cu,validateToolCall:()=>lB,withoutInitialSystemMessage:()=>zt});var j={};Ze(j,{Counted:()=>Sd,Entries:()=>hn,EntriesRegExp:()=>wd,Every:()=>mn,EveryAll:()=>$n,GraphemeCount:()=>cO,HasPropertyKey:()=>pe,IsArray:()=>Fe,IsBigInt:()=>Dr,IsBoolean:()=>fn,IsClassInstance:()=>Gy,IsConstructor:()=>bd,IsDeepEqual:()=>$a,IsEqual:()=>M,IsFunction:()=>gs,IsGreaterEqualThan:()=>Pa,IsGreaterThan:()=>ji,IsInteger:()=>cm,IsLessEqualThan:()=>ys,IsLessThan:()=>Pu,IsMaxLength:()=>Ky,IsMinLength:()=>Hy,IsMultipleOf:()=>By,IsNull:()=>bo,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>Uo,IsString:()=>lt,IsSymbol:()=>Ed,IsUndefined:()=>Bt,IsUnsafePropertyKey:()=>Cu,IsValueLike:()=>Ji,Keys:()=>Se,ShiftLeft:()=>xt,Some:()=>Ca,SomeAll:()=>Wy,Symbols:()=>zy,Values:()=>Td});var oa={};Ze(oa,{Hash:()=>vd,HashCode:()=>Ax});var _t={};Ze(_t,{ExtendsFalse:()=>Ye,ExtendsTrue:()=>we,ExtendsUnion:()=>Zd,IsExtendsFalse:()=>rf,IsExtendsTrue:()=>tf,IsExtendsTrueLike:()=>co,IsExtendsUnion:()=>ef,Match:()=>Sr});var mo={};Ze(mo,{Any:()=>_a,Array:()=>H,BigInt:()=>Lu,Boolean:()=>B,Call:()=>jw,Capitalize:()=>zw,Codec:()=>Im,Conditional:()=>tT,Constructor:()=>Is,ConstructorParameters:()=>nT,Cyclic:()=>Ss,Decode:()=>vx,DecodeBuilder:()=>xm,Dependent:()=>na,Encode:()=>Mx,EncodeBuilder:()=>ym,Enum:()=>yx,Evaluate:()=>Pn,Exclude:()=>sT,Extends:()=>An,ExtendsResult:()=>_t,Extract:()=>aT,Function:()=>bs,Generic:()=>ui,Identifier:()=>Nu,Immutable:()=>Ox,Index:()=>pT,Infer:()=>_u,InstanceType:()=>NT,Instantiate:()=>Mo,Integer:()=>T,Interface:()=>Ew,Intersect:()=>Mn,IsAny:()=>Mr,IsArray:()=>St,IsBigInt:()=>go,IsBoolean:()=>Vn,IsCall:()=>Wa,IsCodec:()=>Kn,IsConstructor:()=>zr,IsCyclic:()=>Xt,IsDependent:()=>qr,IsEnum:()=>un,IsEnumValue:()=>gx,IsFunction:()=>en,IsGeneric:()=>Oa,IsIdentifier:()=>Dx,IsImmutable:()=>sa,IsInfer:()=>an,IsInteger:()=>yn,IsIntersect:()=>Ge,IsKind:()=>Te,IsLiteral:()=>dt,IsNever:()=>ho,IsNull:()=>Ts,IsNumber:()=>Pr,IsObject:()=>He,IsOptional:()=>ln,IsParameter:()=>Ux,IsReadonly:()=>aa,IsRecord:()=>Kt,IsRef:()=>Ft,IsRefine:()=>bm,IsRest:()=>fi,IsSchema:()=>vr,IsString:()=>cn,IsSymbol:()=>Rs,IsTemplateLiteral:()=>tr,IsThis:()=>_m,IsTuple:()=>ct,IsUndefined:()=>ss,IsUnion:()=>be,IsUnknown:()=>tn,IsUnsafe:()=>gm,IsVoid:()=>yo,KeyOf:()=>qT,Literal:()=>s,Lowercase:()=>Vw,Mapped:()=>WT,Module:()=>_R,Never:()=>Vt,NonNullable:()=>QT,Null:()=>On,Number:()=>te,Object:()=>l,Omit:()=>YT,Optional:()=>n,Parameter:()=>ua,Parameters:()=>tR,Partial:()=>nR,Pick:()=>mR,Readonly:()=>_x,ReadonlyObject:()=>Mf,ReadonlyType:()=>dR,Record:()=>ks,RecordKey:()=>di,RecordPattern:()=>xn,RecordValue:()=>or,Ref:()=>pn,Refine:()=>Lx,Required:()=>PR,Rest:()=>ma,ReturnType:()=>$R,Script:()=>qR,String:()=>a,Symbol:()=>Da,TemplateLiteral:()=>BS,This:()=>Om,Tuple:()=>Ur,Uncapitalize:()=>Jw,Undefined:()=>ja,Union:()=>g,Unknown:()=>Ar,Unsafe:()=>Jr,Uppercase:()=>Qw,Void:()=>Lm,With:()=>Ip});var iu={};Ze(iu,{Clear:()=>yA,Entries:()=>_1,Get:()=>D1,Has:()=>N1,IsDate:()=>nu,IsDateTime:()=>Pp,IsDuration:()=>Cp,IsEmail:()=>$p,IsHostname:()=>qp,IsIPv4:()=>Up,IsIPv6:()=>Bp,IsIdnEmail:()=>Fp,IsIdnHostname:()=>jp,IsIri:()=>Kp,IsIriReference:()=>Gp,IsJsonPointer:()=>Wp,IsJsonPointerUriFragment:()=>Hp,IsRegex:()=>zp,IsRelativeJsonPointer:()=>Vp,IsTime:()=>ou,IsUri:()=>Xp,IsUriReference:()=>Jp,IsUriTemplate:()=>Qp,IsUrl:()=>Yp,IsUuid:()=>Zp,Reset:()=>IA,Set:()=>L1,Test:()=>xA});var Ru="shell-guard",Xg=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class b extends Error{constructor(e){super(e);this.name="NotFoundError"}}var kt="chatgpt:subscription";function Yg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Zg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function lM(e,o){if(e===o)return 0;let i=Array.from({length:o.length+1},(u,m)=>m);for(let u=1;u<=e.length;u++){let m=i[0]??0;i[0]=u;for(let p=1;p<=o.length;p++){let f=i[p]??0;i[p]=Math.min((i[p]??0)+1,(i[p-1]??0)+1,m+(e[u-1]===o[p-1]?0:1)),m=f}}return i[o.length]??0}function ey(e,o){let i=Yg(e);if(!i)return[];let u=Zg(e),m=[];for(let p of o){let f=p.id.indexOf("/"),h=f>=0?p.id.slice(f+1):"",I=[p.id,p.name,h].filter(Boolean).map((R)=>({compact:Yg(R),tokens:Zg(R)})).filter((R)=>R.compact.length>0),S=Number.POSITIVE_INFINITY;for(let R of I)if(R.compact===i)S=Math.min(S,0);else if(R.compact.includes(i)||i.includes(R.compact)){let k=Math.abs(R.compact.length-i.length);S=Math.min(S,1+k/Math.max(R.compact.length,i.length))}else{let k=0;for(let A of u)if(R.tokens.has(A))k++;if(k>0){let A=k/Math.max(u.size,R.tokens.size);S=Math.min(S,10+(1-A)*10)}}if(!Number.isFinite(S)&&i.length>=4){let R=Math.max(2,Math.floor(i.length*0.34));for(let k of I){if(Math.abs(k.compact.length-i.length)>R)continue;let A=lM(i,k.compact);if(A<=R)S=Math.min(S,100+A)}}if(Number.isFinite(S))m.push({model:p,score:S})}return m.sort((p,f)=>p.score-f.score||p.model.id.localeCompare(f.model.id))}function dM(e,o,i=5){return ey(e,o).slice(0,Math.max(1,i)).map((u)=>u.model)}function jr(e,o){let i=ey(e,o);if(i.length===0)return;let u=i.filter((p)=>p.score===0);if(u.length===1&&u[0])return u[0].model;if(u.length>1)return;let m=i.filter((p)=>p.score<10);if(m.length===1&&m[0])return m[0].model;return}function Vr(e,o){let i=[...o].sort((f,h)=>f.id.localeCompare(h.id)),u=(f)=>f.name===f.id?f.id:`${f.id} (${f.name})`,m=dM(e,i).map(u),p=i.map(u);return[`unknown model ${e}`,`closest matches: ${m.length>0?m.join(", "):"none"}`,`available models (${p.length}): ${p.length>0?p.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
+ `)}var Li=["openai-completions","openai-responses","anthropic-messages"];function Kr(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let o=e.trim().toLowerCase();if(!o)return;let i=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let u=Number.parseFloat(i[1]??"");if(!Number.isFinite(u)||u<=0)return;let m=i[2];if(m==="k")return Math.round(u*1000);if(m==="m")return Math.round(u*1e6);return Math.round(u)}function od(e){if(e>=1e6&&e%1e5===0)return`${e/1e6}m`;if(e>=1000&&e%1000===0)return`${e/1000}k`;return String(e)}function fM(e){let o=e.trim();if(!o)return;let i,u,m=o,p=m.match(/\s*\[(.*?)\]\s*$/);if(p&&p.index!==void 0){m=m.slice(0,p.index).trim();let S=p[1]?.split(",").map((k)=>k.trim()).filter(Boolean)??[],R=0;for(let k of S){let A=k.indexOf("=");if(A>=0){let v=k.slice(0,A).trim().toLowerCase(),_=Kr(k.slice(A+1).trim());if(v==="context"||v==="ctx"||v==="window"||v==="contextwindow")i=_;else if(v==="max"||v==="output"||v==="maxtokens")u=_}else{let v=Kr(k);if(R===0)i=v;else if(R===1)u=v;R++}}}else{let S=m.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(S?.[1]&&S[2])m=S[1].trim(),i=Kr(S[2])}let f=m.indexOf("="),h,x;if(f<0)h=m.trim(),x=h;else h=m.slice(0,f).trim(),x=m.slice(f+1).trim()||h;if(!h)return;let I={id:h,name:x};if(i!==void 0)I.contextWindow=i;if(u!==void 0)I.maxTokens=u;return I}function ir(e){return e.split(/\r?\n/).map(fM).filter((o)=>o!==void 0)}function qo(e){return e.map((o)=>{let i=o.name===o.id?o.id:`${o.id}=${o.name}`,u=[];if(o.contextWindow!==void 0)u.push(od(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)u.push(od(o.maxTokens));else u.push(`max=${od(o.maxTokens)}`);return u.length>0?`${i} [${u.join(", ")}]`:i}).join(`
8
+ `)}var ty=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var hM=["http","https"];var ry="provider:",ny="oauth:openai",Qr="update:registry";function sd(e){let o=e.trim();if(!o)throw Error("\u8BF7\u8F93\u5165\u4EE3\u7406\u4E3B\u673A\u6216\u5B8C\u6574\u5730\u5740");let i;try{i=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(o)?o:`http://${o}`)}catch{throw Error("\u4EE3\u7406\u5730\u5740\u65E0\u6548")}if(!gM(i.protocol))throw Error("\u4EC5\u652F\u6301 http:// \u6216 https:// \u4EE3\u7406");if(i.username||i.password||i.pathname!=="/"||i.search||i.hash)throw Error("\u4EE3\u7406\u5730\u5740\u53EA\u80FD\u5305\u542B\u534F\u8BAE\u3001\u4E3B\u673A\u548C\u7AEF\u53E3\uFF1B\u8D26\u53F7\u5BC6\u7801\u8BF7\u5355\u72EC\u586B\u5199");return{protocol:i.protocol==="https:"?"https":"http",hostname:i.hostname.replace(/^\[|\]$/g,""),port:i.port?Number(i.port):i.protocol==="https:"?443:8080}}function gM(e){return hM.some((o)=>`${o}:`===e)}function oy(e){return e.startsWith("provider:")&&e.length>9}var Wn=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],Oi=["text","regex"],Ni=["best","recent"],Di=["session","none"];var Ht=4,Ui="https://basalt.work",Bi=["https://basalt.work","https://www.basalt.work"],Xr=7420;var id=["auto","bash","powershell","cmd"];var Go=["active","archived","all"],Fi="session.group";var sy=["pending","in_progress","completed"],ad="basalt-session",nm=["image","text","path"];var iy=["defer","always"],ay=["global","tool","source"];function We(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let i=o;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:o};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:o}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:o};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:o}}}function $i(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var mt=10,yM=15000000;function qt(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&nm.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=yM}function ud(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as uy,existsSync as cy,fsyncSync as my,mkdirSync as py,openSync as ly,readFileSync as dy,renameSync as fy,writeFileSync as hy}from"fs";import{dirname as cd,join as gy}from"path";class Hn{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=gy(e,"auth.json"),this.deviceIdPath=gy(e,"device-id")}load(){if(!cy(this.path))return;let e;try{e=JSON.parse(dy(this.path,"utf8"))}catch{this.quarantine();return}let o=md(e);if(o?.version!==1){this.quarantine();return}let i=md(o.providers);if(!i){this.quarantine();return}for(let[u,m]of Object.entries(i)){if(!xM(m))continue;this.providers[u]=m}}deviceId(){if(cy(this.deviceIdPath)){let o=dy(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return py(cd(this.deviceIdPath),{recursive:!0}),hy(this.deviceIdPath,`${e}
9
+ `),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[kt]??=e,delete o.openai;try{this.persist(o)}catch(i){throw Error("\u8F6C\u79FB ChatGPT \u8BA2\u9605\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u65B0\u542F\u52A8",{cause:i})}this.providers=o,this.dirty=!1}async read(e,o){return o?.signal?.throwIfAborted(),this.flush(),this.providers[e]?structuredClone(this.providers[e]):void 0}async list(e){return e?.signal?.throwIfAborted(),this.flush(),Object.entries(this.providers).map(([o,i])=>({providerId:o,type:i.type}))}modify(e,o,i){return this.enqueue(e,()=>this.applyModify(e,o),i)}delete(e,o){return this.enqueue(e,()=>{if(!(e in this.providers)){this.flush();return}let i={...this.providers};delete i[e],this.persist(i),this.providers=i,this.dirty=!1},o)}async close(){this.closed=!0;try{while(this.chains.size)await Promise.all(this.chains.values());this.flush()}catch(e){throw this.closed=!1,e}}enqueue(e,o,i){if(this.closed)return Promise.reject(Error("\u51ED\u636E\u5B58\u50A8\u6B63\u5728\u5173\u95ED"));let u=i?.signal;if(u?.aborted)return Promise.reject(u.reason);let m=this.chains.get(e)??Promise.resolve(),p,f=m.then(()=>{if(u?.throwIfAborted(),p)u?.removeEventListener("abort",p);return o()}),h=f.then(()=>{return},()=>{return});if(this.chains.set(e,h),h.then(()=>{if(this.chains.get(e)===h)this.chains.delete(e)}),!u)return f;return new Promise((x,I)=>{let S=()=>I(u.reason);if(p=S,u.addEventListener("abort",S,{once:!0}),f.then((R)=>{u.removeEventListener("abort",S),x(R)},(R)=>{u.removeEventListener("abort",S),I(R)}),u.aborted)S()})}async applyModify(e,o){this.flush();let i=this.providers[e]?structuredClone(this.providers[e]):void 0,u=await o(i);if(u===void 0)return i?structuredClone(i):void 0;return this.providers[e]=structuredClone(u),this.dirty=!0,this.flush(),structuredClone(u)}flush(){if(!this.dirty)return;this.persist(this.providers),this.dirty=!1}persist(e){py(cd(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,i=ly(o,"w",384);try{hy(i,`${JSON.stringify({version:1,providers:e},null,2)}
10
+ `),my(i)}finally{uy(i)}if(fy(o,this.path),process.platform==="win32")return;let u=ly(cd(this.path),"r");try{my(u)}catch(m){if(!(m instanceof Error&&("code"in m)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(m.code))))throw m}finally{uy(u)}}quarantine(){try{fy(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function md(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function xM(e){let o=md(e);if(!o)return!1;if(o.type==="api_key")return o.key===void 0||typeof o.key==="string";if(o.type!=="oauth")return!1;return typeof o.refresh==="string"&&typeof o.access==="string"&&typeof o.expires==="number"}var _M=xy(),dd=ky();import{AsyncLocalStorage as LM}from"async_hooks";var K=new LM;var NM=3,Ay=160,DM=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),qM=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),$y=/^[A-Za-z_][A-Za-z0-9_]*=/,FM=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),jM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),UM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,BM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),GM=new Set(["command","builtin","nohup","time","exec"]),KM=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir","-S","--split-string"]],["nice",["-n","--adjustment"]]]);function im(e){return{out:e.out,depth:e.depth+1}}function Py(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function fd(e,o,i,u){let m=e.length,p=0,f=o;while(f<m){let h=e.charAt(f);if(h==="\\"){f+=2;continue}if(h==="'"||h==='"'||h==="`"){let x=f+1;while(x<m){let I=e.charAt(x);if(I==="\\"){x+=2;continue}if(I===h)break;x++}f=x+1;continue}if(h===i)p++;else if(h===u){if(p--,p===0)return f+1}f++}return m}function HM(e){let o={text:"",subs:[],heredocs:[]},i=[],u=[],m=e.length,p=0,f=0,h=null,x=(I)=>{if(e.charAt(I)==="`"){let A=I+1;while(A<m){let v=e.charAt(A);if(v==="\\"){A+=2;continue}if(v==="`")break;A++}return o.subs.push(e.slice(I+1,A)),A<m?A+1:m}if(e.charAt(I+1)==="("){let A=fd(e,I+1,"(",")");if(e.charAt(I+2)==="(")return i.push(e.slice(I,A)),A;return o.subs.push(e.slice(I+2,A-1)),A}let R=fd(e,I+1,"{","}"),k=e.slice(I+2,R-1);for(let A=0;A<k.length;A++){let v=k.charAt(A);if(v==="\\"){A++;continue}if(v==="`"){let _=k.indexOf("`",A+1);o.subs.push(_<0?k.slice(A+1):k.slice(A+1,_)),A=_<0?k.length:_;continue}if(v==="$"&&k.charAt(A+1)==="("){let _=fd(k,A+1,"(",")");o.subs.push(k.slice(A+2,_-1)),A=_-1}}return R};while(p<m){let I=e.charAt(p);if(h==="'"){if(I==="'")h=null;i.push(I),p++;continue}if(h==='"'){if(I==="\\"){if(!'$`"\\\n'.includes(e.charAt(p+1)))i.push("\\");i.push(I,e.charAt(p+1)),p+=2;continue}if(I==='"'){h=null,i.push(I),p++;continue}if(I==="`"||I==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=x(p);continue}i.push(I),p++;continue}if(I==="'"||I==='"'){h=I,i.push(I),p++;continue}if(I==="\\"){i.push(I,e.charAt(p+1)),p+=2;continue}if(I==="`"||I==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=x(p);continue}if(I==="#"){let S=i.at(-1);if(S===void 0||`
11
+ ;&|()`.includes(S)){while(p<m&&e.charAt(p)!==`
12
+ `)p++;continue}i.push(I),p++;continue}if(I==="<"&&e.charAt(p+1)==="<"&&e.charAt(p+2)!=="<"){let S=p+2;if(e.charAt(S)==="-")S++;i.push(e.slice(p,S));let R=S;while(R<m&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let k="";while(R<m){let A=e.charAt(R);if(A==="'"||A==='"'){let v=e.indexOf(A,R+1);if(v<0)break;k+=e.slice(R+1,v),R=v+1;continue}if(A==="\\"){k+=e.charAt(R+1),R+=2;continue}if(` \r
13
+ ;&|()<>`.includes(A))break;k+=A,R++}if(k)u.push(k);p=S;continue}if(I===`
14
+ `){if(u.length>0){let S=UM.test(i.slice(f).join(""));p++;for(let R of u.splice(0)){let k=p,A=m;while(p<m){let v=e.indexOf(`
15
+ `,p),_=v<0?m:v;if(e.slice(p,_).trim()===R){A=p,p=v<0?m:v+1;break}p=v<0?m:v+1}if(S&&A>k)o.heredocs.push(e.slice(k,A))}}else p++;i.push(";",`
16
+ `),f=i.length;continue}i.push(I),p++}return o.text=i.join(""),o}function Au(e,o){if(o.depth>NM)return;let i=HM(e),u;try{u=dd(i.text)}catch{return}let m=[];for(let p of u){if(typeof p==="string"){m.push({kind:"word",text:p});continue}if("pattern"in p){m.push({kind:"word",text:p.pattern});continue}if("op"in p)m.push({kind:"op",text:p.op})}WM(m,o);for(let p of i.subs)Au(p,im(o));for(let p of i.heredocs)Au(p,im(o))}function WM(e,o){let i=[],u=()=>{if(i.length>0)zM(i,o);i=[]};for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;if(p.kind==="op"){if(FM.has(p.text)){u();continue}if(jM.has(p.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();m++}continue}i.push(p.text)}u()}function zM(e,o){let i=0;for(;;){let f=e[i];if(f===void 0)return;if(qM.has(f)||$y.test(f)){i++;continue}let h=JM(Py(f),e,i);if(h===i)break;i=h}let u=e[i];if(u===void 0)return;let m=Py(u),p=e.slice(i+1);if(m==="git"){XM(u,p,o);return}if(DM.has(m)){VM(p,o);return}if(m==="powershell"||m==="pwsh")Cy(p,/^-(command|c)$/i,o);if(m==="cmd")Cy(p,/^\/[ck]$/i,o)}function Cy(e,o,i){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let m=e.slice(u+1).join(" ");if(m.trim())Au(m,im(i));return}}function VM(e,o){for(let i=0;i<e.length;i++){let u=e[i]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){i++;continue}if(u.startsWith("--"))continue;let m=/^-[a-zA-Z]*c(.*)$/.exec(u);if(m){let p=m[1]||e[i+1];if(p)Au(p,im(o));return}if(u.startsWith("-")||u==="")continue;return}}function JM(e,o,i){if(GM.has(e)){let p=i+1;while(o[p]?.startsWith("-"))p++;return p}let u=KM.get(e);if(!u)return i;let m=i+1;for(;;){let p=o[m];if(p===void 0)return m;if(u.includes(p)){m+=2;continue}if($y.test(p)||p.startsWith("-")){m++;continue}return m}}function Fo(e,o){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(o))}function Xn(e,o){return e.some((i)=>i===`--${o}`||i.startsWith(`--${o}=`))}var QM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Fo(e,"f")||Fo(e,"i")||Xn(e,"force")||Xn(e,"interactive"))&&!(Fo(e,"n")||Xn(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Fo(e,"f")||Xn(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Fo(e,"f")||Xn(e,"force")||Fo(e,"C")||Xn(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>Fo(e,"f")||Xn(e,"force")||Xn(e,"force-with-lease")||Xn(e,"force-if-includes")||Xn(e,"delete")||Xn(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>Xn(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Fo(e,"D")||Fo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>Xn(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>Fo(e,"f")||Xn(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(Fo(e,"f")||Xn(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function XM(e,o,i){let u=0;for(;;){let x=o[u];if(x===void 0)break;if(BM.has(x)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(x)||/^-[Cc].+/.test(x)||x.startsWith("-")){u++;continue}break}let m=o[u]?.toLowerCase();if(!m)return;let p=QM[m];if(!p)return;let f=p(o.slice(u+1));if(!f)return;let h=[e,...o.slice(u)].join(" ");i.out.push({rule:m,fragment:h.length>Ay?`${h.slice(0,Ay)}\u2026`:h,reason:f})}function gd(e){let o={out:[],depth:0};return Au(e,o),o.out}function vy(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),i=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${i}`}var hd=new Map;function YM(e,o,i,u,m){let p=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((f)=>{let h=(I)=>{if(!hd.delete(p))return;m?.removeEventListener("abort",x),f(I)},x=()=>{My(e,p),h("aborted")};if(hd.set(p,{session:e,finish:h}),e.appendExtension({namespace:Ru,kind:"requested",schemaVersion:1,payload:{id:p,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:I,reason:S})=>({fragment:I,reason:S})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),m?.aborted)x();else m?.addEventListener("abort",x,{once:!0})})}function My(e,o){try{e.appendExtension({namespace:Ru,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function zo(e,o,i){let u=hd.get(o);if(!u||u.session!==e){if(!ZM(e,o))return"unknown";return My(e,o),"expired"}return e.appendExtension({namespace:Ru,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(i?"approved":"denied"),"answered"}function ZM(e,o){let i=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==Ru)continue;let m=u.payload;if(!m||typeof m!=="object"||!("id"in m)||m.id!==o)continue;if(u.kind==="requested")i=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return i}function yd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${vy(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function Qe(e,o){let i=gd(e);if(!i.at(0))return;let m=vy(i),p=K.getStore();if(p?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${m}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${yd(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let f=await YM(p,e,m,i,o);if(f==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${m} \u672A\u6267\u884C\uFF1A${f==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{existsSync as eO,mkdirSync as tO,writeFileSync as rO}from"fs";import{homedir as nO}from"os";import{join as Mi}from"path";function nt(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=nO();if(process.platform==="win32")return Mi(e.LOCALAPPDATA??Mi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Mi(o,"Library","Application Support","basalt");return Mi(e.XDG_DATA_HOME??Mi(o,".local","share"),"basalt")}function oO(e){return Mi(e,".basalt","tmp")}function xd(e){let o=oO(e);tO(o,{recursive:!0});let i=Mi(o,".gitignore");if(!eO(i))rO(i,`*
17
+ !.gitignore
18
+ `);return o}function am(e){try{let o=xd(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var hs={assign:0,create:0,clone:0,discard:0,update:0};function _i(e,o,i){return e>=o&&e<=i}function Ly(e){return e===8205}function sO(e){return _i(e,55296,56319)}function Oy(e){return _i(e,127462,127487)}function Ny(e){return _i(e,65024,65039)}function Dy(e){return _i(e,768,879)||_i(e,6832,6911)||_i(e,7616,7679)||_i(e,65056,65071)}function um(e){return e>65535?2:1}function _y(e,o){while(o<e.length){let i=e.codePointAt(o);if(Dy(i)||Ny(i))o+=um(i);else break}return o}function Id(e,o){let i=e.codePointAt(o),u=o+um(i);u=_y(e,u);while(u<e.length-1&&Ly(e.codePointAt(u))){let m=e.codePointAt(u+1);u+=1+um(m),u=_y(e,u)}if(Oy(i)&&u<e.length&&Oy(e.codePointAt(u)))u+=um(e.codePointAt(u));return u}function qy(e){return e>=768&&(sO(e)||Dy(e)||Ny(e)||Ly(e))}function Fy(e){let o=0,i=0;while(i<e.length)i=Id(e,i),o++;return o}function iO(e,o){let i=0,u=0;while(u<e.length)if(u=Id(e,u),++i>=o)return!0;return!1}function aO(e,o){let i=0,u=0;while(u<e.length)if(u=Id(e,u),++i>o)return!1;return!0}function jy(e,o){if(o===0)return!0;if(e.length<o)return!1;let i=0;while(!0){if(qy(e.charCodeAt(i)))return iO(e,o);if(++i>=o)return!0}}function Uy(e,o){if(e.length<=o)return!0;let i=0;while(!0){if(qy(e.charCodeAt(i)))return aO(e,o);if(++i>o)return!1}}function Fe(e){return Array.isArray(e)}function Dr(e){return M(typeof e,"bigint")}function fn(e){return M(typeof e,"boolean")}function bd(e){if(Bt(e)||!gs(e))return!1;let o=Function.prototype.toString.call(e);if(/^class\s/.test(o))return!0;if(/\[native code\]/.test(o))return!0;return!1}function gs(e){return M(typeof e,"function")}function cm(e){return Number.isInteger(e)}function bo(e){return M(e,null)}function Ot(e){return Number.isFinite(e)}function Uo(e){return at(e)&&!Fe(e)}function at(e){return M(typeof e,"object")&&!bo(e)}function lt(e){return M(typeof e,"string")}function Ed(e){return M(typeof e,"symbol")}function Bt(e){return M(e,void 0)}function M(e,o){return e===o}function ji(e,o){return e>o}function Pu(e,o){return e<o}function ys(e,o){return e<=o}function Pa(e,o){return e>=o}function By(e,o){if(Dr(e)||Dr(o))return BigInt(e)%BigInt(o)===0n;let i=0.0000000001;if(!Ot(e))return!0;if(cm(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<i}function Gy(e){if(!at(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(bo(o))return!1;return M(typeof o.constructor,"function")&&!(M(o.constructor,globalThis.Object)||M(o.constructor.name,"Object"))}function Ji(e){return Dr(e)||fn(e)||bo(e)||Ot(e)||lt(e)||Bt(e)}function cO(e){return Fy(e)}function Ky(e,o){return Uy(e,o)}function Hy(e,o){return jy(e,o)}function mn(e,o,i){return e.every((u,m)=>m<o||i(u,m))}function $n(e,o,i){let u=!0;return e.forEach((m,p)=>{if(p>=o&&!i(m,p))u=!1}),u}function Ca(e,o){return e.some((i,u)=>o(i,u))}function Wy(e,o){let i=!1;return e.forEach((u,m)=>{if(o(u,m))i=!0}),i}function Sd(e,o){return e.reduce((i,u,m)=>o(u,m)?++i:i,0)}function xt(e,o,i){return M(e.length,0)?i():o(e[0],e.slice(1))}function Cu(e){return M(e,"__proto__")||M(e,"constructor")||M(e,"prototype")}function pe(e,o){return Cu(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function wd(e){return Se(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function hn(e){return Object.entries(e)}function Se(e){return Object.getOwnPropertyNames(e)}function zy(e){return Object.getOwnPropertySymbols(e)}function Td(e){return Object.values(e)}function mO(e,o){if(!at(o))return!1;let i=Se(e);return M(i.length,Se(o).length)&&i.every((u)=>$a(e[u],o[u]))}function pO(e,o){return Fe(o)&&M(e.length,o.length)&&e.every((i,u)=>$a(e[u],o[u]))}function $a(e,o){return Fe(e)?pO(e,o):at(e)?mO(e,o):M(e,o)}var lO=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function dO(e){return lO.test(e)}function Rn(e,o){return`(${e} && ${o})`}function Ir(e,o){return`(${e} || ${o})`}function Un(e){return`!(${e})`}function mm(e){return`Array.isArray(${e})`}function Vy(e){return`typeof ${e} === "bigint"`}function fO(e){return`typeof ${e} === "boolean"`}function hO(e){return`Number.isInteger(${e})`}function gO(e){return`${e} === null`}function Jy(e){return`Number.isFinite(${e})`}function Qy(e){return Rn(Xy(e),Un(mm(e)))}function Xy(e){return`typeof ${e} === "object" && ${e} !== null`}function Yy(e){return`typeof ${e} === "string"`}function yO(e){return`typeof ${e} === "symbol"`}function Rd(e){return`${e} === undefined`}function xO(e){return`typeof ${e} === "function"`}function IO(e){return`Guard.IsConstructor(${e})`}function fo(e,o){return`${e} === ${o}`}function Zy(e,o){return`${e} > ${o}`}function kd(e,o){return`${e} < ${o}`}function Xi(e,o){return`${e} <= ${o}`}function $u(e,o){return`${e} >= ${o}`}function bO(e,o){return`Guard.IsMinLength(${e}, ${o})`}function EO(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function xs(e,o,i,u){return M(o,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${u}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${o}) || (${u}))`}function SO(e,o,i){return`${e}.some((${o[0]}, ${o[1]}) => ${i})`}function wO(e,o,i){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${i}) result = true }); return result })(${e})`}function pm(e,o,i){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${i}) ? ++result : result, 0)`}function ex(e){return`Object.entries(${e})`}function Zi(e){return`Object.getOwnPropertyNames(${e})`}function ea(e,o){return M(o,'"__proto__"')||M(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function tx(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function TO(e){return`[${e.join(", ")}]`}function si(e,o){return`((${e.join(", ")}) => ${o})`}function Er(e,o){return`${e}(${o.join(", ")})`}function Ad(e,o){return`new ${e}(${o.join(", ")})`}function It(e,o){return`${e}${dO(o)?`.${o}`:`[${Ae(o)}]`}`}function Ae(e){if(!Ji(e))throw Error("Unsupported Constant");return lt(e)?JSON.stringify(e):`${e}`}function RO(e,o,i){return`(${e} ? ${o} : ${i})`}function lm(e){return`{ ${e.join("; ")}; }`}function Ds(e,o){return`const ${e} = ${o}`}function rx(e,o){return`if(${e}) { ${o} }`}function dm(e){return`return ${e}`}function vn(e){return M(e.length,0)?"true":e.reduce((o,i)=>Rn(o,i))}function Pd(e){return M(e.length,0)?"false":e.reduce((o,i)=>Ir(o,i))}function kO(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function AO(e){return e instanceof Boolean}function PO(e){return e instanceof Number}function CO(e){return e instanceof String}function nx(e){return globalThis.ArrayBuffer.isView(e)}function ox(e){return e instanceof globalThis.RegExp}function $O(e){return e instanceof globalThis.Date}function vO(e){return e instanceof globalThis.Set}function MO(e){return e instanceof globalThis.Map}var _O={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Bo(){return _O}function ii(e){return Bo().immutableTypes?Object.freeze(e):e}function gn(e,o){return hs.assign+=1,ii({...e,...o})}function LO(e){return e}function NO(e){return pe(e,"~kind")||pe(e,"~unsafe")}function DO(e){let o={};for(let i of Se(e)){if(Cu(i))continue;let u=Object.getOwnPropertyDescriptor(e,i);if(u.value=ta(u.value),M(u.enumerable,!0))o[i]=u.value;else Object.defineProperty(o,i,u)}return o}function qO(e){let o={};for(let i of Se(e)){if(Cu(i))continue;o[i]=ta(e[i])}for(let i of zy(e))o[i]=ta(e[i]);return o}function FO(e){return Gy(e)?LO(e):NO(e)?DO(e):qO(e)}function jO(e){return e.map((o)=>ta(o))}function UO(e){return e.slice()}function BO(e){return new RegExp(e.source,e.flags)}function GO(e){return new Map(ta([...e.entries()]))}function KO(e){return new Set(ta([...e.values()]))}function ta(e){return nx(e)?UO(e):ox(e)?BO(e):MO(e)?GO(e):vO(e)?KO(e):Fe(e)?jO(e):at(e)?FO(e):e}function va(e){return hs.clone+=1,ta(e)}function HO(e,o){for(let i of Object.keys(o))Object.defineProperty(e,i,{configurable:!0,writable:!0,enumerable:!1,value:o[i]});return e}function sx(e,o){return{...e,...o}}function $t(e,o,i={}){hs.create+=1;let u=sx(o,i),m=Bo().enumerableKind?sx(u,e):HO(u,e);return ii(m)}function Ho(e,o){hs.discard+=1;let i={};for(let u of Se(e)){if(o.includes(u))continue;let m=Object.getOwnPropertyDescriptor(e,u);m.value=va(m.value),Object.defineProperty(i,u,m)}return ii(i)}function Et(e,o,i){hs.update+=1;let u=Bo(),m=va(e);for(let p of Object.keys(o))Object.defineProperty(m,p,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[p]});for(let p of Object.keys(i))Object.defineProperty(m,p,{configurable:!0,enumerable:!0,writable:!0,value:i[p]});return ii(m)}function Te(e,o){return at(e)&&pe(e,"~kind")&&M(e["~kind"],o)}function vr(e){return at(e)}function ke(e,o,i){return $t({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:i},{})}function ai(e){return Te(e,"Deferred")}function WO(e){return Et(e,{"~readonly":!0},{})}function Mu(e,o){return Et(WO(e),{},o)}function ix(e,o,i,u){let m=he(e,o,i);return Mu(m,u)}function zO(e){return Et(e,{"~optional":!0},{})}function Ou(e,o){return Et(zO(e),{},o)}function ax(e,o,i,u){let m=he(e,o,i);return Ou(m,u)}function H(e,o){return $t({"~kind":"Array"},{type:"array",items:e},o)}function St(e){return Te(e,"Array")}function Ma(e){return Ho(e,["~kind","type","items"])}function Is(e,o,i={}){return $t({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},i)}function zr(e){return Te(e,"Constructor")}function ux(e){return Ho(e,["~kind","type","parameters","instanceType"])}function bs(e,o,i={}){return $t({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},i)}function en(e){return Te(e,"Function")}function cx(e){return Ho(e,["~kind","type","parameters","returnType"])}function pn(e,o){return $t({["~kind"]:"Ref"},{$ref:e},o)}function Ft(e){return Te(e,"Ref")}function ui(e,o){return $t({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Oa(e){return Te(e,"Generic")}function _a(e){return $t({["~kind"]:"Any"},{},e)}function Mr(e){return Te(e,"Any")}var mx="(?!)";function Vt(e){return $t({"~kind":"Never"},{not:{}},e)}function ho(e){return Te(e,"Never")}function Es(e,o={}){return ke("AddOptional",[e],o)}function ra(e,o={}){return Ou(e,o)}function n(e){return ra(e)}function ln(e){return vr(e)&&pe(e,"~optional")}function px(e){return Se(e).filter((o)=>!ln(e[o]))}function fm(e){return Se(e)}function hm(e){return Td(e)}function l(e,o={}){let i=px(e),u=i.length>0?{required:i}:{};return $t({"~kind":"Object"},{type:"object",...u,properties:e},o)}function He(e){return Te(e,"Object")}function lx(e){return Ho(e,["~kind","type","properties","required"])}function Ar(e){return $t({["~kind"]:"Unknown"},{},e)}function tn(e){return Te(e,"Unknown")}function Ss(e,o,i){let u=Se(e).reduce((m,p)=>({...m,[p]:Et(e[p],{},{$id:p})}),{});return $t({["~kind"]:"Cyclic"},{$defs:u,$ref:o},i)}function Xt(e){return Te(e,"Cyclic")}function Jr(e){return Et(e,{["~unsafe"]:null},{})}function gm(e){return Uo(e)&&pe(e,"~unsafe")&&bo(e["~unsafe"])}function kn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function _u(...e){let[o,i]=kn(e,{2:(u,m)=>[u,m,m],1:(u)=>[u,Ar(),Ar()]});return $t({["~kind"]:"Infer"},{type:"infer",name:o,extends:i},{})}function an(e){return Te(e,"Infer")}function na(e,o,i,u={}){return $t({"~kind":"Dependent"},{if:e,then:o,else:i},u)}function qr(e){return Te(e,"Dependent")}function dx(e){return Ho(e,["~kind","if","then","else"])}function fx(e){return Uo(e)}function hx(e){return Se(e).filter((i)=>isNaN(i)).reduce((i,u)=>[...i,e[u]],[])}function gx(e){return lt(e)||Ot(e)}function yx(e,o){let i=fx(e)?hx(e):e;return $t({"~kind":"Enum"},{enum:i},o)}function un(e){return Te(e,"Enum")}function Mn(e,o={}){return $t({"~kind":"Intersect"},{allOf:e},o)}function Ge(e){return Te(e,"Intersect")}function xx(e){return Ho(e,["~kind","allOf"])}var Cd=void 0;function VO(){try{return bx("null")(),!0}catch{return!1}}function Ix(){if(Bt(Cd))Cd=VO();return Cd&&Bo().useAcceleration}function bx(...e){return new globalThis.Function(...e)}function Fr(){throw Error("Unreachable")}function JO(e){let o=new Set,i=e;while(i&&i!==Object.prototype){for(let u of Reflect.ownKeys(i))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);i=Object.getPrototypeOf(i)}return[...o]}function QO(e){return typeof e==="number"}var Bn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Bn||(Bn={}));var La=BigInt("14695981039346656037"),[XO,YO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],ZO=Array.from({length:256}).map((e,o)=>BigInt(o)),Tx=new Float64Array(1),Rx=new DataView(Tx.buffer),kx=new Uint8Array(Tx.buffer);function Sn(e){La=La^ZO[e],La=La*XO%YO}function e_(e){Sn(Bn.Array);for(let o of e)ci(o)}function t_(e){Sn(Bn.BigInt),Rx.setBigInt64(0,e);for(let o of kx)Sn(o)}function Sx(e){Sn(Bn.Boolean),Sn(e?1:0)}function r_(e){Sn(Bn.Constructor),ci(e.toString())}function n_(e){Sn(Bn.Date),ci(e.getTime())}function o_(e){Sn(Bn.Function),ci(e.toString())}function s_(e){Sn(Bn.Null)}function wx(e){Sn(Bn.Number),Rx.setFloat64(0,e,!0);for(let o of kx)Sn(o)}function i_(e){Sn(Bn.Object);for(let o of JO(e).sort())ci(o),ci(e[o])}function a_(e){Sn(Bn.RegExp),$d(e.toString())}var u_=new TextEncoder;function $d(e){Sn(Bn.String);for(let o of u_.encode(e))Sn(o)}function c_(e){Sn(Bn.Symbol),ci(e.toString())}function m_(e){Sn(Bn.TypeArray);let o=new Uint8Array(e.buffer);for(let i=0;i<o.length;i++)Sn(o[i])}function p_(e){return Sn(Bn.Undefined)}function ci(e){return nx(e)?m_(e):$O(e)?n_(e):ox(e)?a_(e):AO(e)?Sx(e.valueOf()):CO(e)?$d(e.valueOf()):PO(e)?wx(e.valueOf()):QO(e)?wx(e):Fe(e)?e_(e):fn(e)?Sx(e):Dr(e)?t_(e):bd(e)?r_(e):bo(e)?s_(e):at(e)?i_(e):lt(e)?$d(e):Ed(e)?c_(e):Bt(e)?p_(e):gs(e)?o_(e):Fr()}function Ax(e){return La=BigInt("14695981039346656037"),ci(e),La}function vd(e){return Ax(e).toString(16).padStart(16,"0")}function Px(e){switch(e.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"dependentRequired":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"exclusiveMinimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"format":return`must match format "${e.params.format}"`;case"if":return`must match "${e.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${e.params.limit} items`;case"maxLength":return`must not have more than ${e.params.limit} characters`;case"maxProperties":return`must not have more than ${e.params.limit} properties`;case"maximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"minItems":return`must not have fewer than ${e.params.limit} items`;case"minLength":return`must not have fewer than ${e.params.limit} characters`;case"minProperties":return`must not have fewer than ${e.params.limit} properties`;case"minimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"multipleOf":return`must be multiple of ${e.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${e.params.pattern}"`;case"propertyNames":return`property names ${e.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${e.params.requiredProperties.join(", ")}`;case"type":return typeof e.params.type==="string"?`must be ${e.params.type}`:`must be either ${e.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return e.params.message;default:return"an unknown validation error occurred"}}var l_=Px;function Cx(){return l_}class ym{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,i=Kn(o)?(p)=>this.decode(o["~codec"].decode(p)):this.decode,u=Kn(o)?(p)=>o["~codec"].encode(e(p)):e,m={decode:i,encode:u};return Et(this.type,{"~codec":m},{})}}class xm{constructor(e){this.type=e}Decode(e){return new ym(this.type,e)}}function Im(e){return new xm(e)}function vx(e,o){return Im(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function Mx(e,o){return Im(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Kn(e){return vr(e)&&pe(e,"~codec")&&at(e["~codec"])&&pe(e["~codec"],"encode")&&pe(e["~codec"],"decode")}function Ox(e){return Na(e)}function sa(e){return vr(e)&&pe(e,"~immutable")}function ws(e,o={}){return ke("AddReadonly",[e],o)}function ia(e,o={}){return Mu(e,o)}function _x(e){return ia(e)}function aa(e){return vr(e)&&pe(e,"~readonly")}function f_(e,o){let i=bm(e)?[...e["~refine"],o]:[o];return Et(e,{"~refine":i},{})}function Lx(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,()=>"Refine Error"]});return f_(o,{check:i,error:u})}function h_(e){return Uo(e)&&pe(e,"check")&&pe(e,"error")&&gs(e.check)&&gs(e.error)}function bm(e){return vr(e)&&pe(e,"~refine")&&Fe(e["~refine"])&&mn(e["~refine"],0,(o)=>h_(o))}var Nx="-?(?:0|[1-9][0-9]*)n";function Lu(e){return $t({"~kind":"BigInt"},{type:"bigint"},e)}function go(e){return Te(e,"BigInt")}function B(e){return $t({"~kind":"Boolean"},{type:"boolean"},e)}function Vn(e){return Te(e,"Boolean")}function Nu(e){return $t({"~kind":"Identifier"},{name:e})}function Dx(e){return Te(e,"Identifier")}var Em="-?(?:0|[1-9][0-9]*)";function T(e){return $t({"~kind":"Integer"},{type:"integer"},e)}function yn(e){return Te(e,"Integer")}class qx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function g_(e){return Dr(e)?"bigint":fn(e)?"boolean":Ot(e)?"number":lt(e)?"string":(()=>{throw new qx(e)})()}function s(e,o){return $t({"~kind":"Literal"},{type:g_(e),const:e},o)}function Sm(e){return Dr(e)||fn(e)||Ot(e)||lt(e)}function Fx(e){return dt(e)&&Dr(e.const)}function jx(e){return dt(e)&&fn(e.const)}function wm(e){return dt(e)&&Ot(e.const)}function Tm(e){return dt(e)&&lt(e.const)}function dt(e){return Te(e,"Literal")}function On(e){return $t({"~kind":"Null"},{type:"null"},e)}function Ts(e){return Te(e,"Null")}var Rm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function te(e){return $t({"~kind":"Number"},{type:"number"},e)}function Pr(e){return Te(e,"Number")}function Da(e){return $t({"~kind":"Symbol"},{type:"symbol"},e)}function Rs(e){return Te(e,"Symbol")}function ua(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,p],1:(m)=>[m,Ar(),Ar()]});return $t({"~kind":"Parameter"},{name:o,extends:i,equals:u},{})}function Ux(e){return Te(e,"Parameter")}var km=".*";function a(e){return $t({"~kind":"String"},{type:"string"},e)}function cn(e){return Te(e,"String")}function g(e,o={}){return $t({"~kind":"Union"},{anyOf:e},o)}function be(e){return Te(e,"Union")}function Bx(e){return Ho(e,["~kind","anyOf"])}function Du(e){let o=Gx(e);return M(o.length,2)?o[0]:[]}function y_(e){return!0}function Kx(e){return xt(e,(o,i)=>x_(o)?Kx(i):!1,()=>!0)}function Hx(e){return M(e.length,0)?!1:Kx(e)}function x_(e){return be(e)?Hx(e.anyOf):dt(e)?y_(e.const):!1}function Am(e){return Hx(e)}function Pm(e){return $t({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function Wx(e,o,i=[]){return xt(e,(u,m)=>Wx(m,o,[...i,`${u}${o}`]),()=>i)}function I_(e,o){return M(e.length,0)?[`${o}`]:Wx(e,o)}function zx(e,o,i=[]){return xt(o,(u,m)=>zx(e,m,[...i,...Vx(e,u)]),()=>i)}function Vx(e,o){return be(o)?zx(e,o.anyOf):dt(o)?I_(e,o.const):Fr()}function Jx(e,o){return xt(o,(i,u)=>Jx(Vx(e,i),u),()=>e)}function b_(e){return e.map((o)=>s(o))}function E_(e){let o=Jx([],e),i=b_(o);return g(i)}function S_(e){return M(e.length,0)?Fr():M(e.length,1)&&dt(e[0])?e[0]:E_(e)}function Md(e){let o=Du(e);return M(o.length,0)?a():Am(o)?S_(o):Pm(e)}function qu(e){let o=Md(e);return tr(o)?a():o}function Yn(e,o){let u={[e]:o};return $t({["~kind"]:"Record"},{type:"object",patternProperties:u})}function Qx(e){return Yn(Wo,e)}function Xx(e){return l({true:e,false:e})}function Ur(e,o={}){let[i,u,m]=[e,e.length,!1];return $t({["~kind"]:"Tuple"},{type:"array",additionalItems:m,items:i,minItems:u},o)}function ct(e){return Te(e,"Tuple")}function Yx(e){return Ho(e,["~kind","type","items","minItems","additionalItems"])}function w_(e){return Ho(e,["~readonly"])}function Od(e,o){return Et(w_(e),{},o)}function Zx(e,o,i,u){let m=he(e,o,i);return Od(m,u)}function eI(e,o={}){return ke("RemoveReadonly",[e],o)}function tI(e,o={}){return Od(e,o)}function T_(e){return Ho(e,["~optional"])}function _d(e,o){return Et(T_(e),{},o)}function rI(e,o,i,u){let m=he(e,o,i);return _d(m,u)}function nI(e,o={}){return ke("RemoveOptional",[e],o)}function Cm(e,o={}){return _d(e,o)}function Ld(e){return e.reduceRight((i,u,m)=>({[m]:u,...i}),{})}function oI(e){let o=Ld(e.items);return l(o)}function Nd(e){return He(e)||ct(e)}function R_(e,o){return aa(e)?aa(o)?!0:!1:!1}function k_(e,o){return ln(e)?ln(o)?!0:!1:!1}function A_(e,o){let i=R_(e,o),u=k_(e,o),m=Cr([e,o]),p=tI(Cm(m));return i&&u?ia(ra(p)):i&&!u?ia(p):!i&&u?ra(p):p}function P_(e,o,i){return i in e?i in o?A_(e[i],o[i]):e[i]:(i in o)?o[i]:Vt()}function C_(e,o){return[...new Set([...Se(e),...Se(o)])].reduce((m,p)=>({...m,[p]:P_(e,o,p)}),{})}function sI(e){return He(e)?e.properties:ct(e)?Ld(e.items):{}}function iI(e,o){let i=sI(e),u=sI(o),m=C_(i,u);return l(m)}function $_(e,o){let i=qa(e,o);return M(i,ju)?e:M(i,Uu)?o:M(i,Fu)?o:Vt()}function v_(e,o){let i=Nd(e),u=Nd(o);return i&&u?iI(e,o):i&&!u?e:!i&&u?o:$_(e,o)}function aI(e,o){return ho(e)?e:Mr(e)?e:tn(e)?o:ho(o)?o:Mr(o)?o:tn(o)?e:v_(e,o)}function M_(e,o){return be(e)||be(o)}function O_(e,o){let i=vo(e),u=vo(o);return M_(i,u)?Cr([i,u]):aI(i,u)}function uI(e,o,i=[]){return xt(o,(u,m)=>uI(e,m,[...i,O_(u,e)]),()=>M(i.length,0)?[e]:i)}function cI(e,o,i=[]){return xt(e,(u,m)=>cI(m,o,[...i,...Bu([u],o)]),()=>i)}function Bu(e,o=[]){return xt(e,(i,u)=>be(i)?Bu(u,cI(i.anyOf,o)):Bu(u,uI(i,o)),()=>o)}function __(e,o){let i=An({},e,o);return co(i)?[]:[e]}function mI(e,o,i=[]){return xt(e,(u,m)=>mI(m,o,[...i,...__(u,o)]),()=>i)}function $m(e,o){let i=vo(e),u=be(i)?i.anyOf:[i],m=mI(u,o);return Zn(m)}function es(e,o,i){let u=Cr([e,o]),m=$m(i,e);return Zn([u,m])}function Jn(e,o=[]){return xt(e,(i,u)=>Jn(u,[...o,s(i)]),()=>Zn(o))}function Cr(e){let o=Bu(e),i=Dd(o);return Zn(i)}function _n(e){let o=qu(e);return vo(o)}function Zn(e){let o=Dd(e);return mi(o)}function vo(e){return qr(e)?es(e.if,e.then,e.else):un(e)?Jn(e.enum):Ge(e)?Cr(e.allOf):tr(e)?_n(e.pattern):be(e)?Zn(e.anyOf):e}function mi(e){return M(e.length,1)?e[0]:M(e.length,0)?Vt():g(e)}function pI(e,o){let i=Jn(e);return pi(i,o)}function lI(e,o){return Yn(li,o)}function dI(e,o){let i=Cr(e);return pi(i,o)}function fI(e,o){return lt(e)||Ot(e)?l({[e]:o}):M(e,!1)?l({false:o}):M(e,!0)?l({true:o}):l({})}function hI(e,o){return Yn(Fa,o)}function gI(e,o){return pe(e,"pattern")&&(lt(e.pattern)||e.pattern instanceof RegExp)?Yn(e.pattern.toString(),o):Yn(Wo,o)}function yI(e,o){let i=Du(e);return Am(i)?pi(_n(e),o):Yn(e,o)}function L_(e){return be(e)?ca(e.anyOf):[e]}function ca(e,o=[]){return xt(e,(i,u)=>ca(u,[...o,...L_(i)]),()=>o)}function N_(e){return e.some((o)=>cn(o)||Pr(o)||yn(o))}function D_(e,o){return M(N_(e),!0)?Yn(Wo,o):void 0}function q_(e,o){return e.reduce((i,u)=>dt(u)&&(lt(u.const)||Ot(u.const))?{...i,[u.const]:o}:i,{})}function F_(e,o){let i=q_(e,o);return l(i)}function xI(e,o){let i=ca(e),u=D_(i,o);return vr(u)?u:F_(i,o)}function pi(e,o){return Mr(e)?Qx(o):Vn(e)?Xx(o):un(e)?pI(e.enum,o):yn(e)?lI(e,o):Ge(e)?dI(e.allOf,o):dt(e)?fI(e.const,o):Pr(e)?hI(e,o):be(e)?xI(e.anyOf,o):cn(e)?gI(e,o):tr(e)?yI(e.pattern,o):l({})}function qd(e,o,i){return ut([e])?Et(pi(e,o),{},i):vm(e,o,i)}function II(e,o,i,u,m){let p=he(e,o,i),f=he(e,o,u);return qd(p,f,m)}var li=`^${Em}$`,Fa=`^${Rm}$`,Wo=`^${km}$`;function vm(e,o,i={}){return ke("Record",[e,o],i)}function ks(e,o,i={}){return qd(e,o,i)}function bI(e,o){return Yn(e,o)}function Mm(e){return M(e,Wo)?a():M(e,li)?T():M(e,Fa)?te():Md(e)}function xn(e){return Se(e.patternProperties)[0]}function di(e){let o=xn(e);return Mm(o)}function or(e){return e.patternProperties[xn(e)]}function Kt(e){return Te(e,"Record")}function ma(e){return $t({"~kind":"Rest"},{type:"rest",items:e},{})}function fi(e){return Te(e,"Rest")}function Om(e){return $t({["~kind"]:"This"},{$ref:"#"},e)}function _m(e){return Te(e,"This")}function ja(e){return $t({"~kind":"Undefined"},{type:"undefined"},e)}function ss(e){return Te(e,"Undefined")}function Lm(e){return $t({"~kind":"Void"},{type:"void"},e)}function yo(e){return Te(e,"Void")}function U_(e,o){return M(e,"Array")?H(o[0]):M(e,"Capitalize")?Dm(o[0]):M(e,"ConstructorParameters")?Bm(o[0]):M(e,"Evaluate")?DE(o[0]):M(e,"Exclude")?Gm(o[0],o[1]):M(e,"Extract")?Km(o[0],o[1]):M(e,"Index")?Wu(o[0],o[1]):M(e,"InstanceType")?Hm(o[0]):M(e,"Lowercase")?qm(o[0]):M(e,"NonNullable")?Wm(o[0]):M(e,"Omit")?zm(o[0],o[1]):M(e,"Parameters")?Vm(o[0]):M(e,"Partial")?Jm(o[0]):M(e,"Pick")?Qm(o[0],o[1]):M(e,"Readonly")?Xm(o[0]):M(e,"KeyOf")?zu(o[0]):M(e,"Record")?vm(o[0],o[1]):M(e,"Required")?Ym(o[0]):M(e,"ReturnType")?Zm(o[0]):M(e,"Uncapitalize")?Fm(o[0]):M(e,"Uppercase")?jm(o[0]):Hu(pn(e),o)}function pa(){throw Error("Unreachable")}function RI(e,o=[]){return xt(e,(i,u)=>RI(u,[...o,i[1]]),()=>o)}function qs(e){return M(e.length,3)?[e[0],...RI(e[1])]:[]}function kI(e){return ua(e[0],e[2],e[4])}function AI(e){return ua(e[0],e[2],e[2])}function PI(e){return ua(e[0],Ar(),e[2])}function CI(e){return ua(e,Ar(),Ar())}function $I(e){return e}function vI(e){return qs(e)}function MI(e){return e[1]}function OI(e){return qs(e)}function _I(e){return e[1]}function LI(e){return U_(e[0],e[1])}function NI(e){return null}function DI(e){return a()}function qI(e){return te()}function FI(e){return B()}function jI(e){return ja()}function UI(e){return On()}function BI(e){return T()}function GI(e){return Lu()}function KI(e){return Ar()}function HI(e){return _a()}function WI(e){return l({})}function zI(e){return Vt()}function VI(e){return Da()}function JI(e){return Lm()}function QI(e){return Om()}function XI(e){return s(BigInt(e))}function YI(e){return s(M(e,"true"))}function ZI(e){return s(parseFloat(e))}function eb(e){return s(e)}function tb(e){return e[1]}function rb(e){return s(e)}function nb(e){return M(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function ob(e){return e[1]}function sb(e){return Nm(e)}function ib(e){return M(e.length,6)?na(e[1],e[3],e[5]):na(e[1],e[3],Ar())}function ab(e){return e.length>0}function ub(e){return e.reduce((o,i)=>M(i.length,3)?[...o,[i[1]]]:[...o,[]],[])}function cb(e){return M(e.length,6)?[e[1],e[3],e[5]]:[]}function mb(e){return Fe(e)&&M(e.length,3)?e[1]:e}function pb(e){return M(e.length,2)?e[1]:[]}function EI(e,o){return o.reduce((i,u)=>{let m=u;return M(m.length,1)?Wu(i,m[0]):M(m.length,0)?H(i):pa()},e)}function SI(e,o){return M(o.length,3)?Um(e,o[0],o[1],o[2]):e}function B_(e,o){return Fe(o)&&M(o.length,0)?e:ep(e,o)}function lb(e){let[o,i,u,m,p]=e;return B_(o?SI(zu(EI(i,u)),m):SI(EI(i,u),m),p)}function Fd(e,o){return M(o.length,3)?(()=>{let[i,u,m]=o,p=Fd(u,m);if(M(i,"&"))return Ge(p)?Mn([e,...p.allOf]):Mn([e,p]);if(M(i,"|"))return be(p)?g([e,...p.anyOf]):g([e,p]);pa()})():e}function db(e){return e}function fb(e){let[o,i]=e;return Fd(o,i)}function hb(e){return e}function gb(e){let[o,i]=e;return Fd(o,i)}function yb(e){return NE(e[1])}function xb(e){return e[1]}function Ib(e){return ui(e[0],e[2])}function bb(e){return M(e.length,4)?_u(e[1],e[3]):M(e.length,2)?_u(e[1],Ar()):pa()}function Eb(e){return e}function Sb(e){return`${e}`}function wb(e){return e}function Tb(e){return e}function Rb(e){return yn(e[3])?li:Pr(e[3])?Fa:Rs(e[3])?Wo:cn(e[3])?Wo:pa()}function kb(e){return e}function Ab(e){return e.length>0}function Pb(e){return e.length>0}function Cb(e){let[o,i,u,m,p]=e;return{[i]:o&&u?ws(Es(p)):o&&!u?ws(p):!o&&u?Es(p):p}}function $b(e){return e}function vb(e){return qs(e)}function Mb(e){return e.reduce((o,i)=>pe(i,li)||pe(i,Fa)||pe(i,Wo)?[o[0],gn(o[1],i)]:[gn(o[0],i),o[1]],[{},{}])}function Ob(e){return Mb(e[1])}function _b(e){let[o,i]=e,u=M(Se(i).length,0)?{}:{patternProperties:i};return l(o,u)}function Lb(e){return M(e.length,5)?ws(Es(e[4])):M(e.length,3)?e[2]:M(e.length,4)?M(e[2],"readonly")?ws(e[3]):Es(e[3]):pa()}function Nb(e){if(!Fe(e)||!M(e.length,3))return e;let[o,i,u]=e;return o&&u?ws(Es(i)):o&&!u?ws(i):!o&&u?Es(i):i}function Db(e){return M(e.length,2)?ma(e[1]):M(e.length,1)?e[0]:pa()}function qb(e){return qs(e)}function Fb(e){return Ur(e[1])}function jb(e){return ws(Es(e[4]))}function Ub(e){return ws(e[3])}function Bb(e){return Es(e[3])}function Gb(e){return e[2]}function Kb(e){return e}function Hb(e){return M(e.length,2)?ma(e[1]):M(e.length,1)?e[0]:pa()}function Wb(e){return qs(e)}function zb(e){return bs(e[1],e[4])}function Vb(e){return Is(e[2],e[5])}function wI(e,o){return M(e,"remove")?eI(o):M(e,"add")?ws(o):o}function Jb(e){return M(e.length,2)&&M(e[0],"-")?"remove":M(e.length,2)&&M(e[0],"+")?"add":M(e.length,1)?"add":"none"}function TI(e,o){return M(e,"remove")?nI(o):M(e,"add")?Es(o):o}function Qb(e){return M(e.length,2)&&M(e[0],"-")?"remove":M(e.length,2)&&M(e[0],"+")?"add":M(e.length,1)?"add":"none"}function Xb(e){return M(e.length,2)?[e[1]]:[]}function Yb(e){return Fe(e[6])&&M(e[6].length,1)?Gu(Nu(e[3]),e[5],e[6][0],wI(e[1],TI(e[8],e[10]))):Gu(Nu(e[3]),e[5],pn(e[3]),wI(e[1],TI(e[8],e[10])))}function Zb(e){return pn(e)}function eE(e){return BigInt(e)}function tE(e){return parseFloat(e)}function rE(e){return M(e,"true")}function nE(e){return e}function oE(e){return null}function sE(e){return}function iE(e){return{[e[0]]:e[2]}}function aE(e){return qs(e)}function G_(e){return e.reduce((o,i)=>gn(o,i),{})}function uE(e){return G_(e[1])}function cE(e){return qs(e)}function mE(e){return e[1]}function pE(e){return e}function lE(e){return Lu()}function dE(e){return a()}function fE(e){return te()}function hE(e){return T()}function gE(e){return Vt()}function yE(e){return s(e)}function xE(e){return e}function IE(e){return g(e[1])}function bE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function EE(e){return[e[0],...e[1]]}function SE(e){return e}function wE(e){return e[1]}function TE(e){return qs(e)}function RE(e){return M(e.length,2)?e[1]:[]}function kE(e){let o=e[2],i=e[3],[u,m]=e[4],p=M(Se(m).length,0)?{}:{patternProperties:m};return{[e[1]]:ui(o,Ku(i,u,p))}}function AE(e){let o=e[2],[i,u]=e[3],m=M(Se(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Ku(o,i,m)}}function PE(e){return{[e[1]]:ui(e[2],e[4])}}function CE(e){return{[e[1]]:e[3]}}function $E(e){return null}function vE(e){return e}function ME(e){return qs(e)}function OE(e){return e[1]}function _E(e){let[o,i]=[e[0],e[1]];return qE(gn(o,Mb(i)[0]))}function LE(e){return e}function Vu(e){return M(e.length,2)}function wt(e,o,i){return Vu(e)?o(e[0],e[1]):i()}function W_(e,o){return M(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function _r(e,o){for(let i=0;i<e.length;i++){let u=W_(e[i],o);if(Vu(u))return u}return[]}function jd(e,o){return Array.from({length:o-e+1},(i,u)=>String.fromCharCode(e+u))}var FE=[...jd(97,122),...jd(65,90)],Ud="0",Bd=jd(49,57),Ua=[Ud,...Bd],jE=" ",Ba=`
19
+ `;var hi="_",tp=".",UE="$",rp="-";var BE="//",GE="/*",V_="*/";function KE(e){let o=e.indexOf(V_);return M(o,-1)?"":e.slice(o+2)}function HE(e){let o=e.indexOf(Ba);return M(o,-1)?"":e.slice(o)}function J_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function np(e){let o=J_(e);return o.startsWith(GE)?np(KE(o.slice(2))):o.startsWith(BE)?np(HE(o.slice(2))):o}function wn(e){let o=e.trimStart();return o.startsWith(GE)?wn(KE(o.slice(2))):o.startsWith(BE)?wn(HE(o.slice(2))):o}function op(e,o){return wt(_r([e],o),(i,u)=>[i,u],()=>["",o])}function Q_(e,o){return e.includes(o)}function Ga(e,o,i,u=""){return wt(_r(e,i),(m,p)=>Q_(o,m)?Ga(e,o,p,u):Ga(e,o,p,`${u}${m}`),()=>[u,i])}function X_(e){return _r(Bd,e)}var Y_=[...Ua,hi];function Z_(e){return Ga(Y_,[hi],e)}function eL(e){return wt(_r([Ud],e),(o,i)=>[o,i],()=>wt(X_(e),(o,i)=>wt(Z_(i),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[]))}function sp(e){return eL(wn(e))}function tL(e){return op(rp,e)}function rL(e){return wt(tL(e),(o,i)=>wt(sp(i),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function WE(e){return rL(wn(e))}function nL(e){return wt(WE(e),(o,i)=>wt(_r(["n"],i),(u,m)=>[`${o}`,m],()=>[]),()=>[])}function Gd(e){return nL(e)}function Kd(e,o){return _r([e],o)}function X(e,o){return M(e,"")?["",o]:e.startsWith(Ba)?Kd(e,np(o)):e.startsWith(jE)?Kd(e,o):Kd(e,wn(o))}var zE=[...FE,hi,UE];function oL(e){return _r(zE,e)}var sL=[...zE,...Ua];function VE(e,o=""){return wt(_r(sL,e),(i,u)=>VE(u,`${o}${i}`),()=>[o,e])}function iL(e){return wt(oL(e),(o,i)=>wt(VE(i),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function Br(e){return iL(wn(e))}var aL=[...Ua,hi];function uL(e){return Vu(_r([tp],e))}function JE(e){return wt(Ga(aL,[hi],e),(o,i)=>M(o,"")?[]:[o,i],()=>[])}function cL(e){return wt(_r([tp],e),(o,i)=>wt(JE(i),(u,m)=>[`0${o}${u}`,m],()=>[]),()=>[])}function mL(e){return wt(sp(e),(o,i)=>wt(_r([tp],i),(u,m)=>wt(JE(m),(p,f)=>[`${o}${u}${p}`,f],()=>[`${o}`,m]),()=>[`${o}`,i]),()=>[])}function pL(e){return uL(e)?cL(e):mL(e)}function QE(e){return pL(wn(e))}function lL(e){return op(rp,e)}function dL(e){return wt(lL(e),(o,i)=>wt(QE(i),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function ip(e){return dL(wn(e))}function fL(e){return M(e,"")?[]:[e.slice(0,1),e.slice(1)]}function XE(e,o){return xt(e,(i,u)=>o.startsWith(i)?!0:XE(u,o),()=>!1)}function gi(e,o,i=""){return wt(fL(o),(u,m)=>XE(e,o)?[i,o]:gi(e,m,`${i}${u}`),()=>[])}function hL(e,o,i){return wt(_r([e],i),(u,m)=>wt(gi([o],m),(p,f)=>wt(_r([o],f),(h,x)=>[`${p}`,x],()=>[]),()=>[]),()=>[])}function gL(e,o,i){return wt(_r([e],i),(u,m)=>wt(gi([Ba,o],m),(p,f)=>wt(_r([o],f),(h,x)=>[`${p}`,x],()=>[]),()=>[]),()=>[])}function YE(e,o,i,u){return i?hL(e,o,wn(u)):gL(e,o,wn(u))}function yL(e,o){return _r(e,o)}function xL(e,o){return YE(e,e,!1,o)}function IL(e,o){return wt(yL(e,o),(i,u)=>xL(i,`${i}${u}`),()=>[])}function ap(e,o){return IL(e,wn(o))}function ZE(e,o){return wt(gi(e,o),(i,u)=>M(i,"")?[]:[i,u],()=>[])}var w=(e,o,i=()=>[])=>e.length===2?o(e):i(),EL=(e)=>w(w(Br(e),([o,i])=>w(X("extends",i),([u,m])=>w(vt(m),([p,f])=>w(X("=",f),([h,x])=>w(vt(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[kI(o),i]),SL=(e)=>w(w(Br(e),([o,i])=>w(X("extends",i),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[AI(o),i]),wL=(e)=>w(w(Br(e),([o,i])=>w(X("=",i),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[PI(o),i]),TL=(e)=>w(Br(e),([o,i])=>[CI(o),i]),rS=(e)=>w(w(EL(e),([o,i])=>[o,i],()=>w(SL(e),([o,i])=>[o,i],()=>w(wL(e),([o,i])=>[o,i],()=>w(TL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[$I(o),i]),nS=(e,o=[])=>w(w(X(",",e),([i,u])=>w(rS(u),([m,p])=>[[i,m],p])),([i,u])=>nS(u,[...o,i]),()=>[o,e]),RL=(e)=>w(w(w(rS(e),([o,i])=>w(nS(i),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[vI(o),i]),zd=(e)=>w(w(X("<",e),([o,i])=>w(RL(i),([u,m])=>w(X(">",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[MI(o),i]),oS=(e,o=[])=>w(w(X(",",e),([i,u])=>w(vt(u),([m,p])=>[[i,m],p])),([i,u])=>oS(u,[...o,i]),()=>[o,e]),kL=(e)=>w(w(w(vt(e),([o,i])=>w(oS(i),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[OI(o),i]),AL=(e)=>w(w(X("<",e),([o,i])=>w(kL(i),([u,m])=>w(X(">",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[_I(o),i]),PL=(e)=>w(w(Br(e),([o,i])=>w(AL(i),([u,m])=>[[o,u],m])),([o,i])=>[LI(o),i]),sS=(e)=>w(w(w(X(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[NI(o),i]),iS=(e)=>w(X("string",e),([o,i])=>[DI(o),i]),aS=(e)=>w(X("number",e),([o,i])=>[qI(o),i]),CL=(e)=>w(X("boolean",e),([o,i])=>[FI(o),i]),$L=(e)=>w(X("undefined",e),([o,i])=>[jI(o),i]),vL=(e)=>w(X("null",e),([o,i])=>[UI(o),i]),uS=(e)=>w(X("integer",e),([o,i])=>[BI(o),i]),ML=(e)=>w(X("bigint",e),([o,i])=>[GI(o),i]),OL=(e)=>w(X("unknown",e),([o,i])=>[KI(o),i]),_L=(e)=>w(X("any",e),([o,i])=>[HI(o),i]),LL=(e)=>w(X("object",e),([o,i])=>[WI(o),i]),NL=(e)=>w(X("never",e),([o,i])=>[zI(o),i]),cS=(e)=>w(X("symbol",e),([o,i])=>[VI(o),i]),DL=(e)=>w(X("void",e),([o,i])=>[JI(o),i]),qL=(e)=>w(X("this",e),([o,i])=>[QI(o),i]),FL=(e)=>w(w(X("${",e),([o,i])=>w(vt(i),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[tb(o),i]),Hd=(e)=>w(gi(["${","`"],e),([o,i])=>[rb(o),i]),mS=(e)=>w(w(w(Hd(e),([o,i])=>w(FL(i),([u,m])=>w(mS(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w(w(Hd(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w(w(Hd(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[nb(o),i]),Vd=(e)=>w(w(X("`",e),([o,i])=>w(mS(i),([u,m])=>w(X("`",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[ob(o),i]),jL=(e)=>w(Vd(e),([o,i])=>[sb(o),i]),UL=(e)=>w(w(w(X("if",e),([o,i])=>w(vt(i),([u,m])=>w(X("then",m),([p,f])=>w(vt(f),([h,x])=>w(X("else",x),([I,S])=>w(vt(S),([R,k])=>[[o,u,p,h,I,R],k])))))),([o,i])=>[o,i],()=>w(w(X("if",e),([o,i])=>w(vt(i),([u,m])=>w(X("then",m),([p,f])=>w(vt(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[o,i],()=>[])),([o,i])=>[ib(o),i]),BL=(e)=>w(Gd(e),([o,i])=>[XI(o),i]),GL=(e)=>w(w(X("true",e),([o,i])=>[o,i],()=>w(X("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[YI(o),i]),KL=(e)=>w(ip(e),([o,i])=>[ZI(o),i]),HL=(e)=>w(ap(["'",'"'],e),([o,i])=>[eb(o),i]),WL=(e)=>w(w(w(X("keyof",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[ab(o),i]),pS=(e,o=[])=>w(w(w(X("[",e),([i,u])=>w(vt(u),([m,p])=>w(X("]",p),([f,h])=>[[i,m,f],h]))),([i,u])=>[i,u],()=>w(w(X("[",e),([i,u])=>w(X("]",u),([m,p])=>[[i,m],p])),([i,u])=>[i,u],()=>[])),([i,u])=>pS(u,[...o,i]),()=>[o,e]),zL=(e)=>w(pS(e),([o,i])=>[ub(o),i]),VL=(e)=>w(w(w(X("extends",e),([o,i])=>w(vt(i),([u,m])=>w(X("?",m),([p,f])=>w(vt(f),([h,x])=>w(X(":",x),([I,S])=>w(vt(S),([R,k])=>[[o,u,p,h,I,R],k])))))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[cb(o),i]),JL=(e)=>w(w(w(X("(",e),([o,i])=>w(vt(i),([u,m])=>w(X(")",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w(iS(e),([o,i])=>[o,i],()=>w(aS(e),([o,i])=>[o,i],()=>w(CL(e),([o,i])=>[o,i],()=>w($L(e),([o,i])=>[o,i],()=>w(vL(e),([o,i])=>[o,i],()=>w(uS(e),([o,i])=>[o,i],()=>w(ML(e),([o,i])=>[o,i],()=>w(OL(e),([o,i])=>[o,i],()=>w(_L(e),([o,i])=>[o,i],()=>w(LL(e),([o,i])=>[o,i],()=>w(NL(e),([o,i])=>[o,i],()=>w(cS(e),([o,i])=>[o,i],()=>w(DL(e),([o,i])=>[o,i],()=>w(qL(e),([o,i])=>[o,i],()=>w(BL(e),([o,i])=>[o,i],()=>w(GL(e),([o,i])=>[o,i],()=>w(KL(e),([o,i])=>[o,i],()=>w(HL(e),([o,i])=>[o,i],()=>w(jL(e),([o,i])=>[o,i],()=>w(UL(e),([o,i])=>[o,i],()=>w(iN(e),([o,i])=>[o,i],()=>w(cN(e),([o,i])=>[o,i],()=>w(hN(e),([o,i])=>[o,i],()=>w(fN(e),([o,i])=>[o,i],()=>w(IN(e),([o,i])=>[o,i],()=>w(PL(e),([o,i])=>[o,i],()=>w(bN(e),([o,i])=>[o,i],()=>[])))))))))))))))))))))))))))),([o,i])=>[mb(o),i]),QL=(e)=>w(w(w(X("with",e),([o,i])=>w(PS(i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[pb(o),i]),lS=(e)=>w(w(WL(e),([o,i])=>w(JL(i),([u,m])=>w(zL(m),([p,f])=>w(VL(f),([h,x])=>w(QL(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[lb(o),i]),dS=(e)=>w(w(w(X("&",e),([o,i])=>w(lS(i),([u,m])=>w(dS(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[db(o),i]),fS=(e)=>w(w(lS(e),([o,i])=>w(dS(i),([u,m])=>[[o,u],m])),([o,i])=>[fb(o),i]),hS=(e)=>w(w(w(X("|",e),([o,i])=>w(fS(i),([u,m])=>w(hS(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[hb(o),i]),up=(e)=>w(w(fS(e),([o,i])=>w(hS(i),([u,m])=>[[o,u],m])),([o,i])=>[gb(o),i]),XL=(e)=>w(w(X("readonly",e),([o,i])=>w(up(i),([u,m])=>[[o,u],m])),([o,i])=>[yb(o),i]),YL=(e)=>w(w(X("|",e),([o,i])=>w(up(i),([u,m])=>[[o,u],m])),([o,i])=>[xb(o),i]),ZL=(e)=>w(w(zd(e),([o,i])=>w(X("=",i),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[Ib(o),i]),eN=(e)=>w(w(w(X("infer",e),([o,i])=>w(Br(i),([u,m])=>w(X("extends",m),([p,f])=>w(up(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[o,i],()=>w(w(X("infer",e),([o,i])=>w(Br(i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>[])),([o,i])=>[bb(o),i]),vt=(e)=>w(w(eN(e),([o,i])=>[o,i],()=>w(YL(e),([o,i])=>[o,i],()=>w(XL(e),([o,i])=>[o,i],()=>w(up(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[Eb(o),i]),tN=(e)=>w(ip(e),([o,i])=>[Sb(o),i]),rN=(e)=>w(Br(e),([o,i])=>[wb(o),i]),nN=(e)=>w(ap(["'",'"'],e),([o,i])=>[Tb(o),i]),oN=(e)=>w(w(X("[",e),([o,i])=>w(Br(i),([u,m])=>w(X(":",m),([p,f])=>w(w(uS(f),([h,x])=>[h,x],()=>w(aS(f),([h,x])=>[h,x],()=>w(iS(f),([h,x])=>[h,x],()=>w(cS(f),([h,x])=>[h,x],()=>[])))),([h,x])=>w(X("]",x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[Rb(o),i]),gS=(e)=>w(w(tN(e),([o,i])=>[o,i],()=>w(rN(e),([o,i])=>[o,i],()=>w(nN(e),([o,i])=>[o,i],()=>w(oN(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[kb(o),i]),yS=(e)=>w(w(w(X("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Ab(o),i]),xS=(e)=>w(w(w(X("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Pb(o),i]),IS=(e)=>w(w(yS(e),([o,i])=>w(gS(i),([u,m])=>w(xS(m),([p,f])=>w(X(":",f),([h,x])=>w(vt(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[Cb(o),i]),cp=(e)=>w(w(w(X(",",e),([o,i])=>w(X(`
20
+ `,i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X(";",e),([o,i])=>w(X(`
21
+ `,i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X(",",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w(w(X(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w(w(X(`
22
+ `,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))))),([o,i])=>[$b(o),i]),bS=(e,o=[])=>w(w(cp(e),([i,u])=>w(IS(u),([m,p])=>[[i,m],p])),([i,u])=>bS(u,[...o,i]),()=>[o,e]),sN=(e)=>w(w(w(IS(e),([o,i])=>w(bS(i),([u,m])=>w(w(cp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[vb(o),i]),Jd=(e)=>w(w(X("{",e),([o,i])=>w(sN(i),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[Ob(o),i]),iN=(e)=>w(Jd(e),([o,i])=>[_b(o),i]),aN=(e)=>w(w(w(Br(e),([o,i])=>w(X("?",i),([u,m])=>w(X(":",m),([p,f])=>w(X("readonly",f),([h,x])=>w(vt(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[o,i],()=>w(w(Br(e),([o,i])=>w(X(":",i),([u,m])=>w(X("readonly",m),([p,f])=>w(vt(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[o,i],()=>w(w(Br(e),([o,i])=>w(X("?",i),([u,m])=>w(X(":",m),([p,f])=>w(vt(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[o,i],()=>w(w(Br(e),([o,i])=>w(X(":",i),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>[])))),([o,i])=>[Lb(o),i]),eS=(e)=>w(w(aN(e),([o,i])=>[o,i],()=>w(w(yS(e),([o,i])=>w(vt(i),([u,m])=>w(xS(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>[])),([o,i])=>[Nb(o),i]),ES=(e)=>w(w(w(X("...",e),([o,i])=>w(eS(i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(eS(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[Db(o),i]),SS=(e,o=[])=>w(w(X(",",e),([i,u])=>w(ES(u),([m,p])=>[[i,m],p])),([i,u])=>SS(u,[...o,i]),()=>[o,e]),uN=(e)=>w(w(w(ES(e),([o,i])=>w(SS(i),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[qb(o),i]),cN=(e)=>w(w(X("[",e),([o,i])=>w(uN(i),([u,m])=>w(X("]",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[Fb(o),i]),mN=(e)=>w(w(Br(e),([o,i])=>w(X("?",i),([u,m])=>w(X(":",m),([p,f])=>w(X("readonly",f),([h,x])=>w(vt(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[jb(o),i]),pN=(e)=>w(w(Br(e),([o,i])=>w(X(":",i),([u,m])=>w(X("readonly",m),([p,f])=>w(vt(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[Ub(o),i]),lN=(e)=>w(w(Br(e),([o,i])=>w(X("?",i),([u,m])=>w(X(":",m),([p,f])=>w(vt(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[Bb(o),i]),dN=(e)=>w(w(Br(e),([o,i])=>w(X(":",i),([u,m])=>w(vt(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[Gb(o),i]),tS=(e)=>w(w(mN(e),([o,i])=>[o,i],()=>w(pN(e),([o,i])=>[o,i],()=>w(lN(e),([o,i])=>[o,i],()=>w(dN(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[Kb(o),i]),wS=(e)=>w(w(w(X("...",e),([o,i])=>w(tS(i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(tS(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[Hb(o),i]),TS=(e,o=[])=>w(w(X(",",e),([i,u])=>w(wS(u),([m,p])=>[[i,m],p])),([i,u])=>TS(u,[...o,i]),()=>[o,e]),RS=(e)=>w(w(w(wS(e),([o,i])=>w(TS(i),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Wb(o),i]),fN=(e)=>w(w(X("(",e),([o,i])=>w(RS(i),([u,m])=>w(X(")",m),([p,f])=>w(X("=>",f),([h,x])=>w(vt(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[zb(o),i]),hN=(e)=>w(w(X("new",e),([o,i])=>w(X("(",i),([u,m])=>w(RS(m),([p,f])=>w(X(")",f),([h,x])=>w(X("=>",x),([I,S])=>w(vt(S),([R,k])=>[[o,u,p,h,I,R],k])))))),([o,i])=>[Vb(o),i]),gN=(e)=>w(w(w(X("+",e),([o,i])=>w(X("readonly",i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X("-",e),([o,i])=>w(X("readonly",i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Jb(o),i]),yN=(e)=>w(w(w(X("+",e),([o,i])=>w(X("?",i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X("-",e),([o,i])=>w(X("?",i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Qb(o),i]),xN=(e)=>w(w(w(X("as",e),([o,i])=>w(vt(i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Xb(o),i]),IN=(e)=>w(w(X("{",e),([o,i])=>w(gN(i),([u,m])=>w(X("[",m),([p,f])=>w(Br(f),([h,x])=>w(X("in",x),([I,S])=>w(vt(S),([R,k])=>w(xN(k),([A,v])=>w(X("]",v),([_,Q])=>w(yN(Q),([L,z])=>w(X(":",z),([J,Z])=>w(vt(Z),([re,U])=>w(sS(U),([ne,fe])=>w(X("}",fe),([Re,Ee])=>[[o,u,p,h,I,R,A,_,L,J,re,ne,Re],Ee]))))))))))))),([o,i])=>[Yb(o),i]),bN=(e)=>w(Br(e),([o,i])=>[Zb(o),i]),EN=(e)=>w(Gd(e),([o,i])=>[eE(o),i]),SN=(e)=>w(ip(e),([o,i])=>[tE(o),i]),wN=(e)=>w(w(X("true",e),([o,i])=>[o,i],()=>w(X("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[rE(o),i]),TN=(e)=>w(ap(['"',"'"],e),([o,i])=>[nE(o),i]),RN=(e)=>w(X("null",e),([o,i])=>[oE(o),i]),kN=(e)=>w(X("undefined",e),([o,i])=>[sE(o),i]),kS=(e)=>w(w(gS(e),([o,i])=>w(X(":",i),([u,m])=>w(Qd(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[iE(o),i]),AS=(e,o=[])=>w(w(cp(e),([i,u])=>w(kS(u),([m,p])=>[[i,m],p])),([i,u])=>AS(u,[...o,i]),()=>[o,e]),AN=(e)=>w(w(w(kS(e),([o,i])=>w(AS(i),([u,m])=>w(w(cp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[aE(o),i]),PS=(e)=>w(w(X("{",e),([o,i])=>w(AN(i),([u,m])=>w(X("}",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[uE(o),i]),CS=(e,o=[])=>w(w(X(",",e),([i,u])=>w(Qd(u),([m,p])=>[[i,m],p])),([i,u])=>CS(u,[...o,i]),()=>[o,e]),PN=(e)=>w(w(w(Qd(e),([o,i])=>w(CS(i),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[cE(o),i]),CN=(e)=>w(w(X("[",e),([o,i])=>w(PN(i),([u,m])=>w(X("]",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[mE(o),i]),Qd=(e)=>w(w(EN(e),([o,i])=>[o,i],()=>w(SN(e),([o,i])=>[o,i],()=>w(wN(e),([o,i])=>[o,i],()=>w(TN(e),([o,i])=>[o,i],()=>w(RN(e),([o,i])=>[o,i],()=>w(kN(e),([o,i])=>[o,i],()=>w(PS(e),([o,i])=>[o,i],()=>w(CN(e),([o,i])=>[o,i],()=>[])))))))),([o,i])=>[pE(o),i]),$N=(e)=>w(X("-?(?:0|[1-9][0-9]*)n",e),([o,i])=>[lE(o),i]),vN=(e)=>w(X(".*",e),([o,i])=>[dE(o),i]),MN=(e)=>w(X("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,i])=>[fE(o),i]),ON=(e)=>w(X("-?(?:0|[1-9][0-9]*)",e),([o,i])=>[hE(o),i]),_N=(e)=>w(X("(?!)",e),([o,i])=>[gE(o),i]),LN=(e)=>w(ZE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,i])=>[yE(o),i]),NN=(e)=>w(w($N(e),([o,i])=>[o,i],()=>w(vN(e),([o,i])=>[o,i],()=>w(MN(e),([o,i])=>[o,i],()=>w(ON(e),([o,i])=>[o,i],()=>w(_N(e),([o,i])=>[o,i],()=>w(DN(e),([o,i])=>[o,i],()=>w(LN(e),([o,i])=>[o,i],()=>[]))))))),([o,i])=>[xE(o),i]),DN=(e)=>w(w(X("(",e),([o,i])=>w(Xd(i),([u,m])=>w(X(")",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[IE(o),i]),$S=(e)=>w(w(w(Wd(e),([o,i])=>w(X("|",i),([u,m])=>w($S(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w(w(Wd(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[]))),([o,i])=>[bE(o),i]),Wd=(e)=>w(w(NN(e),([o,i])=>w(Xd(i),([u,m])=>[[o,u],m])),([o,i])=>[EE(o),i]),Xd=(e)=>w(w($S(e),([o,i])=>[o,i],()=>w(Wd(e),([o,i])=>[o,i],()=>[])),([o,i])=>[SE(o),i]),Gx=(e)=>w(w(X("^",e),([o,i])=>w(Xd(i),([u,m])=>w(X("$",m),([p,f])=>[[o,u,p],f]))),([o,i])=>[wE(o),i]),vS=(e,o=[])=>w(w(X(",",e),([i,u])=>w(vt(u),([m,p])=>[[i,m],p])),([i,u])=>vS(u,[...o,i]),()=>[o,e]),qN=(e)=>w(w(w(vt(e),([o,i])=>w(vS(i),([u,m])=>w(w(X(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[TE(o),i]),MS=(e)=>w(w(w(X("extends",e),([o,i])=>w(qN(i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[RE(o),i]),FN=(e)=>w(w(X("interface",e),([o,i])=>w(Br(i),([u,m])=>w(zd(m),([p,f])=>w(MS(f),([h,x])=>w(Jd(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[kE(o),i]),jN=(e)=>w(w(X("interface",e),([o,i])=>w(Br(i),([u,m])=>w(MS(m),([p,f])=>w(Jd(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[AE(o),i]),UN=(e)=>w(w(X("type",e),([o,i])=>w(Br(i),([u,m])=>w(zd(m),([p,f])=>w(X("=",f),([h,x])=>w(vt(x),([I,S])=>[[o,u,p,h,I],S]))))),([o,i])=>[PE(o),i]),BN=(e)=>w(w(X("type",e),([o,i])=>w(Br(i),([u,m])=>w(X("=",m),([p,f])=>w(vt(f),([h,x])=>[[o,u,p,h],x])))),([o,i])=>[CE(o),i]),GN=(e)=>w(w(w(X("export",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[$E(o),i]),OS=(e)=>w(w(w(X(";",e),([o,i])=>w(X(`
23
+ `,i),([u,m])=>[[o,u],m])),([o,i])=>[o,i],()=>w(w(X(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>w(w(X(`
24
+ `,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[vE(o),i]),_S=(e,o=[])=>w(w(OS(e),([i,u])=>w(Yd(u),([m,p])=>[[i,m],p])),([i,u])=>_S(u,[...o,i]),()=>[o,e]),KN=(e)=>w(w(w(Yd(e),([o,i])=>w(_S(i),([u,m])=>w(w(OS(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,i])=>[o,i],()=>w([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[ME(o),i]),Yd=(e)=>w(w(GN(e),([o,i])=>w(w(FN(i),([u,m])=>[u,m],()=>w(jN(i),([u,m])=>[u,m],()=>w(UN(i),([u,m])=>[u,m],()=>w(BN(i),([u,m])=>[u,m],()=>[])))),([u,m])=>w(sS(m),([p,f])=>[[o,u,p],f]))),([o,i])=>[OE(o),i]),HN=(e)=>w(w(Yd(e),([o,i])=>w(KN(i),([u,m])=>[[o,u],m])),([o,i])=>[_E(o),i]),LS=(e)=>w(w(HN(e),([o,i])=>[o,i],()=>w(ZL(e),([o,i])=>[o,i],()=>w(vt(e),([o,i])=>[o,i],()=>[]))),([o,i])=>[LE(o),i]);function NS(e){let o=Vd(`\`${e}\``);return M(o.length,2)?o[0]:Fr()}function zN(e){return e.join("|")}function VN(e){return e.slice(1,e.length-1)}function JN(e,o,i){return yi(o,`${i}${e}`)}function QN(e,o){return yi(e,`${o}${Nx}`)}function XN(e,o){return yi(e,`${o}${Em}`)}function YN(e,o){return yi(e,`${o}${Rm}`)}function ZN(e,o){return Ju(g([s("false"),s("true")]),e,o)}function eD(e,o){return yi(e,`${o}${km}`)}function tD(e,o,i){return yi(o,`${i}${VN(e)}`)}function rD(e,o,i){let u=Qu(e,{});return Ju(u,o,i)}function nD(e,o,i){let u=Jn(e);return Ju(u,o,i)}function DS(e,o,i,u=[]){return xt(e,(m,p)=>DS(p,o,i,[...u,Ju(m,[],"")]),()=>yi(o,`${i}(${zN(u)})`))}function Ju(e,o,i){return un(e)?nD(e.enum,o,i):yn(e)?XN(o,i):dt(e)?JN(e.const,o,i):go(e)?QN(o,i):Vn(e)?ZN(o,i):Pr(e)?YN(o,i):cn(e)?eD(o,i):tr(e)?tD(e.pattern,o,i):FS(e)?rD(e.parameters[0],o,i):be(e)?DS(e.anyOf,o,i):mx}function yi(e,o){return xt(e,(i,u)=>Ju(i,u,o),()=>o)}function oD(e){return`^${yi(e,"")}$`}function qS(e){let o=oD(e);return Pm(o)}function Qu(e,o){return ut(e)?Et(qS(e),{},o):Nm(e,o)}function jS(e,o,i,u){let m=So(e,o,i);return Qu(m,u)}function Nm(e,o={}){return ke("TemplateLiteral",[e],o)}function FS(e){return vr(e)&&pe(e,"action")&&M(e.action,"TemplateLiteral")}function US(e){return Qu(e,{})}function sD(e){let o=NS(e);return US(o)}function BS(e,o={}){let i=lt(e)?sD(e):US(e);return Et(i,{},o)}function tr(e){return Te(e,"TemplateLiteral")}function Zd(e){return $t({["~kind"]:"ExtendsUnion"},{inferred:e})}function ef(e){return at(e)&&pe(e,"~kind")&&pe(e,"inferred")&&M(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function we(e){return $t({["~kind"]:"ExtendsTrue"},{inferred:e})}function tf(e){return at(e)&&pe(e,"~kind")&&pe(e,"inferred")&&M(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ye(){return $t({["~kind"]:"ExtendsFalse"},{})}function rf(e){return at(e)&&pe(e,"~kind")&&M(e["~kind"],"ExtendsFalse")}function co(e){return ef(e)||tf(e)}function Sr(e,o,i){return co(e)?o(e.inferred):i()}function iD(e,o,i,u){return Sr(Tt(e,i,u),(m)=>we(gn(gn(e,m),{[o]:i})),()=>Ye())}function aD(e,o){return we(e)}function uD(e,o,i,u,m){return Sr(Tt(e,o,i),(p)=>Sr(Tt(p,o,u),(f)=>we(f),()=>Ye()),()=>Sr(Tt(e,o,m),(p)=>we(p),()=>Ye()))}function cD(e,o,i){let u=Jn(i);return Tt(e,o,u)}function GS(e,o,i){return xt(i,(u,m)=>Sr(Tt(e,o,u),(p)=>GS(p,o,m),()=>Ye()),()=>we(e))}function mD(e,o,i){let u=_n(i);return Tt(e,o,u)}function KS(e,o,i){return xt(i,(u,m)=>Sr(Tt(e,o,u),(p)=>we(p),()=>KS(e,o,m)),()=>Ye())}function Nt(e,o,i){return Mr(i)?aD(e,o):qr(i)?uD(e,o,i.if,i.then,i.else):un(i)?cD(e,o,i.enum):an(i)?iD(e,i.name,o,i.extends):Ge(i)?GS(e,o,i.allOf):tr(i)?mD(e,o,i.pattern):be(i)?KS(e,o,i.anyOf):tn(i)?we(e):Ye()}function HS(e,o,i){return an(i)?Nt(e,o,i):Mr(i)?we(e):tn(i)?we(e):Zd(e)}function pD(e,o){let i=sa(e),u=sa(o);return i&&u?!0:!i&&u?!0:i&&!u?!1:!0}function WS(e,o,i,u){return St(u)?pD(o,u)?Tt(e,i,u.items):Ye():Nt(e,o,u)}function zS(e,o,i){return go(i)?we(e):Nt(e,o,i)}function VS(e,o,i){return Vn(i)?we(e):Nt(e,o,i)}function lD(e,o,i,u,m){let p=an(u)?o:u,f=an(u)?u:o,h=ln(o),x=ln(u);return!h&&x?Ye():Sr(Tt(e,p,f),(I)=>Xu(I,i,m),()=>Ye())}function dD(e,o,i,u){return xt(u,(m,p)=>lD(e,o,i,m,p),()=>ln(o)?we(e):Ye())}function fD(e,o,i){return xt(o,(u,m)=>dD(e,u,m,i),()=>we(e))}function Xu(e,o,i){return fD(e,o,i)}function mp(e,o,i){return yo(i)?we(e):Tt(e,o,i)}function JS(e,o,i,u){return Mr(u)?we(e):tn(u)?we(e):zr(u)?Sr(Xu(e,o,u.parameters),(m)=>mp(m,i,u.instanceType),()=>Ye()):Ye()}function QS(e,o,i,u,m){return Sr(Tt(e,o,m),()=>Tt(e,i,m),()=>Tt(e,u,m))}function XS(e,o,i){let u=Jn(o);return Tt(e,u,i)}function YS(e,o,i,u){return Mr(u)?we(e):tn(u)?we(e):en(u)?Sr(Xu(e,o,u.parameters),(m)=>mp(m,i,u.returnType),()=>Ye()):Ye()}function ZS(e,o,i){return yn(i)?we(e):Pr(i)?we(e):Nt(e,o,i)}function ew(e,o,i){let u=Cr(o);return Tt(e,u,i)}function pp(e,o,i){return o===i?we(e):Ye()}function hD(e,o,i){return dt(i)?pp(e,o,i.const):go(i)?we(e):Nt(e,s(o),i)}function gD(e,o,i){return dt(i)?pp(e,o,i.const):Vn(i)?we(e):Nt(e,s(o),i)}function yD(e,o,i){return dt(i)?pp(e,o,i.const):Pr(i)?we(e):Nt(e,s(o),i)}function xD(e,o,i){return dt(i)?pp(e,o,i.const):cn(i)?we(e):Nt(e,s(o),i)}function tw(e,o,i){return Dr(o.const)?hD(e,o.const,i):fn(o.const)?gD(e,o.const,i):Ot(o.const)?yD(e,o.const,i):lt(o.const)?xD(e,o.const,i):Fr()}function rw(e,o,i){return an(i)?Nt(e,o,i):we(e)}function nw(e,o,i){return Ts(i)?we(e):Nt(e,o,i)}function ow(e,o,i){return Pr(i)?we(e):Nt(e,o,i)}function ID(e,o,i){return ln(o)?ln(i)?we(e):Ye():we(e)}function bD(e,o,i){return an(i)&&ho(i.extends)?Ye():Sr(Tt(e,o,i),(u)=>ID(u,o,i),()=>Ye())}function ED(e,o){return e.reduce((i,u)=>(u in o)?co(o[u])?{...i,...o[u].inferred}:Fr():Fr(),{})}function SD(e,o,i){let u={};for(let f of Se(i))u[f]=f in o?bD({},o[f],i[f]):ln(i[f])?an(i[f])?we(gn(e,{[i[f].name]:i[f].extends})):we(e):Ye();let m=Td(u).every((f)=>co(f)),p=m?ED(Se(u),u):{};return m?we(p):Ye()}function wD(e,o,i){let u=SD(e,o,i);return co(u)?we(gn(e,u.inferred)):Ye()}function TD(e,o,i){return wD(e,o,i)}function RD(e,o){return Se(o).reduce((i,u)=>({...i,[u]:pe(e,u)?be(i[u])?g([...i[u].anyOf,o[u]]):g([e[u],o[u]]):o[u]}),e)}function sw(e,o,i,u){return xt(o,(m,p)=>Sr(Tt({},e[m],i),(f)=>sw(e,p,i,RD(u,f)),()=>Ye()),()=>we(u))}function kD(e,o,i,u){let m=Se(o);return sw(o,m,u,e)}function iw(e,o,i){return Kt(i)?kD(e,o,xn(i),or(i)):He(i)?TD(e,o,i.properties):Nt(e,l(o),i)}function AD(e,o){return M(Se(o).length,0)?we(e):Ye()}function PD(e,o,i,u,m){return Tt(e,i,m)}function aw(e,o,i,u){return Kt(u)?PD(e,Mm(o),i,Mm(xn(u)),or(u)):He(u)?AD(e,u.properties):Mr(u)?we(e):tn(u)?we(e):Ye()}function uw(e,o,i){return cn(i)?we(e):Nt(e,o,i)}function cw(e,o,i){return Rs(i)?we(e):Nt(e,o,i)}function mw(e,o,i){let u=_n(o);return Tt(e,u,i)}function nf(e,o){return $t({"~kind":"Inferrable"},{name:e,type:o},{})}function Yu(e){return at(e)&&pe(e,"~kind")&&pe(e,"name")&&pe(e,"type")&&M(e["~kind"],"Inferrable")&&lt(e.name)&&at(e.type)}function of(e){return fi(e)?an(e.items)?St(e.items.extends)?nf(e.items.name,e.items.extends.items):tn(e.items.extends)?nf(e.items.name,e.items.extends):void 0:Fr():void 0}function lp(e){return an(e)?nf(e.name,e.extends):void 0}function sf(e,o,i=[]){return xt(e,(u,m)=>Sr(Tt({},u,o),()=>sf(m,o,[...i,u]),()=>{return}),()=>i)}function pw(e,o,i,u){let m=sf(i,u);return Fe(m)?we(gn(e,{[o]:Ur(m)})):Ye()}function dp(e,o,i,u){let m=sf(i,u);return Fe(m)?we(gn(e,{[o]:g(m)})):Ye()}function CD(e){return[...e].reverse()}function af(e,o){return o?CD(e):e}function $D(e){let o=e.length>0?e[0]:void 0,i=vr(o)?of(o):void 0;return vr(i)}function vD(e,o,i,u,m,p){return Sr(Tt(e,i,m),(f)=>lw(f,o,u,p),()=>Ye())}function MD(e,o,i,u,m){let p=of(u);return Yu(p)?pw(e,p.name,af(i,o),p.type):xt(i,(f,h)=>vD(e,o,f,h,u,m),()=>Ye())}function OD(e,o,i,u){return xt(u,(m,p)=>MD(e,o,i,m,p),()=>M(i.length,0)?we(e):Ye())}function lw(e,o,i,u){return OD(e,o,i,u)}function _D(e,o,i){let u=xi(e,gr([],[]),i),m=$D(u);return lw(e,m,af(o,m),af(u,m))}function dw(e,o,i){let u=lp(i);return Yu(u)?dp(e,u.name,o,u.type):xt(o,(m,p)=>Sr(Tt(e,m,i),(f)=>dw(f,p,i),()=>Ye()),()=>we(e))}function fw(e,o,i){let u=xi(e,gr([],[]),o);return ct(i)?_D(e,u,i.items):St(i)?dw(e,u,i.items):Nt(e,Ur(u),i)}function hw(e,o,i){return yo(i)?we(e):ss(i)?we(e):Nt(e,o,i)}function gw(e,o,i){return xt(i,(u,m)=>Sr(Tt(e,o,u),(p)=>we(p),()=>gw(e,o,m)),()=>Ye())}function uf(e,o,i){return xt(o,(u,m)=>Sr(gw(e,u,i),(p)=>uf(p,m,i),()=>Ye()),()=>we(e))}function yw(e,o,i){let u=lp(i);return Yu(u)?dp(e,u.name,o,u.type):be(i)?uf(e,o,i.anyOf):uf(e,o,[i])}function xw(e,o,i){return an(i)?Nt(e,o,i):Mr(i)?we(e):tn(i)?we(e):Ye()}function Iw(e,o,i){return yo(i)?we(e):Nt(e,o,i)}function Tt(e,o,i){return Mr(o)?HS(e,o,i):St(o)?WS(e,o,o.items,i):go(o)?zS(e,o,i):Vn(o)?VS(e,o,i):zr(o)?JS(e,o.parameters,o.instanceType,i):qr(o)?QS(e,o.if,o.then,o.else,i):un(o)?XS(e,o.enum,i):en(o)?YS(e,o.parameters,o.returnType,i):yn(o)?ZS(e,o,i):Ge(o)?ew(e,o.allOf,i):dt(o)?tw(e,o,i):ho(o)?rw(e,o,i):Ts(o)?nw(e,o,i):Pr(o)?ow(e,o,i):He(o)?iw(e,o.properties,i):Kt(o)?aw(e,xn(o),or(o),i):cn(o)?uw(e,o,i):Rs(o)?cw(e,o,i):tr(o)?mw(e,o.pattern,i):ct(o)?fw(e,o.items,i):ss(o)?hw(e,o,i):be(o)?yw(e,o.anyOf,i):tn(o)?xw(e,o,i):yo(o)?Iw(e,o,i):Ye()}function LD(e,o){return Cr([...e,l(o)])}function cf(e,o,i){return ut(e)?Et(LD(e,o),{},i):Ku(e,o,i)}function bw(e,o,i,u,m){let p=So(e,o,i),f=Zu(e,o,u);return cf(p,f,m)}function Ku(e,o,i={}){return ke("Interface",[e,o],i)}function Ka(e){return vr(e)&&pe(e,"action")&&M(e.action,"Interface")}function Ew(e,o,i={}){return cf(e,o,i)}function ND(e,o,i){return e.includes(i)?!0:ec([...e,i],o,o[i])}function Sw(e,o,i){let u=hm(i);return la(e,o,u)}function la(e,o,i){return xt(i,(u,m)=>ec(e,o,u)?!0:la(e,o,m),()=>!1)}function ec(e,o,i){return Ft(i)?ND(e,o,i.$ref):St(i)?ec(e,o,i.items):zr(i)?la(e,o,[...i.parameters,i.instanceType]):en(i)?la(e,o,[...i.parameters,i.returnType]):Ka(i)?Sw(e,o,i.parameters[1]):Ge(i)?la(e,o,i.allOf):He(i)?Sw(e,o,i.properties):be(i)?la(e,o,i.anyOf):ct(i)?la(e,o,i.items):Kt(i)?ec(e,o,or(i)):!1}function ww(e,o,i){return ec(e,o,i)}function DD(e,o){return o.reduce((i,u)=>ww([u],e,e[u])?[...i,u]:i,[])}function Tw(e){let o=fm(e);return DD(e,o)}function qD(e,o,i){return i.includes(o)?i:(o in e)?tc(e,e[o],[...i,o]):Fr()}function Rw(e,o,i){let u=hm(o);return Ha(e,u,i)}function Ha(e,o,i){return o.reduce((u,m)=>tc(e,m,u),i)}function tc(e,o,i){return Ft(o)?qD(e,o.$ref,i):St(o)?tc(e,o.items,i):zr(o)?Ha(e,[...o.parameters,o.instanceType],i):en(o)?Ha(e,[...o.parameters,o.returnType],i):Ka(o)?Rw(e,o.parameters[1],i):Ge(o)?Ha(e,o.allOf,i):He(o)?Rw(e,o.properties,i):be(o)?Ha(e,o.anyOf,i):ct(o)?Ha(e,o.items,i):Kt(o)?tc(e,or(o),i):i}function kw(e,o,i){return tc(e,i,[o])}function FD(e){return _a()}function jD(e){return Se(e).reduce((o,i)=>({...o,[i]:da(e[i])}),{})}function rc(e){return e.reduce((o,i)=>[...o,da(i)],[])}function da(e){return Ft(e)?FD(e.$ref):St(e)?H(da(e.items),Ma(e)):zr(e)?Is(rc(e.parameters),da(e.instanceType)):en(e)?bs(rc(e.parameters),da(e.returnType)):Ge(e)?Mn(rc(e.allOf)):He(e)?l(jD(e.properties)):Kt(e)?ks(di(e),da(or(e))):be(e)?g(rc(e.anyOf)):ct(e)?Ur(rc(e.items)):e}function UD(e,o){return o in e?da(e[o]):Ar()}function Aw(e){return UD(e.$defs,e.$ref)}function BD(e,o,i){let u=So(e,gr([],[]),o),m=Zu({},gr([],[]),i);return Cr([...u,l(m)])}function GD(e,o){return Se(e).filter((u)=>o.includes(u)).reduce((u,m)=>{let p=e[m],f=Ka(p)?BD(e,p.parameters[0],p.parameters[1]):p;return{...u,[m]:f}},{})}function Pw(e,o,i){let u=kw(e,o,i),m=GD(e,u);return Ss(m,o)}function Cw(e,o){return o in e?Ft(e[o])?Cw(e,e[o].$ref):e[o]:Vt()}function As(e,o){return Cw(e,o)}function $w(e){return Xt(e)?Aw(e):gm(e)?Ar():e}function An(e,o,i){let u=$w(o),m=$w(i);return Tt(e,u,m)}var Fu=0,nc=1,ju=2,Uu=3;function qa(e,o){let i=[An({},e,o),An({},o,e)];return co(i[0])&&co(i[1])?Fu:co(i[0])&&rf(i[1])?ju:rf(i[0])&&co(i[1])?Uu:nc}function mf(e,o,i=[],u=o){return xt(o,(m,p)=>{let f=qa(e,m);return M(f,ju)||M(f,Fu)?u:M(f,nc)?mf(e,p,[...i,m],u):mf(e,p,i,u)},()=>[...i,e])}function KD(e,o,i){let u=vo(e);return Mr(u)?[u]:tn(u)?[u]:ho(u)?fp(o,i):He(u)?fp(o,[...i,u]):fp(o,mf(u,i))}function fp(e,o=[]){return xt(e,(i,u)=>KD(i,u,o),()=>o)}function Dd(e){let o=fp(e);return ca(o)}function pf(e,o){return Et(vo(e),{},o)}function vw(e,o,i,u){let m=he(e,o,i);return pf(m,u)}function oc(e,o=[]){return ai(e)&&M(e.action,"Conditional")?Ft(e.parameters[0])?oc(e.parameters[2],oc(e.parameters[3],[...o,e.parameters[0].$ref])):oc(e.parameters[2],oc(e.parameters[3],o)):ai(e)&&M(e.action,"Mapped")?ai(e.parameters[1])&&M(e.parameters[1].action,"KeyOf")&&Ft(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function HD(e,o){return e.reduce((i,u)=>[...i,o.includes(u.name)],[])}function _w(e,o,i=[]){return xt(e,(u,m)=>xt(o,(p,f)=>_w(m,f,[...i,[p,u]]),()=>i),()=>i)}function WD(e){return tr(e)?_n(e.pattern):un(e)?Jn(e.enum):e}function zD(e){let o=WD(e);return be(o)?[...o.anyOf]:[o]}function VD(e,o){return e.reduce((i,u)=>[...i,[...u,o]],[])}function Mw(e,o){return o.reduce((i,u)=>[...i,...VD(e,u)],[])}function Ow(e){return e.reduce((o,i)=>M(i[0],!0)?Mw(o,zD(i[1])):Mw(o,[i[1]]),[[]])}function Lw(e,o,i){let u=oc(i),m=HD(e,u),p=_w(o,m);return ai(i)&&M(i.action,"Conditional")?Ow(p):ai(i)&&M(i.action,"Mapped")?Ow(p):[o]}function JD(){return["(not-resolvable)",Vt()]}function QD(){return["(not-generic)",Vt()]}function XD(e,o,i){return[e,ui(o,i)]}function YD(e,o,i){return o in e?Nw(e,o,e[o],i):JD()}function Nw(e,o,i,u){return Oa(i)?XD(o,i.parameters,i.expression):Ft(i)?YD(e,i.$ref,u):QD()}function Dw(e,o,i){return Nw(e,"(anonymous)",o,i)}function ZD(e,o,i){if(an(o)||Wa(o)||co(An({},o,i)))return;let u={parameter:e,expect:i,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function qw(e,o,i,u,m){let p=he(e,o,m);return ZD(i,p,u),gn(e,{[i]:p})}function eq(e,o,i,u,m){let p=he(e,o,i.extends),f=he(e,o,i.equals);return xt(m,(h,x)=>lf(qw(e,o,i.name,p,h),o,u,x),()=>lf(qw(e,o,i.name,p,f),o,u,[]))}function lf(e,o,i,u){return xt(i,(m,p)=>eq(e,o,m,p,u),()=>e)}function Fw(e,o,i,u){return lf(e,o,i,u)}var df=0,ff=0;function tq(){if(Pu(ff,Bo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function rq(){tq(),ff++,df++}function nq(){if(df--,M(df,0))ff=0}function oq(e){return ji(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function sq(e,o){return M(oq(e),o)}function iq(e,o,i,u,m,p){rq();try{let f=Fw(e,o,u,p),h=he(f,gr([...o.callstack,i.$ref],o.visited),m);return he(f,gr([],[]),h)}finally{nq()}}function aq(e,o,i,u,m,p){return p.reduce((f,h)=>{let x=iq(e,o,i,u,m,h);return[...f,x]},[])}function uq(e,o,i,u,m,p){let f=Lw(u,p,m),h=aq(e,o,i,u,m,f);return M(h.length,1)?h[0]:Zn(h)}function hp(e,o,i,u){let m=So(e,o,u),p=Dw(e,i,u),f=p[0],h=p[1];return Oa(h)?sq(o,f)?Hu(pn(f),m):uq(e,o,pn(f),h.parameters,h.expression,m):Hu(i,m)}function Hu(e,o){return $t({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function jw(e,o){return hp({},gr([],[]),e,o)}function Wa(e){return Te(e,"Call")}function cq(e){return Ho(e,["~immutable"])}function Uw(e,o){return Et(cq(e),{},o)}function Bw(e,o,i,u){let m=he(e,o,i);return Uw(m,u)}function Gw(e,o){return e(o)}function Kw(e,o){return lt(o)?s(Gw(e,o)):s(o)}function Hw(e,o){let i=_n(o);return Fs(e,i)}function Ww(e,o){let i=o.map((u)=>Fs(e,u));return g(i)}function Fs(e,o){return dt(o)?Kw(e,o.const):tr(o)?Hw(e,o.pattern):be(o)?Ww(e,o.anyOf):o}function Dm(e,o={}){return ke("Capitalize",[e],o)}function zw(e,o={}){return hf(e,o)}function qm(e,o={}){return ke("Lowercase",[e],o)}function Vw(e,o={}){return gf(e,o)}function Fm(e,o={}){return ke("Uncapitalize",[e],o)}function Jw(e,o={}){return yf(e,o)}function jm(e,o={}){return ke("Uppercase",[e],o)}function Qw(e,o={}){return xf(e,o)}var mq=(e)=>e[0].toUpperCase()+e.slice(1),pq=(e)=>e.toLowerCase(),lq=(e)=>e[0].toLowerCase()+e.slice(1),dq=(e)=>e.toUpperCase();function hf(e,o){return ut([e])?Et(Fs(mq,e),{},o):Dm(e,o)}function gf(e,o){return ut([e])?Et(Fs(pq,e),{},o):qm(e,o)}function yf(e,o){return ut([e])?Et(Fs(lq,e),{},o):Fm(e,o)}function xf(e,o){return ut([e])?Et(Fs(dq,e),{},o):jm(e,o)}function Xw(e,o,i,u){let m=he(e,o,i);return hf(m,u)}function Yw(e,o,i,u){let m=he(e,o,i);return gf(m,u)}function Zw(e,o,i,u){let m=he(e,o,i);return yf(m,u)}function eT(e,o,i,u){let m=he(e,o,i);return xf(m,u)}function Um(e,o,i,u,m={}){return ke("Conditional",[e,o,i,u],m)}function tT(e,o,i,u,m={}){return If({},gr([],[]),e,o,i,u,m)}function fq(e,o,i,u,m,p){let f=An(e,i,u);return ef(f)?g([he(f.inferred,o,m),he(e,o,p)]):tf(f)?he(f.inferred,o,m):he(e,o,p)}function If(e,o,i,u,m,p,f){return ut([i,u])?Et(fq(e,o,i,u,m,p),{},f):Um(i,u,m,p,f)}function rT(e,o,i,u,m,p,f){let h=he(e,o,i),x=he(e,o,u);return If(e,o,h,x,m,p,f)}function Bm(e,o={}){return ke("ConstructorParameters",[e],o)}function nT(e,o={}){return bf(e,o)}function hq(e){let o=zr(e)?e.parameters:[],i=xi({},gr([],[]),o);return Ur(i)}function bf(e,o){return ut([e])?Et(hq(e),{},o):Bm(e,o)}function oT(e,o,i,u){let m=he(e,o,i);return bf(m,u)}function Gm(e,o,i={}){return ke("Exclude",[e,o],i)}function sT(e,o,i={}){return sc(e,o,i)}function sc(e,o,i){return ut([e,o])?Et($m(e,o),{},i):Gm(e,o,i)}function iT(e,o,i,u,m){let p=he(e,o,i),f=he(e,o,u);return sc(p,f,m)}function Km(e,o,i={}){return ke("Extract",[e,o],i)}function aT(e,o,i={}){return Ef(e,o,i)}function gq(e,o){let i=An({},e,o);return co(i)?[e]:[]}function uT(e,o,i=[]){return xt(e,(u,m)=>uT(m,o,[...i,...gq(u,o)]),()=>i)}function cT(e,o){let i=vo(e),u=be(i)?i.anyOf:[i],m=uT(u,o);return Zn(m)}function Ef(e,o,i){return ut([e,o])?Et(cT(e,o),{},i):Km(e,o,i)}function mT(e,o,i,u,m){let p=he(e,o,i),f=he(e,o,u);return Ef(p,f,m)}function yq(e){return e.reduce((o,i)=>Sm(i)?[...o,s(i)]:o,[])}function za(e){let o=yq(e);return g(o)}function Wu(e,o,i={}){return ke("Index",[e,o],i)}function pT(e,o,i={}){let u=Fe(o)?za(o):o;return Sf(e,u,i)}function lT(e,o){let i=As(e,o);return wo(i)}function dT(e,o,i){let u=es(e,o,i);return wo(u)}function xq(e,o){let i=Se(e).filter((S)=>!pe(o,S)),u=Se(o).filter((S)=>!pe(e,S)),m=Se(e).filter((S)=>pe(o,S)),p=i.reduce((S,R)=>({...S,[R]:e[R]}),{}),f=u.reduce((S,R)=>({...S,[R]:o[R]}),{}),h=m.reduce((S,R)=>({...S,[R]:Cr([e[R],o[R]])}),{}),x=gn(p,f);return gn(x,h)}function fT(e){return e.reduce((o,i)=>xq(o,wo(i)),{})}function hT(e){return e}function gT(e){let o=oI(Ur(e));return wo(o)}function Iq(e,o){return Se(e).filter((m)=>(m in o)).reduce((m,p)=>({...m,[p]:Zn([e[p],o[p]])}),{})}function yT(e,o){return xt(e,(i,u)=>yT(u,Iq(o,wo(i))),()=>o)}function xT(e){return xt(e,(o,i)=>yT(i,wo(o)),()=>Fr())}function wo(e){return Xt(e)?lT(e.$defs,e.$ref):qr(e)?dT(e.if,e.then,e.else):Ge(e)?fT(e.allOf):be(e)?xT(e.anyOf):ct(e)?gT(e.items):He(e)?hT(e.properties):{}}function Va(e){let o=wo(e);return l(o)}var bq=new RegExp("^(?:0|[1-9][0-9]*)$");function Ja(e){let o=`${e}`;return bq.test(o)?parseInt(o):e}function Eq(e){return s(Ja(e))}function IT(e){return e.map((o)=>bT(o))}function bT(e){return Ge(e)?Mn(IT(e.allOf)):be(e)?g(IT(e.anyOf)):dt(e)?Eq(e.const):e}function ET(e,o){let i=bT(o),u=An({},i,te());return co(u)?e:dt(o)&&M(o.const,"length")?te():Vt()}function ST(e,o){let i=As(e,o);return xo(i)}function wT(e,o,i){let u=es(e,o,i);return xo(u)}function TT(e){let o=Jn(e);return xo(o)}function RT(e){let o=Cr(e);return xo(o)}function kT(e){return[`${e}`]}function AT(e){let o=_n(e);return xo(o)}function PT(e){return e.reduce((o,i)=>[...o,...xo(i)],[])}function xo(e){return Xt(e)?ST(e.$defs,e.$ref):qr(e)?wT(e.if,e.then,e.else):un(e)?TT(e.enum):Ge(e)?RT(e.allOf):dt(e)?kT(e.const):tr(e)?AT(e.pattern):be(e)?PT(e.anyOf):[]}function Qa(e){return xo(e)}function ic(e,o){return o.map((i)=>ac(e,i))}function ac(e,o){return St(o)?H(ac(e,o.items)):zr(o)?Is(ic(e,o.parameters),ac(e,o.instanceType)):en(o)?bs(ic(e,o.parameters),ac(e,o.returnType)):ct(o)?Ur(ic(e,o.items)):be(o)?g(ic(e,o.anyOf)):Ge(o)?Mn(ic(e,o.allOf)):_m(o)?l(e):o}function CT(e,o){return ac(e,o)}function Sq(e,o){let i=o in e?e[o]:Vt();return CT(e,i)}function $T(e,o){return o.reduce((i,u)=>[...i,Sq(e,u)],[])}function wq(e,o){let i=Qa(o),u=$T(e,i);return Zn(u)}var Tq=new RegExp(li);function Rq(e){return e.filter((i)=>Tq.test(i))}function kq(e){let o=fm(e),i=Rq(o),u=$T(e,i);return Zn(u)}function vT(e,o){return Pr(o)?kq(e):wq(e,o)}function Aq(e){return s(Ja(e))}function MT(e){return e.map((o)=>wf(o))}function wf(e){return Ge(e)?Mn(MT(e.allOf)):be(e)?g(MT(e.anyOf)):dt(e)?Aq(e.const):e}function Pq(e,o){return e.reduceRight((i,u,m)=>{let p=An({},s(m),o);return co(p)?[u,...i]:i},[])}function Cq(e,o){let i=wf(o),u=Pq(e,i);return mi(u)}function $q(e){return mi(e)}function OT(e,o){return dt(o)&&M(o.const,"length")?s(e.length):Pr(o)||yn(o)?$q(e):Cq(e,o)}function _T(e,o){return St(e)?ET(e.items,o):He(e)?vT(e.properties,o):ct(e)?OT(e.items,o):Vt()}function vq(e){return Xt(e)||qr(e)||Ge(e)||be(e)?Va(e):e}function Sf(e,o,i){return ut([e,o])?Et(_T(vq(e),o),{},i):Wu(e,o,i)}function LT(e,o,i,u,m){let p=he(e,o,i),f=he(e,o,u);return Sf(p,f,m)}function Hm(e,o={}){return ke("InstanceType",[e],o)}function NT(e,o={}){return Tf(e,o)}function Mq(e){return zr(e)?e.instanceType:Vt()}function Tf(e,o){return ut([e])?Et(Mq(e),{},o):Hm(e,o)}function DT(e,o,i,u={}){let m=he(e,o,i);return Tf(m,u)}function zu(e,o={}){return ke("KeyOf",[e],o)}function qT(e,o={}){return Rf(e,o)}function FT(){return g([te(),a(),Da()])}function jT(e){return te()}function Oq(e){return e.reduce((i,u)=>Sm(u)?[...i,s(Ja(u))]:Fr(),[])}function UT(e){let o=Se(e),i=Oq(o);return mi(i)}function BT(e){return di(e)}function GT(e){let o=e.map((i,u)=>s(u));return mi(o)}function KT(e){return Mr(e)?FT():St(e)?jT(e.items):He(e)?UT(e.properties):Kt(e)?BT(e):ct(e)?GT(e.items):Vt()}function _q(e){return Xt(e)||qr(e)||Ge(e)||be(e)?Va(e):e}function Rf(e,o){return ut([e])?Et(KT(_q(e)),{},o):zu(e,o)}function HT(e,o,i,u){let m=he(e,o,i);return Rf(m,u)}function Gu(e,o,i,u,m={}){return ke("Mapped",[e,o,i,u],m)}function WT(e,o,i,u,m={}){return kf({},gr([],[]),e,o,i,u,m)}function Lq(e){let o=_n(e);return gp(o)}function Nq(e){return e.reduce((o,i)=>[...o,...gp(i)],[])}function Dq(e){let o=Jn(e);return gp(o)}function qq(e){return Ot(e)?[s(`${e}`)]:[s(e)]}function gp(e){return un(e)?Dq(e.enum):dt(e)?qq(e.const):tr(e)?Lq(e.pattern):be(e)?Nq(e.anyOf):[e]}function zT(e){return gp(e)}function Fq(e){return tr(e)?_n(e.pattern):e}function jq(e,o,i,u,m,p){let f=gn(e,{[i.name]:u}),h=he(f,o,m),x=Fq(h),I=he(f,o,p);return wm(x)||Tm(x)?{[x.const]:I}:{}}function Uq(e,o,i,u,m,p){return u.reduce((f,h)=>[...f,jq(e,o,i,h,m,p)],[])}function Bq(e){return e.reduce((o,i)=>[...o,l(i)],[])}function VT(e,o,i,u,m,p){let f=zT(u),h=Uq(e,o,i,f,m,p),x=Bq(h);return Cr(x)}function kf(e,o,i,u,m,p,f){return ut([u])?Et(VT(e,o,i,u,m,p),{},f):Gu(i,u,m,p,f)}function JT(e,o,i,u,m,p,f){let h=he(e,o,u);return kf(e,o,i,h,m,p,f)}function Gq(e,o,i){let u=gn(e,o);return Se(o).filter((p)=>i.includes(p)).reduce((p,f)=>({...p,[f]:Pw(u,f,o[f])}),{})}function Kq(e,o,i){let u=gn(e,o);return Se(o).filter((p)=>!i.includes(p)).reduce((p,f)=>({...p,[f]:he(u,gr([],[]),o[f])}),{})}function Hq(e,o,i){let u=Tw(o),m=Gq(e,o,u),p=Kq(e,o,u),f={...m,...p};return Et(f,{},i)}function yp(e,o,i,u){return Hq(e,i,u)}function Wm(e,o={}){return ke("NonNullable",[e],o)}function QT(e,o={}){return Af(e,o)}function Wq(e){let o=g([On(),ja()]);return sc(e,o,{})}function Af(e,o){return ut([e])?Et(Wq(e),{},o):Wm(e,o)}function XT(e,o,i,u){let m=he(e,o,i);return Af(m,u)}function zm(e,o,i={}){return ke("Omit",[e,o],i)}function YT(e,o,i={}){let u=Fe(o)?za(o):o;return Pf(e,u,i)}function xp(e){let o=Va(e);return He(o)?o.properties:Fr()}function zq(e,o){return Se(e).reduce((u,m)=>o.includes(m)?u:{...u,[m]:e[m]},{})}function ZT(e,o){let i=xp(e),u=Qa(o),m=zq(i,u);return l(m)}function Pf(e,o,i){return ut([e,o])?Et(ZT(e,o),{},i):zm(e,o,i)}function eR(e,o,i,u,m){let p=he(e,o,i),f=he(e,o,u);return Pf(p,f,m)}function Vm(e,o={}){return ke("Parameters",[e],o)}function tR(e,o={}){return Cf(e,o)}function Vq(e){let o=en(e)?e.parameters:[],i=xi({},gr([],[]),o);return Ur(i)}function Cf(e,o){return ut([e])?Et(Vq(e),{},o):Vm(e,o)}function rR(e,o,i,u){let m=he(e,o,i);return Cf(m,u)}function Jm(e,o={}){return ke("Partial",[e],o)}function nR(e,o={}){return $f(e,o)}function oR(e,o){let i=As(e,o),u=Ps(i);return Ss(gn(e,{[o]:u}),o)}function sR(e,o,i){let u=es(e,o,i);return Ps(u)}function iR(e){let o=Cr(e);return Ps(o)}function aR(e){let o=e.map((i)=>Ps(i));return g(o)}function uR(e){let o=Se(e).reduce((u,m)=>({...u,[m]:ra(e[m])}),{});return l(o)}function Ps(e){return Xt(e)?oR(e.$defs,e.$ref):qr(e)?sR(e.if,e.then,e.else):Ge(e)?iR(e.allOf):be(e)?aR(e.anyOf):He(e)?uR(e.properties):l({})}function $f(e,o){return ut([e])?Et(Ps(e),{},o):Jm(e,o)}function cR(e,o,i,u){let m=he(e,o,i);return $f(m,u)}function Qm(e,o,i={}){return ke("Pick",[e,o],i)}function mR(e,o,i={}){let u=Fe(o)?za(o):o;return vf(e,u,i)}function Jq(e,o){return Se(e).reduce((u,m)=>o.includes(m)?gn(u,{[m]:e[m]}):u,{})}function pR(e,o){let i=xp(e),u=Qa(o),m=Jq(i,u);return l(m)}function vf(e,o,i){return ut([e,o])?Et(pR(e,o),{},i):Qm(e,o,i)}function lR(e,o,i,u,m){let p=he(e,o,i),f=he(e,o,u);return vf(p,f,m)}function Xm(e,o={}){return ke("ReadonlyObject",[e],o)}function Mf(e,o={}){return Of(e,o)}var dR=Mf;function fR(e){return Na(H(e))}function hR(e,o){let i=As(e,o),u=Cs(i);return Ss(gn(e,{[o]:u}),o)}function gR(e,o,i){let u=es(e,o,i);return Cs(u)}function yR(e){let o=Cr(e);return Cs(o)}function xR(e){let o=Se(e).reduce((u,m)=>({...u,[m]:ia(e[m])}),{});return l(o)}function IR(e){return Na(Ur(e))}function bR(e){let o=e.map((i)=>Cs(i));return g(o)}function Cs(e){return St(e)?fR(e.items):Xt(e)?hR(e.$defs,e.$ref):qr(e)?gR(e.if,e.then,e.else):Ge(e)?yR(e.allOf):He(e)?xR(e.properties):ct(e)?IR(e.items):be(e)?bR(e.anyOf):e}function Of(e,o){return ut([e])?Et(Cs(e),{},o):Xm(e)}function ER(e,o,i,u){let m=he(e,o,i);return Of(m,u)}function SR(e,o,i,u){return o.visited.includes(u)?i:(u in e)?he(e,gr(o.callstack,[...o.visited,u]),e[u]):i}function wR(e,o){let i=As(e,o),u=$s(i);return Ss(gn(e,{[o]:u}),o)}function TR(e,o,i){let u=es(e,o,i);return $s(u)}function RR(e){let o=Cr(e);return $s(o)}function kR(e){let o=e.map((i)=>$s(i));return g(o)}function AR(e){let o=Se(e).reduce((u,m)=>({...u,[m]:Cm(e[m])}),{});return l(o)}function $s(e){return Xt(e)?wR(e.$defs,e.$ref):qr(e)?TR(e.if,e.then,e.else):Ge(e)?RR(e.allOf):be(e)?kR(e.anyOf):He(e)?AR(e.properties):l({})}function Ym(e,o={}){return ke("Required",[e],o)}function PR(e,o={}){return _f(e,o)}function _f(e,o){return ut([e])?Et($s(e),{},o):Ym(e,o)}function CR(e,o,i,u){let m=he(e,o,i);return _f(m,u)}function Zm(e,o={}){return ke("ReturnType",[e],o)}function $R(e,o={}){return Lf(e,o)}function Qq(e){return en(e)?e.returnType:Vt()}function Lf(e,o){return ut([e])?Et(Qq(e),{},o):Zm(e,o)}function vR(e,o,i,u={}){let m=he(e,o,i);return Lf(m,u)}function ep(e,o){return ke("With",[e,o],{})}function Ip(e,o){return Nf(e,o)}function Nf(e,o){return ut([e])?Et(e,{},o):ep(e,o)}function MR(e,o,i,u){let m=he(e,o,i);return Nf(m,u)}function Xq(e){return fi(e)?ct(e.items)?Df(e.items.items):an(e.items)?[e]:Ft(e.items)?[e]:[Vt()]:[e]}function Df(e){return e.reduce((i,u)=>[...i,...Xq(u)],[])}function gr(e,o){return{callstack:e,visited:o}}function ut(e){return xt(e,(o,i)=>Ft(o)?!1:ut(i),()=>!0)}function Zu(e,o,i){return Se(i).reduce((u,m)=>({...u,[m]:he(e,o,i[m])}),{})}function xi(e,o,i){let u=So(e,o,i);return Df(u)}function So(e,o,i){return i.map((u)=>he(e,o,u))}function Yq(e,o){let i=ln(e)?Ou(o,{}):o,u=aa(e)?Mu(i,{}):i;return sa(e)?uc(u,{}):u}function Zq(e,o,i,u,m){return M(i,"AddImmutable")?OR(e,o,u[0],m):M(i,"RemoveImmutable")?Bw(e,o,u[0],m):M(i,"AddReadonly")?ix(e,o,u[0],m):M(i,"RemoveReadonly")?Zx(e,o,u[0],m):M(i,"AddOptional")?ax(e,o,u[0],m):M(i,"RemoveOptional")?rI(e,o,u[0],m):M(i,"Capitalize")?Xw(e,o,u[0],m):M(i,"Conditional")?rT(e,o,u[0],u[1],u[2],u[3],m):M(i,"ConstructorParameters")?oT(e,o,u[0],m):M(i,"Evaluate")?vw(e,o,u[0],m):M(i,"Exclude")?iT(e,o,u[0],u[1],m):M(i,"Extract")?mT(e,o,u[0],u[1],m):M(i,"Index")?LT(e,o,u[0],u[1],m):M(i,"InstanceType")?DT(e,o,u[0],m):M(i,"Interface")?bw(e,o,u[0],u[1],m):M(i,"KeyOf")?HT(e,o,u[0],m):M(i,"Lowercase")?Yw(e,o,u[0],m):M(i,"Mapped")?JT(e,o,u[0],u[1],u[2],u[3],m):M(i,"Module")?yp(e,o,u[0],m):M(i,"NonNullable")?XT(e,o,u[0],m):M(i,"Pick")?lR(e,o,u[0],u[1],m):M(i,"Parameters")?rR(e,o,u[0],m):M(i,"Partial")?cR(e,o,u[0],m):M(i,"Omit")?eR(e,o,u[0],u[1],m):M(i,"ReadonlyObject")?ER(e,o,u[0],m):M(i,"Record")?II(e,o,u[0],u[1],m):M(i,"Required")?CR(e,o,u[0],m):M(i,"ReturnType")?vR(e,o,u[0],m):M(i,"TemplateLiteral")?jS(e,o,u[0],m):M(i,"Uncapitalize")?Zw(e,o,u[0],m):M(i,"Uppercase")?eT(e,o,u[0],m):M(i,"With")?MR(e,o,u[0],u[1]):ke(i,u,m)}function eF(e,o,i){let u=Ft(i)?SR(e,o,i,i.$ref):St(i)?H(he(e,o,i.items),Ma(i)):Wa(i)?hp(e,o,i.target,i.arguments):zr(i)?Is(So(e,o,i.parameters),he(e,o,i.instanceType),ux(i)):en(i)?bs(So(e,o,i.parameters),he(e,o,i.returnType),cx(i)):qr(i)?na(he(e,o,i.if),he(e,o,i.then),he(e,o,i.else),dx(i)):Ge(i)?Mn(So(e,o,i.allOf),xx(i)):He(i)?l(Zu(e,o,i.properties),lx(i)):Kt(i)?bI(xn(i),he(e,o,or(i))):fi(i)?ma(he(e,o,i.items)):ct(i)?Ur(xi(e,o,i.items),Yx(i)):be(i)?g(So(e,o,i.anyOf),Bx(i)):i;return Yq(i,u)}function he(e,o,i){return ai(i)?Zq(e,o,i.action,i.parameters,i.options):eF(e,o,i)}function Mo(e,o){return he(e,gr([],[]),o)}function tF(e){return Et(e,{"~immutable":!0},{})}function uc(e,o){return Et(tF(e),{},o)}function OR(e,o,i,u){let m=he(e,o,i);return uc(m,u)}function NE(e,o={}){return ke("AddImmutable",[e],o)}function Na(e,o={}){return uc(e,o)}function DE(e,o={}){return ke("Evaluate",[e],o)}function Pn(e,o={}){return pf(e,o)}function qE(e,o={}){return ke("Module",[e],o)}function _R(e,o={}){return yp({},gr([],[]),e,o)}function rF(e,o){let i=qa(e,o);return M(i,Uu)?1:M(i,nc)?1:0}function LR(e,o,i=[]){return xt(o,(u,m)=>M(rF(e,u),1)?LR(e,m,[...i,u]):[...i,e,...o],()=>[...i,e])}function NR(e,o=[]){return xt(e,(i,u)=>NR(u,LR(i,o)),()=>o)}function DR(e){return NR(e)}function qR(...e){let[o,i,u]=kn(e,{2:(f,h)=>lt(f)?[{},f,h]:[f,h,{}],3:(f,h,x)=>[f,h,x],1:(f)=>[{},f,{}]}),m=LS(i),p=Fe(m)&&M(m.length,2)?he(o,gr([],[]),m[0]):Vt();return Et(p,{},u)}function y(e,o){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let u=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:u}},resolve:async({ctx:i,credential:u,signal:m})=>{if(m.throwIfAborted(),u?.key)return{auth:{apiKey:u.key},env:u.env,source:"stored credential"};for(let p of o){let f=await i.env(p);if(m.throwIfAborted(),f)return{auth:{apiKey:f},source:p}}return}}}function de(e){let o,i=()=>(o??=e.load(),o);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(u,m)=>(await i()).login(u,m),refresh:async(u,m)=>(await i()).refresh(u,m),toAuth:async(u)=>(await i()).toAuth(u)}}var BR="faux",GR="faux",KR="faux-1",nF="Faux Model",oF="http://localhost:0",sF=3,FR=5,Sp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function qn(e){return{type:"text",text:e}}function jo(e){return{type:"thinking",thinking:e}}function iF(e,o,i={}){return{type:"toolCall",id:i.id??jf("tool"),name:e,arguments:o}}function aF(e){if(typeof e==="string")return[qn(e)];return Array.isArray(e)?e:[e]}function Vo(e,o={}){return{role:"assistant",content:aF(e),api:BR,provider:GR,model:KR,usage:Sp,stopReason:o.stopReason??"stop",...o.deferred===void 0?{}:{deferred:o.deferred},...o.errorMessage===void 0?{}:{errorMessage:o.errorMessage},...o.responseId===void 0?{}:{responseId:o.responseId},timestamp:o.timestamp??Date.now()}}function HR(e){return Math.ceil(e.length/4)}function jf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function WR(e){if(typeof e==="string")return e;return e.map((o)=>{if(o.type==="text")return o.text;return`[image:${o.mimeType}:${o.data.length}]`}).join(`
25
+ `)}function zR(e){return e.map((o)=>{if(o.type==="text")return o.text;if(o.type==="thinking")return o.thinking;return`${o.name}:${JSON.stringify(o.arguments)}`}).join(`
26
+ `)}function uF(e){return[e.toolName,...e.content.map((o)=>WR([o]))].join(`
27
+ `)}function cF(e){if(e.role==="system")return[W(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
28
+ `);if(e.role==="user")return WR(e.content);if(e.role==="assistant")return zR(e.content);return uF(e)}function VR(e,o=e.length){let i=o>0?(o-1)*2:0;for(let u=0;u<o;u++)i+=e[u].length;return i}function mF(e,o){let i=0;while(i<e.length&&i<o.length&&e[i]===o[i])i++;let u=(m)=>i===m.length?"":(i>0?`
29
+
30
+ `:"")+m.slice(i).join(`
31
+
32
+ `);return VR(e,i)+pF(u(e),u(o))}function pF(e,o){let i=Math.min(e.length,o.length),u=0;while(u<i&&e[u]===o[u])u++;return u}function jR(e,o,i,u){let m=o.messages.map((k)=>`${k.role}:${cF(k)}`),p=VR(m),f=Math.ceil(p/4),h=HR(zR(e.content)),x=f,I=0,S=0,R=i?.sessionId;if(R&&i?.cacheRetention!=="none"){let k=u.get(R);if(k){let A=mF(k,m);I=Math.ceil(A/4),S=Math.ceil((p-A)/4),x=Math.max(0,f-I)}else S=f;u.set(R,m)}return{...e,usage:{input:x,output:h,cacheRead:I,cacheWrite:S,totalTokens:x+h+I+S,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function qf(e,o,i){let u=[],m=0;while(m<e.length){let p=o+Math.floor(Math.random()*(i-o+1)),f=Math.max(1,p*4);u.push(e.slice(m,m+f)),m+=f}return u.length>0?u:[""]}function lF(e,o,i,u){let m=structuredClone(e);return{...m,api:o,provider:i,model:u,timestamp:m.timestamp??Date.now(),usage:m.usage??Sp}}function UR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:Sp,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function bp(e,o,i,u){return{role:"assistant",content:[],api:o,provider:i,model:u,usage:Sp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function cc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Ff(e,o){if(!o||o<=0)return new Promise((u)=>queueMicrotask(u));let i=HR(e)/o*1000;return new Promise((u)=>setTimeout(u,i))}async function Ep(e,o,i,u,m,p){let f={...o,content:[],stopReason:"pending"};if(p?.aborted){let h=cc(f);e.push({type:"error",reason:"aborted",error:h}),e.end(h);return}e.push({type:"start",partial:{...f}});for(let h=0;h<o.content.length;h++){if(p?.aborted){let I=cc(f);e.push({type:"error",reason:"aborted",error:I}),e.end(I);return}let x=o.content[h];if(x.type==="thinking"){f.content=[...f.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:h,partial:{...f}});for(let I of qf(x.thinking,i,u)){if(await Ff(I,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}f.content[h].thinking+=I,e.push({type:"thinking_delta",contentIndex:h,delta:I,partial:{...f}})}e.push({type:"thinking_end",contentIndex:h,content:x.thinking,partial:{...f}});continue}if(x.type==="text"){f.content=[...f.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:h,partial:{...f}});for(let I of qf(x.text,i,u)){if(await Ff(I,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}f.content[h].text+=I,e.push({type:"text_delta",contentIndex:h,delta:I,partial:{...f}})}e.push({type:"text_end",contentIndex:h,content:x.text,partial:{...f}});continue}f.content=[...f.content,{type:"toolCall",id:x.id,name:x.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:h,partial:{...f}});for(let I of qf(JSON.stringify(x.arguments),i,u)){if(await Ff(I,m),p?.aborted){let S=cc(f);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}e.push({type:"toolcall_delta",contentIndex:h,delta:I,partial:{...f}})}f.content[h].arguments=x.arguments,e.push({type:"toolcall_end",contentIndex:h,toolCall:x,partial:{...f}})}if(o.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(o.stopReason==="error"||o.stopReason==="aborted"){e.push({type:"error",reason:o.stopReason,error:o}),e.end(o);return}e.push({type:"done",reason:o.stopReason,message:o}),e.end(o)}function JR(e){let o=e.api??jf(BR),i=e.provider??GR,u=Math.max(1,Math.min(e.tokenSize?.min??sF,e.tokenSize?.max??FR)),m=Math.max(u,e.tokenSize?.max??FR),p=[],f=e.tokensPerSecond,h={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},x=new Map,I=new Map,R=((e.models?.length)?e.models:[{id:KR,name:nF,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((z)=>({id:z.id,name:z.name??z.id,api:o,provider:i,baseUrl:oF,reasoning:z.reasoning??!1,input:z.input??["text","image"],inputLimits:z.inputLimits,cost:z.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:z.contextWindow??128000,maxTokens:z.maxTokens??16384})),k=async(z,J,Z,re)=>{let U=typeof z==="function"?await z(J,Z,h,re):z;return jR(lF(U,o,i,re.id),J,Z,x)},A=(z,J,Z)=>{let re=ao(),U=p.shift();return h.callCount++,queueMicrotask(async()=>{try{if(await Z?.onResponse?.({status:200,headers:{}},z),!U){let fe=bp(Error("No more faux responses queued"),o,i,z.id);fe=jR(fe,J,Z,x),re.push({type:"error",reason:"error",error:fe}),re.end(fe);return}if(Z?.deferred){let fe={provider:z.provider,modelId:z.id,api:z.api,id:jf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};I.set(fe.id,{handle:fe,step:U,context:J,options:Z,model:z,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await Ep(re,UR(z,fe),u,m,f,Z.signal);return}let ne=await k(U,J,Z,z);await Ep(re,ne,u,m,f,Z?.signal)}catch(ne){let fe=bp(ne,o,i,z.id);re.push({type:"error",reason:"error",error:fe}),re.end(fe)}}),re},v=(z,J,Z)=>A(z,J,Z),_=(z,J,Z)=>{let re=ao();return h.deferredFetchCount++,queueMicrotask(async()=>{try{await Z?.onResponse?.({status:200,headers:{}},z);let U=I.get(J.id);if(!U||U.handle.provider!==J.provider||U.handle.modelId!==J.modelId||U.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(U.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(U.pendingFetches>0){U.pendingFetches--,await Ep(re,UR(z,U.handle),u,m,f,Z?.signal);return}if(!U.final){let{deferred:ne,signal:fe,onResponse:Re,...Ee}=U.options??{};try{U.final=await k(U.step,U.context,Ee,U.model)}catch(ee){U.final=bp(ee,o,i,U.model.id)}}await Ep(re,U.final,u,m,f,Z?.signal)}catch(U){let ne=bp(U,o,i,z.id);re.push({type:"error",reason:"error",error:ne}),re.end(ne)}}),re},Q=async(z,J,Z)=>{h.cancelledDeferred.push(structuredClone(J));let re=I.get(J.id);if(re)re.cancelled=!0;await Z?.onResponse?.({status:200,headers:{}},z)};function L(z){if(!z)return R[0];return R.find((J)=>J.id===z)}return{api:o,provider:i,models:R,stream:A,streamSimple:v,fetchDeferred:_,cancelDeferred:Q,getModel:L,state:h,setResponses(z){p=[...z]},appendResponses(z){p.push(...z)},getPendingResponseCount(){return p.length}}}function Ko(e={}){let o=JR(e);return{provider:d({id:o.provider,auth:{apiKey:{name:"Faux",resolve:async()=>({auth:{}})}},models:o.models,api:{stream:o.stream,streamSimple:o.streamSimple,fetchDeferred:o.fetchDeferred,cancelDeferred:o.cancelDeferred}}),api:o.api,models:o.models,getModel:o.getModel,state:o.state,setResponses:o.setResponses,appendResponses:o.appendResponses,getPendingResponseCount:o.getPendingResponseCount}}function dF(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function fF(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function hF(e){return{type:"toolCall",id:e.id,name:e.name,arguments:structuredClone(e.arguments),...e.thoughtSignature===void 0?{}:{thoughtSignature:e.thoughtSignature},...e.namespace===void 0?{}:{namespace:e.namespace}}}function gF(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function mc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Xa(e){mc(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function Bf(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var yF=Bf(G(""));function Gf(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,m)=>Gf(u,o[m]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let i=o;return Object.entries(e).every(([u,m])=>Object.hasOwn(i,u)&&Gf(m,i[u]))}class QR{started=!1;terminal=!1;blocks=new Map;encode(e){if(this.terminal)throw Error(`Assistant message event ${e.type} follows a terminal event`);switch(e.type){case"start":if(this.started)throw Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:gF(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=Xa(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:dF(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Xa(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=Xa(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:fF(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Xa(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=Xa(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let i=Bf(o.arguments),u=i===yF;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:hF(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let i=G(o.catchupJson);if(Bf(i)!==o.snapshotArguments){let m=G(o.snapshotArguments);if(!Gf(m,i))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=Xa(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(mc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){mc(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(i.kind!==o)throw Error(`Assistant message block ${e} is ${i.kind}, not ${o}`);return i}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,i){let u=this.block(e,i);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let m=u.deltaChars;u.deltaChars+=o.length;let p=Math.max(0,u.coveredChars-m);if(p>=o.length)return;let f=p===0?o:o.slice(p);return i==="text"?{type:"text_delta",contentIndex:e,delta:f}:{type:"thinking_delta",contentIndex:e,delta:f}}}function Uf(e,o,i,u,m){if(mc(i),i!==e.content.length){let p=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${p}`)}e.content.push(structuredClone(u)),o.set(i,m)}function fa(e,o,i,u,m){mc(i);let p=o.get(i),f=e.content[i];if(!p||!f)throw Error(`${m} frame has no started block at index ${i}`);if(p.kind!==u||f.type!==u)throw Error(`${m} frame expected ${u} block at index ${i}, found ${f.type}`);if(p.ended)throw Error(`${m} frame follows the end of block at index ${i}`);return{block:f,state:p}}function xF(e){let o,i,u=new Map;for(let m of e){if(m.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(i!==void 0)throw Error(`${i} frame appears before the start frame`);o=structuredClone(m.partial);continue}if(!o){i??=m.type;continue}switch(m.type){case"text_start":if(m.content.type!=="text")throw Error(`text_start frame contains ${m.content.type} content`);Uf(o,u,m.contentIndex,m.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:p}=fa(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");p.text+=m.delta;break}case"text_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");if(p.text=m.content,delete p.textSignature,m.textSignature!==void 0)p.textSignature=m.textSignature;f.ended=!0;break}case"thinking_start":if(m.content.type!=="thinking")throw Error(`thinking_start frame contains ${m.content.type} content`);Uf(o,u,m.contentIndex,m.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:p}=fa(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");p.thinking+=m.delta;break}case"thinking_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");if(p.thinking=m.content,delete p.thinkingSignature,delete p.redacted,m.thinkingSignature!==void 0)p.thinkingSignature=m.thinkingSignature;if(m.redacted!==void 0)p.redacted=m.redacted;f.ended=!0;break}case"toolcall_start":if(m.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${m.toolCall.type} content`);Uf(o,u,m.contentIndex,m.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");f.json=m.json,p.arguments=G(m.json);break}case"toolcall_delta":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call frame state");f.json+=m.delta;break}case"toolcall_end":{let{block:p,state:f}=fa(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(p.id=m.id,p.name=m.name,p.arguments=structuredClone(m.arguments),delete p.thoughtSignature,delete p.namespace,m.thoughtSignature!==void 0)p.thoughtSignature=m.thoughtSignature;if(m.namespace!==void 0)p.namespace=m.namespace;f.ended=!0;break}}}if(!o)return;for(let[m,p]of u){if(p.kind!=="toolCall"||p.ended||p.json.length===0)continue;let f=o.content[m];if(f?.type!=="toolCall")throw Error("Unreachable tool-call frame state");f.arguments=G(p.json)}return o}var XR=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],IF=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,bF=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ha(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!bF.some((u)=>u.test(e.errorMessage))){if(XR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&IF.test(e.errorMessage))return!0}}if(o&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>o)return!0}if(o&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=o*0.99)return!0}return!1}function EF(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function SF(){return[...XR]}function YR(e){return new RegExp(e.join("|"),"i")}var wF=YR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),TF=YR(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),ZR=60000;function ek(e,o){let i=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(i)?i:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??ZR)}class wp extends Error{constructor(){super("Aborted")}}function RF(e,o){return new Promise((i,u)=>{if(o?.aborted){u(new wp);return}let m=setTimeout(i,e);o?.addEventListener("abort",()=>{clearTimeout(m),u(new wp)},{once:!0})})}async function kF(e,o,i,u){let m=o?.enabled?o.maxRetries:0,p=0,f;for(;;){let h=await e();if(h.stopReason==="aborted"){if(f)await u?.onRetryFinished?.(!1,f.attempt);return h}if(h.stopReason!=="error"){if(f)await u?.onRetryFinished?.(!0,f.attempt);return h}if(p>=m||!tk(h)){if(f)await u?.onRetryFinished?.(!1,f.attempt,h.errorMessage);return h}p++,f={attempt:p,errorMessage:h.errorMessage||"Unknown error"};let x=ek(o,p);await u?.onRetryScheduled?.(p,m,x,f.errorMessage);try{await RF(x,i)}catch(I){if(await u?.onRetryFinished?.(!1,p,f.errorMessage),I instanceof wp){let{errorMessage:S,...R}=h;return{...R,stopReason:"aborted"}}throw I}await u?.onRetryAttemptStart?.()}}function tk(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(wF.test(o))return!1;return TF.test(o)}function AF(e,o){return Jr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function pc(e){return pe(e,"~refine")&&Fe(e["~refine"])&&mn(e["~refine"],0,(o)=>at(o)&&pe(o,"check")&&pe(o,"error")&&gs(o.check)&&gs(o.error))}function In(e){return at(e)&&!Fe(e)}function js(e){return fn(e)}function Ve(e){return In(e)||js(e)}function Ya(e){return pe(e,"additionalItems")&&Ve(e.additionalItems)}function Oo(e){return pe(e,"additionalProperties")&&Ve(e.additionalProperties)}function lc(e){return pe(e,"allOf")&&Fe(e.allOf)&&e.allOf.every((o)=>Ve(o))}function dc(e){return pe(e,"$anchor")&&lt(e.$anchor)}function fc(e){return pe(e,"anyOf")&&Fe(e.anyOf)&&e.anyOf.every((o)=>Ve(o))}function Tp(e){return pe(e,"const")}function vs(e){return pe(e,"contains")&&Ve(e.contains)}function To(e){return pe(e,"default")}function hc(e){return pe(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ve(o)||Fe(o)&&o.every((i)=>lt(i)))}function gc(e){return pe(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Fe(o)&&o.every((i)=>lt(i)))}function Za(e){return pe(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ve(o))}function Us(e){return pe(e,"$dynamicAnchor")&&lt(e.$dynamicAnchor)}function yc(e){return pe(e,"$dynamicRef")&&lt(e.$dynamicRef)}function xc(e){return pe(e,"else")&&Ve(e.else)}function Rp(e){return pe(e,"enum")&&Fe(e.enum)}function Ic(e){return pe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||Dr(e.exclusiveMaximum))}function is(e){return pe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||Dr(e.exclusiveMinimum))}function ga(e){return pe(e,"format")&&lt(e.format)}function Ro(e){return pe(e,"$id")&&lt(e.$id)}function bc(e){return pe(e,"if")&&Ve(e.if)}function Bs(e){return pe(e,"items")&&(Ve(e.items)||Fe(e.items)&&e.items.every((o)=>Ve(o)))}function Ec(e){return Bs(e)&&Fe(e.items)}function Sc(e){return pe(e,"maximum")&&(Ot(e.maximum)||Dr(e.maximum))}function wc(e){return pe(e,"maxContains")&&Ot(e.maxContains)}function eu(e){return pe(e,"maxItems")&&Ot(e.maxItems)}function Tc(e){return pe(e,"maxLength")&&Ot(e.maxLength)}function Rc(e){return pe(e,"maxProperties")&&Ot(e.maxProperties)}function as(e){return pe(e,"minimum")&&(Ot(e.minimum)||Dr(e.minimum))}function Gs(e){return pe(e,"minContains")&&Ot(e.minContains)}function Ii(e){return pe(e,"minItems")&&Ot(e.minItems)}function ya(e){return pe(e,"minLength")&&Ot(e.minLength)}function xa(e){return pe(e,"minProperties")&&Ot(e.minProperties)}function kc(e){return pe(e,"multipleOf")&&(Ot(e.multipleOf)||Dr(e.multipleOf))}function Ac(e){return pe(e,"not")&&Ve(e.not)}function Pc(e){return pe(e,"oneOf")&&Fe(e.oneOf)&&e.oneOf.every((o)=>Ve(o))}function Ia(e){return pe(e,"pattern")&&(lt(e.pattern)||e.pattern instanceof RegExp)}function Ks(e){return pe(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ve(o))}function us(e){return pe(e,"prefixItems")&&Fe(e.prefixItems)&&e.prefixItems.every((o)=>Ve(o))}function Hs(e){return pe(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((o)=>Ve(o))}function tu(e){return pe(e,"propertyNames")&&(at(e.propertyNames)||Ve(e.propertyNames))}function PF(e){return pe(e,"$recursiveAnchor")&&fn(e.$recursiveAnchor)}function Cc(e){return PF(e)&&M(e.$recursiveAnchor,!0)}function $c(e){return pe(e,"$recursiveRef")&&lt(e.$recursiveRef)}function vc(e){return pe(e,"$ref")&&lt(e.$ref)}function cs(e){return pe(e,"required")&&Fe(e.required)&&e.required.every((o)=>lt(o))}function Mc(e){return pe(e,"then")&&Ve(e.then)}function Oc(e){return pe(e,"type")&&(lt(e.type)||Fe(e.type)&&e.type.every((o)=>lt(o)))}function bi(e){return pe(e,"uniqueItems")&&fn(e.uniqueItems)}function Ei(e){return pe(e,"unevaluatedItems")&&Ve(e.unevaluatedItems)}function Si(e){return pe(e,"unevaluatedProperties")&&Ve(e.unevaluatedProperties)}function CF(e){return Ei(e)||Si(e)||Ca(Se(e),(o)=>kp(e[o]))}function $F(e){return Ca(e,(o)=>kp(o))}function kp(e){return Fe(e)?$F(e):at(e)?CF(e):!1}function rk(e,o){return kp(o)||Ca(Se(e),(i)=>kp(e[i]))}class Kf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Er(It("context","Push"),[])}Pop(){return Er(It("context","Pop"),[])}AddIndex(e){return Er(It("context","AddIndex"),[e])}AddKey(e){return Er(It("context","AddKey"),[e])}Merge(e){return Er(It("context","Merge"),[e])}}class Nn{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((i)=>this.GetIndices().add(i)),o.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class Dn extends Nn{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Bo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var Ap={identifier:"External",variables:[]};function _o(e){let o=`External[${Ap.variables.length}]`;return Ap.variables.push(e),o}function nk(){Ap.variables=[]}function ok(){return{...Ap}}function sk(e,o,i,u){let m=_o(i["~refine"].map((p)=>p));return xs(m,Ae(0),["refinement","_"],Er(It("refinement","check"),[u]))}function ik(e,o,i,u){return mn(i["~refine"],0,(m,p)=>m.check(u))}function ak(e,o,i,u,m,p){return $n(m["~refine"],0,(f,h)=>f.check(p)||o.AddError({keyword:"~refine",schemaPath:i,instancePath:u,params:{index:h,message:f.error(p)}}))}var vF=0;function Jt(){return`var_${vF++}`}function Hf(e){return Bs(e)&&Fe(e.items)}function MF(e,o,i,u){let[m,p]=[Jt(),Jt()],f=Qn(e,o,i.additionalItems,m),h=kd(p,Ae(i.items.length)),x=o.AddIndex(p);return xs(u,Ae(0),[m,p],Ir(h,Rn(f,x)))}function OF(e,o,i,u){let[m,p]=[Jt(),Jt()],f=Qn(e,o,i.additionalItems,m),h=kd(p,Ae(i.items.length));return xs(u,Ae(0),[m,p],Ir(h,f))}function uk(e,o,i,u){if(!Hf(i))return Ae(!0);return o.UseUnevaluated()?MF(e,o,i,u):OF(e,o,i,u)}function ck(e,o,i,u){if(!Hf(i))return!0;return mn(u,0,(p,f)=>Pu(f,i.items.length)||ko(e,o,i.additionalItems,p)&&o.AddIndex(f))}function mk(e,o,i,u,m,p){if(!Hf(m))return!0;return mn(p,0,(h,x)=>{let I=`${i}/additionalItems`,S=`${u}/${x}`;return Pu(x,m.items.length)||Ao(e,o,I,S,m.additionalItems,h)&&o.AddIndex(x)})}function ms(e){return new RegExp(e,"u")}function _F(e,o){return!e.UseUnevaluated()&&(M(o,!0)||at(o)&&M(Se(o).length,0))}function LF(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function Wf(e){let o=[];if(Ks(e))o.push(...Se(e.patternProperties));if(Hs(e))o.push(...Se(e.properties).map(LF));return M(o.length,0)?"(?!)":`(${o.join("|")})`}function NF(e,o,i){return cs(o)&&Hs(o)&&!Ks(o)&&M(o.additionalProperties,!1)&&M(Se(o.properties).length,o.required.length)}function DF(e,o,i){return fo(It(Er(It("Object","getOwnPropertyNames"),[i]),"length"),Ae(o.required.length))}function qF(e,o,i,u){let[m,p]=[Jt(),Jt()],f=_o(ms(Wf(i))),h=Qn(e,o,i.additionalProperties,`${u}[${m}]`),x=Er(It(f,"test"),[m]),I=o.AddKey(m),S=o.UseUnevaluated()?Ir(x,Rn(h,I)):Ir(x,h);return xs(Zi(u),Ae(0),[m,p],S)}function pk(e,o,i,u){if(_F(o,i.additionalProperties))return Ae(!0);return NF(o,i,u)?DF(o,i,u):qF(e,o,i,u)}function lk(e,o,i,u){let m=ms(Wf(i));return mn(Se(u),0,(f,h)=>m.test(f)||ko(e,o,i.additionalProperties,u[f])&&o.AddKey(f))}function dk(e,o,i,u,m,p){let f=ms(Wf(m)),h=[];return $n(Se(p),0,(I,S)=>{let R=`${i}/additionalProperties`,k=`${u}/${I}`,A=f.test(I)||Ao(e,o,R,k,m.additionalProperties,p[I])&&o.AddKey(I);if(!A)h.push(I);return A})||o.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:u,params:{additionalProperties:h}})}function wi(e,o,i,u,m){let p=Ds("results","[]"),f=i.map((S,R)=>Ds(`context_${R}`,Ad("CheckContext",[]))),h=i.map((S,R)=>Ds(`condition_${R}`,Er(si(["context"],Lt(e,o,S,u)),[`context_${R}`]))),x=i.map((S,R)=>rx(`condition_${R}`,Er(It("results","push"),[`context_${R}`]))),I=dm(Rn(m,o.Merge("results")));return Er(si([],lm([p,...f,...h,...x,I])),[])}function FF(e,o,i,u){return wi(e,o,i.allOf,u,fo(It("results","length"),Ae(i.allOf.length)))}function jF(e,o,i,u){return vn(i.allOf.map((m)=>Lt(e,o,m,u)))}function fk(e,o,i,u){return o.UseUnevaluated()?FF(e,o,i,u):jF(e,o,i,u)}function hk(e,o,i,u){let m=i.allOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return M(m.length,i.allOf.length)&&o.Merge(m)}function gk(e,o,i,u,m,p){let f=[],h=m.allOf.reduce((I,S,R)=>{let k=`${i}/allOf/${R}`,A=new Dn,v=rr(e,A,k,u,S,p);if(!v)f.push(A);return v?[...I,A]:I},[]),x=M(h.length,m.allOf.length)&&o.Merge(h);if(!x)f.forEach((I)=>I.GetErrors().forEach((S)=>o.AddError(S)));return x}function UF(e,o,i,u){return wi(e,o,i.anyOf,u,Zy(It("results","length"),Ae(0)))}function BF(e,o,i,u){return Pd(i.anyOf.map((m)=>Lt(e,o,m,u)))}function yk(e,o,i,u){return o.UseUnevaluated()?UF(e,o,i,u):BF(e,o,i,u)}function xk(e,o,i,u){let m=i.anyOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return ji(m.length,0)&&o.Merge(m)}function Ik(e,o,i,u,m,p){let f=[],h=m.anyOf.reduce((I,S,R)=>{let k=new Dn,A=`${i}/anyOf/${R}`,v=rr(e,k,A,u,S,p);if(!v)f.push(k);return v?[...I,k]:I},[]),x=ji(h.length,0)&&o.Merge(h);if(!x)f.forEach((I)=>I.GetErrors().forEach((S)=>o.AddError(S)));return x||o.AddError({keyword:"anyOf",schemaPath:i,instancePath:u,params:{}})}function bk(e,o,i,u){return i?Ae(!0):Ae(!1)}function zf(e,o,i,u){return i}function Ek(e,o,i,u,m,p){return zf(e,o,m,p)||o.AddError({keyword:"boolean",schemaPath:i,instancePath:u,params:{}})}function Sk(e,o,i,u){return Ji(i.const)?fo(u,Ae(i.const)):tx(u,_o(i.const))}function Vf(e,o,i,u){return Ji(i.const)?M(u,i.const):$a(u,i.const)}function wk(e,o,i,u,m,p){return Vf(e,o,m,p)||o.AddError({keyword:"const",schemaPath:i,instancePath:u,params:{allowedValue:m.const}})}function Tk(e){return!(Gs(e)&&M(e.minContains,0))}function GF(e,o,i,u){let[m,p]=[Jt(),Jt()],f=Un(fo(It(u,"length"),Ae(0))),h=wO(u,[m,p],Rn(Lt(e,o,i.contains,m),o.AddIndex(p)));return Rn(f,h)}function KF(e,o,i,u){let[m]=[Jt()],p=Un(fo(It(u,"length"),Ae(0))),f=SO(u,[m,"_"],Lt(e,o,i.contains,m));return Rn(p,f)}function Rk(e,o,i,u){if(!Tk(i))return Ae(!0);return o.UseUnevaluated()?GF(e,o,i,u):KF(e,o,i,u)}function Jf(e,o,i,u){if(!Tk(i))return!0;return!M(u.length,0)&&Wy(u,(m,p)=>At(e,o,i.contains,m)&&o.AddIndex(p))}function kk(e,o,i,u,m,p){return Jf(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:1}})}function Ak(e,o,i,u){let m=fo(It(Zi(u),"length"),Ae(0)),p=vn(hn(i.dependencies).map(([f,h])=>{let x=Un(ea(u,Ae(f))),I=Lt(e,o,h,u),S=(R)=>vn(R.map((k)=>ea(u,Ae(k))));return Ir(x,Fe(h)?S(h):I)}));return Ir(m,p)}function Pk(e,o,i,u){let m=M(Se(u).length,0),p=mn(hn(i.dependencies),0,([f,h])=>!pe(u,f)||(Fe(h)?h.every((x)=>pe(u,x)):At(e,o,h,u)));return m||p}function Ck(e,o,i,u,m,p){let f=M(Se(p).length,0),h=$n(hn(m.dependencies),0,([x,I])=>{let S=`${i}/dependencies/${x}`;return!pe(p,x)||(Fe(I)?I.every((R)=>pe(p,R)||o.AddError({keyword:"dependencies",schemaPath:i,instancePath:u,params:{property:x,dependencies:I}})):rr(e,o,S,u,I,p))});return f||h}function $k(e,o,i,u){let m=fo(It(Zi(u),"length"),Ae(0)),p=vn(hn(i.dependentRequired).map(([f,h])=>{let x=Un(ea(u,Ae(f))),I=vn(h.map((S)=>ea(u,Ae(S))));return Ir(x,I)}));return Ir(m,p)}function vk(e,o,i,u){let m=M(Se(u).length,0),p=mn(hn(i.dependentRequired),0,([f,h])=>!pe(u,f)||h.every((x)=>pe(u,x)));return m||p}function Mk(e,o,i,u,m,p){let f=M(Se(p).length,0),h=$n(hn(m.dependentRequired),0,([x,I])=>!pe(p,x)||$n(I,0,(S)=>pe(p,S)||o.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:u,params:{property:x,dependencies:I}})));return f||h}function Ok(e,o,i,u){let m=fo(It(Zi(u),"length"),Ae(0)),p=vn(hn(i.dependentSchemas).map(([f,h])=>{let x=Un(ea(u,Ae(f))),I=Lt(e,o,h,u);return Ir(x,I)}));return Ir(m,p)}function _k(e,o,i,u){let m=M(Se(u).length,0),p=mn(hn(i.dependentSchemas),0,([f,h])=>!pe(u,f)||At(e,o,h,u));return m||p}function Lk(e,o,i,u,m,p){let f=M(Se(p).length,0),h=$n(hn(m.dependentSchemas),0,([x,I])=>{let S=`${i}/dependentSchemas/${x}`;return!pe(p,x)||rr(e,o,S,u,I,p)});return f||h}function Nk(e,o,i,u){let m=e.DynamicRef(i)??!1;return Ws(e,o,m,u)}function Dk(e,o,i,u){let m=e.DynamicRef(i)??!1;return Ve(m)&&At(e,o,m,u)}function qk(e,o,i,u,m,p){let f=e.DynamicRef(m)??!1;return Ve(f)&&rr(e,o,"#",u,f,p)}function Fk(e,o,i,u){return Pd(i.enum.map((m)=>{if(Ji(m))return fo(u,Ae(m));let p=_o(m);return tx(u,p)}))}function Xf(e,o,i,u){return Ca(i.enum,(m)=>Ji(m)?M(u,m):$a(u,m))}function jk(e,o,i,u,m,p){return Xf(e,o,m,p)||o.AddError({keyword:"enum",schemaPath:i,instancePath:u,params:{allowedValues:m.enum}})}function Uk(e,o,i,u){return kd(u,Ae(i.exclusiveMaximum))}function Yf(e,o,i,u){return Pu(u,i.exclusiveMaximum)}function Bk(e,o,i,u,m,p){return Yf(e,o,m,p)||o.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:u,params:{comparison:"<",limit:m.exclusiveMaximum}})}function Gk(e,o,i,u){return Zy(u,Ae(i.exclusiveMinimum))}function Zf(e,o,i,u){return ji(u,i.exclusiveMinimum)}function Kk(e,o,i,u,m,p){return Zf(e,o,m,p)||o.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:u,params:{comparison:">",limit:m.exclusiveMinimum}})}var HF=[0,31,28,31,30,31,30,31,31,30,31,30,31],WF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function zF(e){return e%4===0&&(e%100!==0||e%400===0)}function nu(e){let o=WF.exec(e);if(!o)return!1;let i=+o[1],u=+o[2],m=+o[3];return u>=1&&u<=12&&m>=1&&m<=(u===2&&zF(i)?29:HF[u])}var VF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function ou(e,o=!0){let i=VF.exec(e);if(!i)return!1;if(o&&!i[4]&&!i[5])return!1;let u=+i[1],m=+i[2],p=+i[3];if(u>23||m>59||p>60)return!1;if(i[5]){let S=+i[6],R=+i[7];if(S>23||R>59)return!1}if(p<60)return!0;let f=i[5]==="-"?-1:1,h=+(i[6]||0),x=+(i[7]||0);return((u*60+m-f*(h*60+x))%1440+1440)%1440===1439}function Pp(e){let o=e.split(/T/i);return o.length===2&&nu(o[0])&&ou(o[1])}var JF=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Cp(e){return JF.test(e)}var QF=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function $p(e){return QF.test(e)}var Hk=/^(?!-).*(?<!-)$/,Wk=/^(?!..--)/,zk=/^[a-zA-Z0-9-]*$/;var su=/[^\p{ASCII}]/u;var XF=/[0-9]/,Vk=/[\u{0660}-\u{0669}]/u,YF=/[\u{06f0}-\u{06f9}]/u,ZF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,e1=/[\u{002d}\u{002b}]/u,eh=/\p{Mn}/u,t1=/\p{Mc}/u;var Jk=/[\p{Mn}\p{Mc}\p{Me}]/u,th=/\p{L}/u,r1=/\p{Nd}/u,Qk=/\p{Script=Greek}/u,vp=/\p{Script=Hebrew}/u,Xk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Yk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,rh=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,Zk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,n1=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,o1=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,eA=new RegExp([XF,YF].map((e)=>e.source).join("|"),"u"),tA=new RegExp([th,e1,ZF,r1,eh,t1,n1,o1].map((e)=>e.source).join("|"),"u");function rA(e){return Hk.test(e)&&Wk.test(e)&&zk.test(e)}var ps=36,Lc=1,Nc=26,i1=38,a1=700,oA=72,sA=128;function nh(){throw null}function Mp(e){return e.toLowerCase().startsWith("xn--")}function iA(e,o,i){e=i?Math.floor(e/a1):e>>1,e+=Math.floor(e/o);let u=0;while(e>(ps-Lc)*Nc>>1)e=Math.floor(e/(ps-Lc)),u+=ps;return u+Math.floor((ps-Lc+1)*e/(e+i1))}function Op(e){let o=[],i=sA,u=0,m=oA,p=e.lastIndexOf("-");if(p>0)for(let h=0;h<p;h++){let x=e.charCodeAt(h);if(x>=128)nh();o.push(x)}let f=p<0?0:p+1;while(f<e.length){let h=u,x=1,I=ps;while(!0){if(f>=e.length)nh();let R=e.charCodeAt(f++),k;if(R>=97&&R<=122)k=R-97;else if(R>=48&&R<=57)k=R-48+26;else nh();u+=k*x;let A=I<=m?Lc:I>=m+Nc?Nc:I-m;if(k<A)break;x*=ps-A,I+=ps}let S=o.length+1;m=iA(u-h,S,h===0),i+=Math.floor(u/S),u%=S,o.splice(u,0,i),u++}return String.fromCodePoint(...o)}function nA(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var u1=new RegExp(su.source,"gu");function aA(e){let o=e.replace(u1,""),i=o.length,u=i>0?[o,"-"]:[],m=Array.from(e,(I)=>I.codePointAt(0)),p=sA,f=0,h=oA,x=i;while(x<m.length){let I=1/0;for(let S of m)if(S>=p&&S<I)I=S;f+=(I-p)*(x+1),p=I;for(let S of m){if(S<p)f++;if(S===p){let R=f;for(let k=ps;;k+=ps){let A=k<=h?Lc:k>=h+Nc?Nc:k-h;if(R<A)break;let v=A+(R-A)%(ps-A);u.push(nA(v)),R=Math.floor((R-A)/(ps-A))}u.push(nA(R)),h=iA(f,x+1,x===i),f=0,x++}}f++,p++}return u.join("")}var c1=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,uA=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,m1=/^(?:R|AL|AN)$/;function cA(e){if(Mp(e))try{return _p(Op(e.slice(4).toLowerCase()))}catch{return!1}return _p(e)}function mA(e){let o=String.fromCodePoint(e);return eA.test(o)?"EN":Vk.test(o)?"AN":eh.test(o)?"NSM":vp.test(o)?"R":Yk.test(o)?"AL":th.test(o)?"L":"ON"}function _p(e){for(let o of e)if(m1.test(mA(o.codePointAt(0))))return!0;return!1}function Lp(e){let o=!1,i=uA,u=!1,m=!1,p=!0;for(let f of e){let h=mA(f.codePointAt(0));if(p){if(h!=="L"&&h!=="R"&&h!=="AL")return!1;o=h==="R"||h==="AL",i=o?c1:uA,p=!1}if(!i.test(h))return!1;if(h==="EN")u=!0;else if(h==="AN")m=!0}if(o&&u&&m)return!1;return!0}function p1(e){return su.test(e)&&aA(e).length+4>63}function l1(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Np(e){if(p1(e))return!1;if(_p(e)&&!Lp(e))return!1;let o=[...e],i=o.map((p)=>p.codePointAt(0)),u=i.length;if(l1(o))return!1;if(Jk.test(o[0]))return!1;let m=!1;for(let p=0;p<u;p++){let f=i[p],h=o[p];if(Zk.test(h))return!1;if(!tA.test(h))return!1;if(Xk.test(h))m=!0;let x=i[p-1],I=i[p+1];switch(f){case 183:if(x!==108||I!==108)return!1;break;case 885:if(!I||!Qk.test(o[p+1]))return!1;break;case 1523:case 1524:if(!x||!vp.test(o[p-1]))return!1;break;case 8204:if(!x||x<128&&!rh.test(o[p-1]))return!1;break;case 8205:if(!x||!rh.test(o[p-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!m)return!1;return!0}function Dp(e){if(!Mp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let i=Op(o);if(!su.test(i))return!1;return Np(i)}catch{return!1}}function d1(e){return e.length>0&&e.length<=63}function f1(e){return d1(e)&&(Dp(e)||rA(e))}function fA(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>f1(o))}function h1(e){return e.length>0&&e.length<=63}function g1(e){return h1(e)&&(Dp(e)||Np(e))}function y1(e){return e.replace(/[\uff01-\uff5e]/g,(o)=>String.fromCharCode(o.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function hA(e){if(e.length===0||e.includes(" "))return!1;let o=y1(e);if(o.length>253)return!1;let i=o.split("."),u=i.some((m)=>cA(m));return i.every((m)=>g1(m)&&(!u||Lp(m)))}function qp(e){return fA(e)}var x1=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Fp(e){return x1.test(e.normalize("NFC"))}function jp(e){return hA(e)}var I1=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Up(e){return I1.test(e)}var b1=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function Bp(e){return b1.test(e)}var E1=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,S1=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Gp(e){return!E1.test(e)&&!S1.test(e)&&URL.canParse(e,"http://example.com")}var w1=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,T1=/[\x00-\x20<>\^`{|}\\]/,R1=/%(?![0-9a-fA-F]{2})/;function k1(e){return e.length<2048?e.replace(w1,"[::1]"):e}function Kp(e){if(T1.test(e))return!1;if(R1.test(e))return!1;return URL.canParse(k1(e))}var A1=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function Hp(e){return A1.test(e)}var P1=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Wp(e){return P1.test(e)}function zp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var C1=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Vp(e){return C1.test(e)}var $1=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Jp(e){return $1.test(e)}var v1=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Qp(e){return v1.test(e)}var M1=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Xp(e){return M1.test(e)}function Yp(e){return URL.canParse(e)}var O1=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Zp(e){return O1.test(e)}var wr=new Map;function yA(){wr.clear()}function _1(){return[...wr.entries()]}function L1(e,o){wr.set(e,o)}function N1(e){return wr.has(e)}function D1(e){return wr.get(e)}function xA(e,o){return wr.get(e)?.(o)??!0}function IA(){yA(),wr.set("date-time",Pp),wr.set("date",nu),wr.set("duration",Cp),wr.set("email",$p),wr.set("hostname",qp),wr.set("idn-email",Fp),wr.set("idn-hostname",jp),wr.set("ipv4",Up),wr.set("ipv6",Bp),wr.set("iri-reference",Gp),wr.set("iri",Kp),wr.set("json-pointer-uri-fragment",Hp),wr.set("json-pointer",Wp),wr.set("regex",zp),wr.set("relative-json-pointer",Vp),wr.set("time",ou),wr.set("uri-reference",Jp),wr.set("uri-template",Qp),wr.set("uri",Xp),wr.set("url",Yp),wr.set("uuid",Zp)}IA();function bA(e,o,i,u){return Er(It("Format","Test"),[Ae(i.format),u])}function sh(e,o,i,u){return xA(i.format,u)}function EA(e,o,i,u,m,p){return sh(e,o,m,p)||o.AddError({keyword:"format",schemaPath:i,instancePath:u,params:{format:m.format}})}function SA(e,o,i,u){let m=Mc(i)?i.then:!0,p=xc(i)?i.else:!0;return RO(Lt(e,o,i.if,u),Lt(e,o,m,u),Lt(e,o,p,u))}function wA(e,o,i,u){let m=Mc(i)?i.then:!0,p=xc(i)?i.else:!0;return At(e,o,i.if,u)?At(e,o,m,u):At(e,o,p,u)}function TA(e,o,i,u,m,p){let f=Mc(m)?m.then:!0,h=xc(m)?m.else:!0,x=new Dn,I=rr(e,x,`${i}/if`,u,m.if,p)?rr(e,x,`${i}/then`,u,f,p)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"then"}}):rr(e,o,`${i}/else`,u,h,p)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"else"}});if(I)o.Merge([x]);return I}function q1(e,o,i,u){return vn(i.items.map((m,p)=>{let f=Xi(It(u,"length"),Ae(p)),h=Qn(e,o,m,`${u}[${p}]`),x=o.AddIndex(Ae(p));return Ir(f,Rn(h,x))}))}function F1(e,o,i,u){return vn(i.items.map((m,p)=>{let f=Xi(It(u,"length"),Ae(p)),h=Qn(e,o,m,`${u}[${p}]`);return Ir(f,h)}))}function j1(e,o,i,u){return o.UseUnevaluated()?q1(e,o,i,u):F1(e,o,i,u)}function U1(e,o,i,u){return mn(i.items,0,(m,p)=>ys(u.length,p)||ko(e,o,m,u[p])&&o.AddIndex(p))}function B1(e,o,i,u,m,p){return $n(m.items,0,(f,h)=>{let x=`${i}/items/${h}`,I=`${u}/${h}`;return ys(p.length,h)||Ao(e,o,x,I,f,p[h])&&o.AddIndex(h)})}function G1(e,o,i,u){let m=us(i)?i.prefixItems.length:0,p=Qn(e,o,i.items,"element"),f=o.AddIndex("index");return xs(u,Ae(m),["element","index"],Rn(p,f))}function K1(e,o,i,u){let m=us(i)?i.prefixItems.length:0,p=Qn(e,o,i.items,"element");return xs(u,Ae(m),["element","index"],p)}function H1(e,o,i,u){return o.UseUnevaluated()?G1(e,o,i,u):K1(e,o,i,u)}function W1(e,o,i,u){let m=us(i)?i.prefixItems.length:0;return mn(u,m,(p,f)=>ko(e,o,i.items,p)&&o.AddIndex(f))}function z1(e,o,i,u,m,p){let f=us(m)?m.prefixItems.length:0;return $n(p,f,(h,x)=>{let I=`${i}/items`,S=`${u}/${x}`;return Ao(e,o,I,S,m.items,h)&&o.AddIndex(x)})}function RA(e,o,i,u){return Ec(i)?j1(e,o,i,u):H1(e,o,i,u)}function kA(e,o,i,u){return Ec(i)?U1(e,o,i,u):W1(e,o,i,u)}function AA(e,o,i,u,m,p){return Ec(m)?B1(e,o,i,u,m,p):z1(e,o,i,u,m,p)}function PA(e){return vs(e)}function CA(e,o,i,u){if(!PA(i))return Ae(!0);let[m]=[Jt()],p=pm(u,[m,"_"],Lt(e,o,i.contains,m));return Xi(p,Ae(i.maxContains))}function ih(e,o,i,u){if(!PA(i))return!0;let m=Sd(u,(p)=>At(e,o,i.contains,p));return ys(m,i.maxContains)}function $A(e,o,i,u,m,p){let f=Gs(m)?m.minContains:1;return ih(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:f,maxContains:m.maxContains}})}function vA(e,o,i,u){return Xi(u,Ae(i.maximum))}function ah(e,o,i,u){return ys(u,i.maximum)}function MA(e,o,i,u,m,p){return ah(e,o,m,p)||o.AddError({keyword:"maximum",schemaPath:i,instancePath:u,params:{comparison:"<=",limit:m.maximum}})}function OA(e,o,i,u){return Xi(It(u,"length"),Ae(i.maxItems))}function uh(e,o,i,u){return ys(u.length,i.maxItems)}function _A(e,o,i,u,m,p){return uh(e,o,m,p)||o.AddError({keyword:"maxItems",schemaPath:i,instancePath:u,params:{limit:m.maxItems}})}function LA(e,o,i,u){return EO(u,Ae(i.maxLength))}function ch(e,o,i,u){return Ky(u,i.maxLength)}function NA(e,o,i,u,m,p){return ch(e,o,m,p)||o.AddError({keyword:"maxLength",schemaPath:i,instancePath:u,params:{limit:m.maxLength}})}function DA(e,o,i,u){return Xi(It(Zi(u),"length"),Ae(i.maxProperties))}function mh(e,o,i,u){return ys(Se(u).length,i.maxProperties)}function qA(e,o,i,u,m,p){return mh(e,o,m,p)||o.AddError({keyword:"maxProperties",schemaPath:i,instancePath:u,params:{limit:m.maxProperties}})}function FA(e){return vs(e)}function V1(e,o,i,u){let[m,p]=[Jt(),Jt()],f=pm(u,[m,p],Rn(Lt(e,o,i.contains,m),o.AddIndex(p)));return $u(f,Ae(i.minContains))}function J1(e,o,i,u){let[m]=[Jt()],p=pm(u,[m,"_"],Lt(e,o,i.contains,m));return $u(p,Ae(i.minContains))}function jA(e,o,i,u){if(!FA(i))return Ae(!0);return o.UseUnevaluated()?V1(e,o,i,u):J1(e,o,i,u)}function ph(e,o,i,u){if(!FA(i))return!0;let m=Sd(u,(p,f)=>At(e,o,i.contains,p)&&o.AddIndex(f));return Pa(m,i.minContains)}function UA(e,o,i,u,m,p){return ph(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:m.minContains}})}function BA(e,o,i,u){return $u(u,Ae(i.minimum))}function lh(e,o,i,u){return Pa(u,i.minimum)}function GA(e,o,i,u,m,p){return lh(e,o,m,p)||o.AddError({keyword:"minimum",schemaPath:i,instancePath:u,params:{comparison:">=",limit:m.minimum}})}function KA(e,o,i,u){return $u(It(u,"length"),Ae(i.minItems))}function dh(e,o,i,u){return Pa(u.length,i.minItems)}function HA(e,o,i,u,m,p){return dh(e,o,m,p)||o.AddError({keyword:"minItems",schemaPath:i,instancePath:u,params:{limit:m.minItems}})}function WA(e,o,i,u){return bO(u,Ae(i.minLength))}function fh(e,o,i,u){return Hy(u,i.minLength)}function zA(e,o,i,u,m,p){return fh(e,o,m,p)||o.AddError({keyword:"minLength",schemaPath:i,instancePath:u,params:{limit:m.minLength}})}function VA(e,o,i,u){return $u(It(Zi(u),"length"),Ae(i.minProperties))}function hh(e,o,i,u){return Pa(Se(u).length,i.minProperties)}function JA(e,o,i,u,m,p){return hh(e,o,m,p)||o.AddError({keyword:"minProperties",schemaPath:i,instancePath:u,params:{limit:m.minProperties}})}function QA(e,o,i,u){return kO(u,Ae(i.multipleOf))}function gh(e,o,i,u){return By(u,i.multipleOf)}function XA(e,o,i,u,m,p){return gh(e,o,m,p)||o.AddError({keyword:"multipleOf",schemaPath:i,instancePath:u,params:{multipleOf:m.multipleOf}})}function Q1(e,o,i,u){return wi(e,o,[i.not],u,Un(fo(It("results","length"),Ae(1))))}function X1(e,o,i,u){return Un(Lt(e,o,i.not,u))}function YA(e,o,i,u){return o.UseUnevaluated()?Q1(e,o,i,u):X1(e,o,i,u)}function yh(e,o,i,u){let m=new Nn;return!At(e,m,i.not,u)&&o.Merge([m])}function ZA(e,o,i,u,m,p){return yh(e,o,m,p)||o.AddError({keyword:"not",schemaPath:i,instancePath:u,params:{}})}function Y1(e,o,i,u){return wi(e,o,i.oneOf,u,fo(It("results","length"),Ae(1)))}function Z1(e,o,i,u){let[m]=[Jt()],p=TO(i.oneOf.map((h)=>Lt(e,o,h,u))),f=pm(p,[m,"_"],fo(m,Ae(!0)));return fo(f,Ae(1))}function eP(e,o,i,u){return o.UseUnevaluated()?Y1(e,o,i,u):Z1(e,o,i,u)}function tP(e,o,i,u){let m=i.oneOf.reduce((p,f)=>{let h=new Nn;return At(e,h,f,u)?[...p,h]:p},[]);return M(m.length,1)&&o.Merge(m)}function rP(e,o,i,u,m,p){let f=[],h=[],x=m.oneOf.reduce((S,R,k)=>{let A=new Dn,v=`${i}/oneOf/${k}`,_=rr(e,A,v,u,R,p);if(_)h.push(k);if(!_)f.push(A);return _?[...S,A]:S},[]),I=M(x.length,1)&&o.Merge(x);if(!I&&M(h.length,0))f.forEach((S)=>S.GetErrors().forEach((R)=>o.AddError(R)));return I||o.AddError({keyword:"oneOf",schemaPath:i,instancePath:u,params:{passingSchemas:h}})}function nP(e,o,i,u){let m=_o(lt(i.pattern)?ms(i.pattern):i.pattern);return Er(It(m,"test"),[u])}function xh(e,o,i,u){return(lt(i.pattern)?ms(i.pattern):i.pattern).test(u)}function oP(e,o,i,u,m,p){return xh(e,o,m,p)||o.AddError({keyword:"pattern",schemaPath:i,instancePath:u,params:{pattern:m.pattern}})}function sP(e,o,i,u){return vn(hn(i.patternProperties).map(([m,p])=>{let[f,h]=[Jt(),Jt()],x=_o(ms(m)),I=Un(Er(It(x,"test"),[f])),S=Qn(e,o,p,h),R=o.AddKey(f),k=o.UseUnevaluated()?Ir(I,Rn(S,R)):Ir(I,S);return xs(ex(u),Ae(0),[`[${f}, ${h}]`,"_"],k)}))}function iP(e,o,i,u){return mn(hn(i.patternProperties),0,([m,p])=>{let f=ms(m);return mn(hn(u),0,([h,x])=>!f.test(h)||ko(e,o,p,x)&&o.AddKey(h))})}function aP(e,o,i,u,m,p){return $n(hn(m.patternProperties),0,([f,h])=>{let x=`${i}/patternProperties/${f}`,I=ms(f);return $n(hn(p),0,([S,R])=>{let k=`${u}/${S}`;return!I.test(S)||Ao(e,o,x,k,h,R)&&o.AddKey(S)})})}function uP(e,o,i,u){return vn(i.prefixItems.map((m,p)=>{let f=Xi(It(u,"length"),Ae(p)),h=Qn(e,o,m,`${u}[${p}]`),x=o.AddIndex(Ae(p)),I=o.UseUnevaluated()?Rn(h,x):h;return Ir(f,I)}))}function cP(e,o,i,u){return M(u.length,0)||mn(i.prefixItems,0,(m,p)=>ys(u.length,p)||ko(e,o,m,u[p])&&o.AddIndex(p))}function mP(e,o,i,u,m,p){return M(p.length,0)||$n(m.prefixItems,0,(f,h)=>{let x=`${i}/prefixItems/${h}`,I=`${u}/${h}`;return ys(p.length,h)||Ao(e,o,x,I,f,p[h])&&o.AddIndex(h)})}function el(e,o){return e.includes(o)||Bo().exactOptionalPropertyTypes}function pP(e,o){return Rd(It(e,o))}function Ih(e,o){return Bt(e[o])}function lP(e,o,i,u){let m=cs(i)?i.required:[],p=hn(i.properties).map(([f,h])=>{let x=Un(ea(u,Ae(f))),I=Qn(e,o,h,It(u,f)),S=o.AddKey(Ae(f)),R=o.UseUnevaluated()?Rn(I,S):I,k=m.includes(f)?R:Ir(x,R);return el(m,f)?k:Ir(pP(u,f),k)});return vn(p)}function dP(e,o,i,u){let m=cs(i)?i.required:[];return mn(hn(i.properties),0,([f,h])=>{let x=!pe(u,f)||ko(e,o,h,u[f])&&o.AddKey(f);return el(m,f)?x:Ih(u,f)||x})}function fP(e,o,i,u,m,p){let f=cs(m)?m.required:[];return $n(hn(m.properties),0,([x,I])=>{let S=`${i}/properties/${x}`,R=`${u}/${x}`,k=()=>!pe(p,x)||Ao(e,o,S,R,I,p[x])&&o.AddKey(x);return el(f,x)?k():Ih(p,x)||k()})}function hP(e,o,i,u){let[m,p]=[Jt(),Jt()];return xs(Zi(u),Ae(0),[m,p],Lt(e,o,i.propertyNames,m))}function gP(e,o,i,u){return mn(Se(u),0,(m,p)=>At(e,o,i.propertyNames,m))}function yP(e,o,i,u,m,p){let f=[];return $n(Se(p),0,(x,I)=>{let S=`${u}/${x}`,R=`${i}/propertyNames`,k=rr(e,o,R,S,m.propertyNames,x);if(!k)f.push(x);return k})||o.AddError({keyword:"propertyNames",schemaPath:i,instancePath:u,params:{propertyNames:f}})}function xP(e,o,i,u){let m=e.RecursiveRef(i)??!1;return Ws(e,o,m,u)}function IP(e,o,i,u){let m=e.RecursiveRef(i)??!1;return Ve(m)&&At(e,o,m,u)}function bP(e,o,i,u,m,p){let f=e.RecursiveRef(m)??!1;return Ve(f)&&rr(e,o,"#",u,f,p)}function ej(e,o,i,u){let m=si(["context","value"],Ws(e,o,i,"value")),p=si(["context","value"],lm([Ds("nextContext",Ad("CheckContext",[])),Ds("result",Er(m,["nextContext","value"])),rx("result",o.Merge("[nextContext]")),dm("result")]));return Er(p,["context",u])}function tj(e,o,i,u){return Ws(e,o,i,u)}function EP(e,o,i,u){let m=e.Ref(i)??!1;return o.UseUnevaluated()?ej(e,o,m,u):tj(e,o,m,u)}function SP(e,o,i,u){let m=e.Ref(i)??!1,p=new Nn,f=Ve(m)&&At(e,p,m,u);if(f)o.Merge([p]);return f}function wP(e,o,i,u,m,p){let f=e.Ref(m)??!1,h=new Dn,x=Ve(f)&&rr(e,h,"#",u,f,p);if(x)o.Merge([h]);if(!x)h.GetErrors().forEach((I)=>o.AddError(I));return x}function TP(e,o,i,u){return vn(i.required.map((m)=>ea(u,Ae(m))))}function RP(e,o,i,u){return mn(i.required,0,(m)=>pe(u,m))}function kP(e,o,i,u,m,p){let f=[];return $n(m.required,0,(x)=>{let I=pe(p,x);if(!I)f.push(x);return I})||o.AddError({keyword:"required",schemaPath:i,instancePath:u,params:{requiredProperties:f}})}function AP(e,o,i,u){return M(i,"object")?Qy(u):M(i,"array")?mm(u):M(i,"boolean")?fO(u):M(i,"integer")?hO(u):M(i,"number")?Jy(u):M(i,"null")?gO(u):M(i,"string")?Yy(u):M(i,"bigint")?Vy(u):M(i,"constructor")?IO(u):M(i,"function")?xO(u):M(i,"symbol")?yO(u):M(i,"undefined")?Rd(u):M(i,"void")?Rd(u):Ae(!0)}function bh(e,o,i,u,m){return M(i,"object")?Uo(m):M(i,"array")?Fe(m):M(i,"boolean")?fn(m):M(i,"integer")?cm(m):M(i,"number")?Ot(m):M(i,"null")?bo(m):M(i,"string")?lt(m):M(i,"bigint")?Dr(m):M(i,"constructor")?bd(m):M(i,"function")?gs(m):M(i,"symbol")?Ed(m):M(i,"undefined")?Bt(m):M(i,"void")?Bt(m):!0}function rj(e,o,i,u){return Pd(i.map((m)=>AP(e,o,m,u)))}function PP(e,o,i,u,m){return Ca(i,(p)=>bh(e,o,p,u,m))}function CP(e,o,i,u){return Fe(i.type)?rj(e,o,i.type,u):AP(e,o,i.type,u)}function $P(e,o,i,u){return Fe(i.type)?PP(e,o,i.type,i,u):bh(e,o,i.type,i,u)}function vP(e,o,i,u,m,p){return(Fe(m.type)?PP(e,o,m.type,m,p):bh(e,o,m.type,m,p))||o.AddError({keyword:"type",schemaPath:i,instancePath:u,params:{type:m.type}})}function MP(e,o,i,u){let[m,p]=[Jt(),Jt()],f=Er(It("context","GetIndices"),[]),h=Er(It("indices","has"),[m]),x=Lt(e,o,i.unevaluatedItems,p),I=Er(It("context","AddIndex"),[m]),S=xs(u,Ae(0),[p,m],Rn(Ir(h,x),I));return Er(si(["context"],lm([Ds("indices",f),dm(S)])),["context"])}function OP(e,o,i,u){let m=o.GetIndices();return mn(u,0,(p,f)=>(m.has(f)||At(e,o,i.unevaluatedItems,p))&&o.AddIndex(f))}function _P(e,o,i,u,m,p){let f=o.GetIndices(),h=[];return $n(p,0,(I,S)=>{let R=new Dn,k=(f.has(S)||rr(e,R,i,u,m.unevaluatedItems,I))&&o.AddIndex(S);if(!k)h.push(S);return k})||o.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:u,params:{unevaluatedItems:h}})}function LP(e,o,i,u){let[m,p]=[Jt(),Jt()],f=Er(It("context","GetKeys"),[]),h=Er(It("keys","has"),[m]),x=Er(It("context","AddKey"),[m]),I=Lt(e,o,i.unevaluatedProperties,p),S=xs(ex(u),Ae(0),[`[${m}, ${p}]`,"_"],Ir(h,Rn(I,x)));return Er(si(["context"],lm([Ds("keys",f),dm(S)])),["context"])}function NP(e,o,i,u){let m=o.GetKeys();return mn(hn(u),0,([p,f])=>m.has(p)||At(e,o,i.unevaluatedProperties,f)&&o.AddKey(p))}function DP(e,o,i,u,m,p){let f=o.GetKeys(),h=[];return $n(hn(p),0,([I,S])=>{let R=new Dn,k=f.has(I)||rr(e,R,i,u,m.unevaluatedProperties,S)&&o.AddKey(I);if(!k)h.push(I);return k})||o.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:u,params:{unevaluatedProperties:h}})}function Eh(e){return!M(e.uniqueItems,!1)}function qP(e,o,i,u){if(!Eh(i))return Ae(!0);let m=It(Ad("Set",[Er(It(u,"map"),[It("Hashing","Hash")])]),"size"),p=It(u,"length");return fo(m,p)}function FP(e,o,i,u){if(!Eh(i))return!0;let m=new Set(u.map(vd)).size,p=u.length;return M(m,p)}function jP(e,o,i,u,m,p){if(!Eh(m))return!0;let f=new Set,h=p.reduce((I,S,R)=>{let k=vd(S);if(f.has(k))return[...I,R];return f.add(k),I},[]);return M(h.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:u,params:{duplicateItems:h}})}function Dc(e,o){return Oc(e)&&(Fe(e.type)&&ji(e.type.length,0)&&mn(e.type,0,(i)=>M(i,o))||M(e.type,o))}function nj(e){return Dc(e,"object")}function oj(e){return In(e)&&(Oo(e)||hc(e)||gc(e)||Za(e)||Hs(e)||Ks(e)||tu(e)||xa(e)||Rc(e)||cs(e)||Si(e))}function sj(e){return Dc(e,"array")}function ij(e){return In(e)&&(Ya(e)||Bs(e)||vs(e)||wc(e)||eu(e)||Gs(e)||Ii(e)||us(e)||Ei(e)||bi(e))}function aj(e){return Dc(e,"string")}function uj(e){return In(e)&&(ya(e)||Tc(e)||ga(e)||Ia(e))}function cj(e){return Dc(e,"number")||Dc(e,"bigint")}function mj(e){return In(e)&&(as(e)||Sc(e)||Ic(e)||is(e)||kc(e))}function Qn(e,o,i,u){return o.UseUnevaluated()?Rn(Rn(o.Push(),Lt(e,o,i,u)),o.Pop()):Lt(e,o,i,u)}function Lt(e,o,i,u){e.Push(i);let m=[];if(js(i))return bk(e,o,i,u);if(Oc(i))m.push(CP(e,o,i,u));if(oj(i)){let f=[];if(cs(i))f.push(TP(e,o,i,u));if(Oo(i))f.push(pk(e,o,i,u));if(hc(i))f.push(Ak(e,o,i,u));if(gc(i))f.push($k(e,o,i,u));if(Za(i))f.push(Ok(e,o,i,u));if(Ks(i))f.push(sP(e,o,i,u));if(Hs(i))f.push(lP(e,o,i,u));if(tu(i))f.push(hP(e,o,i,u));if(xa(i))f.push(VA(e,o,i,u));if(Rc(i))f.push(DA(e,o,i,u));let h=vn(f),x=Ir(Un(Qy(u)),h);m.push(nj(i)?h:x)}if(ij(i)){let f=[];if(Ya(i))f.push(uk(e,o,i,u));if(vs(i))f.push(Rk(e,o,i,u));if(Bs(i))f.push(RA(e,o,i,u));if(wc(i))f.push(CA(e,o,i,u));if(eu(i))f.push(OA(e,o,i,u));if(Gs(i))f.push(jA(e,o,i,u));if(Ii(i))f.push(KA(e,o,i,u));if(us(i))f.push(uP(e,o,i,u));if(bi(i))f.push(qP(e,o,i,u));let h=vn(f),x=Ir(Un(mm(u)),h);m.push(sj(i)?h:x)}if(uj(i)){let f=[];if(Tc(i))f.push(LA(e,o,i,u));if(ya(i))f.push(WA(e,o,i,u));if(ga(i))f.push(bA(e,o,i,u));if(Ia(i))f.push(nP(e,o,i,u));let h=vn(f),x=Ir(Un(Yy(u)),h);m.push(aj(i)?h:x)}if(mj(i)){let f=[];if(Ic(i))f.push(Uk(e,o,i,u));if(is(i))f.push(Gk(e,o,i,u));if(Sc(i))f.push(vA(e,o,i,u));if(as(i))f.push(BA(e,o,i,u));if(kc(i))f.push(QA(e,o,i,u));let h=vn(f),x=Ir(Un(Ir(Jy(u),Vy(u))),h);m.push(cj(i)?h:x)}if(vc(i))m.push(EP(e,o,i,u));if($c(i))m.push(xP(e,o,i,u));if(yc(i))m.push(Nk(e,o,i,u));if(Tp(i))m.push(Sk(e,o,i,u));if(Rp(i))m.push(Fk(e,o,i,u));if(bc(i))m.push(SA(e,o,i,u));if(Ac(i))m.push(YA(e,o,i,u));if(lc(i))m.push(fk(e,o,i,u));if(fc(i))m.push(yk(e,o,i,u));if(Pc(i))m.push(eP(e,o,i,u));if(Ei(i))m.push(Ir(Un(mm(u)),MP(e,o,i,u)));if(Si(i))m.push(Ir(Un(Xy(u)),LP(e,o,i,u)));if(pc(i))m.push(sk(e,o,i,u));let p=vn(m);return e.Pop(i),p}function ko(e,o,i,u){return o.Push()&&At(e,o,i,u)&&o.Pop()}function At(e,o,i,u){e.Push(i);let m=js(i)?zf(e,o,i,u):(!Oc(i)||$P(e,o,i,u))&&(!(at(u)&&!Fe(u))||(!cs(i)||RP(e,o,i,u))&&(!Oo(i)||lk(e,o,i,u))&&(!hc(i)||Pk(e,o,i,u))&&(!gc(i)||vk(e,o,i,u))&&(!Za(i)||_k(e,o,i,u))&&(!Ks(i)||iP(e,o,i,u))&&(!Hs(i)||dP(e,o,i,u))&&(!tu(i)||gP(e,o,i,u))&&(!xa(i)||hh(e,o,i,u))&&(!Rc(i)||mh(e,o,i,u)))&&(!Fe(u)||(!Ya(i)||ck(e,o,i,u))&&(!vs(i)||Jf(e,o,i,u))&&(!Bs(i)||kA(e,o,i,u))&&(!wc(i)||ih(e,o,i,u))&&(!eu(i)||uh(e,o,i,u))&&(!Gs(i)||ph(e,o,i,u))&&(!Ii(i)||dh(e,o,i,u))&&(!us(i)||cP(e,o,i,u))&&(!bi(i)||FP(e,o,i,u)))&&(!lt(u)||(!Tc(i)||ch(e,o,i,u))&&(!ya(i)||fh(e,o,i,u))&&(!ga(i)||sh(e,o,i,u))&&(!Ia(i)||xh(e,o,i,u)))&&(!(Ot(u)||Dr(u))||(!Ic(i)||Yf(e,o,i,u))&&(!is(i)||Zf(e,o,i,u))&&(!Sc(i)||ah(e,o,i,u))&&(!as(i)||lh(e,o,i,u))&&(!kc(i)||gh(e,o,i,u)))&&(!vc(i)||SP(e,o,i,u))&&(!$c(i)||IP(e,o,i,u))&&(!yc(i)||Dk(e,o,i,u))&&(!Tp(i)||Vf(e,o,i,u))&&(!Rp(i)||Xf(e,o,i,u))&&(!bc(i)||wA(e,o,i,u))&&(!Ac(i)||yh(e,o,i,u))&&(!lc(i)||hk(e,o,i,u))&&(!fc(i)||xk(e,o,i,u))&&(!Pc(i)||tP(e,o,i,u))&&(!Ei(i)||(!Fe(u)||OP(e,o,i,u)))&&(!Si(i)||(!at(u)||NP(e,o,i,u)))&&(!pc(i)||ik(e,o,i,u));return e.Pop(i),m}function Ao(e,o,i,u,m,p){return o.Push()&&rr(e,o,i,u,m,p)&&o.Pop()}function rr(e,o,i,u,m,p){if(o.AtCapacity())return!1;e.Push(m);let f=js(m)?Ek(e,o,i,u,m,p):!!(+(!Oc(m)||vP(e,o,i,u,m,p))&+(!(at(p)&&!Fe(p))||!!(+(!cs(m)||kP(e,o,i,u,m,p))&+(!Oo(m)||dk(e,o,i,u,m,p))&+(!hc(m)||Ck(e,o,i,u,m,p))&+(!gc(m)||Mk(e,o,i,u,m,p))&+(!Za(m)||Lk(e,o,i,u,m,p))&+(!Ks(m)||aP(e,o,i,u,m,p))&+(!Hs(m)||fP(e,o,i,u,m,p))&+(!tu(m)||yP(e,o,i,u,m,p))&+(!xa(m)||JA(e,o,i,u,m,p))&+(!Rc(m)||qA(e,o,i,u,m,p))))&+(!Fe(p)||!!(+(!Ya(m)||mk(e,o,i,u,m,p))&+(!vs(m)||kk(e,o,i,u,m,p))&+(!Bs(m)||AA(e,o,i,u,m,p))&+(!wc(m)||$A(e,o,i,u,m,p))&+(!eu(m)||_A(e,o,i,u,m,p))&+(!Gs(m)||UA(e,o,i,u,m,p))&+(!Ii(m)||HA(e,o,i,u,m,p))&+(!us(m)||mP(e,o,i,u,m,p))&+(!bi(m)||jP(e,o,i,u,m,p))))&+(!lt(p)||!!(+(!Tc(m)||NA(e,o,i,u,m,p))&+(!ya(m)||zA(e,o,i,u,m,p))&+(!ga(m)||EA(e,o,i,u,m,p))&+(!Ia(m)||oP(e,o,i,u,m,p))))&+(!(Ot(p)||Dr(p))||!!(+(!Ic(m)||Bk(e,o,i,u,m,p))&+(!is(m)||Kk(e,o,i,u,m,p))&+(!Sc(m)||MA(e,o,i,u,m,p))&+(!as(m)||GA(e,o,i,u,m,p))&+(!kc(m)||XA(e,o,i,u,m,p))))&+(!vc(m)||wP(e,o,i,u,m,p))&+(!$c(m)||bP(e,o,i,u,m,p))&+(!yc(m)||qk(e,o,i,u,m,p))&+(!Tp(m)||wk(e,o,i,u,m,p))&+(!Rp(m)||jk(e,o,i,u,m,p))&+(!bc(m)||TA(e,o,i,u,m,p))&+(!Ac(m)||ZA(e,o,i,u,m,p))&+(!lc(m)||gk(e,o,i,u,m,p))&+(!fc(m)||Ik(e,o,i,u,m,p))&+(!Pc(m)||rP(e,o,i,u,m,p))&+(!Ei(m)||(!Fe(p)||_P(e,o,i,u,m,p)))&+(!Si(m)||(!at(p)||DP(e,o,i,u,m,p))))&&(!pc(m)||ak(e,o,i,u,m,p));return e.Pop(m),f}var UP=[0],tl=new Map,qc=new Map;function pj(){return`${UP[0]++}`}function lj(e,o){if(!tl.has(e))tl.set(e,new Map);let i=tl.get(e);if(i.has(o))return i.get(o);let u=pj();return i.set(o,u),u}function dj(e,o,i,u){return e.UseUnevaluated()?Er(`check_${i}`,["context",u]):Er(`check_${i}`,[u])}function fj(e,o,i,u){let m=Lt(e,o,i,"value");return o.UseUnevaluated()?Ds(`check_${u}`,si(["context","value"],m)):Ds(`check_${u}`,si(["value"],m))}function BP(){UP[0]=0,tl.clear(),qc.clear()}function GP(){return[...qc.values()]}function Ws(e,o,i,u){let m=lj(i,e.LexicalBaseURL()),p=dj(o,i,m,u);if(qc.has(m))return p;return qc.set(m,""),qc.set(m,fj(e,o,i,m)),p}function hj(e,o){return at(o)&&!Cu(e)?o[e]:void 0}function gj(e,o){return e.reduce((i,u)=>hj(u,i),o)}function yj(e){if(M(e.length,0))return[];let o=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function xj(e,o){let i=yj(o);return gj(i,e)}var nl="https://json-schema.org";function HP(e,o){if(at(e)&&Us(e)&&M(e.$dynamicAnchor,o))return e;if(at(e))for(let i of Se(e)){let u=HP(e[i],o);if(u)return u}return}function Sh(e,o,i){if(M(e,i))return o.href;let u=In(e)&&Ro(e)?new URL(e.$id,o.href):o;if(Fe(e))for(let m of e){let p=Sh(m,u,i);if(!Bt(p))return p}else if(at(e))for(let m of Se(e)){let p=Sh(e[m],u,i);if(!Bt(p))return p}return}function Ij(e,o,i){if(M(e.$id,i.hash))return e;let u=new URL(i.href,o.href);if(M(o.pathname,u.pathname))return i.hash.startsWith("#")?WP(e,i):e;return}function bj(e,o,i){let u=new URL(`#${e.$anchor}`,o.href),m=new URL(i.href,o.href);return M(u.href,m.href)?e:void 0}function Ej(e,o,i){let u=new URL(`#${e.$dynamicAnchor}`,o.href),m=new URL(i.href,o.href);return M(u.href,m.href)?e:void 0}function WP(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let i=decodeURIComponent(o.hash.slice(1));if(!i.startsWith("/"))return;return xj(e,i)}function Sj(e,o,i){if(Ro(e)){let u=Ij(e,o,i);if(!Bt(u))return u}if(dc(e)){let u=bj(e,o,i);if(!Bt(u))return u}if(Us(e)){let u=Ej(e,o,i);if(!Bt(u))return u}return WP(e,i)}function wj(e,o,i){return e.reduce((u,m)=>{let p=ol(m,o,i);return!Bt(p)?p:u},void 0)}function Tj(e){return M(e,"const")||M(e,"enum")}function Rj(e,o,i){return Se(e).reduce((u,m)=>{if(Tj(m))return u;let p=ol(e[m],o,i);return!Bt(p)?p:u},void 0)}function ol(e,o,i){let u=In(e)&&Ro(e)?new URL(e.$id,o.href):o;if(In(e)){let m=Sj(e,u,i);if(!Bt(m))return m}if(Fe(e))return wj(e,u,i);if(at(e))return Rj(e,u,i);return}function kj(e,o,i){return Sh(e,new URL(o||".",nl),i)}function Aj(e,o,i,u){let m=sl(e,o,i,u,!1);return In(m)&&Ro(m)?m:void 0}function KP(e){return e.href.split("#")[0]}function Pj(e,o){return pe(e,o)?e[o]:void 0}function Cj(e,o,i){return ol(e,o,i)}function $j(e,o,i){let u=KP(i);if(M(u,KP(o)))return;if(!pe(e,u))return;let m=e[u],p=In(m)&&Ro(m)?new URL(m.$id,u):new URL(u);return M(i.hash,"")?m:ol(m,p,i)}function vj(e,o,i,u,m){if(!u.$ref.startsWith("#"))return;if(pe(e,"$schema"))return;let p=kj(o,i,m);if(Bt(p)||M(p,i))return;return{target:m,base:p,root:o}}function Mj(e,o,i){let u=e[o];if(!In(u))return;return{target:i,base:o,root:u}}function Oj(e,o,i,u,m){let p=m?Mj(e.context,u,i):void 0;if(!Bt(p))return p;return vj(e.root,e.lexicalSchema,e.referenceBase,o,i)}function _j(e,o,i,u,m,p){if(Ro(m))return;let f=Aj(e,o,i,u);if(!f||p.includes(f))return;return{target:m,resource:f}}function sl(e,o,i,u,m=!0){let p=new URL(i||".",nl),f=m&&Ro(o)?new URL(o.$id,p):p,h=new URL(u,f.href);return Pj(e,u)??Cj(o,f,h)??$j(e,f,h)}function Lj(e,o,i,u,m,p){let f=new URL(i||".",nl),h=m.$dynamicRef.startsWith("#")?u:o,x=sl(e,h,i,m.$dynamicRef,!1);if(Bt(x)){let R=new URL(m.$dynamicRef,f).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let k=decodeURIComponent(R.slice(1));return p.find((v)=>M(v.$dynamicAnchor,k))??HP(o,k)}return}if(!In(x)||!Us(x))return x;if(new URL(m.$dynamicRef,f).hash.startsWith("#/"))return x;return p.find((R)=>M(R.$dynamicAnchor,x.$dynamicAnchor))??x}function Nj(e,o){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:i,m=sl(e.context,u,e.referenceBase,o.$ref,!1);if(!m||!In(m))return{schema:m};let p=new URL(o.$ref,e.referenceBase).href.split("#")[0],f=!M(p,e.resourceBase),h=Oj(e,o,m,p,f),x=f?_j(e.context,e.root,e.referenceBase,p,m,e.ids):void 0;return{schema:m,retrievedResource:h,resolvedResource:x}}function Dj(e,o){let i=Cc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return sl(e.context,i,e.lexicalBase,o.$recursiveRef,!1)}function qj(e,o){return Lj(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var Lr=function(e,o,i,u){if(i==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?u:i==="a"?u.call(e):u?u.value:o.get(e)},Tr,al,YP,kh,il,zP,VP,JP,QP,Th,Rh,Ah,Ph,XP,ZP;class Ti{constructor(e,o){Tr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return Lr(this,Tr,"m",kh).call(this,this.ids)}Push(e){if(!In(e))return;if(Ro(e))Lr(this,Tr,"m",Ah).call(this,e);if(dc(e))this.anchors.push(e);if(Cc(e))this.recursiveAnchors.push(e);if(Us(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!In(e))return;if(Ro(e))Lr(this,Tr,"m",Ph).call(this,e);if(dc(e))this.anchors.pop();if(Cc(e))this.recursiveAnchors.pop();if(Us(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();Lr(this,Tr,"m",ZP).call(this,e)}Ref(e){let o=Nj(Lr(this,Tr,"m",al).call(this),e);return Lr(this,Tr,"m",YP).call(this,o),o.schema}RecursiveRef(e){let o=Dj(Lr(this,Tr,"m",al).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=qj(Lr(this,Tr,"m",al).call(this),e);if(o)this.pendingResource=!0;return o}}Tr=new WeakSet,al=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:Lr(this,Tr,"m",VP).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:Lr(this,Tr,"m",zP).call(this),resourceBase:Lr(this,Tr,"m",il).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},YP=function(o){if(!Bt(o.schema))this.pendingResource=!0;if(!Bt(o.resolvedResource))Lr(this,Tr,"m",XP).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!Bt(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},kh=function(o){let i=this.retrievedFrames[this.retrievedFrames.length-1],u=i?new URL(i.base):new URL(nl);return(i?o.slice(i.idDepth):o).reduce((p,f)=>new URL(f.$id,p),u).href},il=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return Lr(this,Tr,"m",kh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((i,u)=>new URL(u.$id,i),new URL(o.base)).href},zP=function(){if(this.retrievedFrames.length>0)return Lr(this,Tr,"m",il).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return Lr(this,Tr,"m",il).call(this)},VP=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(o)return this.ids.length>o.idDepth?this.ids[this.ids.length-1]:o.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},JP=function(o){o.forEach((i)=>Lr(this,Tr,"m",Th).call(this,i,!1))},QP=function(o){o.forEach((i)=>Lr(this,Tr,"m",Rh).call(this,i,!1))},Th=function e(o,i=!0){if(js(o))return;if(Fe(o))return Lr(this,Tr,"m",JP).call(this,o);if(!In(o))return;let u=o;if(!i&&Ro(u))return;if(!i&&Us(u))this.dynamicAnchors.push(u);for(let m of Se(u))Lr(this,Tr,"m",e).call(this,u[m],!1)},Rh=function e(o,i=!0){if(js(o))return;if(Fe(o))return Lr(this,Tr,"m",QP).call(this,o);if(!In(o))return;let u=o;if(!i&&Ro(u))return;if(!i&&Us(u))this.dynamicAnchors.pop();for(let m of Se(u))Lr(this,Tr,"m",e).call(this,u[m],!1)},Ah=function(o){this.ids.push(o);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(o);Lr(this,Tr,"m",Th).call(this,o,!0)},Ph=function(o){if(this.ids.pop(),this.resourceIds.length>0&&M(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();Lr(this,Tr,"m",Rh).call(this,o,!0)},XP=function(o,i){Lr(this,Tr,"m",Ah).call(this,i),this.resolvedResources.set(o,i)},ZP=function(o){if(!this.resolvedResources.has(o))return;let i=this.resolvedResources.get(o);Lr(this,Tr,"m",Ph).call(this,i),this.resolvedResources.delete(o)};function Fj(e){let o=e.Functions().join(`;
33
+ `),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${i.join("; ")} }`}function jj(e,o){return bx("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Nn,j,iu,oa,e.External().variables)}function Uj(e){let o=new Ti(e.Context(),e.Schema()),i=new Nn;return(u)=>At(o,i,e.Schema(),u)}function Bj(e,o){return Ix()?jj(e,o):Uj(e)}class eC{constructor(e,o,i){this.isAccelerated=e,this.code=o,this.check=i}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class tC{constructor(e,o,i,u,m,p){this.context=e,this.schema=o,this.external=i,this.functions=u,this.entry=m,this.useUnevaluated=p}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=Fj(this),o=Bj(this,e);return new eC(Ix(),e,o)}}function ul(...e){let[o,i]=kn(e,{2:(x,I)=>[x,I],1:(x)=>[{},x]});nk(),BP();let u=new Ti(o,i),m=new Kf(rk(o,i)),p=Ws(u,m,i,"value"),f=GP(),h=ok();return new tC(o,i,h,f,p,m.UseUnevaluated())}function cl(...e){let[o,i,u]=kn(e,{3:(S,R,k)=>[S,R,k],2:(S,R)=>[{},S,R]}),m=new Ti(o,i),p=new Dn,f=rr(m,p,"#","",i,u),h=p.GetErrors(),x=Cx(),I=h.map((S)=>({...S,message:x(S)}));return[f,I]}function $h(...e){let[o,i,u]=kn(e,{3:(f,h,x)=>[f,h,x],2:(f,h)=>[{},f,h]}),m=new Ti(o,i),p=new Nn;return At(m,p,i,u)}function Yt(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return $h(o,i,u)}function Ms(...e){let[o,i,u]=kn(e,{3:(f,h,x)=>[f,h,x],2:(f,h)=>[{},f,h]}),[m,p]=cl(o,i,u);return p}class ba extends Error{constructor(e,o,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:o},writable:!1,configurable:!1,enumerable:!1})}}function rC(e,o,i){if(!Fe(i))return i;return i.map((u)=>bn(e,o.items,u))}function nC(e,o,i){return bn({...e,...o.$defs},pn(o.$ref),i)}function Hj(e,o){let i=pe(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Mo(e,o),m=Pn(u);return He(m)?Ip(m,i):m}function oC(e,o,i){let u=Hj(e,o);return bn(e,u,i)}function ml(e){return pe(e,"additionalProperties")?e.additionalProperties:void 0}function sC(e,o,i){if(!at(i)||Fe(i))return i;let u=ml(o);for(let m of Se(i)){if(pe(o.properties,m)){i[m]=bn(e,o.properties[m],i[m]);continue}if(fn(u)&&M(u,!0)||vr(u)&&Yt(e,u,i[m])){i[m]=bn(e,u,i[m]);continue}delete i[m]}return i}function iC(e,o,i){if(!at(i))return i;let u=ml(o),[m,p]=[new RegExp(xn(o)),or(o)];for(let f of Se(i)){if(m.test(f)){i[f]=bn(e,p,i[f]);continue}if(fn(u)&&M(u,!0)||vr(u)&&Yt(e,u,i[f])){i[f]=bn(e,u,i[f]);continue}delete i[f]}return i}function aC(e,o,i){return pe(e,o.$ref)?bn(e,e[o.$ref],i):i}function uC(e,o,i){if(!Fe(i))return i;let u=Math.min(i.length,o.items.length);for(let m=0;m<u;m++)i[m]=bn(e,o.items[m],i[m]);return ji(i.length,u)?i.slice(0,u):i}function Gr(e){return va(e)}function cC(e,o,i){for(let u of o.anyOf){let m=bn(e,u,Gr(i));if(Yt(e,u,m))return m}return i}function bn(e,o,i){return St(o)?rC(e,o,i):Xt(o)?nC(e,o,i):Ge(o)?oC(e,o,i):He(o)?sC(e,o,i):Kt(o)?iC(e,o,i):Ft(o)?aC(e,o,i):ct(o)?uC(e,o,i):be(o)?cC(e,o,i):i}function Wj(e,o){for(let i of Se(e)){if(pe(o,i))continue;o[i]=e[i]}return o}function zj(e){let o={};for(let i of Se(e))o[i]=Fc(e[i]);return o}function Vj(e){return vh(DR(e))}function vh(e){return e.map((o)=>Fc(o))}function Fc(e){let o=St(e)?H(Fc(e.items),Ma(e)):Ge(e)?Mn(vh(e.allOf)):be(e)?g(Vj(e.anyOf)):He(e)?l(zj(e.properties)):Kt(e)?ks(di(e),Fc(or(e))):ct(e)?Ur(vh(e.items)):e;return Wj(e,o)}function au(e){return Fc(e)}function Lo(...e){let[o,i,u]=kn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]}),m=Bo().unionPrioritySort?au(i):i;return bn(o,m,u)}function Io(e){return at(e)&&pe(e,"value")}function je(e){return{value:e}}function Rr(){return}function Jj(e){return Fe(e)?je(e):je([e])}function Qj(e){return M(e,!0)?je(BigInt(1)):je(BigInt(0))}var Xj=/^-?(0|[1-9]\d*)n$/,Yj=/^-?(0|[1-9]\d*)\.\d+$/,Zj=/^-?(0|[1-9]\d*)$/;function eU(e){return Xj.test(e)}function tU(e){return Yj.test(e)}function rU(e){return Zj.test(e)}function nU(e){let o=e.toLowerCase();return eU(e)?je(BigInt(e.slice(0,e.length-1))):tU(e)?je(BigInt(e.split(".")[0])):rU(e)?je(BigInt(e)):M(o,"false")?je(BigInt(0)):M(o,"true")?je(BigInt(1)):Rr()}function pl(e){return Dr(e)?je(e):fn(e)?Qj(e):Ot(e)?je(BigInt(Math.trunc(e))):bo(e)?je(BigInt(0)):lt(e)?nU(e):Bt(e)?je(BigInt(0)):Rr()}function oU(e){return M(e,BigInt(0))?je(!1):M(e,BigInt(1))?je(!0):Rr()}function sU(e){return M(e,0)?je(!1):M(e,1)?je(!0):Rr()}function iU(e){return M(e.toLowerCase(),"false")?je(!1):M(e.toLowerCase(),"true")?je(!0):M(e,"0")?je(!1):M(e,"1")?je(!0):Rr()}function mC(e){return Dr(e)?oU(e):fn(e)?je(e):Ot(e)?sU(e):bo(e)?je(!1):lt(e)?iU(e):Bt(e)?je(!1):Rr()}function aU(e){return M(e,BigInt(0))?je(null):Rr()}function uU(e){return M(e,!1)?je(null):Rr()}function cU(e){return M(e,0)?je(null):Rr()}function mU(e){let o=e.toLowerCase();return M(o,"undefined")||M(o,"null")||M(e,"")||M(e,"0")?je(null):Rr()}function pU(e){return Dr(e)?aU(e):fn(e)?uU(e):Ot(e)?cU(e):bo(e)?je(null):lt(e)?mU(e):Bt(e)?je(null):Rr()}var pC=BigInt(Number.MAX_SAFE_INTEGER),lC=BigInt(Number.MIN_SAFE_INTEGER);function lU(e){return e<=pC&&e>=lC?je(Number(e)):Rr()}function dU(e){return je(e?1:0)}function fU(e){let o=+e;if(Ot(o))return je(o);let i=e.toLowerCase();if(M(i,"false"))return je(0);if(M(i,"true"))return je(1);let u=pl(e);if(Io(u))return u.value<=pC&&u.value>=lC?je(Number(u.value)):Rr();return Rr()}function Mh(e){return Dr(e)?lU(e):fn(e)?dU(e):Ot(e)?je(e):bo(e)?je(0):lt(e)?fU(e):Bt(e)?je(0):Rr()}function dC(e){return Dr(e)?je(e.toString()):fn(e)?je(e.toString()):Ot(e)?je(e.toString()):bo(e)?je("null"):lt(e)?je(e):Bt(e)?je(""):Rr()}function hU(e){return M(e,BigInt(0))?je(void 0):Rr()}function gU(e){return M(e,!1)?je(void 0):Rr()}function yU(e){return M(e,0)?je(void 0):Rr()}function xU(e){let o=e.toLowerCase();return M(o,"undefined")||M(o,"null")||M(e,"")||M(e,"0")?je(void 0):Rr()}function fC(e){return Dr(e)?hU(e):fn(e)?gU(e):Ot(e)?yU(e):bo(e)?je(void 0):lt(e)?xU(e):Bt(e)?je(e):Rr()}function hC(e,o,i){return Jj(i).value.map((m)=>Hr(e,o.items,m))}function gC(e,o,i){let u=pl(i);return Io(u)?u.value:i}function yC(e,o,i){let u=mC(i);return Io(u)?u.value:i}function xC(e,o,i){return Hr({...e,...o.$defs},pn(o.$ref),i)}function IC(e,o,i){return Hr(e,Pn(o),i)}function bC(e,o,i){let u=Mh(i);return Io(u)?Math.trunc(u.value):i}function EC(e,o,i){let u=Mo(e,o),m=Pn(u);return Hr(e,m,i)}function IU(e,o,i){let u=pl(i);return Io(u)&&M(o.const,u.value)?u.value:i}function bU(e,o,i){let u=mC(i);return Io(u)&&M(o.const,u.value)?u.value:i}function EU(e,o,i){let u=Mh(i);return Io(u)&&M(o.const,u.value)?u.value:i}function SU(e,o,i){let u=dC(i);return Io(u)&&M(o.const,u.value)?u.value:i}function SC(e,o,i){if(M(o.const,i))return i;return Fx(o)?IU(e,o,i):jx(o)?bU(e,o,i):wm(o)?EU(e,o,i):Tm(o)?SU(e,o,i):Fr()}function wC(e,o,i){let u=pU(i);return Io(u)?u.value:i}function TC(e,o,i){let u=Mh(i);return Io(u)?u.value:i}function ll(e,o,i,u){let m=Se(u);for(let[p,f]of o)for(let h of m)if(!p.test(h))u[h]=Hr(e,i,u[h]);return u}function jc(e,o,i){return ln(e)&&Bt(i[o])}function wU(e,o,i){let u=wd(o.properties),m=Se(i);for(let[p,f]of u)for(let h of m){if(!p.test(h)||jc(f,h,i))continue;i[h]=Hr(e,f,i[h])}return pe(o,"additionalProperties")&&at(o.additionalProperties)?ll(e,u,o.additionalProperties,i):i}function RC(e,o,i){return Uo(i)?wU(e,o,i):i}function TU(e,o,i){let u=wd(o.patternProperties),m=Se(i);for(let[p,f]of u)for(let h of m)if(p.test(h))i[h]=Hr(e,f,i[h]);return pe(o,"additionalProperties")&&at(o.additionalProperties)?ll(e,u,o.additionalProperties,i):i}function kC(e,o,i){return Uo(i)?TU(e,o,i):i}function AC(e,o,i){return pe(e,o.$ref)?Hr(e,e[o.$ref],i):i}function PC(e,o,i){let u=dC(i);return Io(u)?u.value:i}function CC(e,o,i){return Hr(e,Pn(o),i)}function $C(e,o,i){if(!Fe(i))return i;for(let u=0;u<Math.min(o.items.length,i.length);u++)i[u]=Hr(e,o.items[u],i[u]);return i}function vC(e,o,i){let u=fC(i);return Io(u)?u.value:i}function MC(e,o,i){if(o.anyOf.some((f)=>Yt(e,f,i)))return i;let p=o.anyOf.map((f)=>Hr(e,f,Gr(i))).find((f)=>Yt(e,o,f));return Bt(p)?i:p}function OC(e,o,i){let u=fC(i);return Io(u)?void 0:i}function Hr(e,o,i){return St(o)?hC(e,o,i):go(o)?gC(e,o,i):Vn(o)?yC(e,o,i):Xt(o)?xC(e,o,i):un(o)?IC(e,o,i):yn(o)?bC(e,o,i):Ge(o)?EC(e,o,i):dt(o)?SC(e,o,i):Ts(o)?wC(e,o,i):Pr(o)?TC(e,o,i):He(o)?RC(e,o,i):Kt(o)?kC(e,o,i):Ft(o)?AC(e,o,i):cn(o)?PC(e,o,i):tr(o)?CC(e,o,i):ct(o)?$C(e,o,i):ss(o)?vC(e,o,i):be(o)?MC(e,o,i):yo(o)?OC(e,o,i):i}function ds(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return Hr(o,i,u)}function _C(e,o,i){if(!Fe(i))return i;for(let u=0;u<i.length;u++)i[u]=En(e,o.items,i[u]);return i}function LC(e,o,i){return En({...e,...o.$defs},pn(o.$ref),i)}function NC(e,o){if(!Bt(o))return o;return gs(e.default)?e.default():Gr(e.default)}function DC(e,o,i){let u=Mo(e,o),m=Pn(u);return En(e,m,i)}function qC(e,o,i){if(!at(i))return i;let u=Se(o.properties);for(let m of u){let p=En(e,o.properties[m],i[m]);if(Bt(p)&&(ln(o.properties[m])||!pe(o.properties[m],"default")))continue;i[m]=p}if(!Oo(o)||fn(o.additionalProperties))return i;for(let m of Se(i)){if(u.includes(m))continue;i[m]=En(e,o.additionalProperties,i[m])}return i}function FC(e,o,i){if(!at(i))return i;let[u,m]=[new RegExp(xn(o)),or(o)];for(let p of Se(i)){if(!(u.test(p)&&To(m)))continue;i[p]=En(e,m,i[p])}if(!Oo(o))return i;for(let p of Se(i)){if(u.test(p))continue;i[p]=En(e,o.additionalProperties,i[p])}return i}function jC(e,o,i){return pe(e,o.$ref)?En(e,e[o.$ref],i):i}function UC(e,o,i){if(!Fe(i))return i;let[u,m]=[o.items,Math.max(o.items.length,i.length)];for(let p=0;p<m;p++)if(p<u.length)i[p]=En(e,u[p],i[p]);return i}function BC(e,o,i){for(let u of o.anyOf){let m=En(e,u,Gr(i));if(Yt(e,u,m))return m}return i}function En(e,o,i){let u=To(o)?NC(o,i):i;return St(o)?_C(e,o,u):Xt(o)?LC(e,o,u):Ge(o)?DC(e,o,u):He(o)?qC(e,o,u):Kt(o)?FC(e,o,u):Ft(o)?jC(e,o,u):ct(o)?UC(e,o,u):be(o)?BC(e,o,u):u}function zs(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return En(o,i,u)}function uu(e){return(...o)=>{let[i,u,m]=kn(o,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return e.reduce((p,f)=>f(i,u,p),m)}}function RU(e,o,i){return o["~codec"].decode(i)}function kU(e,o,i){return o["~codec"].encode(i)}function kr(e,o,i,u){if(!Kn(i))return u;return M(e,"Decode")?RU(o,i,u):kU(o,i,u)}function AU(e,o,i,u){if(!Fe(u))return u;for(let m=0;m<u.length;m++)u[m]=$r(e,o,i.items,u[m]);return kr(e,o,i,u)}function PU(e,o,i,u){let m=kr(e,o,i,u);if(!Fe(m))return m;for(let p=0;p<m.length;p++)m[p]=$r(e,o,i.items,m[p]);return m}function GC(e,o,i,u){return M(e,"Decode")?AU(e,o,i,u):PU(e,o,i,u)}function KC(e,o,i,u){return u=$r(e,{...o,...i.$defs},pn(i.$ref),u),kr(e,o,i,u)}function HC(e){return e.reduce((o,i)=>({...o,...i}),{})}function WC(e,o){for(let i of o)if(!$a(e,i))return i;return e}function CU(e,o,i,u){if(M(i.allOf.length,0))return kr(e,o,i,u);let m=i.allOf.map((h)=>$r(e,o,h,Lo(h,Gr(u)))),f=m.every((h)=>at(h))?HC(m):WC(u,m);return kr(e,o,i,f)}function $U(e,o,i,u){if(M(i.allOf.length,0))return kr(e,o,i,u);let m=kr(e,o,i,u),p=i.allOf.map((h)=>$r(e,o,h,Lo(h,Gr(m))));if(p.every((h)=>at(h)))return HC(p);return WC(m,p)}function zC(e,o,i,u){return M(e,"Decode")?CU(e,o,i,u):$U(e,o,i,u)}function vU(e,o,i,u){if(!Uo(u))return u;for(let m of Se(i.properties)){if(!pe(u,m)||jc(i.properties[m],m,u))continue;u[m]=$r(e,o,i.properties[m],u[m])}return kr(e,o,i,u)}function MU(e,o,i,u){let m=kr(e,o,i,u);if(!Uo(m))return m;for(let p of Se(i.properties)){if(!pe(m,p)||jc(i.properties[p],p,m))continue;m[p]=$r(e,o,i.properties[p],m[p])}return m}function VC(e,o,i,u){return M(e,"Decode")?vU(e,o,i,u):MU(e,o,i,u)}function OU(e,o,i,u){if(!Uo(u))return u;let m=new RegExp(xn(i));for(let p of Se(u)){if(!m.test(p))continue;u[p]=$r(e,o,or(i),u[p])}return kr(e,o,i,u)}function _U(e,o,i,u){let m=kr(e,o,i,u);if(!Uo(m))return m;let p=new RegExp(xn(i));for(let f of Se(m)){if(!p.test(f))continue;m[f]=$r(e,o,or(i),m[f])}return m}function JC(e,o,i,u){return M(e,"Decode")?OU(e,o,i,u):_U(e,o,i,u)}function QC(e,o,i,u){return pe(o,i.$ref)?$r(e,o,o[i.$ref],u):u}function XC(e,o,i,u){return M(e,"Decode")?kr(e,o,i,QC(e,o,i,u)):QC(e,o,i,kr(e,o,i,u))}function LU(e,o,i,u){if(!Fe(u))return u;for(let m=0;m<Math.min(i.items.length,u.length);m++)u[m]=$r(e,o,i.items[m],u[m]);return kr(e,o,i,u)}function NU(e,o,i,u){let m=kr(e,o,i,u);if(!Fe(m))return u;for(let p=0;p<Math.min(i.items.length,m.length);p++)m[p]=$r(e,o,i.items[p],m[p]);return m}function YC(e,o,i,u){return M(e,"Decode")?LU(e,o,i,u):NU(e,o,i,u)}function DU(e,o,i,u){for(let m of i.anyOf){if(!Yt(o,m,u))continue;let p=$r(e,o,m,u);return kr(e,o,i,p)}return u}function qU(e,o,i,u){let m=kr(e,o,i,u);for(let p of i.anyOf){let f=$r(e,o,p,Gr(m));if(!Yt(o,p,f))continue;return f}return m}function ZC(e,o,i,u){return M(e,"Decode")?DU(e,o,i,u):qU(e,o,i,u)}function $r(e,o,i,u){return St(i)?GC(e,o,i,u):Xt(i)?KC(e,o,i,u):Ge(i)?zC(e,o,i,u):He(i)?VC(e,o,i,u):Kt(i)?JC(e,o,i,u):Ft(i)?XC(e,o,i,u):ct(i)?YC(e,o,i,u):be(i)?ZC(e,o,i,u):kr(e,o,i,u)}class e0 extends ba{constructor(e,o){super("Decode",e,o)}}function FU(e,o,i){if(!Yt(e,o,i))throw new e0(i,Ms(e,o,i));return i}function jU(e,o,i){let u=Bo().unionPrioritySort?au(o):o;return $r("Decode",e,u,i)}var UU=uu([(e,o,i)=>Gr(i),(e,o,i)=>zs(e,o,i),(e,o,i)=>ds(e,o,i),(e,o,i)=>Lo(e,o,i),(e,o,i)=>FU(e,o,i),(e,o,i)=>jU(e,o,i)]);function Oh(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return UU(o,i,u)}class t0 extends ba{constructor(e,o){super("Encode",e,o)}}function BU(e,o,i){if(!Yt(e,o,i))throw new t0(i,Ms(e,o,i));return i}function GU(e,o,i){let u=Bo().unionPrioritySort?au(o):o;return $r("Encode",e,u,i)}var KU=uu([(e,o,i)=>Gr(i),(e,o,i)=>GU(e,o,i),(e,o,i)=>zs(e,o,i),(e,o,i)=>ds(e,o,i),(e,o,i)=>Lo(e,o,i),(e,o,i)=>BU(e,o,i)]);function _h(...e){let[o,i,u]=kn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return KU(o,i,u)}function HU(e,o){return Kn(o)||Ri(e,o.items)}function WU(e,o){return Kn(o)||r0({...e,...o.$defs},pn(o.$ref))}function zU(e,o){return Kn(o)||o.allOf.some((i)=>Ri(e,i))}function VU(e,o){return Kn(o)||Se(o.properties).some((i)=>Ri(e,o.properties[i]))}function JU(e,o){return Kn(o)||Ri(e,or(o))}function r0(e,o){if(Lh.has(o.$ref))return!1;return Lh.add(o.$ref),Kn(o)||pe(e,o.$ref)&&Ri(e,e[o.$ref])}function QU(e,o){return Kn(o)||o.items.some((i)=>Ri(e,i))}function XU(e,o){return Kn(o)||o.anyOf.some((i)=>Ri(e,i))}function Ri(e,o){return St(o)?HU(e,o):Xt(o)?WU(e,o):Ge(o)?zU(e,o):He(o)?VU(e,o):Kt(o)?JU(e,o):Ft(o)?r0(e,o):ct(o)?QU(e,o):be(o)?XU(e,o):Kn(o)}var Lh=new Set;function Nh(...e){let[o,i]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Lh.clear(),Ri(o,i)}class fs extends Error{constructor(e,o){super(o);this.type=e}}function n0(e,o){return gs(o.default)?o.default(o):at(o.default)?Gr(o.default):o.default}function o0(e,o){if(bi(o)&&!To(o))throw new fs(o,"Arrays with uniqueItems constraints must specify a default annotation");let i=Ii(o)?o.minItems:0;return Array.from({length:i},()=>Wr(e,o.items))}function s0(e,o){return is(o)?BigInt(o.exclusiveMinimum)+BigInt(1):as(o)?BigInt(o.minimum):BigInt(0)}function i0(e,o){return!1}function a0(e,o){let i=Wr(e,o.instanceType);return class{constructor(){Object.assign(this,i)}}}function u0(e,o){return Wr({...e,...o.$defs},pn(o.$ref))}function c0(e,o){return Wr(e,Pn(o))}function m0(e,o){let i=Wr(e,o.returnType);return()=>i}function p0(e,o){return is(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:as(o)?o.minimum:0}function l0(e,o){let i=Mo(e,o),u=Pn(i);return Wr(e,u)}function d0(e,o){return o.const}function f0(e,o){throw new fs(o,"Cannot create TNever types")}function h0(e,o){return null}function g0(e,o){return is(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:as(o)?o.minimum:0}function y0(e,o){return(Bt(o.required)?[]:o.required).reduce((u,m)=>({...u,[m]:Wr(e,o.properties[m])}),{})}function x0(e,o){if(xa(o)&&!To(o))throw new fs(o,"Record with the minProperties constraint must have a default annotation");return{}}function I0(e,o){return pe(e,o.$ref)?Wr(e,e[o.$ref]):(()=>{throw new fs(o,"Unable to deref Ref")})()}function b0(e,o){if((Ia(o)||ga(o))&&!To(o))throw Error("Strings with format or pattern constraints must specify default");let u=ya(o)?o.minLength:0;return"".padEnd(u)}function E0(e,o){return Symbol()}function S0(e,o){let i=qu(o.pattern);if(cn(i))throw new fs(o,"Unable to create TemplateLiteral due to infinite type expansion");return Wr(e,i)}function w0(e,o){return Array.from({length:o.minItems},(i,u)=>Wr(e,o.items[u]))}function T0(e,o){return}function R0(e,o){if(M(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Wr(e,o.anyOf[0])}function k0(e,o){return}function Wr(e,o){return To(o)?n0(e,o):St(o)?o0(e,o):go(o)?s0(e,o):Vn(o)?i0(e,o):zr(o)?a0(e,o):Xt(o)?u0(e,o):un(o)?c0(e,o):en(o)?m0(e,o):yn(o)?p0(e,o):Ge(o)?l0(e,o):dt(o)?d0(e,o):ho(o)?f0(e,o):Ts(o)?h0(e,o):Pr(o)?g0(e,o):He(o)?y0(e,o):Kt(o)?x0(e,o):Ft(o)?I0(e,o):cn(o)?b0(e,o):Rs(o)?E0(e,o):tr(o)?S0(e,o):ct(o)?w0(e,o):ss(o)?T0(e,o):be(o)?R0(e,o):yo(o)?k0(e,o):void 0}function Os(...e){let[o,i]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Wr(o,i)}class dl extends ba{constructor(e,o){super("Parse",e,o)}}function YU(e,o,i){if(!Yt(e,o,i))throw new dl(i,Ms(e,o,i));return i}var A0=uu([(e,o,i)=>Gr(i),(e,o,i)=>zs(e,o,i),(e,o,i)=>ds(e,o,i),(e,o,i)=>Lo(e,o,i),(e,o,i)=>YU(e,o,i)]);var eB=l({type:s("insert"),path:a(),value:Ar()}),tB=Object({type:s("update"),path:a(),value:Ar()}),rB=l({type:s("delete"),path:a()}),D_e=g([eB,tB,rB]);class fl{constructor(e,o){this.hasCodec=Nh(e,o),this.buildResult=ul(e,o),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(Bo().correctiveParse)return A0(this.Context(),this.Type(),e);throw new dl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Ms(this.Context(),this.Type(),e)}Clean(e){return Lo(this.Context(),this.Type(),e)}Convert(e){return ds(this.Context(),this.Type(),e)}Create(){return Os(this.Context(),this.Type())}Default(e){return zs(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Oh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?_h(this.Context(),this.Type(),e):this.Parse(e)}}function qh(...e){let[o,i]=kn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return new fl(o,i)}var C0=new WeakMap,sB=Symbol.for("TypeBox.Kind");function iB(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function aB(e,o){switch(o){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function Fh(e){try{return v0(e)}catch{return}}function uB(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let 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 cB(e,o){let i=o.properties,u=new Set(i?Object.keys(i):[]);if(i)for(let[m,p]of Object.entries(i)){if(!(m in e))continue;e[m]=Sa(e[m],p)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[m,p]of Object.entries(e)){if(u.has(m))continue;e[m]=Sa(p,o.additionalProperties)}}function mB(e,o){if(Array.isArray(o.items)){for(let i=0;i<e.length;i++){let u=o.items[i];if(!u)continue;e[i]=Sa(e[i],u)}return}if(o.items&&typeof o.items==="object")for(let i=0;i<e.length;i++)e[i]=Sa(e[i],o.items)}function $0(e,o){for(let i of o)if(Fh(i)?.Check(e))return e;for(let i of o){let u=structuredClone(e),m=Sa(u,i);if(Fh(i)?.Check(m))return m}return e}function Sa(e,o){let i=e;if(Array.isArray(o.allOf))for(let p of o.allOf)i=Sa(i,p);if(Array.isArray(o.anyOf))i=$0(i,o.anyOf);if(Array.isArray(o.oneOf))i=$0(i,o.oneOf);let u=iB(o),m=u.length>1&&u.some((p)=>aB(i,p));if(u.length>0&&!m)for(let p of u){let f=uB(i,p);if(f!==i){i=f;break}}if(u.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))cB(i,o);if(u.includes("array")&&Array.isArray(i))mB(i,o);return i}function hl(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let m=0;m<e.length;m++){let p=o.items[m];if(p)hl(e[m],p)}else if(o.items)for(let m of e)hl(m,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let i=e,u=new Set(o.required??[]);for(let[m,p]of Object.entries(o.properties)){if(!(m in i))continue;if(i[m]===null&&!u.has(m)&&typeof p.$ref!=="string"&&Fh(p)?.Check(null)===!1)delete i[m];else hl(i[m],p)}}function v0(e){let o=e,i=C0.get(o);if(i)return i;let u=qh(e);return C0.set(o,u),u}function pB(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let m=e.instancePath.replace(/^\//,"").replace(/\//g,".");return m?`${m}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function lB(e,o){let i=e.find((u)=>u.name===o.name);if(!i)throw Error(`Tool "${o.name}" not found`);return cu(i,o)}function cu(e,o){let i=structuredClone(o.arguments);hl(i,e.parameters),ds(e.parameters,i);let u=v0(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(sB)){let f=Sa(i,e.parameters);if(f!==i)if(typeof i==="object"&&i!==null&&typeof f==="object"&&f!==null){for(let h of Object.keys(i))delete i[h];Object.assign(i,f)}else return u.Check(f)?f:i}if(u.Check(i))return i;let m=u.Errors(i).map((f)=>` - ${pB(f)}: ${f.message}`).join(`
34
+ `)||"Unknown validation error",p=`Validation failed for tool "${o.name}":
35
+ ${m}
36
+
37
+ Received arguments:
38
+ ${JSON.stringify(o.arguments,null,2)}`;throw Error(p)}var M0;function Uc(){if(!M0)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return M0}async function O0(e,o,i,u,m,p){let f=N0(o,e),h=[...f],x={...o,messages:[...o.messages,...f]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let I of f)await u({type:"message_start",message:I}),await u({type:"message_end",message:I});return await L0(x,h,i,m,u,p??Uc()),h}async function _0(e,o,i,u,m){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let p=[],f={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await L0(f,p,o,u,i,m??Uc()),p}async function L0(e,o,i,u,m,p){let f=e,h=i,x,I=!1,S=await h.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||S.length>0){let A=[];if(x){let J=await h.prepareNextTurn?.(x);if(J)f=J.context??f,A=J.messages??[],h={...h,model:J.model??h.model,reasoning:J.thinkingLevel===void 0?h.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(S.length===0)S=await h.getSteeringMessages?.()||[];await m({type:"turn_start"})}for(let J of N0(f,[...A,...S]))await m({type:"message_start",message:J}),await m({type:"message_end",message:J}),f.messages.push(J),o.push(J);S=[];let v=await h.prepareRequest?.({context:f,model:h.model,thinkingLevel:h.reasoning??"off"},u);if(v)f=v.context??f,h={...h,model:v.model??h.model,reasoning:v.thinkingLevel===void 0?h.reasoning:v.thinkingLevel==="off"?void 0:v.thinkingLevel};let _=await fB(f,h,u,m,p);if(o.push(_),_.stopReason==="error"||_.stopReason==="aborted"){x={message:_,toolResults:[],context:f,newMessages:o},await h.finishTurn?.(x,u),await m({type:"turn_end",message:_,toolResults:[]}),await m({type:"agent_end",messages:o});return}let Q=_.content.filter((J)=>J.type==="toolCall"),L=[];if(R=!1,Q.length>0){let J=_.stopReason==="length"?await hB(Q,m):await gB(f,_,h,u,m);L.push(...J.messages),R=!J.terminate;for(let Z of L)f.messages.push(Z),o.push(Z)}x={message:_,toolResults:L,context:f,newMessages:o};let z=await h.finishTurn?.(x,u);if(await m({type:"turn_end",message:_,toolResults:L}),z?.action==="end"){await m({type:"agent_end",messages:o});return}if(I=z?.action==="continue",S=await h.getSteeringMessages?.()||[],R||S.length>0)I=!1}let k=await h.getFollowUpMessages?.()||[];if(k.length>0){I=!1,S=k;continue}if(I){I=!1;continue}break}await m({type:"agent_end",messages:o})}function N0(e,o){let i=-1;for(let S=o.length-1;S>=0;S--)if(o[S].role==="system"){i=S;break}let u=o[i],m=u?o.map((S,R)=>R===i?jh(u,dB):S):o,p=ni(ae([...e.messages,...m]),(e.tools??[]).map(st)),f=p.toolsAdded.length===0&&p.toolsRemoved.length===0;if(u){if(f&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return m.map((S,R)=>R===i?jh(u,p):S)}if(f)return o;let h=jh({role:"system",content:"",timestamp:Date.now()},p),x=o.findIndex((S)=>S.role!=="system"),I=x===-1?o.length:x;return[...o.slice(0,I),h,...o.slice(I)]}var dB={toolsAdded:[],toolsRemoved:[]};function jh(e,{toolsAdded:o,toolsRemoved:i}){let{toolsAdded:u,toolsRemoved:m,...p}=e;return{...p,...o.length>0?{toolsAdded:o}:{},...i.length>0?{toolsRemoved:i}:{}}}async function fB(e,o,i,u,m){let p=e.messages;if(o.transformContext)p=await o.transformContext(p,i);let f=await o.convertToLlm(p),h=bt({messages:f}),x=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,I=await m(o.model,h,{...o,apiKey:x,signal:i}),S=async()=>Object.assign(await I.result(),{thinkingLevel:o.reasoning??"off"}),R=null,k=!1;for await(let v of I)switch(v.type){case"start":R=v.partial,e.messages.push(R),k=!0,await u({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=v.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:v,message:{...R}});break;case"done":case"error":{let _=await S();if(k)e.messages[e.messages.length-1]=_;else e.messages.push(_);if(!k)await u({type:"message_start",message:{..._}});return await u({type:"message_end",message:_}),_}}let A=await S();if(k)e.messages[e.messages.length-1]=A;else e.messages.push(A),await u({type:"message_start",message:{...A}});return await u({type:"message_end",message:A}),A}async function hB(e,o){let i=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let m={toolCall:u,result:Js(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Bc(m,o);let p=Uh(m);await Bh(p,o),i.push(p)}return{messages:i,terminate:!1}}async function gB(e,o,i,u,m){let p=o.content.filter((h)=>h.type==="toolCall"),f=p.some((h)=>e.tools?.find((x)=>x.name===h.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||f)return yB(e,o,p,i,u,m);return xB(e,o,p,i,u,m)}async function yB(e,o,i,u,m,p){let f=[],h=[];for(let x of i){await p({type:"tool_execution_start",toolCallId:x.id,toolName:x.name,args:x.arguments});let I=await q0(e,o,x,u,m),S;if(I.kind==="immediate")S={toolCall:x,result:I.result,isError:I.isError};else{let k=await j0(I,m,F0(x,p));S=await U0(e,o,I,k,u,m)}await Bc(S,p);let R=Uh(S);if(await Bh(R,p),f.push(S),h.push(R),m?.aborted)break}return{messages:h,terminate:D0(f)}}async function xB(e,o,i,u,m,p){let f=[];for(let I of i){await p({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let S=await q0(e,o,I,u,m);if(S.kind==="immediate"){let R={toolCall:I,result:S.result,isError:S.isError};if(await Bc(R,p),f.push(R),m?.aborted)break;continue}if(f.push(async()=>{if(m?.aborted){let A={toolCall:I,result:Js("Operation aborted"),isError:!0};return await Bc(A,p),A}let R=await j0(S,m,F0(I,p)),k=await U0(e,o,S,R,u,m);return await Bc(k,p),k}),m?.aborted)break}let h=await Promise.all(f.map((I)=>typeof I==="function"?I():Promise.resolve(I))),x=[];for(let I of h){let S=Uh(I);await Bh(S,p),x.push(S)}return{messages:x,terminate:D0(h)}}function D0(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function IB(e,o){if(!e.prepareArguments)return o;let i=e.prepareArguments(o.arguments);if(i===o.arguments)return o;return{...o,arguments:i}}async function q0(e,o,i,u,m,p=e.tools??[]){let f=p.find((h)=>h.name===i.name);if(!f)return{kind:"immediate",result:Js(`Tool ${i.name} not found`),isError:!0};try{let h=IB(f,i),x=cu(f,h);if(u.beforeToolCall){let I=await u.beforeToolCall({assistantMessage:o,toolCall:i,args:x,context:e},m);if(m?.aborted)return{kind:"immediate",result:Js("Operation aborted"),isError:!0};if(I?.block){let S=Js(I.reason||"Tool execution was blocked");if(I.terminate===!0)S.terminate=!0;return{kind:"immediate",result:S,isError:!0}}}if(m?.aborted)return{kind:"immediate",result:Js("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:f,args:x}}catch(h){return{kind:"immediate",result:Js(h instanceof Error?h.message:String(h)),isError:!0}}}function F0(e,o){return(i)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function j0(e,o,i){let u=[],m=!0,p=performance.now(),f=()=>Math.round(performance.now()-p);try{let h=await e.tool.execute(e.toolCall.id,e.args,o,(I)=>{if(!m)return;u.push(Promise.resolve(i(I)))}),x=f();return m=!1,await Promise.all(u),{result:h,isError:h.isError===!0,durationMs:x}}catch(h){let x=f();return m=!1,await Promise.all(u),{result:Js(h instanceof Error?h.message:String(h)),isError:!0,durationMs:x}}finally{m=!1}}async function U0(e,o,i,u,m,p){let{result:f,isError:h}=u;if(m.afterToolCall)try{let x=await m.afterToolCall({assistantMessage:o,toolCall:i.toolCall,args:i.args,result:f,isError:h,context:e},p);if(x){let I=x.structuredContent??(x.content?void 0:f.structuredContent);if(f={...f,content:x.content??f.content,details:x.details??f.details,usage:x.usage??f.usage,terminate:x.terminate??f.terminate},I===void 0)delete f.structuredContent;else f.structuredContent=I;h=x.isError??h}}catch(x){f=Js(x instanceof Error?x.message:String(x)),h=!0}return{toolCall:i.toolCall,result:f,isError:h,durationMs:u.durationMs}}function Js(e){return{content:[{type:"text",text:e}],details:{}}}async function Bc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function Uh(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs},timestamp:Date.now()}}async function Bh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function bB(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var EB={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},SB={id:"unknown",name:"unknown",api:"unknown",provider:"unknown",baseUrl:"",reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function wB(e){let o=e?.tools?.slice()??[],i=e?.messages?.slice()??[],u=no(e?.systemPrompt,o.map(st));if(i[0]?.role!=="system"&&u)i.unshift(u);return{get systemPrompt(){return ri(i)},model:e?.model??SB,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(m){o=m.slice()},get messages(){return i},set messages(m){i=m.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class Gh{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class Kh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let o=e??{};this._state=wB(o.initialState),this.convertToLlm=o.convertToLlm??bB,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Uc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new Gh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new Gh(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=on(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let i=this.normalizePromptInput(e,o);await this.runPromptMessages(i)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(o&&o.length>0)i.push(...o);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(i)=>{await O0(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await _0(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,i=()=>{},u=new Promise((m)=>{i=m});this.activeRun={promise:u,resolve:i,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(m){await this.handleRunFailure(m,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:EB,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,o)}}var gl=Symbol("basalt.rebind-fetch");function Pe(e,...o){return Object.assign(e,{aliases:o})}function wa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function TB(e){let o=[],i="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(i)o.push(i);i="";continue}if(u>="A"&&u<="Z"&&i&&!/[A-Z]$/.test(i))o.push(i),i="";i+=u}if(i)o.push(i);return o}function B0(e,o){if(e.some((v)=>v.name===o))return o;let i=e.map((v)=>v.name),u=(v)=>i.filter((_)=>wa(_)===v),m=u(wa(o));if(m.length===1&&m[0])return m[0];if(m.length>1)return o;let p=o.split(/[.:/]/).pop()??o,f=p===o?[]:u(wa(p));if(f.length===1&&f[0])return f[0];let h=new Map;for(let v of e)for(let _ of v.aliases??[]){let Q=wa(_);h.set(Q,(h.get(Q)??new Set).add(v.name))}let x=(v)=>[...new Set([...u(v),...h.get(v)??[]])],I=x(wa(p));if(I.length===1&&I[0])return I[0];if(I.length>1)return o;let S=TB(p),R=new Set;S.forEach((v,_)=>{R.add(wa(v));let Q=S[_+1];if(Q)R.add(wa(v+Q))});let k=new Set;for(let v of R)for(let _ of x(v))k.add(_);let A=[...k];return A.length===1&&A[0]?A[0]:o}function E(e){return e}function Tn(e,o){let i=o.indexOf("/");if(i<=0)return;return e.getModel(o.slice(0,i),o.slice(i+1))}function ot(e){return`${e.provider}/${e.id}`}function K0(e,o,i){let u=async(p,f)=>{try{if(o){let x=p instanceof Request?p:void 0;o({at:Date.now(),method:f?.method??x?.method??"GET",url:typeof p==="string"?p:p instanceof URL?p.toString():p.url,headers:G0(f?.headers??x?.headers),body:RB(f?.body!==void 0?f.body:x?.body??void 0)})}}catch{}let h=await e(p,f);if(i)try{let x=Date.now(),{status:I,statusText:S}=h,R=G0(h.headers);if(!h.body)return i({at:x,status:I,statusText:S,headers:R,body:""}),h;let k="",A=new TextDecoder,v=new TransformStream({transform(L,z){z.enqueue(L),k+=A.decode(L,{stream:!0}),i({at:x,status:I,statusText:S,headers:R,body:k})},flush(){k+=A.decode(),i({at:x,status:I,statusText:S,headers:R,body:k})}}),_=h.body.pipeThrough(v),Q=new Response(_,h);try{Object.defineProperty(Q,"url",{value:h.url})}catch{}return Q}catch{}return h},m=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:m,[gl]:(p)=>K0(p,o,i)})}function G0(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,m)=>{o[m]=u}),o;let i=Array.isArray(e)?e:Object.entries(e);for(let u of i)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function RB(e){if(e===void 0||e===null)return"";if(typeof e==="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e))return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));return`<${typeof e==="object"&&typeof e.constructor==="function"?e.constructor.name:typeof e}: \u975E\u6587\u672C\u8BF7\u6C42\u4F53\uFF0C\u672A\u8BB0\u5F55\u539F\u6587>`}function kB(e,o){return B0(e,o)}function AB(e,o,i){let u=Date.now(),m=new WeakSet,p=(x)=>{if(!x||typeof x!=="object"||!("role"in x)||x.role!=="assistant")return;let I=Date.now(),S=Math.max(10,I-u);x.generationMs=S},f=async(x)=>{if(!i||!x||typeof x!=="object"||!("role"in x)||x.role!=="assistant")return;if(p(x),m.has(x))return;m.add(x),Object.assign(x,await i(x))},h=(x)=>{let I=x?.content;if(!Array.isArray(I))return;for(let S of I)if(S&&S.type==="toolCall"&&typeof S.name==="string")S.name=kB(o(),S.name)};return{async*[Symbol.asyncIterator](){for await(let x of e){let{partial:I,message:S}=x;h(I),await f(S),h(S),yield x}},result:async()=>{let x=await e.result();return p(x),await f(x),h(x),x}}}function Gc(e,o){let i=(o??[]).filter((h)=>h.kind==="path").map((h)=>`<file path=${JSON.stringify(h.data)} />`),u=(o??[]).filter((h)=>h.kind==="text").map((h)=>`<file name=${JSON.stringify(h.name)}>
39
+ ${h.data}
40
+ </file>`),m=(o??[]).filter((h)=>h.kind==="image").map((h)=>({type:"image",data:h.data,mimeType:h.mimeType})),p=(o??[]).filter((h)=>h.kind==="image"&&h.id).map((h)=>`<image id=${JSON.stringify(h.id)} name=${JSON.stringify(h.name)} />`);return{merged:[...i,...u,...p,...e.trim()?[e]:[]].join(`
41
+
42
+ `),images:m}}function Hh(e,o){let{merged:i,images:u}=Gc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:i},...u]:i,timestamp:Date.now()}}function H0(e){let o=new Set;for(let h of e.tools){let x=h.name.toLowerCase();if(o.has(x))throw Error(`Tool names collide ignoring case: ${h.name}`);o.add(x)}let i=new Kh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(h,x,I)=>{let{captureRequest:S,captureResponse:R}=e,k=S||R?{...I,fetch:K0(I?.fetch??globalThis.fetch,S?(v)=>S({...v,model:ot(h)}):void 0,R?(v)=>R({...v,model:ot(h)}):void 0)}:I,A=h.api==="openai-completions"||h.api==="openai-responses"?{...h,compat:{...h.compat,supportsDeveloperRole:!1}}:h;return AB(e.models.streamSimple(A,x,k),()=>i.state.tools,e.hooks.response)},convertToLlm:(h)=>h,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:h,model:x})=>{let I=h.messages.findIndex((A)=>A.role!=="system"),S=h.messages.slice(0,I===-1?h.messages.length:I),R=e.hooks.prepare,k=e.hooks.tools?.()??h.tools;if(k){i.state.tools=k;let A=S[0];if(A?.role==="system")S[0]={...A,toolsAdded:k.map(st),toolsRemoved:void 0}}return{context:{...h,tools:k,messages:await R(S,k,x)}}}:void 0}),u=new Map,m=new Map,p=new WeakSet,f;return i.subscribe((h)=>{if(h.type==="message_update"&&h.message.role==="assistant"){m.clear(),e.hooks.draft(W0(h.message));return}if(h.type==="tool_execution_update"){let I=u.get(h.toolCallId)??We(h.toolName,h.args),S=Array.isArray(h.partialResult?.content)?h.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";m.set(h.toolCallId,{type:"tool_call",id:h.toolCallId,name:I.name,input:I.input,...I.source?{source:I.source}:{},output:S}),e.hooks.draft([...m.values()]);return}if(h.type==="tool_execution_end"){if(m.delete(h.toolCallId))e.hooks.draft(m.size>0?[...m.values()]:null);return}if(h.type!=="message_end")return;if(p.has(h.message)){e.steerConsumed?.(h.message);return}let x=h.message.role==="user"&&f?{type:"user",text:f.text,...f.attachments?.length?{attachments:f.attachments}:{}}:PB(h.message);if(h.message.role==="user")f=void 0;if(x?.type==="assistant"){for(let I of x.parts)if(I.type==="tool_call")u.set(I.id,I)}if(x?.type==="tool_result"){let I=u.get(x.callID);if(I?.source)Object.assign(x,{name:I.name,source:I.source})}if(x)e.hooks.message(x,h.message);if(h.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(h,x)=>{f={text:h,attachments:x};let{merged:I,images:S}=Gc(h,x);return i.prompt(I,S.length>0?S:void 0)},retry:async()=>{let h=i.state.messages;if(h.at(-1)?.role==="assistant")i.state.messages=h.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(h)=>{p.add(h),i.steer(h)},unsteer:(h)=>{let I=i.steeringQueue?.messages;if(!I)return!1;let S=I.indexOf(h);if(S<0){let k=JSON.stringify(h);S=I.findIndex((A)=>JSON.stringify(A)===k)}if(S<0)return!1;let[R]=I.splice(S,1);if(R)p.delete(R);return!0},abort:()=>i.abort()}}function Wh(e){if(e?.role!=="assistant")return{reason:"done"};if(e.stopReason==="aborted")return{reason:"aborted"};if(e.stopReason==="error")return{reason:"error",error:e.errorMessage};return{reason:"done"}}function yl(e,o="\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"){let{name:i,source:u}=We(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:i,...u?{source:u}:{},output:o,isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:o}],isError:!0,timestamp:Date.now()}}}function W0(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...We(o.name,o.arguments)}})}function PB(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:W0(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class ht extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function C(e){return e}import{createHash as z0}from"crypto";import{existsSync as CB}from"fs";import{readFile as V0,realpath as xl}from"fs/promises";import{dirname as $B,isAbsolute as J0,relative as Q0,resolve as X0,sep as Y0}from"path";var Z0=[...ty];class Il extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class bl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let i=$B(X0(e)),u=X0(i,o??"web.tsx");if(!o&&!CB(u))return;let m=Q0(await xl(i),await xl(u));if(J0(m)||m===".."||m.startsWith(`..${Y0}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let i=this.pending.get(e);if(i)return i;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let i=this.cache.get(e);if(i){let I=!0;for(let[S,R]of i.inputs){let k=await V0(S).catch(()=>{return});if(!k||z0("sha256").update(k).digest("hex")!==R){I=!1;break}}if(I)return i.source;this.cache.delete(e)}let u=await xl(o),m=new Map,p=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:Z0,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(I){I.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(S)=>{if(!Z0.includes(S.path))throw Error(`Unsupported shared web import: ${S.path}`);return{path:S.path,external:!0}}),I.onLoad({filter:/.*/},async(S)=>{let R=Q0(u,await xl(S.path));if(J0(R)||R===".."||R.startsWith(`..${Y0}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await V0(S.path);m.set(S.path,z0("sha256").update(k).digest("hex"));return})}}]}).catch((I)=>{let R=(I instanceof AggregateError?I.errors:[I]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:I})});if(!p.success)throw new Il(p.logs.filter((I)=>I.level==="error").map((I)=>({file:I.position?.file??null,line:I.position?.line??null,message:I.message})));let f=p.outputs.find((I)=>I.kind==="entry-point"&&I.path.endsWith(".js")),h=p.outputs.find((I)=>I.path.endsWith(".css"));if(!f||p.outputs.some((I)=>I!==f&&I!==h))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let x=await f.text();return this.cache.set(e,{source:x,css:await h?.text(),inputs:m}),x}}function No(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function _s(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function El(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
43
+
44
+ `)}function mu(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function pu(e){return e.role==="assistant"&&e.content.length>0}function Po(e){let o=[],i=new Map,u=0;for(let m of e){let p=m.raw;if(p.role==="assistant"){if(pu(p))u++;for(let f of p.content){if(f.type!=="toolCall")continue;let h={call:f,step:u,message:p};o.push(h),i.set(f.id,h)}}else if(p.role==="toolResult"){let f=i.get(p.toolCallId);if(f)f.result=p}}return o}var Sl=new Set(["edit","write"]),e$=new Set(["grep","glob"]);function po(e,o){let i=We(e.name,e.arguments).input?.[o];return typeof i==="string"?i:void 0}function t$(e){return[...new Set(Po(e).flatMap((o)=>Sl.has(We(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&po(o.call,"path")?[po(o.call,"path")]:[]))]}function zh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function wl(e){let o=[{source:"ASSISTANT_TOOL",text:`${We(e.call.name,e.call.arguments).name}(${No(We(e.call.name,e.call.arguments).input)}) [${zh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:mu(e.result)});return o}function F(e){let o=0,i=0,u=0;for(let m of e){let p=m.codePointAt(0);if(p<=127)o++;else if(p>=19968&&p<=40959||p>=12288&&p<=12351||p>=65280&&p<=65519||p>=131072&&p<=173791)i++;else u++}return Math.max(0,Math.ceil(o/4+i+u/2))}var Vh=8192;function q(e){let o=e,i=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let m of o.content)if(m.type==="text")u+=m.text;else i++;else if(o.role==="assistant")for(let m of o.content)if(m.type==="text")u+=m.text;else if(m.type==="thinking")u+=m.thinking;else u+=`${m.name}${No(m.arguments)}`;else if(o.role==="toolResult")for(let m of o.content)if(m.type==="text")u+=m.text;else i++;else u=No(e);return F(u)+16+i*Vh}function ki(e=[]){return e.reduce((o,i)=>o+F(i.name+i.description+No(i.parameters))+16,0)}function Fn(e,o){let i=e.replace(/\s+/g," ").trim();if(F(i)<=o)return i;let u=Math.min(i.length,o*4);while(u>0&&F(i.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${i.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Co(e,o,i=Number.POSITIVE_INFINITY){if(F(e)<=o&&e.length<=i)return e;let u=`
45
+ [... omitted; use history tools for the full text ...]
46
+ `,m=Math.floor((o-F(u))/2);if(m<=0)return"";let p=(f)=>{let h=0,x=Math.max(0,Math.min(e.length,m*4,Math.floor((i-u.length)/2)));while(h<x){let I=Math.ceil((h+x)/2),S=f?e.slice(-I):e.slice(0,I);if(F(S)<=m)h=I;else x=I-1}if(!h)return"";return f?e.slice(-h).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,h).replace(/[\uD800-\uDBFF]$/,"")};return`${p(!1)}${u}${p(!0)}`}function Tl(e,o){if(F(e.join(`
47
+ `))<=o)return e;let i=(S)=>`- [... ${S} steps omitted; use history tools for the full text ...]`,u=o-F(i(e.length)),m=[],p=[],f=0,h=0,x=e.length-1;while(h<=x){let S=m.length<=p.length,R=S?e[h]:e[x],k=F(`${R}
48
+ `);if(f+k>u)break;if(f+=k,S)m.push(e[h++]);else p.unshift(e[x--])}let I=x-h+1;return[...m,...I>0?[i(I)]:[],...p]}function Qs(e){let o=[],i;for(let u of e){let m=u.entry;if(m.type==="run"&&m.state==="start"){i={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(i);continue}if(m.type==="run"&&m.state==="end"){if(i)i.end=m.seq,i.status=vB(m.reason,i.records);i=void 0;continue}if(m.type==="extension"||!u.raw)continue;if(!i&&m.type==="user"&&m.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!i)i={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(i);i.records.push(u)}for(let u of o)u.records=Jh(u.records);return o}function Jh(e){if(e.length<=1)return[...e];let o=[],i=[],u=new Set;for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;let f=p.raw?.role;if(f==="assistant"){let x=p.raw.content?.filter((I)=>I.type==="toolCall")??[];if(x.length>0)for(let I of x)u.add(I.id);if(o.push(p),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(f==="toolResult"){let h=p.raw;if(h.toolCallId)u.delete(h.toolCallId);if(o.push(p),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(f==="user"){if(o.length===0){o.push(p);continue}let h=e.slice(m+1).some((x)=>x.raw?.role==="assistant");if(u.size>0||h){i.push(p);continue}o.push(p);continue}o.push(p)}if(i.length>0)o.push(...i);return o}function vB(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&ha(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ha(i)?"interrupted":"failed";default:return"interrupted"}}function Ta(e){for(let o=e.length-1;o>=0;o--){let i=e[o]?.entry;if(i?.type==="compaction")return i.through}return 0}function Rl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((i)=>i.entry.seq<=o)}function Qh(e,o){return e.find((i)=>i.start<o&&!Rl(i,o)&&i.records.some((u)=>u.entry.seq<=o))}function lu(e){let o=Ta(e),u=Qs(e).findLast((m)=>m.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function kl(e){let o=Ta(e);return Qh(Qs(e),o)?.end}function Kc(e,o){let i=Ta(e),u=Qs(e).at(-1);if(!u||u.end!==void 0)return;let m=u.records.filter((S)=>S.entry.seq>i),p=[],f=new Set;for(let S of m){let R=S.raw,k=q(S.raw);if(R.role==="assistant"){for(let A of R.content)if(A.type==="toolCall")f.add(A.id)}else if(R.role==="toolResult")f.delete(R.toolCallId);if(pu(R)||!p.length||R.role==="user"&&p.at(-1)?.assistant)p.push({end:S.entry.seq,tokens:k,assistant:pu(R),pending:f.size});else{let A=p.at(-1);A.end=S.entry.seq,A.tokens+=k,A.pending=f.size}}let h=p.findLastIndex((S)=>S.assistant),x=0,I;for(let S=p.length-1;S>=0;S--){let R=p[S];if(S<h&&R.assistant&&R.pending===0&&(x<=o||I===void 0))I=R.end;if(x+=R.tokens,x>o&&I!==void 0)break}if(x<=o)return;return I}var r$=2000;function Ai(e,o){let i=F(o);if(i<=r$)return o;let u=new TextEncoder().encode(o).length,m=o.split(`
49
+ `).length,p=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${m} lines, approximately ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
50
+ `),f="</user-text-reference>",h=r$-F(`${p}
51
+
52
+ ${f}`);if(h<=0)return o;let x=`${p}
53
+ ${Co(o,h,o.length-p.length-f.length-3)}
54
+ ${f}`;return x.length<o.length&&F(x)<i?x:o}function n$(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let m=Ai(e.entry.seq,o.content);return m===o.content?o:{...o,content:m}}let i=!1,u=o.content.map((m)=>{if(m.type!=="text")return m;let p=Ai(e.entry.seq,m.text);if(p!==m.text)i=!0;return p===m.text?m:{...m,text:p}});return i?{...o,content:u}:o}function Xh(e,o=!1){let i=e.records.filter((A)=>A.entry.type==="user"&&!A.entry.notices&&A.raw.role==="user"),u=i.flatMap((A)=>{let v=A.raw.content;return typeof v==="string"?[]:v.filter((_)=>_.type==="image")}),m=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,p=e.status==="open"?"interrupted":e.status,f="";if(i.length){let A=o?Co(i.map((v)=>_s(v.raw)).join(`
55
+
56
+ `),600):i.map((v,_)=>`<user-message sequence="${_+1}">
57
+ ${Ai(v.entry.seq,_s(v.raw))}
58
+ </user-message>`).join(`
59
+
60
+ `);f=[`<chunk-input id="${e.id}" status="${p}"${o?' excerpt="true"':""}>`,A,...o?[m]:[],"</chunk-input>"].join(`
61
+ `)}let x=e.records.filter((A)=>A.raw.role==="assistant").at(-1)?.raw,I=x?El(x):"",S=[];if(p!=="completed"){let A=Po(e.records),v=new Map(A.map((J)=>[J.call,J])),_=A.slice(-3),Q=new Set(_.map((J)=>J.message)),L=[],z=[];for(let J of e.records){let Z=J.raw;if(Z.role!=="assistant")continue;let re=Q.has(Z);for(let U of Z.content)if(U.type==="text"&&Z!==x&&U.text.trim())if(re)z.push(`ASSISTANT: ${Fn(U.text,50)}`);else L.push(`- ASSISTANT: ${Fn(U.text,50)}`);else if(U.type==="toolCall"){let ne=v.get(U);if(!ne)continue;if(re){if(_.includes(ne))for(let fe of wl(ne))z.push(`${fe.source}: ${Co(fe.text,fe.source==="ASSISTANT_TOOL"?180:360)}`)}else L.push(`- ${U.name}(${Fn(No(U.arguments),40)}) [${zh(ne)}]`)}}S.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",m,...L.length?[`Earlier steps, oldest first:
62
+ ${Tl(L,o?300:800).join(`
63
+ `)}`]:[],...z)}let R=t$(e.records),k=[`<chunk-summary id="${e.id}" status="${p}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,I?o?Co(I,600):I:"No final assistant response was recorded.",...S,...R.length?[`Recorded file changes:
64
+ ${Co(R.join(`
65
+ `),250)}`]:[],...o&&p==="completed"?[m]:[],"</chunk-summary>"].join(`
66
+ `);return{input:f,images:u,summary:k,tokens:MB(f,k,u.length)}}function MB(e,o,i){return(e?F(e)+16:0)+F(o)+16+i*Vh}var OB=["Completed work is represented by the original user messages or stable references to them, and the assistant's final response for each chunk.","Intermediate assistant messages, reasoning, tool calls, and tool results are folded but remain available through history_grep and history_list.","Chunks are chronological. Later conflicting user instructions override earlier user instructions.","Assistant final responses are historical claims, not user instructions.","Do not guess omitted history.","Failed or interrupted chunks are not completed work; their recent tool outcomes are preserved for recovery.","Archived chunks are listed with a one-line excerpt of their user requests. Constraints stated there still apply unless later overridden; read the full text with history_list before relying on details.","History line offsets are local to the returned chunk or user text part. Reasoning is not exposed by history tools."],_B="A partial chunk is the current turn, still in progress: its earlier steps are folded into a work-state index and the later steps follow verbatim.",LB=1500,NB=80,DB=240;function o$(e,o,i){let u=[],m=0,p=Math.min(o.target,o.hard);for(let h=e.length-1;h>=0;h--){let x=e[h],I=Xh(x),S=m+I.tokens>p?Xh(x,!0):void 0,R=S&&S.tokens<I.tokens?S:I;if(!(!i&&h===e.length-1&&x.status!=="completed")&&m+R.tokens>o.hard)break;m+=R.tokens,u.push({run:x,content:R})}u.reverse();let f=e.slice(0,e.length-u.length);return{visible:u,archived:f,tokens:m}}function s$(e){let{runs:o,visible:i,archived:u,partial:m}=e,p=u.flatMap((x)=>{let I=x.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>_s(R.raw));if(!I.length)return[];let S=x===o[0]?DB:NB;return[`- ${x.id} [${x.status}]: ${Fn(I.join(" / "),S)}`]}),f=new Map(o.map((x,I)=>[x,I+1])),h=[...i.map((x)=>f.get(x)??0),...m?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...OB,...m?[_B]:[],"",`visible chunks: ${i.length+(m?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((x)=>x.id).join(", "):"none"}`,`visible sequences: ${h.length?`${h[0]}..${h.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...p.length?["archived requests, oldest first:",Co(p.join(`
67
+ `),LB)]:[],"</conversation-checkpoint>"].join(`
68
+ `)}function i$(e,o){let i=e.split(`
69
+ `),u=o.split(`
70
+ `),m=new Set(i),p=new Set(u),f=[...i.filter((x)=>x.trim()&&!p.has(x)).map((x)=>`- ${Fn(x,40)}`),...u.filter((x)=>x.trim()&&!m.has(x)).map((x)=>`+ ${Fn(x,40)}`)],h=i.find((x)=>x.trim()&&p.has(x));return[...f.slice(0,6),...f.length>6?[`\u2026 ${f.length-6} more changed lines`]:[],...h&&f.every((x)=>x.startsWith("+"))?[`@ ${Fn(h,40)}`]:[]]}function Al(e,o){if(!o)return e;let i=o.endsWith("/")?o:`${o}/`;return e.startsWith(i)?e.slice(i.length):e}function qB(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((i)=>{let u=i&&typeof i==="object"?i.path:void 0;return typeof u==="string"?[u]:[]})}function FB(e,o){let i=po(e,"path");if(Sl.has(e.name)&&i)return`file:${Al(i,o)}`;let u=po(e,"command");if(u)return`command:${u}`;return`${e.name}:${No(e.arguments)}`}function jB(e,o){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let p of Po(e)){let f=u.get(p.step)??[];f.push(p),u.set(p.step,f)}let m=new Map;for(let p of e){let f=p.raw;if(!pu(f))continue;let h=++i.steps,x=El(f);if(x)i.narration.push({step:h,text:Fn(x,60)});for(let{call:I,result:S}of u.get(h)??[]){if(!S)continue;let R=We(I.name,I.arguments),k={...I,name:R.name,arguments:R.input},A=FB(k,o),v=mu(S);if(S.isError){let Z=po(k,"command"),re=Z?`${k.name} \`${Fn(Z,40)}\``:`${k.name} ${A.startsWith("file:")?A.slice(5):Fn(No(k.arguments),40)}`,U={step:h,key:A,what:re,detail:Co(v.trim().split(`
71
+ `).slice(0,8).join(`
72
+ `),200)};i.errors.push(U);let ne=m.get(A)??[];ne.push(U),m.set(A,ne);continue}for(let Z of m.get(A)??[])Z.resolved=h;m.delete(A);let _=po(k,"path");if(Sl.has(k.name)&&_){let Z=Al(_,o),re=i.files.get(Z)??{count:0,first:h,last:h,diffs:[]};if(re.count++,re.last=h,re.diffs.push({step:h,lines:k.name==="edit"?po(k,"old_string")!==void 0?i$(po(k,"old_string")??"",po(k,"new_string")??""):[]:i$("",po(k,"content")??"")}),re.diffs.length>3)re.diffs.shift();i.files.set(Z,re);continue}let Q=k.name==="read"?[..._?[_]:[],...qB(k)]:[];if(Q.length){for(let Z of Q){let re=Al(Z,o),U=i.reads.get(re)??[];U.push(h),i.reads.set(re,U)}continue}if(e$.has(k.name)){let Z=_?` in ${Al(_,o)}`:"",re=k.name==="grep"&&po(k,"glob")?` (${po(k,"glob")})`:"",U=`${k.name} ${po(k,"pattern")??""}${Z}${re}`.replace(/\s+/g," "),ne=i.searches.get(U)??{steps:[],head:""};ne.steps.push(h),ne.head=Fn(v.trim().split(`
73
+ `)[0]??"",25),i.searches.set(U,ne);continue}let L=po(k,"command");if(L){let Z=v.trim().split(`
74
+ `);i.commands.push({step:h,command:Fn(L,40),exit:"0",lines:Z.length,tail:Z.slice(-3).map((re)=>Fn(re,40))});continue}let z=`${k.name} ${Fn(No(k.arguments),40)}`,J=i.other.get(z)??[];J.push(h),i.other.set(z,J)}}return i}function a$(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Hc(e,o,i){let u=(I,S)=>S===void 0||!I.length?I:Tl(I,S),m=[`<work-state chunk="${o.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${o.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],p=[...e.files];m.push("",`## Modified files (${p.length})`),p.forEach(([I,S],R)=>{if(m.push(`- ${I}: ${S.count} change${S.count>1?"s":""} (step ${S.first}${S.last!==S.first?`-${S.last}`:""})`),R<p.length-i.diffFiles)return;for(let k of S.diffs)m.push(` step ${k.step}:`,...k.lines.map((A)=>` ${A}`))}),m.push("",`## Errors (${e.errors.length})`,...e.errors.map((I)=>I.resolved?`- step ${I.step} ${I.what} (resolved at step ${I.resolved})${i.lists===void 0?`: ${I.detail.replace(/\n/g,`
75
+ `)}`:""}`:`- step ${I.step} ${I.what} (UNRESOLVED): ${I.detail.replace(/\n/g,`
76
+ `)}`)),m.push("","## Steps",...u(e.narration.map((I)=>`- ${I.step}. ${I.text}`),i.narration));let f=[...e.reads].map(([I,S])=>`- ${I} @ ${S.join(",")}`);m.push("",`## Files read (${f.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(f,i.lists));let h=[...e.searches].map(([I,S])=>`- ${I} \u2192 ${S.head||"(no output)"} (${a$(S.steps)})`);m.push("",`## Searches (${h.length})`,...u(h,i.lists));let x=e.commands.map((I)=>[`- ${I.step}. \`${I.command}\` exit=${I.exit}, ${I.lines} output lines, last ${I.tail.length}:`,...I.tail.map((S)=>` ${S}`)].join(`
77
+ `));if(m.push("",`## Commands (${x.length})`,...u(x,i.lists)),e.other.size){let I=[...e.other].map(([S,R])=>`- ${S} (${a$(R)})`);m.push("",`## Other tool calls (${I.length})`,...u(I,i.lists))}return m.push("</work-state>"),m.join(`
78
+ `)}function Pl(e,o,i,u){let m=jB(e,u),p=Hc(m,o,{diffFiles:Number.POSITIVE_INFINITY});if(F(p)<=i)return p;let f={...m,narration:[]};for(let I of[Number.POSITIVE_INFINITY,20,10,5]){let S=F(Hc(f,o,{diffFiles:I}));if(S>i*0.7)continue;return Hc(m,o,{narration:Math.max(500,i-S),diffFiles:I})}let h=Math.max(300,Math.floor(i*0.1)),x=F(Hc(f,o,{diffFiles:0,lists:h}));return Hc(m,o,{narration:Math.max(500,i-x),diffFiles:0,lists:h})}function Cl(e){return{role:"user",content:e,timestamp:0}}function Yh(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function u$(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:Cl(e.input)}function du(e){let o=[];for(let i of e){let u=o.at(-1),m=i;if(u?.role==="user"&&m.role==="user"){let p=(f)=>typeof f.content==="string"?[{type:"text",text:f.content}]:f.content;o[o.length-1]={...m,content:[...p(u),{type:"text",text:`
79
+
80
+ `},...p(m)]};continue}o.push(i)}return o}function c$(e){let o=[],i=new Map;for(let u of e){let m=u;if(m.role==="toolResult"){if(!i.has(m.toolCallId))continue;let p=i.get(m.toolCallId);if(p===void 0)i.set(m.toolCallId,o.length),o.push(u);else o[p]=u;continue}if(m.role==="assistant"){if(i=new Map,m.stopReason!=="error"&&m.stopReason!=="aborted"){for(let p of m.content)if(p.type==="toolCall")i.set(p.id,void 0)}}else if(m.role==="user")i=new Map;o.push(u)}return o}function UB(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Me(e,o,i,u={}){let m=Ta(e),p=Qs(e),f=p.filter((Ee)=>Rl(Ee,m)),h=Qh(p,m),x=[],I=[],S=0;for(let Ee of p){if(Rl(Ee,m))continue;let ee=[];for(let ue of Ee.records){if(Ee===h&&ue.entry.seq<=m)continue;let $e=ue.raw.role==="user"?n$(ue):ue.raw;S+=q($e),x.push($e),ee.push($e)}if(u.inspect&&ee.length)I.push({id:`recent-${Ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Ee.id}`,tokens:ee.reduce((ue,$e)=>ue+q($e),0),detail:JSON.stringify(ee,UB,2)})}if(!f.length&&!h)return{items:I,messages:du(x),visible:0,archived:0,open:S,tokens:S,untrimmed:S};let R=o$(f,i,!!h),{visible:k,archived:A}=R,v=R.tokens,_=[],Q="",L="";if(h){let Ee=h.records.filter((ue)=>ue.entry.seq<=m),ee=Ee.filter((ue)=>ue.entry.type==="user"&&!ue.entry.notices&&ue.raw.role==="user");if(ee.length){Q=[`<chunk-input id="${h.id}" status="partial">`,...ee.map(($e,gt)=>`<user-message sequence="${gt+1}">
81
+ ${Ai($e.entry.seq,_s($e.raw))}
82
+ </user-message>`),"</chunk-input>"].join(`
83
+ `);let ue=ee.flatMap(($e)=>{let gt=$e.raw.content;return typeof gt==="string"?[]:gt.filter((Ke)=>Ke.type==="image")});_.push(ue.length?{role:"user",content:[{type:"text",text:Q},...ue],timestamp:0}:Cl(Q))}L=Pl(Ee,h,i.index,u.cwd),_.push(Yh(L,o))}let z=e.flatMap((Ee)=>{let ee=Ee.raw;if(Ee.entry.seq>m||ee?.role!=="toolResult"||ee.toolName!=="skill")return[];return[Cl(ee.content.filter((ue)=>ue.type==="text").map((ue)=>ue.text).join(`
84
+ `))]}),J="",Z=()=>{J=s$({runs:f,visible:k.map((ee)=>ee.run),archived:A,partial:!!h,tokens:v,budget:i});let Ee=[Cl(J)];for(let{content:ee}of k){if(ee.input)Ee.push(u$(ee));Ee.push(Yh(ee.summary,o))}return[...Ee,...z,..._]},re=(Ee)=>Ee.reduce((ee,ue)=>ee+q(ue),0),U=Z(),ne=re(U)+S,fe=ne,{trim:Re}=u;while(Re&&Re.fixed+ne>Re.limit){let Ee=h||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!Ee.length)break;let ee=0,ue=0;for(let $e of Ee)if(ue++,ee+=$e.content.tokens,ee>=Re.fixed+ne-Re.limit)break;A=[...A,...k.slice(0,ue).map(($e)=>$e.run)],k=k.slice(ue),v-=ee,U=Z(),ne=re(U)+S}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:q(U[0]),detail:J},...k.map(({run:Ee,content:ee})=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"sealed",tokens:(ee.input?q(u$(ee)):0)+q(Yh(ee.summary,o)),detail:[ee.input,ee.summary].filter(Boolean).join(`
85
+
86
+ `)})),...A.map((Ee)=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...h?[{id:h.id,label:`Chunk ${h.id}`,state:"folded",tokens:re(_),detail:[Q,L].filter(Boolean).join(`
87
+
88
+ `)}]:[],...I]:[],messages:du([...U,...x]),visible:k.length,archived:A.length,open:S,tokens:ne,untrimmed:fe}}function me(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Zh=0.97,BB=0.97,m$=0.5,GB=0.05,KB=20000,HB=24000;function Wc(e){return{target:KB,hard:HB,index:Math.floor(me(e)*GB)}}function eg(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class zc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,i=()=>{return}){this.records=e;this.fold=o;this.cwd=i}budget(e){return Wc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(me(e)*Zh/this.ratio)}prepare(e,o,i,u){let m=me(i),p=Wc(i),f=e.reduce((U,ne)=>U+q(ne),0)+ki(o),h=this.records().at(-1)?.entry.seq??0,x=()=>u?[...u,...this.records().filter((U)=>U.entry.seq>h)]:this.records(),I=()=>Me(x(),i,p,{cwd:this.cwd(),trim:{fixed:f,limit:Math.floor(m*Zh/this.ratio)}}),S=x().findLast((U)=>U.raw?.role==="assistant"),R=S?x().filter((U)=>U.entry.seq>S.entry.seq&&U.raw):[],k=S?.raw,A=()=>S!==void 0&&(S.entry.seq===this.reshapedAfter||x().some((U)=>U.entry.type==="compaction"&&U.entry.seq>S.entry.seq)),v=this.dueSeal(i);if(v!==void 0)this.fold(v,!1),this.reshapedAfter=S?.entry.seq??-1;let _=I(),Q=R.reduce((U,ne)=>U+q(ne.raw),0);if(this.lastEstimate===0&&S&&k&&!A()){let U=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,ne=f+_.untrimmed-q(k)-Q;if(U>0&&ne>0)this.ratio=Math.min(2,Math.max(0.5,U/ne))}let z=((U)=>{let ne=f+U.untrimmed,fe=f+U.tokens;return((S&&k&&!A()&&eg(k)>0?eg(k)+Math.round(this.ratio*Q):void 0)??Math.round(ne*this.ratio))-Math.round((ne-fe)*this.ratio)})(_);if(z>m*BB){let U=z-_.open*this.ratio,ne=Math.max(1000,Math.floor((m*m$-U-p.index)/this.ratio)),fe=S?.entry.seq??-1,Re=x().findLast(($e)=>$e.entry.type==="compaction"&&$e.entry.partial)?.entry.seq??-1,Ee=Math.max(this.lastFoldSeq,Re),ue=(Ee>0?x().filter(($e)=>$e.entry.seq>Ee&&$e.raw?.role==="assistant").length:999)<=1;if(!ue||this.consecutivePartialFolds<2){let $e=Kc(x(),ne);if($e!==void 0)this.fold($e,!0),this.reshapedAfter=fe,this.lastFoldSeq=fe,this.consecutivePartialFolds=ue?this.consecutivePartialFolds+1:1,_=I()}}else this.consecutivePartialFolds=0;this.lastEstimate=f+_.tokens;let J=_.messages,Z=f+_.tokens;if(Math.round(Z*this.ratio)>m)J=WB(J,Math.floor((m-f)/this.ratio)),Z=f+J.reduce((U,ne)=>U+q(ne),0);return this.lastEstimate=Z,{messages:du([...e,...J]),estimate:Z}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(kl(o)===void 0){let i=o.findLast((h)=>h.raw?.role==="assistant"),u=i?.raw,m=i!==void 0&&(i.entry.seq===this.reshapedAfter||o.some((h)=>h.entry.type==="compaction"&&h.entry.seq>i.entry.seq)),f=(i?o.filter((h)=>h.entry.seq>i.entry.seq&&h.raw):[]).reduce((h,x)=>h+q(x.raw),0);if(m||!u||eg(u)+f<Math.floor(me(e)*Zh))return}return lu(o)}recover(e){let o=me(e),i=Wc(e),u=Me(this.records(),e,i,{cwd:this.cwd()}),m=Math.floor((o*m$-(o-u.open*this.ratio)-i.index)/this.ratio),p=Kc(this.records(),m);if(p===void 0)return!1;return this.fold(p,!0),this.reshapedAfter=this.records().findLast((f)=>f.raw?.role==="assistant")?.entry.seq??-1,!0}}function WB(e,o){let i=e.reduce((m,p)=>m+q(p),0);if(i<=o)return e;let u=[];for(let m of e){let p=m;if(p.role!=="toolResult"||i<=o){u.push(m);continue}let f=q(m);if(f<=1500){u.push(m);continue}let h=Math.max(500,Math.floor(f/2)),x=p.content.map((R)=>{if(R.type!=="text")return R;return{...R,text:Co(R.text,h)}}),I={...p,content:x},S=q(I);i-=f-S,u.push(I)}return u}var zB=2000;function fu(e,o){let i=[];for(let u of o.replace(/\r\n/g,`
89
+ `).split(`
90
+ `))for(let m=0;m<Math.max(u.length,1);){let p=Math.min(u.length,m+zB);if(p<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(p-1)))p--;i.push({source:e,text:u.slice(m,p)}),m=p>m?p:m+1}return i}function hu(e){let o=[],i=Po(e.records),u=new Map(i.map((p)=>[p.call,p])),m=new Set(i.flatMap((p)=>p.result?[p.result]:[]));for(let p of e.records){let f=p.raw;if(f.role==="user")o.push(...fu(p.entry.type==="user"&&p.entry.notices?"NOTICE":"USER",_s(f)));else if(f.role==="assistant"){for(let h of f.content)if(h.type==="text"&&h.text.trim())o.push(...fu("ASSISTANT",h.text));else if(h.type==="toolCall"){let x=u.get(h);if(x)for(let I of wl(x))o.push(...fu(I.source,I.text))}}else if(f.role==="toolResult"&&!m.has(f))o.push(...fu(f.isError?"TOOL_ERROR":"TOOL_OUTPUT",mu(f)))}return o.map((p,f)=>({chunk:e.id,line:f,...p}))}function $l(e,o){let i=e.find((u)=>u.entry.seq===o);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return fu("USER",_s(i.raw)).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function vl(e,o){let i=e.find((u)=>u.entry.seq===o)?.entry;if(i?.type!=="extension"||!i.display)return;return fu("EXTENSION",i.display.text).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function Vc(e,o=""){return e.map((i,u)=>{let m=e[u-1],p=m&&m.source===i.source&&m.chunk===i.chunk&&m.line===i.line-1;return`${o}${p?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
91
+ `)}import{AsyncLocalStorage as VB}from"async_hooks";import{chmodSync as f$,existsSync as JB,mkdirSync as QB,readFileSync as XB,renameSync as YB,writeFileSync as ZB}from"fs";import{dirname as eG,join as tG}from"path";function p$(){let e=Bun.version.split(".").map(Number);if(!((e[0]??0)>1||e[0]===1&&(e[1]??0)>4||e[0]===1&&e[1]===4&&(e[2]??0)>=3))throw Error("\u4EE3\u7406\u4F20\u8F93\u9700\u8981 Bun 1.4.3 \u6216\u66F4\u65B0\u7248\u672C\uFF0C\u8BF7\u5148\u5347\u7EA7 Bun")}function l$(e=process.env){let o={...e};for(let i of["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY"])delete o[i],delete o[i.toLowerCase()];return o}function Jc(e){let o=e.hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1]??o;return u==="localhost"||u.endsWith(".localhost")||u==="::1"||u==="::"||/^(?:0\.|127\.)/.test(u)}function d$(e,o){let i=async(m,p,f)=>{let h=await e(m,{...p,...o.proxy?{proxy:o.proxy}:{proxy:!1},...o.tls==="insecure"?{tls:{rejectUnauthorized:!1}}:{},redirect:"manual"});if(![301,302,303,307,308].includes(h.status))return h;let x=h.headers.get("location");if(!x)return h;if(f>=10)throw Error("\u4EE3\u7406\u8BF7\u6C42\u91CD\u5B9A\u5411\u6B21\u6570\u8FC7\u591A");let I=m instanceof Request?m:void 0,S=new URL(I?.url??String(m)),R=new URL(x,S);if(R.protocol!=="http:"&&R.protocol!=="https:")throw Error("\u62D2\u7EDD\u91CD\u5B9A\u5411\u5230\u975E HTTP \u5730\u5740");if(Jc(R)&&!Jc(S))throw Error("\u62D2\u7EDD\u4ECE\u516C\u7F51\u91CD\u5B9A\u5411\u5230\u56DE\u73AF\u5730\u5740");let k=new Headers(I?.headers);if(new Headers(p?.headers).forEach((_,Q)=>{k.set(Q,_)}),S.origin!==R.origin)k.delete("authorization"),k.delete("cookie"),k.delete("proxy-authorization");let A=(p?.method??I?.method??"GET").toUpperCase(),v={...p,method:A,headers:k};if(h.status===303||(h.status===301||h.status===302)&&A==="POST")v.method="GET",delete v.body,k.delete("content-length"),k.delete("content-type");else if(A!=="GET"&&A!=="HEAD"&&p?.body===void 0&&I?.body)throw Error("\u65E0\u6CD5\u5B89\u5168\u91CD\u5B9A\u5411\u5E26\u6D41\u5F0F\u8BF7\u6C42\u4F53\u7684\u8BF7\u6C42");return await h.body?.cancel(),i(R,v,f+1)};return Object.assign((m,p)=>i(m,p,0),{preconnect:e.preconnect})}var tg=ny,g$=Qr,h$=new VB;class Gn{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;p$(),this.path=tG(e,"proxy.json");let i=async(u,m)=>{let p=h$.getStore();if(!p)return this.baseFetch(u,m);return this.createFetch(p)(u,m)};globalThis.fetch=Object.assign(i,{preconnect:o.preconnect})}load(){if(!JB(this.path))return;this.config=this.validate(JSON.parse(XB(this.path,"utf8")))}settings(){return{...this.config,defaultProfileID:this.config.defaultProfileID,routes:{...this.config.routes},profiles:this.config.profiles.map((e)=>{let{password:o,...i}=e;return{...i,hasPassword:Boolean(o)}})}}save(e){let o=this.validate(e);for(let i of o.profiles)i.password||=this.config.profiles.find((u)=>u.id===i.id)?.password;try{QB(eG(this.path),{recursive:!0});let i=`${this.path}.tmp-${process.pid}`;ZB(i,`${JSON.stringify(o,null,2)}
92
+ `,{mode:384}),f$(i,384),YB(i,this.path),f$(this.path,384)}catch(i){throw Error("\u4FDD\u5B58\u4EE3\u7406\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:i})}return this.config=o,this.settings()}createFetch(e,o=this.baseFetch){let i=(m,p="verify")=>d$(o,{proxy:m,tls:p});return Object.assign(async(m,p)=>{let f=m instanceof Request?m.url:String(m),x=this.profileFor(e)?.noProxy?.some((S)=>oG(f,S))??!1;if(Jc(new URL(f))||x)return i()(m,p);let I=this.proxyURL(e);return i(I,this.profileFor(e)?.tls)(m,p)},{preconnect:o.preconnect})}models(e){return new y$(e,this)}providerOptions(e,o,i){let u=Object.assign({},e),m=e?.fetch,f=m?.[gl]?.call(m,this.baseFetch)??m??this.baseFetch;u.fetch=this.createFetch(o,f);let h=l$({...process.env,...e?.env}),x=!1;if(i)try{x=Jc(new URL(i))}catch{}let I=x?void 0:this.proxyURL(o),S=this.profileFor(o);return u.env={...h,...I?{HTTP_PROXY:I,HTTPS_PROXY:I,ALL_PROXY:I}:{},...S?.noProxy?.length?{NO_PROXY:S.noProxy.join(",")}:{}},u}run(e,o){return h$.run(e,o)}wrapProvider(e){let o=sr(e.id),i={...e.auth},u=e.auth.oauth;if(u){let S=e.id==="openai"||e.id===kt?tg:o;i.oauth={...u,login:(R,k)=>this.run(S,()=>u.login(R,k)),refresh:(R,k)=>this.run(S,()=>u.refresh(R,k)),toAuth:(R)=>this.run(S,()=>u.toAuth(R))}}let m={...e,auth:i},p=e.refreshModels;if(p)m.refreshModels=(S)=>this.run(o,()=>p(S));m.stream=(S,R,k)=>this.run(o,()=>e.stream(S,R,this.providerOptions(k,o,S.baseUrl))),m.streamSimple=(S,R,k)=>this.run(o,()=>e.streamSimple(S,R,this.providerOptions(k,o,S.baseUrl)));let f=e.fetchDeferred;if(f)m.fetchDeferred=(S,R,k)=>this.run(o,()=>f(S,R,this.providerOptions(k,o,S.baseUrl)));let h=e.cancelDeferred;if(h)m.cancelDeferred=(S,R,k)=>this.run(o,()=>h(S,R,this.providerOptions(k,o,S.baseUrl)));let x=e.generateImages;if(x)m.generateImages=(S,R,k)=>this.run(o,()=>x(S,R,this.providerOptions(k,o,S.baseUrl)));let I=e.classify;if(I)m.classify=(S,R,k)=>this.run(o,()=>I(S,R,this.providerOptions(k,o,S.baseUrl)));return m}proxyURL(e){let o=this.profileFor(e);if(!o)return;let i=sd(o.address),u=o.username?`${encodeURIComponent(o.username)}:${encodeURIComponent(o.password??"")}@`:"",m=i.hostname.includes(":")?`[${i.hostname}]`:i.hostname;return`${i.protocol}://${u}${m}:${i.port}`}profileFor(e){let o=e?this.config.routes[e]:this.config.defaultProfileID,i=e&&o!==void 0?o:this.config.defaultProfileID;if(!i)return;let u=this.config.profiles.find((m)=>m.id===i);if(!u)throw Error(`\u4EE3\u7406\u7EBF\u8DEF ${i} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u9875\u91CD\u65B0\u9009\u62E9`);return u}validate(e){let o=rg(e);if(o?.version!==1)throw new t("\u4EE3\u7406\u914D\u7F6E\u7248\u672C\u65E0\u6548");let u=(Array.isArray(o.profiles)?o.profiles:[]).map(rG),m=new Set(u.map((x)=>x.id));if(m.size!==u.length)throw new t("\u4EE3\u7406\u914D\u7F6E ID \u4E0D\u80FD\u91CD\u590D");let p=nG(o.defaultProfileID);if(p&&!m.has(p))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let f=rg(o.routes)??{},h={};for(let[x,I]of Object.entries(f)){if(x!==tg&&x!==g$&&!oy(x))throw new t(`\u4EE3\u7406\u7528\u9014\u65E0\u6548\uFF1A${x}`);if(I!==null&&(typeof I!=="string"||!m.has(I)))throw new t(`\u7528\u9014 ${x} \u7684\u7EBF\u8DEF\u4E0D\u5B58\u5728`);h[x]=I}return{version:1,defaultProfileID:p,routes:h,profiles:u}}}class y${source;manager;wrapped=new Map;constructor(e,o){this.source=e;this.manager=o;for(let i of e.getProviders())this.install(i)}getProviders(){return this.source.getProviders().map((e)=>this.wrap(e))}getProvider(e){let o=this.source.getProvider(e);return o?this.wrap(o):void 0}getModels(...e){return this.source.getModels(...e)}getModel(...e){return this.source.getModel(...e)}getModelsOfType(e,o){return this.source.getModelsOfType(e,o)}getModelOfType(e,o,i){return this.source.getModelOfType(e,o,i)}getAllModels(...e){return this.source.getAllModels(...e)}refresh(...e){return this.source.refresh(...e)}checkAuth(...e){return this.source.checkAuth(...e)}getAvailable(...e){return this.source.getAvailable(...e)}getAvailableOfType(e,o,i){return this.source.getAvailableOfType(e,o,i)}getAllAvailable(...e){return this.source.getAllAvailable(...e)}getAuth(e,o){if(typeof e==="string")return this.source.getAuth(e,o);return this.source.getAuth(e,o)}login(...e){return this.source.login(...e)}logout(...e){return this.source.logout(...e)}stream(e,o,i){return this.source.stream(e,o,i)}complete(e,o,i){return this.source.complete(e,o,i)}streamSimple(...e){return this.source.streamSimple(...e)}completeSimple(...e){return this.source.completeSimple(...e)}streamDeferred(...e){return this.source.streamDeferred(...e)}fetchDeferred(...e){return this.source.fetchDeferred(...e)}cancelDeferred(...e){return this.source.cancelDeferred(...e)}generateImages(...e){return this.source.generateImages(...e)}classify(...e){return this.source.classify(...e)}setProvider(e){this.install(e)}deleteProvider(e){this.source.deleteProvider(e),this.wrapped.delete(e)}clearProviders(){this.source.clearProviders(),this.wrapped.clear()}wrap(e){return this.wrapped.get(e.id)??this.install(e)}install(e){if(this.wrapped.get(e.id)===e)return this.source.setProvider(e),e;let o=this.manager.wrapProvider(e);return this.wrapped.set(e.id,o),this.source.setProvider(o),o}}function sr(e){return`${ry}${e}`}function Xo(e){return[{id:tg,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:g$,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:sr(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function rG(e){let o=rg(e);if(!o)throw new t("\u4EE3\u7406\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof o.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(o.id))throw new t("\u4EE3\u7406\u914D\u7F6E ID \u65E0\u6548");let i;try{i=sd(String(o.address??""))}catch(p){throw new t(p instanceof Error?p.message:"\u4EE3\u7406\u5730\u5740\u65E0\u6548")}let u=Array.isArray(o.noProxy)?o.noProxy:[];if(!u.every((p)=>typeof p==="string"&&p.trim()))throw new t("\u76F4\u8FDE\u4F8B\u5916\u5FC5\u987B\u662F\u975E\u7A7A\u4E3B\u673A");let m=i.hostname.includes(":")?`[${i.hostname}]`:i.hostname;return{id:o.id,name:typeof o.name==="string"&&o.name.trim()?o.name.trim():i.hostname,address:`${i.protocol}://${m}:${i.port}`,username:typeof o.username==="string"&&o.username?o.username:void 0,password:typeof o.password==="string"&&o.password?o.password:void 0,tls:o.tls==="insecure"?"insecure":"verify",noProxy:u.map((p)=>String(p).trim())}}function nG(e){if(e===void 0||e===null||e==="")return;if(typeof e!=="string")throw new t("\u4EE3\u7406\u7EBF\u8DEF ID \u65E0\u6548");return e}function rg(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function oG(e,o){try{let i=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/^\./,"");return i===u||i.endsWith(`.${u}`)}catch{return!1}}import{join as Wg}from"path";import{existsSync as N$}from"fs";import{realpath as D$}from"fs/promises";import{dirname as q$,isAbsolute as EG,join as F$,relative as SG,resolve as cg,sep as wG}from"path";import{existsSync as sG,watch as iG}from"fs";import{readdir as aG,stat as uG}from"fs/promises";import{basename as ng,dirname as cG,join as x$,resolve as mG}from"path";class og{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,i,u=150){this.host=e;this.slots=o;this.watching=i;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let i=[],u=[];for(let h of[...new Set(e)]){let x;try{x=await aG(h)}catch(I){if(I instanceof Error&&"code"in I&&I.code==="ENOENT")continue;throw I}for(let I of x.sort()){let S=x$(h,I),R=(await uG(S)).isDirectory()?x$(S,"index.ts"):S;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(k){let A=ng(R)==="index.ts"?ng(cG(R)):ng(R,".ts");if(this.slots.has(A))throw Error(`Duplicate plugin: ${A}`);let v={id:A,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${A}; repair the file and reload`)}};i.push({definition:v,path:R}),this.slots.set(A,{definition:v,path:R,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let m=o.filter((h)=>![...u,...i].some((x)=>x.definition.id===h.definition.id)),p=[...m,...u],f=this.order(p.map(({definition:h})=>h));for(let h of f){let x=p.find((S)=>S.definition===h)?.path,I=m.some((S)=>S.definition===h);try{await this.host.install(h,x,I)}catch(S){this.slots.set(h.id,{definition:h,path:x,builtin:I,enabled:!0,error:S instanceof Error?S.message:String(S)})}}if(this.watching())for(let h of[...p,...i]){if(!sG(h.path))continue;let x=iG(h.path,()=>{let I=h.definition.id,S=this.debounceTimers.get(I);if(S)clearTimeout(S);let R=setTimeout(()=>{this.debounceTimers.delete(I),this.host.reload(I).catch((k)=>{let A=this.slots.get(I);if(A)A.error=k instanceof Error?k.message:String(k)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(I,R)});x.on("error",(I)=>{let S=this.slots.get(h.definition.id);if(S)S.error=I.message,this.host.changed()}),this.watchers.push(x)}}order(e,o=!1){let i=new Map;for(let h of e){if(this.validate(h),i.has(h.id)||!o&&this.slots.has(h.id))throw Error(`Duplicate plugin: ${h.id}`);i.set(h.id,h)}let u=[],m=new Set,p=new Set,f=(h)=>{if(p.has(h.id))return;if(m.has(h.id))throw Error(`Plugin dependency cycle: ${h.id}`);m.add(h.id);for(let x of h.deps??[]){let I=i.get(x);if(I)f(I);else if(!this.slots.has(x))throw Error(`Missing plugin dependency: ${x}`)}m.delete(h.id),p.add(h.id),u.push(h)};for(let h of e)f(h);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${mG(e)}?v=${++this.revision}`);if(!o.default)throw Error("Plugin module must export a default definition");return this.validate(o.default),o.default}}async function I$(e,o,i=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,m;try{return await Promise.race([i?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((p,f)=>{m=setTimeout(()=>{u.abort(),f(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(m)}}import{AsyncLocalStorage as pG}from"async_hooks";import{isDeepStrictEqual as b$}from"util";var Ra=new pG;function Ls(){let e=Ra.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function gu(e){let o=structuredClone(e),i=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let m of Object.values(u))i(m)};return i(o),o}function E$(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let x of["seq","time","session_id","raw"])if(x in o)throw Error(`Entry replacement contains protected field: ${x}`);let i=JSON.parse(JSON.stringify(o,(x,I)=>{if(typeof I==="function"||typeof I==="symbol"||typeof I==="number"&&!Number.isFinite(I))throw Error("Entry replacement must contain JSON values");return I}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let u=i,m=[];switch(e.type){case"user":m.push("text","attachments");break;case"assistant":m.push("parts","error");break;case"tool_result":m.push("output","images");break;case"extension":m.push("payload","display");break;case"notice_pending":m.push("notice");break;case"run":if(e.state==="end")m.push("error");break;case"compaction":break}let p={...e};for(let x of new Set([...Object.keys(e),...Object.keys(u)])){if(!m.includes(x)&&!b$(p[x],u[x]))throw Error(`Entry replacement changed protected field: ${x}`);if(["seq","time","session_id","raw"].includes(x))throw Error(`Entry replacement contains protected field: ${x}`)}let f=(x)=>x===void 0||typeof x==="string",h=!0;switch(e.type){case"user":h=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((x)=>x&&typeof x.name==="string"&&typeof x.mimeType==="string"&&nm.includes(x.kind)&&typeof x.data==="string"));break;case"assistant":h=f(u.error)&&Array.isArray(u.parts)&&u.parts.every((x)=>x&&(["text","thinking"].includes(x.type)&&typeof x.text==="string"||x.type==="tool_call"&&typeof x.id==="string"&&typeof x.name==="string"&&("input"in x)));break;case"tool_result":h=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((x)=>x&&typeof x.mimeType==="string"&&typeof x.data==="string"));break;case"extension":{let x=u.display;h="payload"in u&&(x===void 0||x!==null&&typeof x==="object"&&("text"in x)&&typeof x.text==="string"&&(!("title"in x)||f(x.title)));break}case"notice_pending":{let I=["text"],S=p.notice,R=u.notice;if(h=!!R&&typeof R==="object"&&!Array.isArray(R),!h)break;let k=R;for(let A of new Set([...Object.keys(S),...Object.keys(k)]))if(I.includes(A)){if(typeof k[A]!=="string")h=!1}else if(!b$(S[A],k[A]))h=!1;break}case"run":h=f(u.error);break;case"compaction":break}if(!h)throw Error("Invalid entry replacement content");return i}function S$(e,o,i,u,m,p){let f=u;for(let h of i.generations)for(let x of h.hooks.get("entry.before_append")??[]){if(h.disabled)break;let I={phase:"before",violated:!1};try{let S=Ra.run(I,()=>{let R=gu(f),k=performance.now(),A=x(R,{sessionID:m,seq:p});if(A&&(typeof A==="object"||typeof A==="function")&&"then"in A&&typeof A.then==="function")throw Promise.resolve(A).catch(()=>{}),Error("entry.before_append must be synchronous");let v=A===void 0?void 0:E$(f,A);if(I.violated)throw Error("entry.before_append attempted a database write");return{validated:v,slow:performance.now()-k>e}});if(S.validated&&JSON.stringify(S.validated)!==JSON.stringify(f))f=S.validated;if(S.slow)throw Error("entry.before_append exceeded budget");h.beforeFailures=0,h.failures=0}catch(S){h.failures=h.beforeFailures++,o(h,S)}}return f}function lG(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return gu(o);return structuredClone(o)}async function w$(e,o,i,u,m,p,f,h,x="end"){let I=p;for(let S of u){if(S.disabled)continue;let R=S.hooks.get(m)??[];for(let k of R){if(S.disabled)break;let A=S.hookOptions.get(k);if(m==="prompt.fragments"&&(A?.promptPosition??"end")!==x)continue;let v=m==="prompt.fragments"?JSON.stringify([f?.id,I]):void 0,_=v===void 0?void 0:S.promptCache.get(k)?.get(v);try{let Q=lG(m,I),L=A?.timeoutMs,z=typeof L==="function"?L({runtime:e.runtime,session:f,connection:h}):L,J=await o((Z)=>k(Q,{runtime:e.runtime,session:f,connection:h,signal:Z}),z);if(v!==void 0){let Z=J===void 0?I:J;if(!Array.isArray(Z)||Z.some((U)=>typeof U!=="string"))throw Error("Prompt fragments must be strings");if(_&&JSON.stringify(_)!==JSON.stringify(Z))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let re=S.promptCache.get(k)??new Map;re.set(v,[...Z]),S.promptCache.set(k,re)}if(S.failures=0,J!==void 0&&m!=="entry.after_append")I=J}catch(Q){if(_)I=structuredClone(_);if(i(S,Q),A?.errorMode==="propagate")throw Q}}}return I}class Qc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,i,u,m="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,i,u,m)}has(e,o){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((u)=>o===void 0||(i.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...i)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((i)=>i(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let u of i.historyResolvers){let m=u(e,o);if(m)return m}}}policy(e){return this.generations.findLast((o)=>!o.disabled&&o.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as dG}from"fs";import{dirname as fG,resolve as T$}from"path";var sg=new WeakMap;function R$(e){return[...e].map((o)=>{let i=Boolean(o.path&&(Boolean(o.definition.webEntry)||dG(T$(fG(T$(o.path)),"web.tsx"))));if(o.current&&!sg.has(o.current))sg.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:i,webRevision:o.current?sg.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class ig{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,i){this.host=e;this.deadline=o;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,i){let u=this.host.pin(),m=(async()=>{try{let p=[];for(let f of u.generations){if(f.disabled)continue;for(let h of f.hooks.get(e)??[]){let x=f.hookOptions.get(h)?.timeoutMs,I=typeof x==="function"?x({runtime:this.host.runtime,session:o,connection:i}):x;p.push(this.deadline((S)=>h(o,{runtime:this.host.runtime,session:o,connection:i,signal:S}),I,!0).catch((S)=>this.fail(f,S)))}}await Promise.all(p)}finally{await u.release()}})();this.pending.add(m),m.then(()=>this.pending.delete(m),()=>this.pending.delete(m))}finishEntry(e,o,i){let u=i===void 0?void 0:gu(i),m=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Ra.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,m),this.pending.add(m);let p=()=>{if(this.pending.delete(m),this.entryQueues.get(o)===m)this.entryQueues.delete(o)};m.then(p,p)}}function k$(e){return e.replace(/(?:(?:request[- ]?)?headers?)["']?\s*[=:][\s\S]*/gi,"[headers redacted]").replace(/\b(?:api[-_ ]?key|authorization|cookie|password|secret|access[-_ ]?token)\b[^\n]*/gi,"[redacted]").replace(/\bBearer\s+[^\s"',}]+/gi,"[redacted]").replace(/(?:authorization|[\w-]*api[-_]?key|password|secret|cookie|[\w-]*token|key)["']?\s*[=:][^\n]*/gi,"[redacted]").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi,"[address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[address]").replace(/\blocalhost(?::\d+)?\b/gi,"[address]").replace(/\b(?:sk|key)-[\w-]+/gi,"[redacted]").replace(/[\r\n\t]+/g," ").slice(0,300)}function hG(e){if(typeof e.prompt!=="string"||!e.prompt.trim())throw Error("Completion prompt must not be empty");if(e.system!==void 0&&typeof e.system!=="string")throw Error("Invalid completion system prompt");if(e.sessionID!==void 0&&typeof e.sessionID!=="string")throw Error("Invalid completion sessionID")}async function gG(e,o){let i=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!i)throw Error("Completion session not found");let u=o.model??i?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let m=Tn(e.options.models,u);if(!m&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!m){let p=(await e.models()).models.filter((h)=>h.available===!0),f=m?ot(m):u;if(!p.some((h)=>h.id===f)){let h=p[0];if(h)m=Tn(e.options.models,h.id)}}if(!m)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return m}async function A$(e,o){hG(o);let i=await gG(e,o),u=o.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>i.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let m="",p=!1;try{let f=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],h=e.options.models.streamSimple(i,{messages:f},{maxTokens:u,signal:o.signal});for await(let x of h){if(o.signal?.aborted)throw Error("cancelled");if(x.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${k$(x.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(x.type==="text_delta")m+=x.delta;if(x.type==="done"){if(x.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(x.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${x.reason}\uFF09`);p=!0}}}catch(f){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${k$(f instanceof Error?f.message:String(f))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!p)throw Error("Model completion ended without a stop response; retry");return{text:m,model:ot(i)}}var yG=["active","archived","all"];function P$(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function xG(e){let{projectID:o,children:i,archive:u,since:m}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!yG.includes(u))throw Error("sessions archive must be active, archived or all");if(m!==void 0&&!Number.isFinite(m))throw Error("sessions since must be a finite timestamp in milliseconds")}function IG(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function C$(e){function o(i,u={}){let{types:m,bodies:p}=u;if(m!==void 0&&!Array.isArray(m))throw Error("sessions types must be an array");let f=P$(u.limit),h=u.after??0;if(!Number.isSafeInteger(h)||h<0)throw Error("sessions after must be a non-negative integer");let x=(e.get(i)?.entries(h,m,p!==!1)??[]).slice(0,f);return structuredClone(p===!1?x.map(IG):x)}return{list(i={}){xG(i);let u=i.limit===void 0?void 0:P$(i.limit),m=e.list(i.children??!1,{archive:i.archive}).filter((p)=>i.projectID===void 0||p.projectID===i.projectID).filter((p)=>i.since===void 0||p.created>=i.since);return structuredClone(u===void 0?m:m.slice(0,u))},get(i){return structuredClone(e.get(i)?.info())},entries:o}}async function $$(e,o,i,u,m,p){let f={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},h=e.runtime.store.db,x=new Map,I=!1,S=!0,R=()=>{if(!S||f.disposed)throw Error("Plugin registration scope is closed")},k=(L,z)=>{if(R(),!I){x.set(L,z);return}if(z===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,L);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,L,z)},A={get:(L)=>{R();let z=x.has(L)?x.get(L):h.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,L)?.value;return z==null?void 0:JSON.parse(z)},set:(L,z)=>{let J=JSON.stringify(z);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");k(L,J)},delete:(L)=>k(L,null)},v=()=>{if(R(),I)throw Error("Register resources during setup only")},_=[...o.migrations??[]].sort((L,z)=>L.version-z.version),Q=new Set;try{for(let L of _){if(!Number.isSafeInteger(L.version)||L.version<1||Q.has(L.version))throw Error("Plugin migration versions must be unique positive integers");if(Q.add(L.version),h.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,L.version))continue;h.transaction(()=>{if(L.sql!==void 0)h.run(L.sql);else L.up({...A,db:h});for(let[z,J]of x)if(J===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,z);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,z,J);h.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,L.version)})(),e.runtime.store.invalidateEntryCache(),x.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:C$(e.runtime),complete:(L)=>A$(e.runtime,L),kv:A,database:h,broadcast:(L)=>{e.runtime.emitEvent(L)},registerInputGate:(L)=>{v(),f.gates.push(L)},registerNoticeSource:(L,z)=>{if(v(),!L||!Number.isSafeInteger(z.textLimit)||z.textLimit<1||!Number.isSafeInteger(z.summaryLimit)||z.summaryLimit<1)throw Error("Notice source limits must be positive integers");f.noticeSources.set(L,{...z})},provide:(L,z)=>{if(v(),L.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(f.services.has(L.name))throw Error(`Duplicate plugin service: ${L.name}`);if(!L.validate(z))throw Error(`Invalid plugin service: ${L.name}`);f.services.set(L.name,z)},on:(L,z,J)=>{if(v(),J?.promptPosition&&L!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let Z=f.hooks.get(L)??[];if(Z.push(z),f.hooks.set(L,Z),J)f.hookOptions.set(z,J)},registerHistoryResolver:(L)=>{v(),f.historyResolvers.push(L)},registerTool:(L,z)=>{if(v(),!L.name||["toolsearch","tool_search","tool_call"].includes(L.name.toLowerCase())||bG(e,m,o.id).has(L.name.toLowerCase())||f.tools.some((Z)=>Z.name.toLowerCase()===L.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${L.name}`);let J=i?"always":"defer";if(typeof z?.defer==="boolean")J=z.defer?"defer":"always";else if(z?.defer!==void 0)J=z.defer;f.tools.push({...L,defer:J,source:`plugin:${o.id}`,group:z?.group,aliases:z?.aliases,builtin:i})},registerRoute:(L)=>{if(v(),!(L.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((z)=>L.path===z||L.path.startsWith(`${z}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(L.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(f.routes.some((z)=>z.path===L.path&&z.method===L.method))throw Error("Duplicate plugin route");f.routes.push(L)},registerWebSocket:(L)=>{if(v(),!L.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(f.websockets.some((z)=>z.path===L.path))throw Error("Duplicate plugin WebSocket route");f.websockets.push(L)},registerCommand:(L)=>{v(),f.commands.push(L)},registerWebContribution:(L)=>{v(),f.web.push(L)},registerToolPolicy:(L,z)=>{v(),f.policies.set(L,z)},appendExtension:(L,z)=>{if(Ls(),R(),!I)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(L,z)},onDeactivate:(L)=>{v(),f.deactivators.push(L)},onDispose:(L)=>{v(),f.disposers.push(L)}})),h.transaction(()=>{for(let[L,z]of x)if(z===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,L);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,L,z)})(),x.clear(),I=!0,f}catch(L){throw S=!1,await p(f),L}}function bG(e,o,i){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((m)=>m.name)].map((m)=>m.toLowerCase()));for(let[m,p]of o){if(m===i)continue;for(let f of p.current?.tools??[])u.add(f.name.toLowerCase())}return u}class ag{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(i){e.error=i instanceof Error?i.message:String(i)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(i){e.error=i instanceof Error?i.message:String(i)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function v$(e,o,i,u){for(let m of o){let p=m.current;if(!p||p.disabled||p.retired)continue;let f=p.websockets.find((h)=>h.path===u);if(!f)continue;return{connect:(h)=>{let x=!1;p.references++,p.connections.add(h);let I={send:(R)=>{if(x||p.retired||p.disabled)return;h.send(R)},close:(R,k)=>h.close(R,k)},S=async(R)=>{if(x||p.retired||p.disabled){h.close(1012,"Plugin unavailable");return}try{await i(R),p.failures=0}catch(k){if(p.failures++,p.error=k instanceof Error?k.message:String(k),h.close(1011,"Plugin callback failed"),p.failures>=e.failureThreshold){p.disabled=!0;for(let A of p.connections)A.close(1011,"Plugin disabled")}}};return{open:()=>S(()=>f.open?.(I)),message:(R)=>S(()=>f.message(I,R)),close:async()=>{if(x)return;x=!0,p.connections.delete(h);try{await i(()=>f.close?.(I))}catch(R){p.error=R instanceof Error?R.message:String(R)}finally{p.references--,await e.collect(p)}}}}}}return}function ug(e,o){let i=e.split("/"),u=new URL(o.url).pathname.split("/");if(i.length!==u.length)return;let m={};return i.every((f,h)=>{let x=u[h];if(x===void 0)return!1;if(!f.startsWith(":"))return x===f;try{m[f.slice(1)]=decodeURIComponent(x)}catch{return!1}return x.length>0})?m:void 0}async function M$(e,o,i,u,m){let p=e.pin();try{let f=p.generations.find((h)=>h.definition.id===i)?.commands.find((h)=>h.id===u);if(!f)throw new b("Plugin command is unavailable");return await o(()=>f.execute(m))}finally{await p.release()}}function O$(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((m)=>m.method===o.method&&ug(m.path,o)!==void 0))}finally{i.release()}}function _$(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((m)=>m.public===!0&&m.method===o.method&&ug(m.path,o)!==void 0))}finally{i.release()}}async function L$(e,o,i){let u=e.pin(),m=!0;try{for(let p of u.generations)for(let f of p.routes){if(f.method!==i.method)continue;let h=ug(f.path,i);if(h){let x=await o(()=>f.handler(i,h),f.timeoutMs);if(!x)return;if(x.body&&x.body instanceof ReadableStream){m=!1;let I=!1,S=()=>{if(I)return;I=!0,u.release()},R=x.body.getReader(),k=new ReadableStream({async pull(A){try{let{done:v,value:_}=await R.read();if(v)A.close(),S();else A.enqueue(_)}catch(v){A.error(v),S()}},async cancel(A){try{await R.cancel(A)}finally{S()}}});return new Response(k,{status:x.status,statusText:x.statusText,headers:x.headers})}return x}}return}finally{if(m)await u.release()}}class mg{runtime;options;slots=new Map;retirement=new ag(this.deadline.bind(this));observers=new ig(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new bl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,o={}){this.runtime=e;this.options=o;if(o.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(o.beforeAppendBudgetMs)||o.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new og(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new b(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=o.current.services.get(e.name);if(!e.validate(i))throw new b(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let i of e)this.directories.add(cg(i));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await D$(e),i=[...this.directories,F$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>F$(u.directory,".basalt","plugins"))];for(let u of i){if(!N$(u))continue;let m=SG(await D$(u),o);if(m&&m!==".."&&!m.startsWith(`..${wG}`)&&!EG(m)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),i=await this.checkEntry(o);if(!i.ok)throw new ht(i.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,i)})}async installDefinition(e,o,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),m={definition:e,path:o,builtin:i,enabled:u?.enabled!==0};if(m.enabled)m.current=await this.stage(e,i);this.slots.set(e.id,m)}reload(e){return this.exclusive(async()=>{let o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let h=await this.checkEntry(o.path);if(!h.ok)throw new ht(h.errors)}let i=o.builtin&&!N$(o.path)?o.definition:await this.catalog.read(o.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((h)=>h.definition.id===e?i:h.definition),!0),m=await this.stage(i),p=o.current;o.definition=i,o.current=m,o.error=void 0,o.discoveryFailed=!1;let f=new Map(this.slots);this.slots.clear();for(let h of u){let x=f.get(h.id);if(x)this.slots.set(h.id,x)}if(p)await this.retirement.retire(p)}catch(i){throw o.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,o){return this.exclusive(async()=>{let i=this.require(e);if(o===i.enabled&&(!o||i.current&&!i.current.disabled))return;if(!o){for(let f of this.slots.values())if(f.enabled&&f.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${f.definition.id}`)}let u=o&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let m=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let p=i.current;if(i.definition=u,o)i.discoveryFailed=!1;if(i.enabled=o,i.current=m,i.error=void 0,p)await this.retirement.retire(p)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let 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 $$(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,i){this.observers.notify(e,o,i)}resolveHistory(e,o){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let u of i.current.historyResolvers){let m=u(e,o);if(m)return m}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Qc(this,e)}async invoke(e,o,i,u,m,p="end"){return w$(this,this.deadline.bind(this),this.fail.bind(this),e,o,i,u,m,p)}pinEntry(e){if(Ra.getStore()?.phase==="after")return;let o;for(let i of this.slots.values()){let u=i.current;if(!i.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Qc(this,o)}beforeEntry(e,o,i,u){return S$(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,i,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let i of e.connections)i.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,i){this.observers.finishEntry(e,o,i)}deadline(e,o=this.timeoutMs,i=!1){return I$(e,o,i)}appendExtension(e,o){return Ls(),new Promise((i)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let m=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),i(m)})}list(){return R$(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(i&&o.path)await this.webBuilder.build(i,q$(cg(o.path)));return{ok:!0}}catch(o){if(o instanceof Il)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let i=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!i)return;return this.webBuilder.build(i,q$(cg(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let i=await this.webBuilder.entry(o.path,o.definition.webEntry);return i?this.webBuilder.cache.get(i)?.css:void 0}command(e,o,i){return M$(this,this.deadline.bind(this),e,o,i)}hasRoute(e){return O$(this,e)}isPublicRoute(e){return _$(this,e)}route(e){return L$(this,this.deadline.bind(this),e)}websocket(e){return v$(this,this.slots.values(),this.deadline.bind(this),e)}collect(e){return this.retirement.collect(e)}async close(){this.catalog.close(),await this.serial,await this.idle(),this.closed=!0;for(let e of this.slots.values())if(e.current)await this.retirement.retire(e.current);await this.retirement.collectRetired()}}import{statSync as j$}from"fs";import{join as TG}from"path";var RG=500,kG=1000,AG=3600000,PG=5000,CG=2000,$G=3,vG=1073741824;class pg{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;constructor(e){this.options=e;if(this.indexPath=TG(e.dataDir,Gi),this.features={...zi(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,i=o?.backfill;if(!o||!i)return{...e,state:"backfilling"};if(i.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=j$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=j$(this.options.store.path).size}catch{}return Math.max(vG,Math.round(e*0.6))}async setEnabled(e){if(this.closed||e===this.enabledFlag)return;if(this.enabledFlag=e,this.failure=void 0,this.restarts=0,e){if(this.clearTimer)clearInterval(this.clearTimer);if(this.clearTimer=void 0,this.usable)this.start();else this.idleMaintenance()}else await this.stopWorker(),this.idleMaintenance();this.pushStatus()}async rebuild(){if(!this.usable)return;await this.stopWorker(),lo(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.worker;if(!o)return e();Atomics.store(this.flags,ze,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Rt,0,PG);try{return e()}finally{Atomics.store(this.flags,ze,0),Atomics.notify(this.flags,ze)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=Vi(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,ze,0),Atomics.store(this.flags,Rt,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<$G&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,ze,0),Atomics.notify(this.flags,ze);let o=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(CG)]),e.terminate(),this.worker=void 0,this.stopped=void 0,this.closeReader(),this.resolveFlushes(),this.prune()})();try{await this.stopping}finally{this.stopping=void 0}}resolveFlushes(){for(let e of this.flushes.values())e();this.flushes.clear()}closeReader(){this.reader?.close(),this.reader=void 0}schedulePrune(){if(this.pruneTimer)return;let e=Math.max(0,RG-(performance.now()-this.lastPrune));this.pruneTimer=setTimeout(()=>{this.pruneTimer=void 0,this.prune()},e),this.pruneTimer.unref?.()}prune(){let e=this.engineStatus?.queueDone??0;if(e<=this.pruned)return;this.lastPrune=performance.now();try{this.options.store.db.query("DELETE FROM search_queue WHERE id <= ?").run(e),this.pruned=e}catch{}}idleMaintenance(){if(this.engineStatus=void 0,!this.enabledFlag)lo(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),AG),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,kG-(performance.now()-this.lastPush)),i=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),m=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(m===this.lastPushed)return;this.lastPushed=m,this.lastPush=performance.now(),e(u)};if(o===0)i();else this.statusTimer=setTimeout(i,o),this.statusTimer.unref?.()}}import{existsSync as Iu,mkdirSync as qG,readdirSync as V$,readFileSync as K$,realpathSync as lg,statSync as Nl,writeFileSync as dg}from"fs";import{dirname as Ll,isAbsolute as fg,relative as J$,resolve as FG}from"path";import{existsSync as Xc}from"fs";import{dirname as NG,join as xu}from"path";import{mkdirSync as MG,writeFileSync as OG}from"fs";import{tmpdir as _G}from"os";import{join as U$}from"path";var Ml=2000,Ce=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function yu(e,o){return e.map((i,u)=>{let m=i.length>Ml?`${i.slice(0,Ml)}\u2026 [line truncated]`:i;return`${String(o+u).padStart(6)} ${m}`}).join(`
93
+ `)}function le(e,o){if(e.length<=o)return e;let i=Math.floor(o*0.4),u=o-i,m=e.length-i-u,p=e.slice(i,e.length-u).split(`
94
+ `).length-1;return`${e.slice(0,i)}
95
+
96
+ \u2026 [${m} characters, ~${p} lines omitted] \u2026
97
+
98
+ ${e.slice(-u)}`}var LG=0;function it(e,o,i){if(e.length<=o)return e;let u=le(e,o);try{let m=i?xd(i):U$(_G(),"basalt-output");MG(m,{recursive:!0});let p=U$(m,`${process.pid}-${Date.now().toString(36)}-${LG++}.txt`);return OG(p,e),`${u}
99
+ [Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var B$=120000,G$=600000,ka;function DG(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function ar(){if(ka!==void 0)return ka||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let m=xu(u,"bash.exe");if(DG(m))continue;if(Xc(m))return ka=m,m}for(let u of o){let m=xu(u,"git.exe");if(Xc(m)){let p=NG(u),f=xu(p,"bin","bash.exe");if(Xc(f))return ka=f,f;let h=xu(p,"usr","bin","bash.exe");if(Xc(h))return ka=h,h}}let 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?xu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?xu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of i)if(Xc(u))return ka=u,u;ka="";return}class Ol{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let i=0;while(i<o.length){if(o[i]<128){i+=1;continue}let m=o[i+1];if(m===void 0)break;let p=m>=48&&m<=57?4:2;if(i+p>o.length)break;i+=p}return this.gbkPending=o.slice(i),this.gbk.decode(o.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let i=new Uint8Array(this.sniffPending.length+e.length);if(i.set(this.sniffPending),i.set(e,this.sniffPending.length),i.length<2)return this.sniffPending=i,"";this.sniffPending=void 0;let u=i[0]===255&&i[1]===254,m=!1;for(let p=1;p<i.length;p+=2)if(i[p]===0){m=!0;break}this.isUtf16=u||m,o=i}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Aa(e,o){let i=process.platform==="win32",u=o??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[ar()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let m=ar();if(m)return{argv:[m,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function lr(e,o){let i=await Qe(e,o.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:u,isWindows:m}=Aa(e,o.shell),p=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!m,windowsHide:!0,env:{...process.env,...am(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...m?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((Z)=>Z.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),f=!1,h=()=>{try{if(m)p.kill();else process.kill(-p.pid,"SIGKILL")}catch{}},x=setTimeout(()=>{f=!0,h()},o.timeout);o.signal?.addEventListener("abort",h,{once:!0});let I=Ce*2,S="",R="",k=0,A=0,v="",_=(Z=!1)=>{let re=k-S.length-R.length,U=re>0?`${S}
100
+ \u2026 [${re} characters omitted] \u2026
101
+ ${R}`:S+R;if(!Z)return le(U,Ce);return it(v.length===k?v:U,Ce,o.cwd)},Q=()=>{let Z=new Ol;return async(re)=>{for await(let ne of re){let fe=Z.decode(ne);if(k+=fe.length,v.length<4000000)v+=fe;if(S.length<I)S+=fe;else R=(R+fe).slice(-I);if(o.onOutput){let Re=performance.now();if(Re-A>=80)A=Re,o.onOutput(_())}}let U=Z.flush();if(U){if(k+=U.length,v.length<4000000)v+=U;if(S.length<I)S+=U;else R=(R+U).slice(-I)}}},L=Promise.all([Q()(p.stdout),Q()(p.stderr)]),z=await p.exited;if(clearTimeout(x),o.signal?.removeEventListener("abort",h),await Promise.race([L.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
102
+ [background processes are still running; their later output is not captured]`;return{output:_(!0),code:f?null:z,timedOut:f}}class hg{seen=new Map;mark(e,o=Nl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Nl(e).mtimeMs!==o?"changed":void 0}}var H$=2000,jG=500,UG=10485760,_l=20,BG=6,GG=40000,KG=80000;function HG(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return}function Q$(e,o,i=[],u){let m=(v)=>fg(v)?v:FG(e,v),p=(v)=>{let _=J$(e,v);return _&&!_.startsWith("..")&&!fg(_)?_:v},f=(v)=>{let _=v;while(!Iu(_)&&Ll(_)!==_)_=Ll(_);let Q=lg(_);if(i.some((L)=>Iu(L)&&z$(lg(L),Q))&&!z$(lg(e),Q))throw Error("External directories are read-only")},h=(v,_,Q)=>{let L=m(v);if(!Iu(L))throw Error(`No such file or directory: ${L}${JG(L)}`);let z=Nl(L);if(z.isDirectory()){let ue=V$(L,{withFileTypes:!0}).map((Ke)=>Ke.isDirectory()?`${Ke.name}/`:Ke.name).sort(),$e=ue.slice(0,jG),gt=ue.length-$e.length;return c(`${$e.join(`
103
+ `)}${gt>0?`
104
+ \u2026 and ${gt} more entries`:""}`||"(empty directory)").content}let J=K$(L),Z=HG(J);if(Z){if(z.size>UG)throw Error(`${L} exceeds the 10 MB image limit (${z.size} bytes)`);return o.mark(L),[{type:"text",text:`Read image ${p(L)} (${Z}, ${z.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:Z}]}if(J.subarray(0,8192).includes(0))throw Error(`${L} looks like a binary file (${z.size} bytes)`);o.mark(L);let re=J.toString("utf8");if(!re)return c("(empty file)").content;let U=re.replace(/\r?\n$/,"").split(/\r?\n/),ne=(_??1)-1;if(ne>=U.length)throw Error(`offset ${_} is past the end of the file (${U.length} lines)`);let fe=Math.min(U.length,ne+(Q??H$)),Re=0,Ee=ne;while(Ee<fe){let ue=U[Ee]?.length??0;if(Ee>ne&&Re+ue>GG)break;Re+=ue,Ee++}let ee=yu(U.slice(ne,Ee),ne+1);if(Ee<fe)ee+=`
105
+
106
+ (Showing lines ${ne+1}-${Ee} of ${U.length} (truncated at line ${Ee} due to safety budget). Use offset/limit to read specific windows.)`;else if(ne>0||Ee<U.length)ee+=`
107
+
108
+ (Showing lines ${ne+1}-${Ee} of ${U.length}. Use offset/limit to read other parts.)`;return c(ee).content},x=E({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
109
+ - path may be absolute or relative to the working directory.
110
+ - By default reads up to ${H$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
111
+ - Lines longer than ${Ml} characters are truncated.
112
+ - Reading a directory lists its entries (directories end with /).
113
+ - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
114
+ - To read several files at once, give paths instead of path (up to ${_l}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
115
+ - Always read a file before editing or overwriting it.`,parameters:l({path:n(a({description:"File or directory path"})),offset:n(T({minimum:1,description:"1-based line number to start from"})),limit:n(T({minimum:1,description:"Maximum number of lines to return"})),paths:n(H(l({path:a({description:"File or directory path"}),offset:n(T({minimum:1,description:"1-based line number to start from"})),limit:n(T({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:_l,description:"Several files or directories to read in one call, instead of path"}))}),async execute(v,_){let Q=[..._.path!==void 0?[{path:_.path,offset:_.offset,limit:_.limit}]:[],..._.paths??[]];if(Q.length===0)throw Error("Give path, or paths to read several files");if(Q.length===1){let re=Q[0];return{content:h(re.path,re.offset,re.limit),details:void 0}}if(Q.length>_l)throw Error(`Read at most ${_l} paths per call`);let L=[],z=[],J=0,Z=(re)=>{let U=L.at(-1);if(re.type==="text"&&U?.type==="text")U.text+=`
116
+
117
+ ${re.text}`;else L.push(re)};for(let re of Q){let U=`==> ${p(m(re.path))} <==`;if(J>=KG){Z({type:"text",text:`${U}
118
+ (Skipped due to total read safety budget; read in separate calls)`});continue}try{let ne=h(re.path,re.offset,re.limit);for(let fe=0;fe<ne.length;fe++){let Re=ne[fe];if(!Re)continue;if(Re.type==="text")J+=Re.text.length,Z(fe===0?{...Re,text:`${U}
119
+ ${Re.text}`}:Re);else Z(Re)}}catch(ne){let fe=ne instanceof Error?ne.message:String(ne);z.push(fe),Z({type:"text",text:`${U}
120
+ Error: ${fe}`})}}if(z.length===Q.length)throw Error(z.join(`
121
+ `));return{content:L,details:void 0}}}),I=async(v,_,Q,L)=>{let z=L?.update,J=await lr(v,{cwd:e,timeout:120000,signal:Q,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:z?(fe)=>z(c(`${L.prefix}
122
+
123
+ $ ${v}
124
+ ${fe.trimEnd()}`)):void 0}),Z=J.output.trimEnd()||"(no output)",re=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,U=J.timedOut||J.code!==0,ne=U?`
125
+ ${_}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
126
+
127
+ $ ${v}
128
+ ${Z}
129
+ [${re}]${ne}`,failed:U}},S=(v,_=!1)=>{let Q=o.check(v);if(Q==="changed")return`Note: ${p(v)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(Q==="unread"&&_)return`Note: ${p(v)} existed and had not been read; it was replaced whole.`;return},R=E({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
130
+ - An existing file is replaced whole, including changes made since you last read it.
131
+ - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
132
+ - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
133
+ - Do not create documentation or README files unless asked.`,parameters:l({path:a({description:"File path"}),content:a({description:"The full file content"}),then_run:n(a({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(v,_,Q,L){let z=m(_.path);f(z);let J=Iu(z),Z;if(J){if(Nl(z).isDirectory())throw Error(`${z} is a directory`);Z=S(z,!0)}qG(Ll(z),{recursive:!0}),dg(z,_.content),o.mark(z);let re=_.content?_.content.split(`
134
+ `).length:0,U=`${J?"Overwrote":"Created"} ${p(z)} (${re} lines)${Z?`
135
+ ${Z}`:""}`;if(_.then_run){let ne=await I(_.then_run,`${p(z)} was written as given`,Q,{prefix:U,update:L});if(U+=ne.out,ne.failed)return{...c(U),isError:!0}}return c(U)}}),k=(v,_,Q,L)=>{let z=m(v);if(!Iu(z))throw Error(`File not found: ${z} (use write to create it)`);f(z);let J=S(z),Z=K$(z,"utf8"),re=Z,U=re.includes(`\r
136
+ `),ne=[],fe=[],Re=0,Ee=0;return _.forEach((ee,ue)=>{let $e=L?`edits[${Q+ue}]: `:"";try{if(ee.old_string===ee.new_string)throw Error(`${$e}old_string and new_string are identical`);if(!ee.old_string)throw Error(`${$e}old_string is empty (use write to create or replace a whole file)`);let gt=U&&!ee.old_string.includes(`\r
137
+ `),Ke=gt?ee.old_string.replace(/\n/g,`\r
138
+ `):ee.old_string,Zt=gt?ee.new_string.replace(/\n/g,`\r
139
+ `):ee.new_string,_e=WG(re,Ke).map((Pt)=>[Pt,Pt+Ke.length]);if(_e.length===0)_e=zG(re,Ke);if(_e.length===0)throw Error(`${$e}old_string not found in ${p(z)}; read the relevant lines and copy the exact text.${VG(re,Ke)}`);if(_e.length>1&&!ee.replace_all){let Pt=_e.map(([tt])=>W$(re,tt)).join(", ");throw Error(`${$e}old_string occurs ${_e.length} times (lines ${Pt}); add surrounding lines to make it unique, or set replace_all.`)}let qe=W$(re,_e[0][0]),Dt=ee.replace_all?_e:[_e[0]],pt="",Mt=0;for(let[Pt,tt]of Dt)pt+=re.slice(Mt,Pt)+Zt,Mt=tt;re=pt+re.slice(Mt),Re++,Ee+=Dt.length;let xr=re.split(/\r?\n/),nr=qe+Zt.split(/\r?\n/).length-1,Ut=Math.max(1,qe-1),et=Math.min(xr.length,nr+1);if(et-Ut+1<=BG+2)ne.push(yu(xr.slice(Ut-1,et),Ut));else ne.push(`${yu(xr.slice(Ut-1,qe+1),Ut)}
140
+ \u2026 (${nr-qe-3} lines as given)
141
+ ${yu(xr.slice(nr-2,et),nr-1)}`)}catch(gt){fe.push(gt instanceof Error?gt.message:String(gt))}}),{path:z,original:Z,content:re,echoes:ne,applied:Re,total:Ee,count:_.length,note:J,failed:fe}},A=E({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
142
+ - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
143
+ - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
144
+ - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
145
+ - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
146
+ - To create a file use write; to delete or move files use bash.
147
+ - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
148
+ - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(a({description:"File path (the default for edits items without their own path)"})),old_string:n(a({description:"The exact text to replace (only when edits is absent)"})),new_string:n(a({description:"The replacement text (only when edits is absent)"})),replace_all:n(B({description:"Replace every occurrence (default false)"})),edits:n(H(l({path:n(a({description:"The file of this replacement, when it is not path"})),old_string:a({description:"The exact text to replace"}),new_string:a({description:"The replacement text"}),replace_all:n(B({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(a({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(v,_,Q,L){let z=_.edits&&_.edits.length>0?_.edits.map((ee)=>({path:ee.path??_.path,step:ee})):_.old_string!==void 0&&_.new_string!==void 0?[{path:_.path,step:{old_string:_.old_string,new_string:_.new_string,replace_all:_.replace_all}}]:[];if(z.length===0)throw Error("Give old_string and new_string, or edits");let J=z.length>1,Z=new Map;z.forEach((ee,ue)=>{if(!ee.path)throw Error(`${J?`edits[${ue}]: `:""}path is required`);let $e=m(ee.path),gt=Z.get($e)??{raw:ee.path,steps:[],offset:ue};gt.steps.push(ee.step),Z.set($e,gt)});let re=[],U=[];for(let ee of Z.values())try{let ue=k(ee.raw,ee.steps,ee.offset,J);if(ue.applied>0)re.push(ue);U.push(...ue.failed)}catch(ue){let $e=ue instanceof Error?ue.message:String(ue);U.push(`${J?`edits[${ee.offset}]: `:""}${$e}`)}if(re.length===0)throw Error(U.join(`
149
+ `));let ne=[];try{for(let ee of re)dg(ee.path,ee.content),ne.push(ee)}catch(ee){for(let ue of ne)dg(ue.path,ue.original);throw ee}for(let ee of re)o.mark(ee.path);let Re=re.map((ee)=>{let ue=ee.total===1?"1 occurrence":`${ee.total} occurrences`,$e=ee.note?`
150
+ ${ee.note}`:"";if(!J)return`Edited ${p(ee.path)} (${ue}).${$e}
151
+ ${ee.echoes[0]}`;let gt=ee.failed.length>0?`, ${ee.failed.length} failed`:"";return`Edited ${p(ee.path)} (${ee.applied} edits${gt}, ${ue}). Regions are shown as they were right after each edit; later edits may shift line numbers.${$e}
152
+ ${ee.echoes.map((Ke,Zt)=>`--- edit ${Zt+1}
153
+ ${Ke}`).join(`
154
+ `)}`}).join(`
155
+
156
+ `),Ee=!1;if(_.then_run){let ee=await I(_.then_run,"The edits above were applied",Q,{prefix:Re,update:L});if(Re+=ee.out,ee.failed)Ee=!0}if(U.length>0)Re+=`
157
+
158
+ ${U.length===1?"1 edit":`${U.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
159
+ - ${U.join(`
160
+ - `)}`,Ee=!0;return Ee?{...c(Re),isError:!0}:c(Re)}});return[Pe(x,"cat","view","read_file","view_file","open_file","open"),Pe(R,"write_file","create_file","new_file","save_file"),Pe(A,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function WG(e,o){let i=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))i.push(u);return i}function W$(e,o){let i=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)i++;return i}function zG(e,o){let i=o.replace(/\r?\n$/,"").split(/\r?\n/).map((x)=>x.trimEnd()),u=[],m=e.split(`
161
+ `),p=0;for(let x of m)u.push(p),p+=x.length+1;let f=m.map((x)=>x.replace(/\r$/,"").trimEnd()),h=[];for(let x=0;x+i.length<=f.length;x++)if(i.every((I,S)=>f[x+S]===I)){let I=x+i.length-1,S=u[I]+m[I].replace(/\r$/,"").length,R=o.endsWith(`
162
+ `)&&S<e.length?e[S]==="\r"?2:1:0;h.push([u[x],S+R]),x+=i.length-1}return h}function VG(e,o){let i=(h)=>h.replace(/\s+/g," ").trim(),u=i(o);if(!u)return"";let m=e.split(/\r?\n/),p=o.split(/\r?\n/).length;for(let h=0;h+p<=m.length;h++)if(i(m.slice(h,h+p).join(`
163
+ `))===u)return` A match ignoring whitespace exists at line ${h+1}; copy the exact indentation and line breaks from the read output:
164
+ ${le(yu(m.slice(h,h+p),h+1),4000)}`;let f=o.split(/\r?\n/).find((h)=>h.trim())?.trim();if(f){let h=m.findIndex((x)=>x.includes(f));if(h!==-1)return` Its first line appears at line ${h+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function JG(e){let o=Ll(e);if(!Iu(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let m=V$(o).filter((p)=>{let f=p.toLowerCase().replace(/\.[^.]*$/,"");return f&&(f.includes(u)||u.includes(f))}).slice(0,5);return m.length?`. Did you mean: ${m.join(", ")}?`:""}function z$(e,o){let i=J$(e,o);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!fg(i)}var gg=20,yg=80,QG=5,XG=(e)=>e!==void 0&&e>0?e:void 0;function X$(e,o){let i=$l(e,o)??vl(e,o);if(!i)throw Error(`No user message with seq ${o}`);return i}function Dl(e,o){let i=(f)=>{if(o)return o(f);if(f.source&&f.source!=="self"||f.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(f)=>{let h=i(f),x=XG(f.seq);return{scope:h,seq:x,runs:()=>Qs(h.records),reference:`session_id=${h.sessionID}`,both:x!==void 0&&f.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
165
+ `:""}},m=E({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
166
+ - Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
167
+ - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),pattern:a({minLength:1,description:"Text to search for"}),also:n(H(a({minLength:1}),{maxItems:QG,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(a({description:"Only search this chunk"})),seq:n(T({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(B({description:"Default false"})),head_limit:n(T({minimum:1,maximum:gg,description:`Hits to return (default ${gg})`})),offset:n(T({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(f,h){let{scope:x,seq:I,runs:S,reference:R,both:k}=u(h),A;if(I!==void 0)A=[X$(x.records,I)];else{let ne=S(),fe=h.chunk_id?ne.filter((Re)=>Re.id===h.chunk_id):ne;if(h.chunk_id&&!fe.length)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);A=fe.map(hu)}let v=(ne)=>h.case_sensitive?ne:ne.toLowerCase(),_=[h.pattern,...(h.also??[]).filter(Boolean)].map(v),Q=h.head_limit??gg,L=h.offset??0,z=[],J=new Map,Z=0;for(let ne of A)ne.forEach((fe,Re)=>{let Ee=v(fe.text);if(!_.every((ue)=>Ee.includes(ue)))return;if(J.set(fe.chunk,(J.get(fe.chunk)??0)+1),Z++,Z<=L||z.length>=Q)return;let ee=ne.slice(Math.max(0,Re-2),Re+3);z.push(`${R} chunk ${fe.chunk} line ${fe.line}:
168
+ ${Vc(ee," ")}`)});if(!Z)return c(`${k}No matches`);if(!z.length)return c(`${k}No matches at offset ${L} (total ${Z})`);let re=Z-L-z.length,U=J.size>1?` (all matches by chunk: ${[...J].map(([ne,fe])=>`${ne} ${fe}`).join(", ")})`:"";return c(`${k}${z.join(`
169
+
170
+ `)}${re>0?`
171
+
172
+ \u2026 ${re} more matches${U}; continue with offset=${L+z.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=E({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),chunk_id:n(a({description:"Chunk to read"})),seq:n(T({description:"User message to read (from a user-text-reference)"})),offset:n(T({minimum:0,description:"First line (default 0)"})),limit:n(T({minimum:1,maximum:yg,description:`Lines to return (default ${yg})`}))}),async execute(f,h){let{scope:x,seq:I,runs:S,reference:R,both:k}=u(h),A;if(I!==void 0)A=X$(x.records,I);else if(h.chunk_id){let L=S().find((z)=>z.id===h.chunk_id);if(!L)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);A=hu(L)}else{let L=S().map((z)=>`${R} ${z.id} (${z.status}, ${hu(z).length} lines)`);return c(L.length?`Pass chunk_id or seq. Chunks in this session:
173
+ ${L.join(`
174
+ `)}`:"This session has no history yet")}let v=h.offset??0,_=A.slice(v,v+(h.limit??yg));if(!_.length)return c(`No lines at offset ${v} (total ${A.length})`);let Q=A.length-v-_.length;return c(`${k}${R} ${I!==void 0?`seq=${I}`:h.chunk_id}
175
+ ${Vc(_)}${Q>0?`
176
+
177
+ \u2026 ${Q} more lines; continue with offset=${v+_.length}`:""}`)}});return[m,p]}import{existsSync as YG,statSync as Y$}from"fs";import{isAbsolute as Z$,relative as ZG,resolve as ev}from"path";var ql=200,eK=30000,Fl=Bun.which("rg");async function xg(e,o,i){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[m,p,f]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(f>1)throw Error(p.trim()||`${e[0]} exited with ${f}`);return m}function tv(e){let o=(p)=>p?Z$(p)?p:ev(e,p):e,i=(p)=>{let f=ZG(e,p);return f&&!f.startsWith("..")&&!Z$(f)?f:p},u=E({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
178
+ - Respects .gitignore and skips .git. Use it instead of find or ls -R.
179
+ - To search file contents, use grep.`,parameters:l({pattern:a({description:"Glob pattern, matched relative to path"}),path:n(a({description:"Directory to search (default: working directory)"}))}),async execute(p,f,h){let x=o(f.path),I=!1;try{I=Y$(x).isDirectory()}catch{}if(!I)throw Error(`Directory not found: ${i(x)}`);let S;if(Fl)S=(await xg([Fl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",f.pattern],x,h)).split(`
180
+ `).filter(Boolean);else{S=[];for await(let v of new Bun.Glob(f.pattern).scan({cwd:x,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(v))S.push(v)}if(!S.length)return c("No files found");let R=S.map((v)=>{let _=ev(x,v);try{return{path:_,time:Y$(_).mtimeMs}}catch{return{path:_,time:0}}});R.sort((v,_)=>_.time-v.time);let k=R.slice(0,ql).map((v)=>i(v.path)),A=S.length-k.length;return c(`${k.join(`
181
+ `)}${A>0?`
182
+ \u2026 ${A} more files; narrow the pattern`:""}`)}}),m=E({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
183
+ - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
184
+ - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
185
+ - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
186
+ - Use this instead of running grep or rg through bash.`,parameters:l({pattern:a({description:"Regular expression"}),path:n(a({description:"File or directory to search (default: working directory)"})),glob:n(a({description:"Only search files matching this glob"})),output:n(g([s("files"),s("content"),s("count")],{description:"Output mode (default files)"})),ignore_case:n(B()),context:n(T({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(p,f,h){let x=o(f.path);if(!YG(x))throw Error(`Path not found: ${i(x)}`);let I=f.output??"files",S;if(Fl){let A=[Fl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(f.ignore_case)A.push("-i");if(f.glob)A.push("--glob",f.glob);if(I==="files")A.push("-l");else if(I==="count")A.push("-c");else if(A.push("-n","--no-heading"),f.context)A.push("-C",String(f.context));A.push("--",f.pattern,x),S=await xg(A,e,h)}else{let A=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(f.ignore_case)A.push("-i");if(f.glob)A.push(`--include=${f.glob}`);if(I==="files")A.push("-l");else if(I==="count")A.push("-c");else if(A.push("-n"),f.context)A.push(`-C${f.context}`);A.push("--",f.pattern,x),S=await xg(A,e,h)}let R=`${e}/`,k=S.split(`
187
+ `).filter(Boolean).map((A)=>A.startsWith(R)?A.slice(R.length):A).filter((A)=>I!=="count"||!A.endsWith(":0"));if(!k.length)return c("No matches");if(I==="files"&&k.length>ql)return c(`${k.slice(0,ql).join(`
188
+ `)}
189
+ \u2026 ${k.length-ql} more files; narrow the search`);return c(it(k.join(`
190
+ `),eK,e))}});return[Pe(u,"find","find_files","list_files","file_search","ls","list","list_dir"),Pe(m,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function rv(e){return Pe(E({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
191
+ Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
192
+ - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
193
+ - Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
194
+ - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:H(l({content:a({minLength:1,description:"What to do, in imperative form"}),status:g(sy.map((o)=>s(o)))}))}),async execute(o,i){let u=i.todos.map((f)=>({content:f.content,status:f.status}));e(u);let m=u.filter((f)=>f.status==="completed").length,p=u.find((f)=>f.status==="in_progress");return c(`Todo list updated (${m}/${u.length} completed${p?`; in progress: ${p.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function nv(e){let o=me(e);return{target:o,hard:o,index:o}}class jl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},i){this.records=e;this.cwd=o;if(i)this.defaultPolicy=new zc(e,i,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??nv(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??me(e)}prepare(e,o,i,u,m=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,i,u);let p=e.reduce((I,S)=>I+q(S),0)+ki(o),f=Math.max(0,me(i)*this.recoveryRatio-p),h=Me(u??this.records(),i,nv(i),{cwd:this.cwd()}).messages,x=h.reduce((I,S)=>I+q(S),0);if(m&&x>f)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(x>f&&h.length>1){let I=h.shift();if(I)x-=q(I);while(h[0]?.role==="toolResult"){let S=h.shift();if(S)x-=q(S)}}if(x>f){let I=h.at(-1),S=I&&"content"in I&&typeof I.content==="string"?I.content:"[Context omitted: use history tools to retrieve earlier messages.]";h.length=0;let R=S;while(R&&q({role:"user",content:R,timestamp:0})>f)R=R.slice(Math.ceil(R.length/2));if(R)h.push({role:"user",content:R,timestamp:0});x=h.reduce((k,A)=>k+q(A),0)}return this.lastMessageCount=h.length,{messages:[...e,...h],estimate:p+x}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as bg,readFileSync as tK}from"fs";import{homedir as rK}from"os";import{dirname as ov,join as Eg,resolve as nK}from"path";var oK=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
195
+
196
+ # How to work
197
+
198
+ - 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.
199
+ - 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.
200
+ - 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.
201
+ - 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.
202
+
203
+ # Making changes
204
+
205
+ - 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.
206
+ - 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.
207
+ - 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.
208
+ - 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).
209
+ - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
210
+ - 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.
211
+
212
+ # Verifying
213
+
214
+ - 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.
215
+ - 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.
216
+ - 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.
217
+ - 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.
218
+ - 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.
219
+
220
+ # Tools
221
+
222
+ - Tool calls are the only way to act; describing an action does not perform it.
223
+ - 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.
224
+ - 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.
225
+ - 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.
226
+ - 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.
227
+ - 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.
228
+ - 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 &&.
229
+ - 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.
230
+
231
+ # Honesty
232
+
233
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
234
+ - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
235
+ - When the user asks you to run something, run it, even when you can predict the result.
236
+ - If a step failed, was skipped or could not be verified, say which one and why.
237
+
238
+ # Safety
239
+
240
+ - 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.
241
+ - 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.
242
+ - 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.
243
+ - Never print, log or commit secrets such as API keys, tokens or passwords.
244
+
245
+ # Communication
246
+
247
+ - Reply in the same language the user writes in.
248
+ - 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.
249
+ - Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
250
+ - Do not use emojis unless the user does or asks for them.
251
+ - When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
252
+ - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,sK=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
253
+
254
+ # Tools
255
+
256
+ - 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.
257
+ - 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.
258
+ - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
259
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
260
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
261
+
262
+ # Communication
263
+
264
+ - Reply in the same language the user writes in.
265
+ - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
266
+ - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,iK=["AGENTS.md","CLAUDE.md"],aK=20000;function sv(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?oK:sK}],i=[];if(e.globalInstructions?.trim())i.push(Ig("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of uK(e.project.directory))i.push(Ig(u.path,u.content));if(e.project.instructions.trim())i.push(Ig(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
267
+
268
+ # Instructions from the user and project
269
+
270
+ 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.
271
+
272
+ ${i.join(`
273
+
274
+ `)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
275
+
276
+ ${cK(e)}`}),o}function Ig(e,o){return`<instructions source="${e}">
277
+ ${le(o.trim(),aK)}
278
+ </instructions>`}function uK(e){let o=[],i=e;for(let u=0;u<20;u++){for(let p of iK){let f=Eg(i,p);if(bg(f)){try{o.unshift({path:f,content:tK(f,"utf8")})}catch{}break}}if(bg(Eg(i,".git"))||i===rK())break;let m=ov(i);if(m===i)break;i=m}return o}function cK(e){let o=e.now??new Date,i=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),m=e.project?.directory??process.cwd(),{shellName:p}=Aa("",e.shell),f=[`Working directory: ${m}`,`Shell: ${p}`,`Date: ${i} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)f.push(e.git??"Git: not a git repository");return`<environment>
279
+ ${f.join(`
280
+ `)}
281
+ </environment>`}function mK(e){let o=nK(e);while(!0){if(bg(Eg(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let i=ov(o);if(i===o)return!1;o=i}}async function iv(e,o){if(o?.aborted||mK(e))return;let i=async(...x)=>{try{let I=Bun.spawn(["git",...x],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[S,R]=await Promise.all([new Response(I.stdout).text(),I.exited]);return R===0?S.trim():void 0}catch{return}},u=await i("rev-parse","--abbrev-ref","HEAD");if(u===void 0)return;let[m="",p=""]=await Promise.all([i("status","--short"),i("log","--oneline","-5")]),f=m?m.split(`
282
+ `):[],h=f.length>30?[...f.slice(0,30),`\u2026 ${f.length-30} more`]:f;return[`Git branch: ${u}`,`Git status at session start:${h.length?`
283
+ ${h.join(`
284
+ `)}`:" clean"}`,p?`Recent commits:
285
+ ${p}`:"Recent commits: none"].join(`
286
+ `)}function cr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((m)=>m.entry.type==="compaction"))?Dl(e.records,e.history):[],u=e.directory??process.cwd();return[...Q$(u,new hg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...tv(u),rv(e.onTodos),...i]}class Pi{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!ay.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!iy.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let i=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[u];else i[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let m=u,p=m.source??"core",f=u.name.toLowerCase(),h=m.defer??"always",x="suggestion";if(o.global)h=o.global,x="global";if(Object.hasOwn(o.sources,p))h=o.sources[p]??h,x="source";if(Object.hasOwn(o.tools,f))h=o.tools[f]??h,x="tool";if(p==="core"||m.builtin&&m.defer!=="defer")h="always",x="suggestion";return{name:u.name,source:p,mode:h,origin:x,deferred:h==="defer"}})}}function Sg(e){return{name:e.name,description:e.description,parameters:e.parameters}}function wg(e,o){if(!o)return e;let i=Array.isArray(o.type)?o.type:[o.type],u=e;if(i.includes("number")||i.includes("integer")){let m=typeof u==="string"&&u.trim()?Number(u):u;if(typeof m!=="number"||!Number.isFinite(m))return u;let p=m;if(typeof o.maximum==="number"&&p>o.maximum)p=o.maximum;if(typeof o.minimum==="number"&&p<o.minimum)p=o.minimum;return p===m?u:p}if(typeof u==="string"&&(i.includes("object")||i.includes("array")))try{let m=JSON.parse(u),p=Array.isArray(m);if(typeof m==="object"&&m!==null&&!p&&i.includes("object")||p&&i.includes("array"))u=m}catch{}if(Array.isArray(u)){let m=o.items;if(!m||typeof m!=="object"||Array.isArray(m))return u;return u.map((p)=>wg(p,m))}if(typeof u==="object"&&u!==null&&o.properties){let m={...u};for(let[p,f]of Object.entries(o.properties))if(p in m)m[p]=wg(m[p],f);return m}return u}function pK(e){let o=e.prepareArguments;return{...e,prepareArguments:(i)=>{let u=wg(i,e.parameters);return o?o(u):u}}}function lK(e,o,i){let u=e.prepareArguments?e.prepareArguments(i):i;return cu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class Tg{retrieved=new Map;stub(e,o){let i=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${i}
287
+ (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,m,p,f)=>{let h=JSON.stringify(Sg(e)),x;try{x=lK(e,u,m??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
288
+ Schema: ${h}`),isError:!0}}let I=await e.execute(u,x,p,f),S=I.content.map((R)=>R.type==="text"?{...R,text:it(R.text,Ce,o)}:R);return{...I,content:S}}}}assemble(e,o,i,u){let m=e.map(pK),p=new Set(o.filter((h)=>h.deferred).map((h)=>h.name));if(!p.size)return m;let f=m.filter((h)=>p.has(h.name)&&i(h.name)).sort((h,x)=>h.name<x.name?-1:h.name>x.name?1:0);return[...m.filter((h)=>!p.has(h.name)),...f.map((h)=>this.stub(h,u)),Pe(E({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:a(),max_results:n(T({minimum:1,maximum:100}))}),execute:async(h,x)=>{let I=x.query.trim().toLowerCase(),S=I.startsWith("select:")?I.slice(7).split(",").map((k)=>k.trim()):void 0,R=f.filter((k)=>i(k.name)&&(S?S.includes(k.name.toLowerCase()):`${k.name} ${k.description}`.toLowerCase().includes(I))).slice(0,x.max_results??5);return c(JSON.stringify(R.map((k)=>{let A=JSON.stringify(Sg(k)),v=this.retrieved.get(k.name);if(v?.schema===A)return{name:k.name,status:"\u5DF2\u53D6\u56DE",callID:v.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(k.name,{schema:A,callID:h}),Sg(k)})))}}),"tool_search")]}}async function Ul(e,o,i,u){let m=await o.setup(e,u),p=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!i)return m;if(i.has("session.setup"))m=await i.invoke("session.setup",m,e);if(i.has("tools.configure"))m=await i.invoke("tools.configure",m,e);let f=m.systemPrompt,h=m.systemParts?.at(-1);if(h?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let R=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),k=f.length-h.detail.length;f=f.slice(0,k)+R.join("")+h.detail}let x=await i.invoke("prompt.fragments",[],e),I=[...m.tools,...i.tools()],S=i.has("tools.visible")?await i.invoke("tools.visible",I,e):I;return{...m,systemPrompt:f+x.join(""),tools:S}}var dK=3,av={attempts:10,delayMs:2000},fK=/\b(400|401|402|403|404|405|413|422)\b|invalid[_ ]?(api[_ ]?key|request|argument|model)|unauthori[sz]ed|forbidden|permission|authentication|incorrect api key|not[_ ]found|insufficient|billing|quota|credit|content[_ ]?(policy|filter)|safety|unsupported|does not support/i;function hK(e,o){if(e.stopReason!=="error")return!1;if(ha(e,o))return!1;return!fK.test(e.errorMessage??"")}function uv(e,o,i){if(ha(e,o))return!0;if(i?.preserveHistory!==!0)return!1;return e.errorMessage===(i.overflowError??"Context exceeds the request budget")}function gK(e,o){return new Promise((i,u)=>{if(o.aborted)return u(o.reason);let m=setTimeout(()=>{o.removeEventListener("abort",p),i()},e),p=()=>{clearTimeout(m),u(o.reason)};o.addEventListener("abort",p,{once:!0})})}async function cv(e,o,i,u,m,p,f,h,x=!1){let I=x?void 0:await o?.invoke("run.start",{text:p},e);if(I)p=I.text;if(h.throwIfAborted(),p===void 0)await u.resume();else await u.prompt(p,f);let S=0,R=0;while(S<dK){let _=e.records.findLast((L)=>L.raw?.role==="assistant")?.raw;if(_?.stopReason!=="error")return;if(!uv(_,m.contextWindow,i)){if(!hK(_,m.contextWindow)||R>=av.attempts)return;R++,await gK(av.delayMs,h),await u.retry();continue}if(!e.context.recover(m)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}h.throwIfAborted(),S++,await u.retry()}let A=e.records.findLast((v)=>v.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&A?.stopReason==="error"&&uv(A,m.contextWindow,i))throw Error(i.overflowError??"Context exceeds the request budget")}async function mv(e,o,i,u,m,p){p.throwIfAborted();let f,h;try{h=await Promise.race([Ul(e,o,i(),p),new Promise((k,A)=>{f=()=>A(p.reason),p.addEventListener("abort",f,{once:!0})})])}finally{if(f)p.removeEventListener("abort",f)}p.throwIfAborted();let x=i(),I=(k)=>{if(!x)return k;return{...k,execute:async(A,v,_,Q)=>{let L=u()??h.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),z=L?x.policy(L):void 0;if(L&&!z?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${L}`);let J=await x.invoke("tool.before_call",{name:k.name,callID:A,args:v},e);if(J.block)throw Error(J.block);let Z=await K.run(e,()=>k.execute(A,J.args,_,Q));return x.invoke("tool.after_result",Z,e)}}};if(x)h.tools=h.tools.map(I);let S=h.tools,R=()=>{if(!S.some((A)=>A.name==="history_grep")){if(e.records.some((v)=>v.entry.type==="compaction")){let _=Dl(()=>e.records,(Q)=>e.resolveHistory(Q)).map(I);for(let Q of _)if(!S.some((L)=>L.name===Q.name))S.push(Q)}}let k=new Pi(o.store).partition(S);return h.tools=m.assemble(S,k,(A)=>e.permitsTool(A),h.cwd),h.tools};return h.tools=R(),{setup:h,executionTools:S,assemble:R}}function pv(e,o,i,u,m,p,f){return{response:async(h)=>{let x=await o()?.invoke("model.after_response",h,e)??h;if(x.role==="assistant")for(let I of x.content){if(I.type!=="toolCall"||I.name.toLowerCase()!=="tool_call")continue;let S=I.arguments.name;if(typeof S==="string"){let R=f.find((k)=>k.name.toLowerCase()===S.toLowerCase());I.arguments.name=R?.name??S}}return x},payload:(h)=>o()?.invoke("model.before_request",h,e)??Promise.resolve(h),transformContext:(h)=>o()?.invoke("transformContext",h,e)??Promise.resolve(h),boundary:async()=>{if(u())return!0;let h=await o()?.invoke("step.after",{notices:[]},e);for(let I of h?.notices??[])e.notice(I);await p.work;let x=await p.flushNotices();if(x&&!m())e.agent?.steer(x)},prepare:async(h,x,I)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let S=await o()?.invoke("model.check",{},e);if(S?.error)throw Error(S.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let L of R?.notices??[])e.notice(L);await p.work,await p.flushNotices();let k=await o()?.invoke("projection.before",e.records,e),A=await o()?.invoke("projection.prefix",[],e)??[],v=e.context.prepare([...h,...A],x,I,k,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&v.estimate>me(I))throw Error(i()?.overflowError??"Context exceeds the request budget");let _=v.messages,Q=await o()?.invoke("projection.after",_,e)??_;return du(c$(Q))}}}async function lv(e,o,i){let u=o.store.pendingNotices(e.id);if(!u.length)return;let m=u,p=o.plugins?.pin();try{if(p){let A=await p.invoke("notice.deliver",u,e);m=u.map((v,_)=>({...v,text:A[_]?.text??v.text}))}}finally{await p?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let f=m.map((A)=>A.text).join(`
289
+ `),h=m.map((A)=>o.plugins?.noticeSource(A.sourceKind)),x=Math.max(800,...h.map((A)=>A?.summaryLimit??800)),I=f.length>x?`
290
+ [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${h.find((A)=>A?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
291
+ ${f.slice(0,x)}${I}`,k={role:"user",content:R,timestamp:Date.now()};return i({type:"user",text:R,notices:u.map(({text:A,...v})=>v)},k),k}class Rg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,i,u,m,p,f,h){this.session=e;this.context=o;this.isStopped=i;this.isRunning=u;this.waiting=m;this.start=p;this.invalidateAgent=f;this.append=h}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let i of e){if(i.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:i.dedupeKey,sourceKind:i.sourceKind,sourceID:i.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((i)=>i.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((i)=>{this.failure=i}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=lv(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((o)=>o.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var yK=new Set(["authorization","proxy-authorization","x-api-key","api-key","x-goog-api-key","x-auth-token","x-amz-security-token","cookie","set-cookie"]);function kg(e){let o={};for(let[i,u]of Object.entries(e)){if(!yK.has(i.toLowerCase())){o[i]=u;continue}let m=/^bearer\s+/i.exec(u)?.[0];o[i]=m?`${m}***`:"***"}return o}function dv(e,o,i,u){let p=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((U,ne)=>({id:`system-${ne}`,label:U.label,detail:U.detail,tokens:F(U.detail)+(ne===0?16:0)})),f=i.tools.map((U)=>{let ne=U,fe=ne.defer==="defer"||U.description.includes("(Parameters not inlined: use toolsearch");return{name:U.name,description:U.description,group:ne.group??"\u5185\u7F6E",schema:U.parameters,deferred:fe}});p.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:ki(i.tools),detail:JSON.stringify(f,null,2)});let h=p.reduce((U,ne)=>U+ne.tokens,0),x=u!==void 0?e.records.filter((U)=>U.entry.seq<=u):e.records,I=Me(x,o,e.context.budget(o),{inspect:!0,cwd:i.cwd,trim:{fixed:h,limit:e.context.previewLimit(o)}}),S,R=0,k=0;for(let U of x){if(U.raw?.role!=="assistant")continue;let ne=U.raw.usage;S??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},S.input+=ne.input,S.output+=ne.output,S.cacheRead+=ne.cacheRead,S.cacheWrite+=ne.cacheWrite,S.cost+=ne.cost.total;let fe=U.entry.generationMs??U.raw.generationMs;if(typeof fe==="number"&&fe>0&&ne.output>0)R+=fe,k+=ne.output}if(S){let U=S.input+S.cacheRead+S.cacheWrite;if(U>0)S.cacheHitRate=S.cacheRead/U}if(S&&R>0&&k>0)S.generationMs=R,S.tps=Number((k/(R/1000)).toFixed(1));let A=h+I.tokens,v=e.context.calibrationRatio??1,_=Math.round(A*v),Q=x.findLast((U)=>U.raw?.role==="assistant"),L=Q?.raw,J=(Q?x.filter((U)=>U.entry.seq>Q.entry.seq&&U.raw):x.filter((U)=>U.raw)).length>0,Z,re;if(L){let U=L.usage,ne=U.input+U.cacheRead+U.cacheWrite;if(ne>0)Z=ne,re=U.cacheRead/ne}return{contextWindow:o.contextWindow,usableWindow:me(o),items:[...p,...I.items],calibratedTokens:_,calibrationRatio:v,lastInputTokens:Z,lastCacheHitRate:re,hasPendingOutput:J,tools:f,usage:S}}class ft extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class ce extends Error{constructor(e="session"){super(`${e} is busy`)}}var Ag="medium";class Bl{row;ctx;events;notices;lease;policyID;discovery=new Tg;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Ul(this,this.ctx,e);return new Pi(this.ctx.store).partition(o.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new ce;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,i){this.row=e;this.ctx=o;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new Rg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let m=this.entries(0,["extension","run"],!1),p=m.findLast((h)=>h.type==="extension"&&h.namespace==="session"&&h.kind==="stop_requested"),f=m.findLast((h)=>h.type==="run"&&h.state==="start");if(p&&p.seq>(f?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let h=this.entries(u.seq,["user"],!1).length>0,x=o.store.pendingNotices(e.id).some((I)=>I.wake&&I.recovery!=="discard");if(!this.stopped&&(h||x))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new jl(()=>this.records,()=>this.cwd,(h,x)=>this.appendCompaction(h,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=Tn(this.ctx.models,this.row.model);if(!e)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");return e}lastModelRequest(){let e=this.lastRequestSnapshot;return e?{...e,headers:kg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:kg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??Ag}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get runningTools(){return this.agent?.agent.state.pendingToolCalls.size??0}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:i,model:u,thinking:m,metadata:p,created:f,updated:h,todos:x}=this.row;return{id:e,title:o,projectID:i,model:u,thinking:m??Ag,metadata:p,created:f,updated:h,archivedAt:this.row.archivedAt,status:this.status,todos:x,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,o,i){return this.ctx.store.entriesAround(this.row.id,e,o,i)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,i=!0){return this.ctx.store.entries(this.row.id,e,o,i)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let i=Tn(this.ctx.models,this.row.model);if(!i)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),m;try{m=this.setup??await Ul(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)m.tools=this.discovery.assemble(m.tools,new Pi(this.ctx.store).partition(m.tools),(f)=>this.permitsTool(f),m.cwd);let p=dv(this,i,m,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:p};return p})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new ft}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!Tn(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,ud(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let i=ud(o),u=Hh(e,i),m=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},u);if(this.recallableSteers.set(m.seq,u),this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((p)=>p.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let i=o.raw,u=this.pendingSteers.indexOf(i);if(u<0){let p=JSON.stringify(i);u=this.pendingSteers.findIndex((f)=>JSON.stringify(f)===p)}let m=!1;if(u>=0)this.pendingSteers.splice(u,1),m=!0;else m=this.agent?.unsteer(i)??!1;if(!m)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new ce;if(e!==void 0)this.stopped=!1;let u=Tn(this.ctx.models,this.row.model);if(!u&&i===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let m=new AbortController;if(this.starting=m,!this.row.title&&e!==void 0)this.row={...this.row,title:xK(e,o)},this.ctx.store.updateSession(this.row);let p=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let f=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=f.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(m.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let h=this.records.filter((R)=>R.entry.seq>p),x=h.filter((R)=>R.entry.type==="user"&&!R.raw);if(x.length>1)return{reason:"interrupted"};let I=x[0];if(I?.entry.type==="user"){if(h.some((R)=>R.entry.seq>I.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=I.entry.text,o=I.entry.attachments,this.pendingUserSeq=I.entry.seq}for(let R of Po(h.filter((k)=>k.raw))){if(R.result)continue;let k=R.message.stopReason;if(k==="error"||k==="aborted")continue;let{body:A,raw:v}=yl(R.call);this.append(A,v)}if(!I&&this.waitingForInput())return{reason:"waiting_user"};let S=this.records.findLast((R)=>R.entry.seq>p&&R.raw)?.raw;if(!I&&S?.role==="assistant")return Wh(S);if(!I&&!S&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let f=await this.prepareAgent(u,m.signal);m.signal.throwIfAborted();while(this.pendingSteers.length>0){let h=this.pendingSteers.shift();if(h)f.steer(h)}return await cv(this,this.lease,this.setup,f,u,e,o,m.signal,i!==void 0&&e===void 0),Wh(this.records.findLast((h)=>h.entry.seq>p&&h.raw?.role==="assistant")?.raw)}).then((f)=>m.signal.aborted?{reason:"aborted"}:f,(f)=>m.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(f)}).then(async(f)=>{try{if(!this.suspended&&f.reason!=="interrupted"){if(!m.signal.aborted&&this.waitingForInput())f={reason:"waiting_user"};if(f.reason!=="interrupted")f=await this.lease?.invoke("run.end",{reason:f.reason,error:f.error},this)??f}}catch(h){f={reason:"error",error:String(h)}}finally{try{await this.lease?.release()}catch(h){f={reason:"error",error:String(h)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...f});let h=Tn(this.ctx.models,this.row.model);if(h)this.context.settle(h)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:i,executionTools:u,assemble:m}=await mv(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=i,this.row.parentID&&(!i.toolPolicy||!this.lease?.policy(i.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=i.cwd,this.agent=H0({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((p)=>!this.pendingSteers.includes(p.raw)).flatMap((p)=>p.raw?[p.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??Ag,captureRequest:(p)=>{this.lastRequestSnapshot=p},captureResponse:(p)=>{this.lastResponseSnapshot=p},steerConsumed:(p)=>this.markSteerConsumed(p),hooks:{tools:m,...pv(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(p,f)=>{if(this.suspended&&f.role==="assistant"&&(f.stopReason==="aborted"||f.stopReason==="error"))return;if(f.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,f);let h=this.loaded?.find((x)=>x.entry.seq===this.pendingUserSeq);if(h)h.raw=f;this.pendingUserSeq=void 0;return}if(f.role==="assistant")this.context.calibrate(f);this.append(p,f)},draft:(p)=>{this.draftParts=p,this.events.draft(p)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let i=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...i?{saved:i}:{}})}measureCompactionSavings(e,o){let i=Tn(this.ctx.models,this.row.model);if(!i)return;let u=this.context.budget(i),m=Me(this.records,i,u,{cwd:this.cwd}).tokens,p={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},f=Me([...this.records,p],i,u,{cwd:this.cwd}).tokens;return{before:m,after:f}}compact(){this.assertWritable();let e=lu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function xK(e,o){let u=(e.trim()||o?.map((m)=>m.name).join(" ")||"").split(`
292
+ `)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var hv=new Set(["user","assistant","tool_result","run","compaction"]),IK=new Set(["user","assistant","toolResult"]);function gv(e,o,i){return{format:ad,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...i?{project:i}:{},records:o.filter((u)=>hv.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function Jo(e){if(!yr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===ad)return bK(e);if(yr(e.info)&&Array.isArray(e.messages))return SK(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 bK(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!yr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let i=0,u=e.records.flatMap((m,p)=>{let f=`records[${p}]`;if(!yr(m)||!yr(m.entry))throw new t(`${f} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let h=m.entry;if(h.type==="notice_pending"||h.type==="extension")return[];if(typeof h.type!=="string"||!hv.has(h.type))throw new t(`${f} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(h.type)}`);let{seq:x,time:I}=h;if(typeof x!=="number"||!Number.isSafeInteger(x)||x<=i)throw new t(`${f} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof I!=="number"||!Number.isFinite(I))throw new t(`${f} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=x,EK(h,f);let S=m.raw;if(S!==void 0&&!(yr(S)&&typeof S.role==="string"&&IK.has(S.role)))throw new t(`${f} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:h,...S===void 0?{}:{raw:S}}]});return{title:Nr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(xv):[],created:Xs(o.created)??Date.now(),updated:Xs(o.updated)??Date.now(),needsRaw:!1,records:u}}function EK(e,o){let i=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);switch(e.type){case"user":if(typeof e.text!=="string")throw i("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw i("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw i("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&Xg.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 SK(e){let o=e.info,i=yr(o.time)?o.time:{},u=yr(o.model)?o.model:void 0,m=e.messages.filter(yr).sort(wK),p=[],f=0,h=0,x=(Q,L)=>{h=Math.max(h,L??h),f+=1,p.push({entry:{...Q,seq:f,time:h}})},I=!1,S=(Q,L)=>{if(!I)return;I=!1,x({type:"run",state:"end",reason:Q,...L?{error:L}:{}},void 0)};for(let Q of m){let L=yr(Q.info)?Q.info:{},z=Array.isArray(Q.parts)?Q.parts.filter(yr):[],J=Xs(yr(L.time)?L.time.created:void 0);if(L.role==="user"){S("done");let Z=TK(z);if(!Z)continue;x({type:"run",state:"start"},J),x(Z,J),I=!0}else if(L.role==="assistant"){if(!I)x({type:"run",state:"start"},J),I=!0;AK(L,z,x);let Z=yv(L.error);if(Z)S(Z.aborted?"aborted":"error",Z.aborted?void 0:Z.message)}}S("done");let R=m.findLast((Q)=>yr(Q.info)&&Q.info.role==="assistant"),k=yr(R?.info)?R.info:void 0,A=Nr(u?.providerID)||Nr(k?.providerID),v=Nr(u?.id)||Nr(k?.modelID),_=A&&v?`${A}/${v}`:void 0;return{title:Nr(o.title),model:_,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(xv):[],created:Xs(i.created)??p[0]?.entry.time??Date.now(),updated:Xs(i.updated)??p.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:p}}function wK(e,o){let i=(m)=>(yr(m.info)&&yr(m.info.time)?Xs(m.info.time.created):void 0)??0,u=(m)=>yr(m.info)?Nr(m.info.id):"";return i(e)-i(o)||u(e).localeCompare(u(o))}function TK(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Nr(u.text)).join(`
293
+
294
+ `),i=e.flatMap((u)=>u.type==="file"?RK(u):[]);if(!o.trim()&&i.length===0)return;return{type:"user",text:o,...i.length?{attachments:i}:{}}}function RK(e){let o=Nr(e.mime)||"application/octet-stream",i=Nr(e.filename)||"file",u=Nr(e.url),m=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(m){let p=m[3]??"";if(o.startsWith("image/"))return[{name:i,mimeType:o,kind:"image",data:m[2]?p:btoa(p)}];if(o.startsWith("text/")||o==="application/json"){let f=m[2]?new TextDecoder().decode(Uint8Array.from(atob(p),(h)=>h.charCodeAt(0))):p;return[{name:i,mimeType:o,kind:"text",data:f}]}return[]}if(u.startsWith("file://"))try{return[{name:i,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function kK(e){let o=[[]];for(let i of e){if(i.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(i.type==="reasoning"||i.type==="text"||i.type==="tool")o.at(-1)?.push(i)}return o.filter((i)=>i.length>0)}function AK(e,o,i){let u=`${Nr(e.providerID)}/${Nr(e.modelID)}`,m=yv(e.error),p=kK(o);p.forEach((f,h)=>{let x=f.flatMap((R)=>{if(R.type==="reasoning")return Nr(R.text).trim()?[{type:"thinking",text:Nr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Nr(R.text).trim()?[{type:"text",text:Nr(R.text)}]:[];return[{type:"tool_call",id:fv(R.callID),name:Nr(R.tool),input:yr(R.state)&&yr(R.state.input)?R.state.input:{}}]}),I=h===p.length-1,S=PK(f);i({type:"assistant",parts:x,model:u,...I&&m&&!m.aborted?{error:m.message}:{}},S);for(let R of f){if(R.type!=="tool")continue;let k=yr(R.state)?R.state:{},A=k.status==="error",v=k.status==="pending"||k.status==="running",_=A?[Nr(k.output),Nr(k.error)].filter(Boolean).join(`
295
+ `):v?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Nr(k.output);i({type:"tool_result",callID:fv(R.callID),name:Nr(R.tool),output:_,isError:A||v},Xs(yr(k.time)?k.time.end:void 0))}})}function fv(e){return Nr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function yv(e){if(!yr(e))return;let o=yr(e.data)?e.data:{};return{message:Nr(o.message)||Nr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function PK(e){for(let o of e){let i=yr(o.time)?Xs(o.time.start):yr(o.state)?CK(o.state):void 0;if(i!==void 0)return i}return}function CK(e){return yr(e.time)?Xs(e.time.start):void 0}function xv(e){if(!yr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function Iv(e,o){let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let m=u.time;switch(u.type){case"user":return{entry:u,raw:$K(u,m)};case"assistant":{let p=u.parts.flatMap((h)=>{if(h.type==="text")return[{type:"text",text:h.text}];if(h.type==="thinking")return[];return[{type:"toolCall",id:h.id,name:h.name,arguments:vK(h.input)}]}),f=p.some((h)=>h.type==="toolCall");return{entry:u,raw:{role:"assistant",content:p,api:o.api,provider:o.provider,model:o.id,usage:i,stopReason:u.error?"error":f?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:m}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:m}};default:return{entry:u}}})}function $K(e,o){let i=(e.attachments??[]).flatMap((p)=>p.kind==="path"?[`<file path=${JSON.stringify(p.data)} />`]:p.kind==="text"?[`<file name=${JSON.stringify(p.name)}>
296
+ ${p.data}
297
+ </file>`]:[]),u=(e.attachments??[]).filter((p)=>p.kind==="image").map((p)=>({type:"image",data:p.data,mimeType:p.mimeType})),m=[...i,...e.text.trim()?[e.text]:[]].join(`
298
+
299
+ `);return{role:"user",content:u.length?[{type:"text",text:m},...u]:m,timestamp:o}}function yr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Nr(e){return typeof e==="string"?e:""}function Xs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function vK(e){return yr(e)?e:{}}function ur(e,o){let i=e.at(-1)?.entry.seq??0,u,m,p;for(let{entry:I}of e){if(I.type==="run"&&I.state==="start")u=I.seq;if(I.seq===o)if(I.type==="user"&&!I.notices)i=(u??I.seq)-1;else m=u;if(I.type==="run"&&I.state==="end"){if(m!==void 0&&u===m)p=I.seq;u=void 0}}let f=e.find((I)=>I.entry.seq===o)?.entry;if(o!==void 0&&!f)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(f&&!(f.type==="user"&&!f.notices)){if(m!==void 0&&p===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=p??f.seq}else if(o===void 0&&u!==void 0)i=e.findLast(({entry:I})=>I.type==="run"&&I.state==="end")?.entry.seq??0;let h=e.filter(({entry:I})=>I.seq<=i&&(I.type!=="compaction"||I.through<=i)),x=new Map(h.map(({entry:I},S)=>[I.seq,S+1]));return h.map((I,S)=>{let R=structuredClone(I);if(R.entry.seq=S+1,R.entry.type==="compaction"){let k=R.entry.through,A=h.findLast(({entry:v})=>v.seq<=k);R.entry.through=A?x.get(A.entry.seq)??0:0}return R})}function pr(e){let o=new Map,i=[];for(let u of e){if(u.type==="assistant"){for(let f of u.parts)if(f.type==="tool_call"&&f.name==="todo")o.set(f.id,f.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let m=o.get(u.callID);if(!m||typeof m!=="object"||!("todos"in m)||!Array.isArray(m.todos))continue;let p=[];for(let f of m.todos){if(!f||typeof f!=="object"||!("content"in f)||typeof f.content!=="string"||!("status"in f)||f.status!=="pending"&&f.status!=="in_progress"&&f.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");p.push({content:f.content,status:f.status})}i=p}return i}import{Buffer as Sv}from"buffer";import{createHash as MK}from"crypto";import{isDeepStrictEqual as Gl}from"util";var Kl="@blob:";function bu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function bv(e,o,i){if(typeof e!=="string"||e.length<256||e.startsWith(Kl))return;let u=Sv.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let m=MK("sha256").update(u).digest("hex");return i.put(m,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Kl}${m}`}function Ev(e,o){if(typeof e!=="string"||!e.startsWith(Kl))return;let i=o.get(e.slice(Kl.length));if(i===void 0)return;return Sv.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Hl(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=bv(m.data,m.mimeType,o);if(p===void 0)return m;return i=!0,{...m,data:p}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((m)=>{let p=bv(m.data,m.mimeType,o);if(p===void 0)return m;return i=!0,{...m,data:p}});if(!i)return e;return{...e,images:u}}return e}function Ys(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=Ev(m.data,o);if(p===void 0)return m;return i=!0,{...m,data:p}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((m)=>{let p=Ev(m.data,o);if(p===void 0)return m;return i=!0,{...m,data:p}});if(!i)return e;return{...e,images:u}}return e}function Yc(e,o){if(!bu(o))return o;if(e.type==="user"){let{merged:i,images:u}=Gc(e.text,e.attachments),m=u.length>0?[{type:"text",text:i},...u]:i,p=Object.keys(o),{role:f,timestamp:h,content:x}=o;if(p.length===3&&f==="user"&&typeof h==="number"&&"content"in o&&Gl(x,m))return{role:"user",timestamp:h};return o}if(e.type==="tool_result"){let{role:i,toolCallId:u,toolName:m,isError:p,timestamp:f,content:h}=o;if(i!=="toolResult"||u!==e.callID||typeof m!=="string"||p!==e.isError||typeof f!=="number")return o;let x=[{type:"text",text:e.output},...(e.images??[]).map((z)=>({type:"image",mimeType:z.mimeType,data:z.data}))];if("details"in o?!Gl(o.details,e.meta):e.meta!==void 0)return o;let{role:S,toolCallId:R,toolName:k,content:A,details:v,isError:_,timestamp:Q,...L}=o;if(Gl(h,x))return{role:"toolResult",...m!==e.name?{toolName:m}:{},...L,timestamp:f};if(Array.isArray(h)){let z=e.images??[],J=0,Z=!0,re=h.map((U)=>{if(bu(U)&&U.type==="image"){let ne=z[J++],fe=Object.keys(U);if(ne&&fe.length===3&&U.mimeType===ne.mimeType&&U.data===ne.data)return{type:"image",mimeType:U.mimeType};Z=!1}return U});if(Z&&J===z.length)return{role:"toolResult",...m!==e.name?{toolName:m}:{},content:re,...L,timestamp:f}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let m=!1,p=u.map((f,h)=>{let x=e.parts[h];if(bu(f)){if(f.type==="text"&&x?.type==="text"&&f.text===x.text){m=!0;let I={...f};return delete I.text,I}if(f.type==="thinking"&&x?.type==="thinking"&&f.thinking===x.text){m=!0;let I={...f};return delete I.thinking,I}if(f.type==="toolCall"&&x?.type==="tool_call"&&f.id===x.id&&f.name===x.name&&"arguments"in f&&Gl(f.arguments,x.input)){m=!0;let I={...f};return delete I.id,delete I.name,delete I.arguments,I}}return f});if(!m)return o;return{...o,content:p}}return o}function Pg(e,o){if(!bu(o))return o;if(e.type==="user"){let{role:i,timestamp:u}=o;if(i==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:m,images:p}=Gc(e.text,e.attachments);return{role:"user",content:p.length>0?[{type:"text",text:m},...p]:m,timestamp:u}}return o}if(e.type==="tool_result"){let{role:i,timestamp:u}=o;if(i==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:p,toolName:f,content:h,timestamp:x,...I}=o,S;if(Array.isArray(h)){let R=e.images??[],k=0;S=h.map((A)=>{if(bu(A)&&A.type==="image"&&!("data"in A)){let v=R[k++];if(v)return{type:"image",mimeType:A.mimeType,data:v.data}}return A})}else S=[{type:"text",text:e.output},...(e.images??[]).map((R)=>({type:"image",mimeType:R.mimeType,data:R.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof f==="string"?f:e.name,content:S,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...I,timestamp:u}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u))return o;let m=!1,p=u.map((f,h)=>{let x=e.parts[h];if(bu(f)){if(f.type==="text"&&!("text"in f)&&x?.type==="text"){m=!0;let{type:I,...S}=f;return{type:I,text:x.text,...S}}if(f.type==="thinking"&&!("thinking"in f)&&x?.type==="thinking"){m=!0;let{type:I,...S}=f;return{type:I,thinking:x.text,...S}}if(f.type==="toolCall"&&!("arguments"in f)&&x?.type==="tool_call"){m=!0;let{type:I,...S}=f;return{type:I,id:x.id,name:x.name,arguments:structuredClone(x.input),...S}}}return f});if(!m)return o;return{...o,content:p}}return o}function wv(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(x,I,S){o.run(x,I,S)},get(x){return i.get(x)?.data}},m=e.query("SELECT session_id, seq, body, raw FROM entries").all(),p=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),f=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),h=0;return e.transaction(()=>{for(let x of m){let I;try{I=JSON.parse(x.body)}catch{continue}let S=Ys(I,u),R=Hl(S,u),k=R===I?x.body:JSON.stringify(R),A=x.raw;if(x.raw!==null)try{let v=JSON.parse(x.raw),_=Pg(S,v),Q=Yc(S,_);A=JSON.stringify(Q)}catch{A=x.raw}if(k!==x.body)p.run(k,A,x.session_id,x.seq),h++;else if(A!==x.raw)f.run(A,x.session_id,x.seq),h++}})(),h}import{Database as OK}from"bun:sqlite";import{chmodSync as Tv,existsSync as _K,mkdirSync as LK}from"fs";import{dirname as NK}from"path";var Cg=[`
300
+ CREATE TABLE projects (
301
+ id TEXT PRIMARY KEY,
302
+ name TEXT NOT NULL,
303
+ directory TEXT NOT NULL UNIQUE,
304
+ instructions TEXT NOT NULL DEFAULT '',
305
+ created INTEGER NOT NULL,
306
+ updated INTEGER NOT NULL
307
+ );
308
+ CREATE TABLE automations (
309
+ id TEXT PRIMARY KEY,
310
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
311
+ name TEXT NOT NULL,
312
+ prompt TEXT NOT NULL,
313
+ schedule TEXT NOT NULL,
314
+ model TEXT NOT NULL,
315
+ enabled INTEGER NOT NULL,
316
+ created INTEGER NOT NULL,
317
+ updated INTEGER NOT NULL,
318
+ next_run INTEGER,
319
+ last_run INTEGER,
320
+ last_session_id TEXT
321
+ );
322
+ CREATE TABLE sessions (
323
+ id TEXT PRIMARY KEY,
324
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
325
+ automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
326
+ title TEXT NOT NULL DEFAULT '',
327
+ model TEXT NOT NULL,
328
+ todos TEXT NOT NULL DEFAULT '[]',
329
+ created INTEGER NOT NULL,
330
+ updated INTEGER NOT NULL
331
+ );
332
+ CREATE INDEX sessions_project ON sessions(project_id);
333
+ CREATE TABLE entries (
334
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
335
+ seq INTEGER NOT NULL,
336
+ time INTEGER NOT NULL,
337
+ body TEXT NOT NULL,
338
+ raw TEXT,
339
+ PRIMARY KEY (session_id, seq)
340
+ ) WITHOUT ROWID;
341
+ `,"","","",`
342
+ ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
343
+ ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
344
+ ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
345
+ CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
346
+ ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
347
+ 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,
348
+ PRIMARY KEY (namespace, key));
349
+ CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
350
+ PRIMARY KEY (namespace, version));
351
+ 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);
352
+ CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
353
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
354
+ END;
355
+ CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
356
+ INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
357
+ END;
358
+ CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
359
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
360
+ END;
361
+ CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
362
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
363
+ END;
364
+ CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
365
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
366
+ END;
367
+ CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
368
+ INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
369
+ END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
370
+ WHERE json_extract(body,'$.type')='compaction';
371
+ CREATE TABLE IF NOT EXISTS blobs (
372
+ hash TEXT PRIMARY KEY,
373
+ mime TEXT NOT NULL,
374
+ data BLOB NOT NULL
375
+ ) WITHOUT ROWID;
376
+ CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`,"ALTER TABLE projects ADD COLUMN position INTEGER NOT NULL DEFAULT 0;","ALTER TABLE projects ADD COLUMN closed_at INTEGER;"];var DK=[20,50,100,200,400,800];function qK(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function $g(e){let o=0;while(!0)try{return e()}catch(i){let u=DK[o];if(u===void 0||!qK(i))throw i;o++,Bun.sleepSync(u)}}function Rv(e,o){if(e!==":memory:")LK(NK(e),{recursive:!0});let i=new OK(e,{create:!0,strict:!0}),u=(p,f=!0)=>new Proxy(function(...h){return Reflect.apply(p,this,h)},{apply(h,x,I){Ls();let S=o.length===0&&!i.inTransaction,R=f?Reflect.get(p,"immediate"):void 0,k=()=>{let A=[];o.push(A);let v=!1;try{let _=typeof R==="function"?Reflect.apply(R,p,I):Reflect.apply(h,x,I);return v=!0,_}finally{o.pop();let _=o.at(-1);if(v&&_)_.push(...A);else for(let Q of A)if(v)Q.commit();else Q.rollback()}};return S?$g(k):k()},get(h,x){let I=Reflect.get(p,x);if(["deferred","immediate","exclusive"].includes(String(x))&&typeof I==="function")return u(I,!1);return I}}),m=new Proxy(i,{get(p,f){let h=Reflect.get(p,f,p);if(typeof h!=="function")return h;return(...x)=>{Ls();let R=(f==="run"||f==="exec")&&o.length===0&&!i.inTransaction?$g(()=>Reflect.apply(h,p,x)):Reflect.apply(h,p,x);if(f==="transaction"&&typeof R==="function")return u(R,!0);if(f!=="query"&&f!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(k,A,v){let _=Reflect.get(k,A,k);if(typeof _!=="function")return _;return(...Q)=>{Ls();let J=(A==="run"||A==="get"||A==="all"||A==="values")&&o.length===0&&!i.inTransaction?$g(()=>Reflect.apply(_,k,Q)):Reflect.apply(_,k,Q);return J===k?v:J}}})}}});if(e!==":memory:")Tv(e,384);if(m.run("PRAGMA journal_mode = WAL"),m.run("PRAGMA synchronous = FULL"),m.run("PRAGMA foreign_keys = ON"),m.run("PRAGMA busy_timeout = 10000"),m.run("PRAGMA mmap_size = 268435456"),FK(m),m.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),m.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let p of["-wal","-shm"]){let f=e+p;if(_K(f))Tv(f,384)}return m}function FK(e,o=Cg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=i;u<o.length;u++)e.transaction(()=>{let m=o[u]??"",p=Array.isArray(m)?m:u>=4?jK(m):[m];for(let f of p)try{if(f.trim())e.run(f)}catch(h){if(!(h instanceof Error)||!/already exists|duplicate column name/i.test(h.message))throw h}e.run(`PRAGMA user_version = ${u+1}`)})()}function jK(e){let o=[],i=0,u=0,m=[],p=!1,f=0,h=(x)=>{let I=e.slice(i,x).trim();if(I)o.push(I);i=x+1,m=[],p=!1,f=0};while(u<e.length){let x=e[u];if(x==="'"||x==='"'||x==="`"||x==="["){let I=x==="["?"]":x;u++;while(u<e.length)if(e[u]===I)if(I!=="]"&&e[u+1]===I)u+=2;else break;else u++;u++;continue}if(x==="-"&&e[u+1]==="-"){let I=e.indexOf(`
377
+ `,u);u=I===-1?e.length:I+1;continue}if(x==="/"&&e[u+1]==="*"){let I=e.indexOf("*/",u+2);u=I===-1?e.length:I+2;continue}if(/[A-Za-z_]/.test(x)){let I=u+1;while(I<e.length&&/[A-Za-z0-9_$]/.test(e[I]))I++;let S=e.slice(u,I).toUpperCase();if(m.length<3)m.push(S),p=m[0]==="CREATE"&&(m[1]==="TRIGGER"||m[2]==="TRIGGER");if(p){if(S==="BEGIN"||S==="CASE"&&f>0)f++;else if(S==="END"&&f>0)f--}u=I;continue}if(x===";"&&f===0)h(u);u++}return h(e.length),o}var Wl=({position:e,closed_at:o,...i})=>({...i,closedAt:o??null}),zl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var Vl=new Set(["user","run","extension","notice_pending","compaction"]);class Jl{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=Rv(e,this.entryTransactions),this.blobs={put:(o,i,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,i,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Wl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Wl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Wl(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[i,u]of e.entries())o.run(i,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){let o=this.sessionIDs(e);for(let i of o)this.invalidateEntryCache(i);this.db.transaction(()=>{let i=new Set;for(let u of o)for(let m of this.collectSessionBlobHashes(u))i.add(m);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(i)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(zl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(zl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(zl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,i){this.insertSessionWithRecords(o,ur(this.records(e),i))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:m}of o){let{seq:p,time:f,...h}=u,x=h,I=Hl(x,this.blobs),S=m===void 0?null:JSON.stringify(Yc(x,m));i.run(e.id,p,f,JSON.stringify(I),S)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{let i=this.collectSessionBlobHashes(e.id,o);this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e),this.pruneCandidateBlobs(i)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)i.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.transaction(()=>{let o=new Set,i=[e];while(i.length>0){let u=i.pop();if(!u)continue;for(let m of this.collectSessionBlobHashes(u))o.add(m);for(let m of this.childSessions(u))i.push(m.id)}this.db.query("DELETE FROM sessions WHERE id = ?").run(e),this.pruneCandidateBlobs(o)})()}collectSessionBlobHashes(e,o=1){let i=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq >= ? AND body LIKE '%@blob:%'").all(e,o),u=new Set;for(let m of i)for(let p of m.body.matchAll(/@blob:([0-9a-f]{64})/g))if(p[1])u.add(p[1]);return u}pruneCandidateBlobs(e){if(e.size===0)return;let o=this.db.query("SELECT 1 AS one FROM entries WHERE body LIKE ? LIMIT 1"),i=this.db.query("DELETE FROM blobs WHERE hash = ?");for(let u of e)if(!o.get(`%@blob:${u}%`))i.run(u)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,i,u){Ls();let m=this.plugins,p=m?.pinEntry(i),f;try{return f=this.db.transaction(()=>{let h=Math.max(o??0,this.lastSeq(e)+1),I=(p&&m?m.beforeEntry(p,i,e,h):void 0)??i,S=JSON.stringify(I),R=p?JSON.parse(S):I,k={...R,seq:h,time:Date.now()},A=Hl(R,this.blobs),v=A===R&&!p?S:JSON.stringify(A),_=u===void 0?null:JSON.stringify(Yc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,h,k.time,v,_),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return this.cacheAppended(e,k,v),k})(),f}finally{if(p&&m){let h={commit:()=>m.finishEntry(p,e,f),rollback:()=>m.finishEntry(p,e)},x=this.entryTransactions.at(-1);if(x)x.push(h);else h.commit()}}}setEntryRaw(e,o,i){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let m=Ys(JSON.parse(u.body),this.blobs),p=Yc(m,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(p),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,i,u=!0){if(i&&i.length===0)return[];let m=i?.every((f)=>Vl.has(f))?this.cachedEntries(e):void 0;if(m&&i)return m.filter((h)=>h.seq>o&&i.includes(h.type)).map((h)=>({...u?Ys(h,this.blobs):h}));return(i?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...i):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((f)=>({...Ys(JSON.parse(f.body),u?this.blobs:void 0),seq:f.seq,time:f.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let i=[...Vl],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...i).map((m)=>({...JSON.parse(m.body),seq:m.seq,time:m.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,i){let u=this.smallEntries.get(e);if(!u||!Vl.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(i),seq:o.seq,time:o.time})}entriesRange(e,o,i=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,i).map((u)=>({...Ys(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let i=this.lastSeq(e),u=(x)=>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,x),m=u(o),p=m?.type==="run"&&m.state==="start"?o+1:o;if(p>=i)return i;let f=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,p,p);if(!f)return i;if(f.end)return f.seq;let h=u(f.seq-1);return h?.type==="run"&&h.state==="start"&&f.seq-1>p?f.seq-2:f.seq-1}entriesAround(e,o,i,u){let m=this.lastSeq(e);if(m===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let p=Math.min(Math.max(1,o),m),f=this.alignToUser(e,Math.max(1,p-i)),h=this.alignToTurnEnd(e,Math.min(m,p+u));return this.window(e,f,h,m)}entriesFrom(e,o,i){let u=this.lastSeq(e),m=Math.max(1,o);if(m>u)return{entries:[],from:m,to:u,hasBefore:u>0,hasAfter:!1};let p=this.alignToTurnEnd(e,Math.min(u,m+i-1));return this.window(e,m,p,u)}window(e,o,i,u){let m=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,i+1),from:o,to:i,hasBefore:m!==null,hasAfter:i<u}}replayStart(e,o,i){let u=this.lastSeq(e),m=this.lastEntry(e,"compaction"),p=m?.type==="compaction"?m.through+1:1,f=Math.max(1,u-i+1,Math.min(p,u-o+1));return this.alignToUser(e,f)}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((i)=>{let u=Ys(JSON.parse(i.body),this.blobs);return{entry:{...u,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:Pg(u,JSON.parse(i.raw))}}})}lastEntry(e,o){if(Vl.has(o)){let u=this.cachedEntries(e);if(u){let m=u.findLast((p)=>p.type===o);return m?{...Ys(m,this.blobs)}:void 0}}let i=this.db.query("SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return i?{...Ys(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,o){let i=this.truncationEpoch(e),u=o;if(this.plugins){let m=this.plugins.pin();try{let p=await m.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(p===null)return!1;o={...p,dedupeKey:u.dedupeKey,wake:u.wake&&p.wake,recovery:u.recovery}}finally{await m.release()}}return this.db.transaction(()=>{let m=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!m||m.truncation_epoch!==i)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((h)=>h.type==="notice_pending"&&h.notice.dedupeKey===o.dedupeKey||h.type==="user"&&h.notices?.some((x)=>x.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let p of i)if(p.type==="user"&&p.notices)for(let f of p.notices)u.add(f.dedupeKey);else if(p.type==="extension"&&p.namespace==="basalt.notice"&&p.kind==="discarded"&&p.payload&&typeof p.payload==="object"&&"dedupeKey"in p.payload&&typeof p.payload.dedupeKey==="string")u.add(p.payload.dedupeKey);let m=[];for(let p of i)if(p.type==="notice_pending"&&!u.has(p.notice.dedupeKey))m.push(p.notice);return m}}function se(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as UK,readdirSync as Pv,statSync as Cv}from"fs";import{join as $v}from"path";function Zc(e){try{return Cv(e).size}catch{return 0}}function vv(e){try{return Math.round(Cv(e).mtimeMs)}catch{return}}function Mv(e){let o=0,i=0;try{let u=Pv(e,{withFileTypes:!0});for(let m of u){let p=$v(e,m.name);if(m.isDirectory()){let f=Mv(p);o+=f.bytes,i+=f.files}else if(m.isFile())o+=Zc(p),i+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:i}}function BK(e){if(!UK(e))return[];try{return Pv(e,{withFileTypes:!0}).flatMap((o)=>{let i=$v(GK(e),o.name),u=vv(i);if(o.isDirectory()){let m=Mv(i);return[{name:o.name,kind:"directory",bytes:m.bytes,files:m.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Zc(i),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,i)=>i.bytes-o.bytes||o.name.localeCompare(i.name))}catch{return[]}}function GK(e){return e}function Zs(e,o){let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return 0;let u=Object.values(i)[0];return typeof u==="number"?u:0}function kv(e,o){try{let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return;let u=Object.values(i)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var KK={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},HK={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function WK(e){let o=new Map;try{let i=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let p of u)i.set(p.name,p.tbl_name);let m=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let p of m){let f=i.get(p.name)??p.name;if(f.startsWith("sqlite_autoindex_")){let x=f.slice(17),I=x.lastIndexOf("_");if(I>0)f=x.slice(0,I)}let h=o.get(f)??{bytes:0,pages:0};o.set(f,{bytes:h.bytes+(Number(p.bytes)||0),pages:h.pages+(Number(p.pages)||0)})}}catch{}return o}function zK(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
378
+ count(*) AS total,
379
+ sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
380
+ sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
381
+ sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
382
+ sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
383
+ FROM sessions`).get(),u=e.db.query(`SELECT
384
+ count(*) AS total,
385
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
386
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
387
+ min(time) AS oldest_time,
388
+ max(time) AS newest_time
389
+ FROM entries`).get(),p=e.db.query(`SELECT
390
+ coalesce(json_extract(body, '$.type'), 'unknown') AS type,
391
+ count(*) AS count,
392
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
393
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes
394
+ FROM entries
395
+ GROUP BY type
396
+ ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((x)=>({type:String(x.type||"unknown"),count:Number(x.count)||0,bodyBytes:Number(x.body_bytes)||0,rawBytes:Number(x.raw_bytes)||0})),f=p.find((x)=>x.type==="compaction")?.count??0,h=[];try{let x=new Map,I=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let k of I)x.set(k.namespace,Number(k.max_ver)||0);let S=e.db.query(`SELECT
397
+ namespace,
398
+ count(*) AS keys,
399
+ coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
400
+ FROM plugin_kv
401
+ GROUP BY namespace
402
+ ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let k of S){R.add(k.namespace);let A=x.get(k.namespace);h.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...A!==void 0?{migrationVersion:A}:{}})}for(let[k,A]of x.entries())if(!R.has(k))h.push({namespace:k,keys:0,bytes:0,migrationVersion:A})}catch{}return{projectCount:o,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:f,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:p,pluginNamespaces:h}}function Ql(e,o){let i=Zs(e,"page_size"),u=Zs(e,"page_count"),m=Zs(e,"freelist_count"),p=e.db.query("PRAGMA journal_mode").get(),f=e.db.query("SELECT sqlite_version() AS v").get(),h=Zs(e,"synchronous"),x=Zs(e,"auto_vacuum"),I=Zs(e,"cache_size"),S=I<0?Math.abs(I)*1024:I*i,R=Zs(e,"foreign_keys")===1,k=Zs(e,"busy_timeout"),A=kv(e,"encoding")??"UTF-8",v=kv(e,"quick_check(1)")??"ok",_=e.path!==":memory:"?vv(e.path):void 0,Q=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),L=WK(e),z=BK(o);return{dataDir:o,databasePath:e.path,dataBytes:z.reduce((J,Z)=>J+Z.bytes,0),database:{size:Zc(e.path),walSize:Zc(`${e.path}-wal`),shmSize:Zc(`${e.path}-shm`),sqliteVersion:f?.v??"unknown",journalMode:p?.journal_mode??"unknown",synchronous:KK[h]??String(h),foreignKeys:R,busyTimeout:k,encoding:A,autoVacuum:HK[x]??String(x),cacheSizeBytes:S,pageSize:i,pageCount:u,freelistCount:m,reclaimableBytes:m*i,schemaVersion:Zs(e,"user_version"),..._!==void 0?{lastModified:_}:{},integrity:v},analytics:zK(e),entries:z,tables:Q.map(({name:J,sql:Z})=>{let re=J.replaceAll('"','""'),U=e.db.query(`SELECT count(*) AS count FROM "${re}"`).get().count,ne=e.db.query(`PRAGMA table_info("${re}")`).all().map((ee)=>ee.name),fe=e.db.query(`PRAGMA index_list("${re}")`).all().length,Re=Boolean(Z&&/WITHOUT\s+ROWID/i.test(Z)),Ee=L.get(J);return{name:J,rows:U,...Ee?{bytes:Ee.bytes,pages:Ee.pages}:{},indexes:fe,columns:ne,withoutRowid:Re}})}}function Av(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let p of i)for(let f of p.body.matchAll(/@blob:([0-9a-f]{64})/g)){let h=f[1];if(h)u.add(h)}let m=[];for(let p of o)if(!u.has(p.hash))m.push(p.hash);if(m.length===0)return 0;try{e.db.transaction(()=>{let p=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let f of m)p.run(f)})()}catch{return 0}return m.length}function Ov(e,o,i){let u=Ql(e,o);if(i.vacuum)wv(e.db),e.invalidateEntryCache(),Av(e),e.db.run("VACUUM");else if(i.checkpoint)Av(e);if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Ql(e,o)}}var VK=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Xl{plugins;builtinNames;registered=new Map;constructor(e,o){this.plugins=e;this.builtinNames=o}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let o=e.name.trim().toLowerCase();if(!o)throw Error("Tool name cannot be empty");if(VK.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function _v(e,o){let i=sn(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function Lv(e,o){let u=(await e.options.models.getAvailable().catch(()=>[])).map((p)=>({..._v(ot(p),p),available:!0})),m=new Set(u.map((p)=>p.id));for(let p of[o,...e.list(!0,{archive:"all"}).map((f)=>f.model)]){if(m.has(p))continue;let f=Tn(e.options.models,p);if(!f)continue;m.add(p),u.push({..._v(p,f),available:!1})}return{models:u}}function Nv(e,o){if(typeof o!=="string"||!Tn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as JK,statSync as QK}from"fs";import{basename as XK,resolve as YK}from"path";class vg{runtime;sessions;emit;arm;constructor(e,o,i,u){this.runtime=e;this.sessions=o;this.emit=i;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new b("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=YK(e.directory.trim());if(!JK(o)||!QK(o).isDirectory())throw new t(`${o} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(o);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let u=Date.now(),m={id:se("p"),name:e.name?.trim()||XK(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(m),this.emit({type:"project",project:m}),m}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let m of this.sessions.values())if(m.projectID===e)m.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((m)=>typeof m==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((m)=>m.id)),i=new Set(e);if(!(i.size===e.length&&i.size===o.size&&e.every((m)=>o.has(m))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),i=[...this.sessions.values()].filter((m)=>m.projectID===e);if(i.some((m)=>m.status==="busy"))throw new ce("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let m of i)m.close(),this.runtime.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as IH,readFileSync as bH}from"fs";import{homedir as EH}from"os";import{join as Eu}from"path";var Gv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),ZK={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"]},eH=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),_g={'"':['"'],"\u201C":["\u201D",'"']},Mg=(e)=>e!==void 0&&/\s/.test(e),Kv=(e)=>[...new Set(e)],em=(e)=>[...e].length;var tH={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function rH(e,o){let i=e.trim().toLowerCase(),u=new Date(o),m=u.getFullYear(),p=u.getMonth(),f=u.getDate();if(i==="today")return{start:new Date(m,p,f).getTime(),end:new Date(m,p,f+1).getTime()};if(i==="yesterday")return{start:new Date(m,p,f-1).getTime(),end:new Date(m,p,f).getTime()};let h=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(h)return{start:o-Number(h[1])*tH[h[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 x=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!x)return null;let I=Number(x[1]),S=Number(x[3]);if(S<1||S>12)return null;if(x[4]===void 0){if(x[5]!==void 0)return null;return{start:new Date(I,S-1,1).getTime(),end:new Date(I,S,1).getTime()}}let R=Number(x[4]),k=Number(x[5]??0),A=Number(x[6]??0),v=Number(x[7]??0);if(k>23||A>59||v>59)return null;let _=new Date(I,S-1,R,k,A,v);if(_.getMonth()!==S-1||_.getDate()!==R)return null;if(x[5]!==void 0)return{start:_.getTime()};return{start:_.getTime(),end:new Date(I,S-1,R+1).getTime()}}var nH=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),Lg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),Ng=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function Og(e,o,i,u,m,p){let f=i.trim(),h=(I,S)=>e.diagnostics.push({code:I,message:S,filter:o});if(!f)return h("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return h("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let x=m?[f]:f.split(",").map((I)=>I.trim()).filter(Boolean);switch(o){case"in":case"project":for(let I of x){let S=I.toLowerCase();if(o==="in"&&S==="this")e.currentSession=!0;else if(o==="in"&&S==="title")e.fields.push("title");else e.projectID.push(I)}return;case"session":for(let I of x)if(I.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(I);return;case"from":case"role":for(let I of x){let S=ZK[I.toLowerCase()];if(S)e.fields.push(...S);else h("bad_filter_value",`${o}:${I} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...x);return;case"model":e.model.push(...x);return;case"is":for(let I of x){let S=I.toLowerCase();if(S==="error")e.isError=!u;else if(S==="archived")e.archived=!u;else if(S==="compacted")e.compacted=!u;else h("bad_filter_value",`is:${I} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let I=rH(f,p);if(!I)return h("bad_filter_value",`${o}:${f} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=Lg(e.after,I.start);else if(o==="before")e.before=Ng(e.before,I.start);else if(e.after=Lg(e.after,I.start),I.end!==void 0)e.before=Ng(e.before,I.end)}}}function oH(e,o){let i={},u=(v,_)=>{let Q=Kv([...v??[],..._]);return Q.length?Q:void 0},m=u(e?.projectID,o.projectID),p=u(e?.sessionID,o.sessionID),f=u(e?.fields,o.fields),h=u(e?.tools,o.tools),x=u(e?.model,o.model);if(m)i.projectID=m;if(p)i.sessionID=p;if(f)i.fields=f;if(h)i.tools=h;if(x)i.model=x;let I=o.isError??e?.isError,S=o.archived??e?.archived,R=o.compacted??e?.compacted;if(I!==void 0)i.isError=I;if(S!==void 0)i.archived=S;if(R!==void 0)i.compacted=R;let k=Lg(e?.after,o.after),A=Ng(e?.before,o.before);if(k!==void 0)i.after=k;if(A!==void 0)i.before=A;if(k!==void 0&&A!==void 0&&k>=A)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function Dv(e,o){let i=_g[e[o]]??['"'],u="",m=o+1;while(m<e.length){let p=e[m],f=e[m+1];if(p==="\\"&&f!==void 0&&(f==="\\"||f==='"'||f==="\u201C"||f==="\u201D")){u+=f,m+=2;continue}if(i.includes(p))return{text:u,next:m+1,closed:!0};u+=p,m++}return{text:u,next:m,closed:!1}}function qv(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let i=e.slice(0,-1).map((m)=>m.esc||!/[A-Za-z]/.test(m.c)?"":m.c).join("");if(i.length!==e.length-1)return;let u=i.toLowerCase();return Gv.has(u)?u:void 0}function Fv(e,o,i){let u=e==="word"&&!i&&em(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:i,fuzzy:u}}function sH(e,o){let i=[],u=e.length,m=0;while(m<u){if(Mg(e[m])){m++;continue}let p=!1;if(e[m]==="-"){if(m+1>=u||Mg(e[m+1])){m++;continue}p=!0,m++}if(_g[e[m]]){let A=Dv(e,m);if(m=A.next,!A.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let v=A.text.trim();if(v)i.push({kind:"term",negated:p,term:Fv("phrase",v,!1)});continue}let f=[],h;while(m<u&&!Mg(e[m])){let A=e[m],v=e[m+1];if(A==="\\"&&v!==void 0&&eH.has(v)){f.push({c:v,esc:!0}),m+=2;continue}let _=_g[A]?qv(f):void 0;if(_){let Q=Dv(e,m);if(m=Q.next,!Q.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});h={key:_,value:Q.text,quoted:!0};break}f.push({c:A,esc:!1}),m++}if(h){i.push({kind:"filter",negated:p,...h});continue}let x=f.findIndex((A,v)=>v>0&&!A.esc&&(A.c===":"||A.c==="\uFF1A")),I=x>0?qv(f.slice(0,x+1)):void 0;if(I){i.push({kind:"filter",negated:p,key:I,value:f.slice(x+1).map((A)=>A.c).join(""),quoted:!1});continue}if(!p&&f.length===2&&f.every((A)=>!A.esc)&&f[0]?.c==="O"&&f[1]?.c==="R"){i.push({kind:"or"});continue}let S=f[f.length-1],R=f.length>1&&S!==void 0&&!S.esc&&S.c==="*",k=(R?f.slice(0,-1):f).map((A)=>A.c).join("");if(k)i.push({kind:"term",negated:p,term:Fv("word",k,R)})}return i}var iH=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function jv(e){let o=[];return{rest:e.replace(iH,(u,m,p,f,h)=>{let x=f.toLowerCase();if(!Gv.has(x))return u;let I=h.startsWith('"')&&h.length>=2;return o.push({key:x,value:I?h.slice(1,-1).replace(/\\(["\\])/g,"$1"):h,negated:p==="-",quoted:I}),m}).trim(),filters:o}}var Uv={n:`
403
+ `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function aH(e){let o=[...e],i=0,u=(S)=>{let R=o.slice(i,i+S).join("");if(R.length!==S||!/^[0-9a-fA-F]+$/.test(R))return;return i+=S,String.fromCodePoint(Number.parseInt(R,16))},m=()=>{let S=o[i++];if(S===void 0)return{kind:"lit",ch:"\\"};if(S in Uv)return{kind:"lit",ch:Uv[S]};if("dDwWsS".includes(S))return{kind:"any"};if(S==="b"||S==="B")return{kind:"zero"};if(S>="1"&&S<="9"){while(o[i]!==void 0&&/\d/.test(o[i]))i++;return{kind:"any"}}if(S==="k"||S==="p"||S==="P"){let R=o[i];if(R==="<"||R==="{"){let k=R==="<"?">":"}",A=o.indexOf(k,i);i=A<0?o.length:A+1}return{kind:"any"}}if(S==="c")return i++,{kind:"any"};if(S==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(S==="u"){if(o[i]==="{"){let k=o.indexOf("}",i),A=k<0?"":o.slice(i+1,k).join("");if(/^[0-9a-fA-F]{1,6}$/.test(A)&&Number.parseInt(A,16)<=1114111)return i=k+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(A,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:S}},p=()=>{if(o[i]==="^")i++;while(i<o.length&&o[i]!=="]")i+=o[i]==="\\"?2:1;return i++,{kind:"any"}},f=()=>{let S="capture";if(o[i]==="?"){let k=o[i+1],A=o[i+2];if(k===":")S="plain",i+=2;else if(k==="="||k==="!")S="look",i+=2;else if(k==="<"&&(A==="="||A==="!"))S="look",i+=3;else if(k==="<"){let v=o.indexOf(">",i);i=v<0?o.length:v+1}else{S="opaque";while(i<o.length&&o[i]!==":"&&o[i]!==")")i++;if(o[i]===":")i++}}let R=I();if(o[i]===")")i++;if(S==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:S==="opaque"}},h=()=>{let S=o[i],R=1,k=!0;if(S==="*"||S==="?")R=0,i++;else if(S==="+")i++;else if(S==="{"){let A=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(i,i+24).join(""));if(!A)return{quantified:!1,min:1};R=Number(A[1]),i+=A[0].length}else return{quantified:!1,min:1};if(o[i]==="?")i++;return{quantified:k,min:R}},x=()=>{let S=[];while(i<o.length){let R=o[i];if(R==="|"||R===")")break;i++;let k;if(R==="(")k=f();else if(R==="[")k=p();else if(R==="\\")k=m();else if(R===".")k={kind:"any"};else if(R==="^"||R==="$")k={kind:"zero"};else if(R==="*"||R==="+"||R==="?")k={kind:"zero"};else k={kind:"lit",ch:R};S.push({atom:k,...h()})}return S};function I(){let S=[x()];while(o[i]==="|")i++,S.push(x());return S}return I()}function Bv(e){let o=[],i="",u=()=>{if(i)o.push([i]);i=""},m=(p)=>{for(let f of p){let h=f.atom;if(h.kind==="lit")if(f.min>=1){if(i+=h.ch,f.quantified)u()}else u();else if(h.kind==="group"&&!h.opaque&&f.min>=1)if(h.alts.length===1&&!f.quantified)m(h.alts[0]);else u(),o.push(...Hv(h.alts));else u()}};return m(e),u(),o}function Hv(e){if(e.length===1)return Bv(e[0]);let o=[];for(let i of e){let u=Bv(i).filter((m)=>m.length===1).map((m)=>m[0]);if(!u.length)return[];o.push(u.reduce((m,p)=>em(p)>em(m)?p:m))}return[Kv(o)]}var uH=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function cH(e){return!/^\s*$/.test(e)&&(em(e)>=2||uH.test(e))}function mH(e){let o;try{o=Hv(aH(e))}catch{return[]}let i=o.filter((x)=>x.every(cH)),u=i.filter((x)=>x.length===1).map((x)=>x[0]),m=i.filter((x)=>{if(x.length!==1)return!0;let I=x[0];return!u.some((S)=>S!==I&&S.includes(I))}),p=new Set,f=m.filter((x)=>{let I=JSON.stringify(x);if(p.has(I))return!1;return p.add(I),!0}),h=(x)=>Math.min(...x.map(em));return f.sort((x,I)=>h(I)-h(x))}function pH(e){let o=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(o)}function lH(e,o){let i=`m${o?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(u){let m=u instanceof Error?u.message:String(u),p="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(m))p="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(m))p="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(m))p="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(m))p="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${p}`}}}function Yl(e,o={}){let i=o.now??Date.now(),u=e.q??"",m=nH(),p=m.diagnostics,f,h=[];if(e.mode==="regex"){let _=jv(u);for(let Q of _.filters)Og(m,Q.key,Q.value,Q.negated,Q.quoted,i);f=_.rest}else{let _=jv(u),Q=/^\/([\s\S]+)\/$/.exec(_.rest);if(Q){for(let L of _.filters)Og(m,L.key,L.value,L.negated,L.quoted,i);f=Q[1]}else{h=[{include:[],exclude:[]}];for(let L of sH(u,p)){let z=h[h.length-1];if(L.kind==="or")h.push({include:[],exclude:[]});else if(L.kind==="filter")Og(m,L.key,L.value,L.negated,L.quoted,i);else(L.negated?z.exclude:z.include).push(L.term)}h=h.filter((L)=>L.include.length||L.exclude.length)}}let x=h.flatMap((_)=>[..._.include,..._.exclude]),I=f!==void 0?pH(f):x.some((_)=>/\p{Lu}/u.test(_.text)),S=e.caseSensitive??I,R=e.caseSensitive===void 0&&I,k,A;if(f){let _=lH(f,S);if("message"in _)A={code:"bad_regex",message:_.message};else{let Q=mH(f);k={source:f,flags:_.flags,literals:Q,deepScan:Q.length===0}}}let v=oH(e.filters,m);return{mode:f!==void 0?"regex":"text",branches:h,...k?{regex:k}:{},filters:v,currentSession:m.currentSession,caseSensitive:S,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:h.some((_)=>_.include.some((Q)=>Q.fuzzy)),hasPositive:k!==void 0||h.some((_)=>_.include.length>0),hasFilters:Object.keys(v).length>0||m.currentSession,...A?{error:A}:{},diagnostics:p}}var qg={title:8,user:5,assistant:3,error:3,tool_input:2,notice:2,extension:1,thinking:0.5,tool_output:0.5,attachment:0.5},Wv=new WeakMap;function zv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,i=Wv.get(e);if(i?.version===o)return i.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return Wv.set(e,{version:o,terms:u}),u}var Dg=32,dH=1024,tm=(e)=>`"${e.replaceAll('"','""')}"`;function fH(e,o){let i=Array.from({length:o.length+1},(u,m)=>m);for(let u=0;u<e.length;u++){let m=[u+1];for(let p=0;p<o.length;p++)m.push(Math.min((m[p]??0)+1,(i[p+1]??0)+1,(i[p]??0)+Number(e[u]!==o[p])));i=m}return i[o.length]??e.length}function Fg(e,o){let i=Ct(o.trim());if(!i||i.length>64)return[];let u=zv(e),m=u.filter((h)=>h.t.startsWith(i)).slice(0,8).map((h)=>h.t);if(m.length>=8||i.length<4)return m;let p=i.length>=8?2:1,f=[];for(let h of u){if(Math.abs(h.t.length-i.length)>p)continue;if(fH(i,h.t)<=p)f.push(h.t);if(f.length>=8)break}return[...new Set([...m,...f])].slice(0,8)}function Vv(e,o){let i=!1,u=[],m=[],p=o.filters,f=(Q,L)=>{if(!L?.length)return;m.push(`${Q} IN (${L.map(()=>"?").join(",")})`),u.push(...L)};if(f("s.project_id",p.projectID),p.sessionID?.length){m.push(`(${p.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let Q of p.sessionID)u.push(Q,Q)}if(p.archived!==void 0)m.push(`s.archived_at IS ${p.archived?"NOT ":""}NULL`);let h=m.length?m.join(" AND "):"1",x=[...u];if(f("r.kind",p.fields?.map((Q)=>Be[Q])),f("r.tool",p.tools),p.model?.length){m.push(`(${p.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let Q of p.model)u.push(Q,Q)}if(p.isError!==void 0)m.push("r.err = ?"),u.push(Number(p.isError));if(p.compacted!==void 0)m.push(`(r.seq>0 AND r.seq<=COALESCE((
404
+ SELECT max(json_extract(body,'$.through')) FROM store.entries
405
+ WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
406
+ ),0)) = ?`),u.push(Number(p.compacted));if(p.after!==void 0)m.push("r.time >= ?"),u.push(p.after);if(p.before!==void 0)m.push("r.time < ?"),u.push(p.before);let I=e.query("SELECT v FROM meta WHERE k='layout'").get(),S=I&&JSON.parse(I.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),k=(Q)=>{let L=(Z)=>{let re=Ct(Z);if(!Q&&S){if([...re].length<3){let ee=[...re].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(re,`${re}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(re);if([...re].length===1&&ee.length>Dg)ee.length=Dg,i=!0;if(!ee.length)return tm("__basalt_no_short_match__");return`(${ee.map((ue)=>tm(ue.term)).join(" OR ")})`}return tm(re)}let U=/^[\p{Script=Latin}\p{N}]+$/u.test(Z)?[re]:Yi(Z),ne=U.filter((ee)=>!/^[a-z0-9]{1,2}$/.test(ee)),fe=ne.length?ne:U;if(!fe.length){R=!0;return}let Re=fe.map((ee,ue)=>{let $e=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(ee),gt=fe.length>2&&ue>0&&ue<fe.length-1;if($e||gt){let _e=e.query("SELECT n FROM term WHERE t=?").get(ee)?.n??0;return{expression:tm(ee),frequency:_e}}let Ke=[ee],Zt=0;for(let _e of zv(e)){if(!_e.t.includes(ee))continue;if(Zt+=_e.n,_e.t!==ee)Ke.push(_e.t);if(Ke.length>=Dg){i=!0;break}}return{expression:`(${Ke.map(tm).join(" OR ")})`,frequency:Zt}});return Re.sort((ee,ue)=>ee.frequency-ue.frequency),`(${Re.slice(0,(Re[0]?.frequency??1/0)<=dH?1:2).map((ee)=>ee.expression).join(" AND ")})`},z=o.regex?o.regex.literals:o.branches.map((Z)=>Z.include.map((re)=>re.text));if(o.regex){let Z=z.map((re)=>re.map(L));if(Z.some((re)=>re.some((U)=>!U)))return;return Z.map((re)=>`(${re.join(" OR ")})`).join(" AND ")||void 0}let J=z.map((Z)=>{let re=Z.filter((U)=>!/^[a-z0-9]{1,2}$/i.test(U));return(re.length?re:Z).map(L)});if(J.some((Z)=>!Z.length||Z.some((re)=>!re)))return;return J.map((Z)=>`(${Z.join(" AND ")})`).join(" OR ")||void 0},A=k(!1),v=k(!0),_=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:A,out:v,scan:R,where:m.length?m.join(" AND "):"1",bindings:u,forks:_,sessionWhere:h,sessionBindings:x,partial:i,candidateLimit:o.branches.some((Q)=>Q.include.length>0&&Q.include.every((L)=>[...L.text].length<2))?512:void 0}}function Jv(e){let o=1/0,i=-1/0;for(let u of e)o=Math.min(o,u.relevance),i=Math.max(i,u.relevance);return e.map((u)=>({...u,relevance:o===i?-1:-(0.5+0.5*(i-u.relevance)/(i-o))}))}function Zl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(qg).map(([i,u])=>`WHEN ${Be[i]} THEN ${u}`).join(" ")} ELSE 1 END) *
407
+ (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function Qv(e,o,i,u){let m=Math.max(0,u-i)/86400000;return Math.max(0.000000001,-e)*qg[o]*(0.3+0.7/(1+m/30))}function jg(e,o){return e.sort((i,u)=>(o==="best"?u.score-i.score:0)||(o==="recent"?u.time-i.time:0)||(i.sessionID<u.sessionID?-1:Number(i.sessionID>u.sessionID))||u.seq-i.seq||i.field.localeCompare(u.field))}var Bg=512;function Xv(e,o,i){let u=performance.now(),m=o.partial;Gg(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[p,f]of[["fts",o.msg],["fts_out",o.out]]){if(!f)continue;let h=o.candidateLimit??2000,x=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
408
+ ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(f,o.candidateLimit?h+1:h);if(o.candidateLimit&&x.length>h)x.length=h,m=!0;else if(!o.candidateLimit&&x.length===h){let S=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
409
+ AND rowid NOT IN (SELECT value FROM json_each(?))`).all(f,JSON.stringify(x.map((R)=>R.doc)));for(let R of S)x.push(R)}let I=Jv(x);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
410
+ FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(I))}return i?.("match",performance.now()-u),m}function Yv(e,o,i,u,m){let p=performance.now();if(o.candidateLimit){let h=e.query(`
411
+ SELECT r.session_id,r.seq,${Zl(u)} AS score
412
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
413
+ ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
414
+ WHERE ${o.where} LIMIT ${o.candidateLimit+1}
415
+ `).all(...o.bindings);if(h.length>o.candidateLimit)h.length=o.candidateLimit,o.partial=!0;let x=new Map;for(let I of h){let S=i?I.seq:0,R=JSON.stringify([I.session_id,S]),k=x.get(R);if(!k||I.score>k.score)x.set(R,{...I,seq:S})}return m?.("filter",performance.now()-p),[...x.values()].sort((I,S)=>S.score-I.score||(I.session_id<S.session_id?-1:Number(I.session_id>S.session_id))||S.seq-I.seq)}let f=e.query(`
416
+ SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Zl(u)}) AS score
417
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
418
+ ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
419
+ WHERE ${o.where}
420
+ GROUP BY r.session_id${i?",r.seq":""}
421
+ ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
422
+ `).all(...o.bindings);return m?.("filter",performance.now()-p),f}var Zv=new WeakMap,hH=`WITH RECURSIVE lineage(child,ancestor,through) AS (
423
+ SELECT id,forked_from_id,forked_from_seq FROM store.sessions
424
+ WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
425
+ UNION
426
+ SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
427
+ FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
428
+ WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
429
+ )`;function Gg(e,o){if(!o.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${hH} 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();Zv.set(e,new Map(i.map((u)=>[u.ancestor,u.through])))}function Ug(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
430
+ SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
431
+ JOIN store.sessions ps ON ps.id=pr.session_id
432
+ WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
433
+ AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
434
+ AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
435
+ SELECT 1 FROM store.entries original JOIN store.entries copied
436
+ ON copied.session_id=r.session_id AND copied.seq=r.seq
437
+ WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
438
+ ))
439
+ ))`}function eM(e,o,i,u,m){let p=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let f=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,h=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
440
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${f>4000?"INDEXED BY ref_time":""}
441
+ ${h} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${Ug(o)}
442
+ ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${u} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],i);let x=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(x===u){let I=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(I)e.query(`
443
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${h}
444
+ WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
445
+ AND ${o.where} AND ${Ug(o)} AND NOT EXISTS (
446
+ SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
447
+ )`).run(I.session_id,I.seq,...o.bindings,...o.forks?o.bindings:[]),x=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return m?.("filter",performance.now()-p),x}function tM(e,o,i,u,m,p,f){let h=performance.now(),x=o.group==="none",I=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",S=e.query(`
448
+ SELECT r.session_id,${x?"r.seq":"0"} AS seq,
449
+ max(${Zl(m)}) AS relevance,max(r.time) AS time
450
+ FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
451
+ WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
452
+ GROUP BY r.session_id${x?",r.seq":""}
453
+ ORDER BY ${I},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(p),u,i);return f?.("group",performance.now()-h),S}function rM(e,o,i,u,m,p){let f=performance.now(),h=m?o:{...o,forks:!1},x=e.query(`
454
+ SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
455
+ ${h.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
456
+ WHERE r.session_id=? ${u?"AND r.seq=?":""}
457
+ AND ${o.where} AND ${Ug(h)}
458
+ ${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(i.session_id,...u?[i.seq]:[],...o.bindings,...h.forks?o.bindings:[]);return p?.("filter",performance.now()-f),x}function Kg(e,o,i,u){if(!o.forks)return[];let m=Zv.get(e)?.get(i.session_id);if(m===void 0||i.seq>m)return[];return e.query(`
459
+ SELECT DISTINCT r.session_id,s.title,e.body
460
+ FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
461
+ CROSS JOIN ref r ON r.session_id=l.child
462
+ JOIN store.sessions s ON s.id=r.session_id
463
+ LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
464
+ WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...o.bindings).filter((p)=>{if(i.seq===0)return p.title===u;if(!p.body)return!1;let f=JSON.parse(p.body);return Je(f,!0).some((h)=>h.part===i.part&&h.kind===uo[i.kind]&&h.text===u)}).map((p)=>p.session_id)}function gH(e,o){let i=o?e:Ct(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let u="",m=[],p=[],f=0;for(let h of e){let x=o?h:Ct(h);u+=x;for(let I=0;I<x.length;I++)m.push(f),p.push(f+h.length);f+=h.length}return{normalized:u,starts:m,ends:p}}function ed(e,o){if(o.regex){let x=new RegExp(o.regex.source,`${o.regex.flags}g`),I=[];for(let S of e.matchAll(x)){if(o.wholeWord&&!nM(e,S.index,S.index+S[0].length))continue;I.push([S.index,S.index+S[0].length])}return I.length?I:void 0}let{normalized:i,starts:u,ends:m}=gH(e,o.caseSensitive),p=(x)=>{let I=o.caseSensitive?x.text:Ct(x.text),S=[],R=i.indexOf(I);while(R>=0&&I){let k=u?u[R]:R,A=m?m[R+I.length-1]:R+I.length,v=k===0||k!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(k-1,k))||/[a-z0-9][A-Z]/.test(e.slice(k-1,k+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(x.text));if(k!==void 0&&A!==void 0&&(!x.prefix||v)&&(!o.wholeWord||nM(e,k,A)))S.push([k,A]);R=i.indexOf(I,R+Math.max(1,I.length))}return S};if(!o.branches.length)return[];let f=[],h=!1;for(let x of o.branches){if(x.exclude.some((S)=>p(S).length))continue;let I=x.include.map(p);if(I.some((S)=>!S.length))continue;h=!0,f.push(...I.flat())}return h?f:void 0}function nM(e,o,i){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(i===e.length||!u.test(e.slice(i,i+1)))}function td(e,o){let i=e.split(`
465
+ `),u=new Set,m=0,p=i.map((f,h)=>{let x=m;if(o.some(([I,S])=>I<=x+f.length&&S>=x))for(let I=Math.max(0,h-1);I<=Math.min(i.length-1,h+1);I++)u.add(I);return m+=f.length+1,x});if(!u.size)u.add(0);return[...u].sort((f,h)=>f-h).slice(0,5).map((f)=>{let h=i[f]??"",x=p[f]??0,I=o.filter(([A,v])=>v>x&&A<x+h.length),S=Math.max(0,(I[0]?.[0]??x)-x-100),R=h.slice(S,S+300),k=I.map(([A,v])=>[Math.max(0,A-x-S),Math.min(R.length,v-x-S)]);return{text:R,line:f+1,ranges:k.filter(([A,v])=>A<v)}})}var oM=3;function yH(e){return Boolean(e&&typeof e==="object"&&"score"in e&&typeof e.score==="number"&&Number.isFinite(e.score)&&"sessionID"in e&&typeof e.sessionID==="string"&&e.sessionID.length<=1024&&"seq"in e&&typeof e.seq==="number"&&Number.isSafeInteger(e.seq)&&e.seq>=0)}function sM(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function xH(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===o&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let u="window"in i?i.window:0,m="seen"in i?i.seen:[],p="emitted"in i?i.emitted:[],f="after"in i?i.after:void 0;if(f!==void 0&&!yH(f))throw Error("invalid best cursor");let h=(x)=>Array.isArray(x)&&x.every((I)=>typeof I==="string"&&I.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&h(m)&&h(p))return{offset:i.offset,key:o,now:i.now,window:u,seen:m,emitted:p,after:f}}}catch{}throw Error("invalid search cursor")}function zn(e,o){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return xH(e.cursor,i)}async function Yr(e,o,i){let u="search"in e?e.search:e,m=performance.now(),p=(_e)=>{if(!i.signal?.aborted)i.onEvent(_e)};if(i.signal?.aborted)return;let f=zn(o,i.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let h=Yl(o,{now:f.now});if(h.error){p({type:"error",...h.error});return}if(h.currentSession){if(!i.sessionID){p({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}h.filters.sessionID=[i.sessionID]}if(!o.deep&&h.regex?.deepScan){p({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let x=performance.now(),I=u.withIndex((_e)=>Vv(_e,h));if(!I){p({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}i.onTiming?.("plan",performance.now()-x);let S=I.partial,R=f.after,k=new Map,A=new Map,v=[],_=!1,Q=new Map,L=new WeakMap,z=new Map,J=new Map,{offset:Z,window:re}=f,U=[...f.seen],ne=[...f.emitted],fe=!1,Re=Math.max(1,Math.min(200,o.limit??30)),Ee=Math.min(I.candidateLimit??2000,o.group==="none"?Bg:Math.min(2000,Math.max(Bg,Re*32))),ee=(_e,qe)=>{let Dt=k.get(qe);if(Dt)return Dt;let pt=_e.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(qe);if(pt)k.set(qe,pt);return pt??void 0},ue=(_e,qe,Dt)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(qe.session_id))return;if(i.excludeEntry?.sessionID===qe.session_id&&i.excludeEntry.seq===qe.seq)return;let pt=ee(_e,qe.session_id);if(!pt)return;let Mt=uo[qe.kind];if(!Mt)return;let xr=pt.title;if(qe.seq!==0){let tt=`${qe.session_id}:${qe.seq}`,Qt=J.get(tt);if(!Qt){let dn=Dt?void 0:_e.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(qe.session_id,qe.seq);if(!Dt&&!dn)return;let Wt=Dt??JSON.parse(dn?.body??"null");Qt=Je(Wt,!0),J.set(tt,Qt)}let er=Qt.find((dn)=>dn.part===qe.part&&dn.kind===Mt);if(!er)return;xr=er.text}let nr=ed(xr,h);if(!nr)return;let Ut=A.get(pt.id);if(Ut===void 0)Ut=_e.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(pt.id)?.through??0,A.set(pt.id,Ut);let et=qe.seq>0&&qe.seq<=Ut;if(h.filters.compacted!==void 0&&et!==h.filters.compacted)return;let Pt={sessionID:pt.id,seq:qe.seq,time:qe.time,field:Mt,tool:qe.tool??void 0,isError:Boolean(qe.err),model:qe.model??void 0,snippet:[],score:Qv(qe.relevance,Mt,qe.time,f.now),flags:{archived:pt.archived_at!==null,compacted:et,partial:xr.length>Ki+Qi}};return Q.set(Pt,{text:xr,ranges:nr}),v.push(Pt),_=!0,z.set(Pt,{doc:qe.doc,part:qe.part}),Pt},$e=(_e)=>{let qe=performance.now(),Dt=[..._e].sort((et,Pt)=>et.time-Pt.time||et.sessionID.localeCompare(Pt.sessionID)),pt=[],Mt=new Map;for(let et of Dt){let Pt=z.get(et),Qt=k.get(et.sessionID),er=new Set;while(Qt?.forked_from_id&&Qt.forked_from_seq!==null&&et.seq<=Qt.forked_from_seq&&!er.has(Qt.id))er.add(Qt.id),Qt=k.get(Qt.forked_from_id)??u.withIndex(($o)=>ee($o,Qt?.forked_from_id??""));let dn=`${Qt?.id??et.sessionID}:${et.seq}:${Pt?.part}:${Pt?.doc}`,Wt=Mt.get(dn);if(Wt){if(Wt.sessionID!==et.sessionID)Wt.forks=[...new Set([...Wt.forks??[],et.sessionID])]}else Mt.set(dn,et),pt.push(et)}let xr=[],nr=new Map,Ut=new Map;for(let et of pt){let Pt=`${et.sessionID}:${et.seq}`,tt=Ut.get(Pt);if(!tt){Ut.set(Pt,et),L.set(et,[et]);continue}let Qt=[...L.get(tt)??[tt],et],er=et.score>tt.score?et:tt;if(er.forks=[...new Set([...tt.forks??[],...et.forks??[]])],!er.forks.length)er.forks=void 0;er.flags={archived:tt.flags.archived||et.flags.archived,compacted:tt.flags.compacted||et.flags.compacted,partial:tt.flags.partial||et.flags.partial},Ut.set(Pt,er),L.set(er,Qt)}for(let et of jg([...Ut.values()],o.sort??"best")){let Pt=k.get(et.sessionID);if(!Pt)continue;let tt=o.group==="none"?void 0:nr.get(Pt.id);if(!tt)tt={session:{id:Pt.id,title:Pt.title,projectID:Pt.project_id,updated:Pt.updated},hits:[],more:0,...S&&o.group!=="none"?{moreIsLowerBound:!0}:{}},xr.push(tt),nr.set(Pt.id,tt);if(tt.hits.length<oM||o.group==="none")tt.hits.push(et);else tt.more++}return i.onTiming?.("group",performance.now()-qe),xr},gt=(_e)=>{for(let qe of _e)for(let Dt of qe.hits){if(i.allowedSessionIDs&&Dt.forks)Dt.forks=Dt.forks.filter((xr)=>i.allowedSessionIDs?.has(xr));let pt=performance.now(),Mt=new Map;for(let xr of L.get(Dt)??[Dt]){let nr=Q.get(xr);if(!nr)continue;for(let Ut of td(nr.text,nr.ranges)){let et=`${Ut.line}:${Ut.text}`,Pt=Mt.get(et);if(!Pt)Mt.set(et,Ut);else Pt.ranges=[...new Map([...Pt.ranges,...Ut.ranges].map((tt)=>[tt.join(":"),tt])).values()]}}Dt.snippet=[...Mt.values()],i.onTiming?.("snippet",performance.now()-pt)}},Ke=o.deep||I.scan,Zt=(_e,qe)=>{let Dt=ee(_e,qe.session_id);if(!Dt)return[];let pt=rM(_e,I,qe,o.group==="none",Dt.forked_from_id!==null,i.onTiming);if(I.candidateLimit&&pt.length>I.candidateLimit)pt.length=I.candidateLimit,S=!0;let Mt=v.length,xr=performance.now();for(let nr of pt){if(i.signal?.aborted)break;let Ut=ue(_e,nr);if(!Ut)continue;let et=Kg(_e,I,nr,Q.get(Ut)?.text??"");if(et.length)Ut.forks=et}return i.onTiming?.("body",performance.now()-xr),v.slice(Mt)};if(Ke){S=!1;let _e=[],qe=new Set,Dt=u.withIndex((tt)=>{Gg(tt,I);for(let Wt of tt.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())k.set(Wt.id,Wt);let Qt=new Set(tt.query(`SELECT s.id FROM store.sessions s WHERE ${I.sessionWhere}`).all(...I.sessionBindings).map((Wt)=>Wt.id)),er=(Wt)=>{if(qe.has(Wt.id))return;qe.add(Wt.id);let $o=Wt.forked_from_id?k.get(Wt.forked_from_id):void 0;if($o)er($o);if(Qt.has(Wt.id))_e.push(Wt)};for(let Wt of k.values())er(Wt);return(tt.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
466
+ SELECT s.id FROM store.sessions s WHERE ${I.sessionWhere}
467
+ )`).get(...I.sessionBindings)?.n??0)+Qt.size})??0,pt=0,Mt=0,xr=0;if(h.regex?.deepScan)p({type:"groups",groups:[]});let nr=new Set,Ut=new Set,et=new Map,Pt=()=>{let tt=$e(v),Qt=[];for(let er of tt){let dn=er.session.id,Wt=o.group==="none"?void 0:et.get(dn);if(o.group!=="none"&&Ut.has(dn)&&!Wt)continue;if(!Wt){if(Ut.add(dn),Mt<f.offset){Mt++;continue}if(xr>=Re){fe=!0;break}xr++,Z++}if(o.group!=="none"){let $o=(Wt?.count??0)+er.hits.length+er.more;er.hits=er.hits.slice(0,oM-(Wt?.shown??0));let Su=(Wt?.shown??0)+er.hits.length;er.more=$o-Su,et.set(dn,{shown:Su,count:$o})}Qt.push(er)}if(Qt.length)gt(Qt),p({type:"groups",groups:Qt});v.length=0,Q.clear(),z.clear(),J.clear()};for(let tt of _e){if(i.signal?.aborted||fe)break;let Qt=-1,er;for(;;){if(i.signal?.aborted||fe)break;let dn=u.withIndex((Wt)=>{let $o=Wt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(tt.id,Math.max(0,Qt));if(Qt<0)$o.unshift({seq:0,time:tt.updated,body:null});for(let Ci of $o){if(i.signal?.aborted)break;let wu=Ci.body?JSON.parse(Ci.body):void 0;if(wu?.type==="assistant")er=wu.model;let pM=wu?Je(wu,!0):[{part:0,kind:"title",text:tt.title}];for(let Do of pM){if(i.signal?.aborted)break;let Ns={session_id:tt.id,seq:Ci.seq,part:Do.part,doc:Number(BigInt(Bun.hash(Do.text))&0x1fffffffffffffn),kind:Be[Do.kind],tool:Do.tool??null,err:Number(Do.err??!1),model:Do.model??(Do.tool?er:void 0)??null,time:Ci.time,relevance:-1};if(!Wt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
468
+ JOIN store.sessions s ON s.id=r.session_id WHERE ${I.where}`).get(Ns.session_id,Ns.seq,Ns.kind,Ns.tool,Ns.err,Ns.model,Ns.time,...I.bindings))continue;let oi=tt,zg=new Set;while(oi.forked_from_id&&oi.forked_from_seq!==null&&Ci.seq<=oi.forked_from_seq&&!zg.has(oi.id)){zg.add(oi.id);let Tu=k.get(oi.forked_from_id);if(!Tu)break;oi=Tu}let Vg=`${oi.id}:${Ci.seq}:${Do.part}:${Bun.hash(Do.text)}`;if(nr.has(Vg))continue;let Jg=ue(Wt,Ns,wu);if(Jg){if(nr.add(Vg),I.forks){let Tu=Wt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(tt.id,Ci.seq,Do.part);if(Tu){let Qg=Kg(Wt,I,{...Ns,doc:Tu.doc},Do.text);if(Qg.length)Jg.forks=Qg}}}}}let Su=$o.at(-1);if(Su)Qt=Su.seq;return $o.length});if(dn===void 0){p({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(pt+=dn,p({type:"progress",scanned:pt,total:Dt}),i.signal?.aborted)return;if(Pt(),!dn||fe)break;await Bun.sleep(0)}}}else u.withIndex((_e)=>{if(S=Xv(_e,I,i.onTiming)||S,h.regex?h.regex.literals.every((pt)=>pt.some((Mt)=>[...Mt].length<3)):h.branches.some((pt)=>pt.include.length>0&&pt.include.every((Mt)=>[...Mt.text].length<3)))_e.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let pt=Yv(_e,I,o.group==="none",f.now,i.onTiming);if(S||=I.partial,I.candidateLimit&&pt.length>I.candidateLimit)pt.length=I.candidateLimit,S=!0;let Mt=[];for(let nr of pt){if(i.signal?.aborted)return;let Ut=Mt[Re]?.key.score;if(Ut!==void 0&&nr.score+0.000000000001<Ut)break;let et=v.length,Pt=Zt(_e,nr);v.splice(et);let tt=jg([...Pt],"best")[0];if(!tt)continue;let Qt={score:tt.score,sessionID:tt.sessionID,seq:o.group==="none"?tt.seq:0};if(f.after&&sM(Qt,f.after)<=0)continue;if(Mt.push({key:Qt,hits:Pt}),Mt.sort((er,dn)=>sM(er.key,dn.key)),Mt.length>Re+1)Mt.length=Re+1}fe=Mt.length>Re;let xr=Mt.slice(0,Re);for(let nr of xr)v.push(...nr.hits);R=xr.at(-1)?.key;return}let Dt=0;for(;;){if(i.signal?.aborted)return;let pt=eM(_e,I,re,Ee,i.onTiming),Mt=I.candidateLimit!==void 0&&re+pt>=I.candidateLimit;S||=Mt;let xr=tM(_e,o,Z,Re-Dt+1,f.now,U,i.onTiming);fe=xr.length>Re-Dt;let nr=xr.slice(0,Re-Dt);if(!nr.length){if(pt<Ee||Mt){fe=!1;break}re+=pt,Z=0,U=[...new Set([...U,...ne])],ne=[];continue}for(let Ut of nr)if(Z++,Zt(_e,Ut).length){if(Dt++,o.group!=="none")ne.push(Ut.session_id)}if(Dt>=Re){fe||=!Mt&&pt>=Ee;break}if(!fe){if(pt<Ee||Mt)break;re+=pt,Z=0,U=[...new Set([...U,...ne])],ne=[]}}});if(i.signal?.aborted)return;if(!Ke){let _e=$e(v);gt(_e),p({type:"groups",groups:_e})}if(!_){let _e=h.branches.flatMap((qe)=>qe.include).find((qe)=>qe.fuzzy)?.text;if(_e)p({type:"suggest",terms:u.withIndex((qe)=>Fg(qe,_e))??[]})}p({type:"done",cursor:fe?Buffer.from(JSON.stringify(!Ke&&o.sort!=="recent"?{...f,offset:0,window:0,seen:[],emitted:[],after:R}:{...f,offset:Z,window:re,seen:U,emitted:ne})).toString("base64url"):void 0,tookMs:performance.now()-m,partial:S,index:u.status()})}function Yo(e,o){return e.withIndex((i)=>Fg(i,o))??[]}function iM(e,o,i){let u=E({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(g([a({maxLength:2000}),On()])),scope:n(g([s("session"),s("project"),s("all"),s(""),On()])),fields:n(g([H(Jr({type:"string",enum:[...Wn]})),On()])),tool:n(g([a(),On()])),isError:n(g([B(),On()])),after:n(g([a(),te(),On()])),before:n(g([a(),te(),On()])),limit:n(g([T(),On()])),session:n(g([a(),On()])),seq:n(g([T(),On()])),around:n(g([T(),On()]))}),async execute(m,p,f){let h={query:p.query?.trim(),scope:p.scope||void 0,fields:p.fields?.length?p.fields:void 0,tool:p.tool?.trim(),isError:p.isError??void 0,after:p.after??void 0,before:p.before??void 0,limit:p.limit||void 0,session:p.session?.trim(),seq:p.seq??void 0,around:p.around??void 0},x=h.query?.trim(),I=!x&&Boolean(h.session?.trim())&&Number.isSafeInteger(h.seq)&&(h.seq??0)>=1;if(I&&h.around!==void 0&&(!Number.isInteger(h.around)||h.around<0||h.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(h.scope&&!["session","project","all"].includes(h.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(f?.aborted)throw Error("History search cancelled");let S=e.sessions().find((ee)=>ee.id===i);if(!S)throw Error("History session is unavailable");let R=(ee)=>{if(ee===void 0||ee===0||typeof ee==="string"&&!ee.trim())return;if(typeof ee==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(ee))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let ue=typeof ee==="number"?ee:Date.parse(ee);if(!Number.isFinite(ue)||Math.abs(ue)>8640000000000000){if(typeof ee==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return ue},k=I?void 0:R(h.after),A=I?void 0:R(h.before);if(k!==void 0&&A!==void 0&&k>=A)throw Error("after must precede before");let v=[];if(I&&h.session&&h.seq!==void 0){if(!e.sessions().find((Ke)=>Ke.id===h.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let ue=h.around??3,$e=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(h.session,Math.max(1,h.seq-ue),h.seq+ue);if(!$e.some((Ke)=>Ke.seq===h.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:$e.map((Ke)=>{let Zt={...JSON.parse(Ke.body),seq:Ke.seq,time:Ke.time};return`[seq=${Ke.seq}]
469
+ ${Je(Zt,!0).map((_e)=>`${_e.kind}: ${_e.kind==="error"?_e.text.replace(/^(?:error:\s*)+/i,""):_e.text}`).join(`
470
+ `).slice(0,4000)}`}).join(`
471
+
472
+ `)||"No history content"}],details:{groups:v,count:$e.length}}}if(!x)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let _=Number.isFinite(h.limit)?Math.max(1,Math.min(30,Math.trunc(h.limit??10))):10,Q=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,L=new Set(e.sessions().filter((ee)=>{if(h.scope==="session")return ee.id===i;if((h.scope??"project")==="project"&&S.projectID)return ee.projectID===S.projectID;return!0}).map((ee)=>ee.id)),z={q:x,filters:{tools:h.tool?.trim()?[h.tool.trim()]:void 0,isError:h.isError,after:k,before:A},group:"none",limit:_},J=Yl(z);if(J.error)throw Error(J.error.message);if(h.fields?.length){if(J.filters.fields=h.fields.filter((ee)=>(ee in Be)),J.filters.fields.length!==h.fields.length)throw Error("Unknown search field")}if((h.scope??"project")==="session")J.filters.sessionID=[i];else if((h.scope??"project")==="project"&&S.projectID)J.filters.projectID=[S.projectID];let Z=o.status().state!=="ready",re=!1;if(!Z){let ee=J.filters.fields??Object.keys(Be).filter((gt)=>(gt in Be)),ue=ee.filter((gt)=>gt!=="title"),$e=ue.length?[ue]:[];if(ee.includes("title"))$e.push(["title"]);for(let gt of $e){if(v.length>=_&&re)break;if(await Yr(o,{...z,limit:Math.max(1,_-v.length),filters:{...J.filters,fields:gt}},{signal:f,excludeEntry:Q===void 0?void 0:{sessionID:i,seq:Q},sessionID:i,allowedSessionIDs:L,onEvent(Ke){if(Ke.type==="groups")v.push(...Ke.groups);if(Ke.type==="done")re||=Boolean(Ke.cursor)||Ke.partial;if(Ke.type==="error")if(Ke.code==="unavailable")Z=!0;else throw Error(Ke.message)}}),Z)break}}let U=[],ne=0;if(Z){v.length=0;let ee=performance.now()+2000;e:for(let ue of e.sessions()){if(!L.has(ue.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(ue.id))continue;if(J.filters.projectID&&(!ue.projectID||!J.filters.projectID.includes(ue.projectID)))continue;let $e=Number.MAX_SAFE_INTEGER,gt=!0;for(;;){let Ke=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(ue.id,$e);if(gt)Ke.push({body:"null",seq:0,time:ue.updated}),gt=!1;if(!Ke.length)break;for(let Zt of Ke){if(Zt.seq>0)$e=Zt.seq;if(f?.aborted)throw Error("History search cancelled");if(ne>=1e4||performance.now()>ee){re=!0;break e}if(ne++,ue.id===i&&Zt.seq===Q)continue;if(J.filters.after!==void 0&&Zt.time<J.filters.after||J.filters.before!==void 0&&Zt.time>=J.filters.before)continue;let _e=Zt.seq===0?[{part:0,kind:"title",text:ue.title,tool:void 0,err:!1}]:Je(JSON.parse(Zt.body),!0);for(let qe of _e){if(J.filters.fields&&!J.filters.fields.includes(qe.kind))continue;if(J.filters.tools&&(!qe.tool||!J.filters.tools.includes(qe.tool)))continue;if(J.filters.isError!==void 0&&Boolean(qe.err)!==J.filters.isError)continue;let Dt=ed(qe.text,J);if(!Dt)continue;if(v.length>=_&&qe.kind!=="title"){re=!0;break e}(qe.kind==="title"?U:v).push({session:{id:ue.id,title:ue.title,projectID:ue.projectID,updated:ue.updated},more:0,hits:[{sessionID:ue.id,seq:Zt.seq,time:Zt.time,field:qe.kind,tool:qe.tool,isError:Boolean(qe.err),snippet:td(qe.text,Dt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(f?.aborted)throw Error("History search cancelled");if(U.length>Math.max(0,_-v.length))re=!0;if(v.push(...U.slice(0,_)),v.sort((ee,ue)=>Number(ee.hits[0]?.field==="title")-Number(ue.hits[0]?.field==="title")),v.length>_)re=!0;v.length=Math.min(v.length,_);let fe=new Map;for(let ee of v)for(let ue of ee.hits){let $e=fe.get(ee.session.id)??[];$e.push(`[${ee.session.title.replace(/[\r\n]/g," ")} \xB7 ${ue.sessionID} \xB7 ${ue.seq} \xB7 ${new Date(ue.time).toISOString()} \xB7 ${ue.field}${ue.tool?`/${ue.tool}`:""}]
473
+ ${ue.snippet.slice(0,3).map((gt)=>{let Ke=gt.text;for(let[Zt,_e]of[...gt.ranges].sort((qe,Dt)=>Dt[0]-qe[0]))Ke=`${Ke.slice(0,Zt)}\u3010${Ke.slice(Zt,_e)}\u3011${Ke.slice(_e)}`;return Ke}).join(`
474
+ `)}`),fe.set(ee.session.id,$e)}let Re="";if(Z){if(Re="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")Re="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let Ee=v.reduce((ee,ue)=>ee+ue.hits.length,0);return{content:[{type:"text",text:[Re,Z&&re?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ne} \u6761`:"",[...fe.values()].map((ee)=>ee.join(`
475
+
476
+ `)).join(`
477
+
478
+ `),Ee===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${Ee} \u6761\uFF1B${re?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
479
+ `)}],details:{groups:v,count:Ee}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var Hg="basalt.git-snapshot";async function aM(e,o,i){let u=o.projectID?e.store.project(o.projectID):void 0,m=u?.directory??process.cwd(),f=o.info().kind==="sub",h=()=>f||o.entries(0,["compaction"],!1).length>0,x=e.options.tools??cr({directory:u?.directory,records:()=>o.records,history:(R)=>e.resolveHistory(o.id,R),onTodos:(R)=>o.setTodos(R),shell:()=>e.serverShell(),hasCompacted:h});if(e.options.tools===void 0)x.push(iM(e.store,e.search,o.id));let I;if(u&&e.options.systemPrompt===void 0){let R=o.entries(0,["compaction"],!1).length,k=e.store.db,A=k.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(Hg,o.id),v;try{v=A?JSON.parse(A.value):void 0}catch{v=void 0}if(v?.compactions===R&&(v.summary===void 0||typeof v.summary==="string"))I=v.summary;else if(I=await iv(u.directory,i),!e.isClosed&&!i?.aborted)k.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(Hg,o.id,JSON.stringify({compactions:R,summary:I})),k.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(Hg)}let S=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:sv({project:u,globalInstructions:wH(e),git:I,shell:e.serverShell()});return{systemPrompt:S.map((R)=>R.detail).join(""),systemParts:S,tools:[...x,...e.tools.snapshot()],cwd:m}}var SH=[Eu(".basalt","AGENTS.md"),Eu(".agents","AGENTS.md"),Eu(".opencode","AGENTS.md"),Eu(".claude","CLAUDE.md"),Eu(".codex","AGENTS.md")];function wH(e){let o=e.options.homeDir??EH();for(let i of SH){let u=Eu(o,i);try{if(IH(u))return bH(u,"utf8")}catch{return}}return}class Zr{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new vg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Jl(Wg(e.dataDir,"basalt.db")),this.plugins=new mg(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Xl(this.plugins,()=>this.builtinToolNames()),this.search=new pg({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let i=this.open(o,"restore");this.sessions.set(o.id,i),this.restored.add(i)}}static async create(e){let o=new Zr(e);try{return await o.initialize(),o}catch(i){throw await o.close(),i}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[Wg(this.options.dataDir,"plugins"),...this.projects().map((e)=>Wg(e.directory,".basalt","plugins"))],this.options.plugins?.builtins===!1?[]:this.options.builtinPlugins??[]).then(async()=>{for(let e of this.restored)this.plugins.notify("session.open",e);if(this.initialized=!0,await this.plugins.idle(),!this.closed)for(let e of this.restored)e.recover();this.restored.clear()}),this.initialization}get ready(){return this.initialize()}builtinToolNames(){if(this.options.tools)return this.options.tools.map((e)=>e.name);return["read","write","edit","grep","glob","bash","todo","history_grep","history_list"]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}models(){return Lv(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{...Ql(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>Ov(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let u=o.archive??"active";return u==="all"||i.archivedAt!==null===(u==="archived")}).sort((i,u)=>u.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let i=this.get(e);if(!i)throw new t("History session is unavailable");return i.resolveHistory(o)}openStoredSession(e,o="restore"){let i=this.open(e,o);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let o=e.model??this.defaultModel;if(!Tn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),u={id:se("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let m=this.open(u);return this.sessions.set(u.id,m),this.emit({type:"session",session:m.info()}),m}copyHistory(e,o,i){o={...o,archivedAt:null},this.store.copySession(e,o,i);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new b("no such session");let i=o.info(),u=i.projectID?this.store.project(i.projectID):void 0;return gv(i,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let i=[o.model,e.model,this.defaultModel].find((f)=>f!==void 0&&Tn(this.options.models,f)!==void 0),u=i?Tn(this.options.models,i):void 0;if(!i||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let m={id:se("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:i,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(m,e.needsRaw?Iv(e.records,u):e.records);let p=this.open(m);return this.sessions.set(m.id,p),this.emit({type:"session",session:p.info()}),p}truncateHistory(e,o){let i=this.sessions.get(e.id);if(!i)throw new b("no such session");if(i.assertWritable(),i.status==="busy")throw new ce;if(!Tn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);i.close();for(let f of this.sessions.values()){if(f.info().parentID!==e.id)continue;if(f.status==="busy")f.abort();f.close()}this.store.truncateSession(e,o);let u=[],m=this.store.lastEntry(e.id,"run");if(m?.type==="run"&&m.state==="start"){let f=this.store.records(e.id,m.seq).filter((h)=>h.raw);for(let h of Po(f)){if(h.result)continue;let{body:x,raw:I}=yl(h.call,"\u4E4B\u540E\u7684\u6D88\u606F\u88AB\u7528\u6237\u4FEE\u6539\uFF0C\u8FD9\u6B21\u8C03\u7528\u7684\u7ED3\u679C\u5DF2\u968F\u622A\u65AD\u4E22\u5F03\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\u3002");u.push(this.store.appendEntry(e.id,void 0,x,I))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let p=this.open(e,"replay");this.sessions.set(e.id,p),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let f of u)this.emit({type:"entry",sessionID:e.id,entry:f});return p}setArchived(e,o){let i=this.sessions.get(e);if(!i)throw new b("no such session");let u=i.info().parentID;if(!o&&u&&this.sessions.get(u)?.isArchived)throw new t("\u8BF7\u5148\u6062\u590D\u6240\u5C5E\u7236\u4F1A\u8BDD");let m=this.sessionTree(i);if(m.some((p)=>p.status==="busy"))throw new ce;if(i.isArchived===o)return i.info();this.store.setArchived(m.map((p)=>p.id),o?Date.now():null);for(let p of m)p.refreshArchive();for(let p of m)p.archiveChanged();return i.info()}sessionTree(e){let o=[e];for(let i=0;i<o.length;i++){let u=o[i];if(!u)continue;for(let m of this.sessions.values())if(m.info().parentID===u.id)o.push(m)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new b("no such session");if(o.status==="busy")throw new ce;let i=this.sessionTree(o).slice(1),u=()=>{for(let m of i)m.close(),this.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return u();o.close();for(let m of i)m.close(),m.abort();return Promise.all(i.map((m)=>m.idle())).then(u)}open(e,o="create"){let i=e.id,u=new Bl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(m,p)=>aM(this,m,p)},{entry:(m)=>{this.emit({type:"entry",sessionID:i,entry:m})},entryRemoved:(m)=>{this.emit({type:"entry_removed",sessionID:i,seq:m})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(m)=>this.emit({type:"draft",sessionID:i,parts:m}),changed:()=>{let m=this.sessions.get(i);if(m)this.emit({type:"session",session:m.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new Pi(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!id.includes(e))throw new t(`Invalid shell type; must be ${id.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return Nv(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(i){console.error("runtime listener failed",i)}}}var Le={now:()=>Date.now(),after(e,o){let i=setTimeout(o,e);return()=>clearTimeout(i)}};var uM=1048576,cM=8;class Gt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,i,u){this.cwd=e;this.outputLimit=o;this.terminal=i;this.shellPreference=u}setTerminalObserver(e){this.terminal=e}start(e,o,i){let u=i?.observer,m=i?.clock??Le;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let Q=gd(e);if(Q.length>0)throw Error(yd(Q))}if(this.list().filter((Q)=>Q.state==="running").length>=cM)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${cM}\uFF09`);let f=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:h,isWindows:x}=Aa(e,f),I=Bun.spawn(h,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!x,windowsHide:!0,env:{...process.env,...am(this.cwd)}}),S={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:I,started:m.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(S.id,S);let R=()=>{for(let Q of S.waiters.splice(0))Q()},k=async(Q,L)=>{let z=new Ol;for await(let Z of Q){let re=z.decode(Z);S.output+=re,u?.output(re,L);let U=Buffer.from(S.output);if(U.length>uM){let ne=U.length-uM;while(ne<U.length&&(U[ne]??0)>>6===2)ne++;let fe=U.subarray(ne).toString(),Re=S.output.length-fe.length;S.unreadDroppedBytes+=Buffer.byteLength(S.output.slice(Math.max(0,S.readAt-S.dropped),Re)),S.output=fe,S.dropped+=Re}R()}let J=z.flush();if(S.output+=J,J)u?.output(J,L)},A,v=Promise.all([k(I.stdout,"stdout"),k(I.stderr,"stderr")]).catch((Q)=>{A=Q,this.kill(S)}),_=!1;if(S.done=(async()=>{if(S.code=await I.exited,S.timer?.(),this.kill(S),await v,A)throw A;if(S.state==="running")S.state="exited";if(_=!0,u?.end(S.state,S.code),!u&&S.state!=="killed")this.terminal?.(S);R()})().catch((Q)=>{if(S.state="exited",S.output+=`
480
+ [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(Q)}]`,!_)u?.end(S.state,S.code);if(u)throw Q;if(!u)this.terminal?.(S,Q);R()}),o!==void 0)S.timer=m.after(o,()=>{if(S.state==="running")S.state="timeout",this.kill(S)});return S}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128)try{e.proc.kill()}catch{}}else process.kill(-e.proc.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,o,i=0,u=!1,m){let p=this.find(e),f=o?new RegExp(o):void 0,h=Date.now()+i;m?.throwIfAborted();while(p.state==="running"){m?.throwIfAborted();let k=p.output.slice(Math.max(0,p.readAt-p.dropped));if((f?f.test(k):!u)||Date.now()>=h)break;await new Promise((A,v)=>{let _=()=>{clearTimeout(L);let z=p.waiters.indexOf(Q);if(z>=0)p.waiters.splice(z,1);v(m?.reason)},Q=()=>{clearTimeout(L),m?.removeEventListener("abort",_);let z=p.waiters.indexOf(Q);if(z>=0)p.waiters.splice(z,1);A()},L=setTimeout(Q,Math.max(0,h-Date.now()));p.waiters.push(Q),m?.addEventListener("abort",_,{once:!0})})}m?.throwIfAborted();let x=p.unreadDroppedBytes;p.unreadDroppedBytes=0;let I=p.output.slice(Math.max(0,p.readAt-p.dropped));p.readAt=p.dropped+p.output.length;let S=I.slice(-this.outputLimit),R=x+Buffer.byteLength(I.slice(0,I.length-S.length));return{job:p,output:`${R?`[truncated ${R} bytes]
481
+ `:""}${S}`}}async write(e,o,i=!1,u){let m=this.find(e);if(m.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let p=m.proc.stdin;if(!p||typeof p==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let f=await Qe(o,u);if(f)throw Error(f);p.write(o)}if(i)await p.end();else await p.flush()}async stop(e){let o=this.find(e);if(o.state==="running")o.state="killed",this.kill(o);return await o.done,{id:o.id,state:o.state,code:o.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var rd=new WeakMap,nd=new WeakMap;function dr(e,o){let i=rd.get(e);if(!i)i=o(),rd.set(e,i);return i}function mr(e){nd.set(e,(nd.get(e)??0)+1)}function hr(e,o){let i=(nd.get(o)??1)-1;if(nd.set(o,i),i>0)return!1;if(o.close(),rd.get(e)===o)rd.delete(e);return!0}async function O(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function P(e,o){let i=e[o];if(!i)throw new t(`${o} is required`);return i}var jn=100,fr=1e4,TH=60000,RH=200,Cn=()=>a(),mM=()=>n(T({minimum:1,maximum:fr})),rm=()=>n(a({minLength:1,maxLength:128})),kH=g([l({click:g([Cn(),l({selector:Cn()})])}),l({type:l({label:Cn(),text:Cn()})}),l({waitText:Cn(),timeoutMs:mM()}),l({expectText:Cn(),within:n(Cn())}),l({waitSelector:Cn(),timeoutMs:mM()}),l({expectCount:l({selector:Cn(),n:T({minimum:0})})}),l({snapshot:l({selector:Cn(),depth:n(T({minimum:0,maximum:RH}))})}),l({expectCalls:l({onOpen:n(H(Cn())),onClose:n(T({minimum:0}))})}),l({expectValue:l({label:Cn(),value:Cn()})})]),AH=l({status:T({minimum:100,maximum:599}),body:Ar(),delayMs:n(T({minimum:0,maximum:fr}))}),PH=g([s("paths"),s("request"),s("verify"),s("ui_test"),s("list"),s("docs"),s("check"),s("load"),s("reload"),s("enable"),s("disable")]),CH=g([s("page"),s("tab"),s("card"),s("sidebar")]),Wi=l({action:PH,path:n(a({minLength:1,maxLength:4096})),method:n(Cn()),body:n(ks(Cn(),Ar())),importTimeoutMs:n(T({minimum:1,maximum:fr})),timeoutMs:n(T({minimum:1,maximum:TH})),sessionID:rm(),scope:n(g([s("user"),s("all")])),id:rm(),slot:rm(),view:rm(),codeBlock:rm(),kind:n(CH),props:n(ks(Cn(),Ar())),context:n(ks(Cn(),Ar())),steps:n(H(kH,{maxItems:jn})),mockRoutes:n(ks(Cn(),AH)),topic:n(a({maxLength:100})),grep:n(a({minLength:1,maxLength:200}))});
482
+ export{t,b,kt,jr,Vr,Li,Kr,ir,qo,Qr,Wn,Oi,Ni,Di,Ht,Ui,Bi,Xr,Go,Fi,We,$i,mt,qt,Hn,K,zo,Qe,nt,H,n,l,Jr,B,T,s,te,a,g,y,de,qn,jo,Vo,Ko,Qo,Pe,E,ot,ht,C,F,q,Me,me,Gn,sr,Xo,Ce,c,le,it,ar,lr,cr,ft,ce,Jo,ur,pr,se,zn,Yr,Yo,Zr,Le,Gt,dr,mr,hr,O,P,Zo,jn,fr,Wi};