@bkm016/basalt 0.1.11 → 0.1.12

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 (207) hide show
  1. package/{chunk-755sy11p.js → chunk-01nve4qy.js} +1 -1
  2. package/{chunk-jtsve11b.js → chunk-0fc9apfn.js} +9 -9
  3. package/{chunk-d5j74pcp.js → chunk-1h34mzh7.js} +4 -4
  4. package/{chunk-fgwda4m0.js → chunk-1xfv4bd7.js} +1 -1
  5. package/{chunk-mbpb5c7w.js → chunk-2fyjph3f.js} +1 -1
  6. package/{chunk-13gvs0ax.js → chunk-2kxnw7vs.js} +1 -1
  7. package/{chunk-95964592.js → chunk-37zystxb.js} +11 -11
  8. package/{chunk-h1kb8b49.js → chunk-3pf1d62g.js} +2 -2
  9. package/{chunk-29qrxygd.js → chunk-5wnmbc1b.js} +2 -2
  10. package/{chunk-c71173py.js → chunk-6mges89p.js} +4 -4
  11. package/{chunk-d0a1jxk5.js → chunk-6sz5q3df.js} +2 -2
  12. package/chunk-7er5pz7s.js +479 -0
  13. package/{chunk-gbjn6d81.js → chunk-7g5smgjj.js} +1 -1
  14. package/chunk-7m3jagqn.js +2 -0
  15. package/{chunk-wnzvnskb.js → chunk-85v69h91.js} +2 -2
  16. package/{chunk-38g3gctw.js → chunk-9c4gdg1q.js} +2 -2
  17. package/{chunk-en218k4y.js → chunk-cbgpymt4.js} +1 -1
  18. package/{chunk-a1rb1a48.js → chunk-cdw03j4t.js} +2 -2
  19. package/chunk-ch1r3ted.js +2 -0
  20. package/{chunk-dfh9m9n7.js → chunk-db7ws33a.js} +2 -2
  21. package/{chunk-1n7dat03.js → chunk-ejjem0tc.js} +3 -3
  22. package/{chunk-c4qr1f41.js → chunk-eq4wqxzt.js} +2 -2
  23. package/{chunk-zc9ar0r4.js → chunk-eyrtbbdd.js} +1 -1
  24. package/{chunk-r4ttdkrz.js → chunk-fhxy6y34.js} +2 -2
  25. package/{chunk-zyyzk5ha.js → chunk-fy82qxa1.js} +1 -1
  26. package/{chunk-xtq1xpq0.js → chunk-hc300148.js} +1 -1
  27. package/{chunk-vtqr7dm8.js → chunk-j64dc767.js} +2 -2
  28. package/{chunk-msm9hmk9.js → chunk-jpnf71q7.js} +2 -2
  29. package/{chunk-q9f4xb0w.js → chunk-kpe7pnhy.js} +4 -4
  30. package/{chunk-a98wma9j.js → chunk-ksk49hv0.js} +1 -1
  31. package/{chunk-bdjr0kfr.js → chunk-m4bg1apa.js} +5 -5
  32. package/{chunk-dq01v5eq.js → chunk-nhm9z3d8.js} +1 -1
  33. package/{chunk-30rjf7my.js → chunk-ntks40jd.js} +2 -2
  34. package/{chunk-a1352w87.js → chunk-nw1xpt3s.js} +1 -1
  35. package/{chunk-xh444pfn.js → chunk-p2pmdbt2.js} +8 -8
  36. package/{chunk-hb4f2v34.js → chunk-qfcr5g35.js} +2 -2
  37. package/{chunk-n2jcx65v.js → chunk-qs8zzg50.js} +2 -2
  38. package/{chunk-qaeyhe65.js → chunk-r4gm8ngh.js} +1 -1
  39. package/{chunk-pz2afna8.js → chunk-rks90mh1.js} +1 -1
  40. package/{chunk-asyr3gnq.js → chunk-rwks9zaw.js} +2 -2
  41. package/{chunk-v3ee9z3f.js → chunk-t7te60m7.js} +1 -1
  42. package/{chunk-4dw43syb.js → chunk-tv52xajf.js} +1 -1
  43. package/{chunk-c0zfefq8.js → chunk-v7wcchy2.js} +1 -1
  44. package/{chunk-tevejprz.js → chunk-vjne04dp.js} +3 -3
  45. package/{chunk-ax04trym.js → chunk-w0rr66z7.js} +1 -1
  46. package/{chunk-gkf5jwvj.js → chunk-w6f2r052.js} +1 -1
  47. package/{chunk-jymx3a77.js → chunk-wqqjzsjt.js} +310 -278
  48. package/{chunk-c6q04xrd.js → chunk-xef4642x.js} +1 -1
  49. package/compiled.js +7 -7
  50. package/package.json +1 -1
  51. package/ui-test-worker.js +2 -2
  52. package/web/{chunk-jhpg2kcf.js → chunk-04drx71p.js} +1 -1
  53. package/web/chunk-0rdgt4jb.css +1 -0
  54. package/web/{chunk-cbwvfedy.js → chunk-19zd0tye.js} +3 -3
  55. package/web/chunk-1m0kp0g3.js +8 -0
  56. package/web/{chunk-j4gvtszc.js → chunk-1zwc09e8.js} +2 -2
  57. package/web/{chunk-a3pye9ag.js → chunk-2cyzaqjy.js} +3 -3
  58. package/web/{chunk-8csw0mvf.js → chunk-2jfesv7m.js} +2 -2
  59. package/web/chunk-3j2tcphs.js +1 -0
  60. package/web/chunk-3k9h7a73.js +1142 -0
  61. package/web/chunk-3m1bb2fw.js +1 -0
  62. package/web/{chunk-4rwwtfnd.js → chunk-3n9ypydh.js} +2 -2
  63. package/web/{chunk-90fkdzx3.js → chunk-3psgr0q8.js} +13 -13
  64. package/web/{chunk-nafe18y9.js → chunk-3qxxrwsp.js} +6 -6
  65. package/web/{chunk-hjyev38w.js → chunk-3rkkp6ed.js} +4 -4
  66. package/web/{chunk-v3dn9bfw.js → chunk-4f6a8dsk.js} +1 -1
  67. package/web/chunk-55nvm2mj.js +1 -0
  68. package/web/chunk-5dkqfnh7.js +2 -0
  69. package/web/{chunk-96xhmmqz.js → chunk-5g8md2wg.js} +4 -4
  70. package/web/{chunk-mpdeqzc9.js → chunk-5np514v5.js} +8 -8
  71. package/web/{chunk-1zfxaafq.js → chunk-60mym60n.js} +1 -1
  72. package/web/{chunk-nhx8pw7p.js → chunk-6f2sz84q.js} +2 -2
  73. package/web/{chunk-q8v5j963.js → chunk-7adsmqv6.js} +2 -2
  74. package/web/{chunk-27812gqr.js → chunk-7ksg3ccg.js} +3 -3
  75. package/web/chunk-7ky5nrrr.js +1 -0
  76. package/web/{chunk-pq56b3mq.js → chunk-7tkgbbf9.js} +2 -2
  77. package/web/{chunk-tpdcrrf1.js → chunk-7v85yvb2.js} +1 -1
  78. package/web/{chunk-dk0fnj87.js → chunk-7vgh17es.js} +1 -1
  79. package/web/{chunk-rqympya7.js → chunk-80z8s8zb.js} +1 -1
  80. package/web/{chunk-36dc7tcg.js → chunk-81s15c2e.js} +2 -2
  81. package/web/{chunk-mykbcvqz.js → chunk-8539865x.js} +1 -1
  82. package/web/{chunk-wbwets5x.js → chunk-8cnjd0f2.js} +17 -17
  83. package/web/{chunk-48479gnx.js → chunk-8sdjgv3k.js} +1 -1
  84. package/web/chunk-9bxtzwtc.js +1 -0
  85. package/web/{chunk-drchr3yn.js → chunk-aa46mrgh.js} +1 -1
  86. package/web/{chunk-8151c970.js → chunk-act3rr85.js} +1 -1
  87. package/web/{chunk-94denx9h.js → chunk-aebrw6cv.js} +3 -3
  88. package/web/{chunk-3a57m7xm.js → chunk-aeymdtm1.js} +2 -2
  89. package/web/{chunk-3020mmp1.js → chunk-ar6jnhm5.js} +1 -1
  90. package/web/{chunk-e763h2px.js → chunk-b5zf1hs3.js} +66 -66
  91. package/web/{chunk-5ahx98zj.js → chunk-b99k8q22.js} +8 -8
  92. package/web/chunk-bcjgzwef.js +1 -0
  93. package/web/{chunk-f79ajymt.js → chunk-bra33pt0.js} +2 -2
  94. package/web/{chunk-57pyz29y.js → chunk-bygwbpvq.js} +2 -2
  95. package/web/{chunk-3ftb27f3.js → chunk-c3fty2c2.js} +5 -5
  96. package/web/{chunk-d3f763n7.js → chunk-cxpnj495.js} +1 -1
  97. package/web/{chunk-8z7texmv.js → chunk-d1btrqmw.js} +1 -1
  98. package/web/{chunk-jqqbkdtw.js → chunk-d57fm7k0.js} +2 -2
  99. package/web/{chunk-1t38sgrk.js → chunk-d73zkc4q.js} +4 -4
  100. package/web/chunk-d94t9z70.js +1 -0
  101. package/web/{chunk-2ds0a2z1.js → chunk-dndd757x.js} +3 -3
  102. package/web/{chunk-d4519smc.js → chunk-e94pd9rr.js} +10 -10
  103. package/web/{chunk-qykt7avq.js → chunk-enwfd8d5.js} +2 -2
  104. package/web/chunk-fr4fft89.js +1 -0
  105. package/web/{chunk-g0rtcedn.js → chunk-g488hxx0.js} +3 -3
  106. package/web/{chunk-b6sqwmq7.js → chunk-g4zm0crw.js} +1 -1
  107. package/web/{chunk-086dshck.js → chunk-gckmcef6.js} +1 -1
  108. package/web/{chunk-0hvxb5d5.js → chunk-gkmaryr4.js} +1 -1
  109. package/web/chunk-gnb09wmx.js +1 -0
  110. package/web/chunk-gx340asc.js +1 -0
  111. package/web/chunk-h0c42zy3.js +1 -0
  112. package/web/chunk-h24ybwp6.js +1 -0
  113. package/web/{chunk-m24yb8md.js → chunk-h754ntg7.js} +1 -1
  114. package/web/{chunk-3b4wqmnh.js → chunk-hn8m1vsg.js} +7 -7
  115. package/web/{chunk-2f2agfpj.js → chunk-hqxc9m07.js} +7 -7
  116. package/web/chunk-hrgqc1vr.js +1 -0
  117. package/web/{chunk-793m5jjh.js → chunk-hva7xyne.js} +2 -2
  118. package/web/{chunk-yrh86m0n.js → chunk-hxbfkdjd.js} +1 -1
  119. package/web/chunk-j9c8fa82.js +1 -0
  120. package/web/{chunk-4gc663j0.js → chunk-jeafmjsm.js} +1 -1
  121. package/web/chunk-jyf7a7yp.js +2 -0
  122. package/web/chunk-jz5mmp64.js +1 -0
  123. package/web/{chunk-s0xy00v5.js → chunk-k0cg4n2k.js} +2 -2
  124. package/web/{chunk-g31dbnzm.js → chunk-k4dnjf8n.js} +4 -4
  125. package/web/{chunk-59nk506k.js → chunk-kerfb21g.js} +1 -1
  126. package/web/chunk-m0136xav.js +1 -0
  127. package/web/chunk-m6vyvgm5.js +1 -0
  128. package/web/{chunk-0y971zgq.js → chunk-mxkbmgcv.js} +2 -2
  129. package/web/{chunk-0fy590s0.js → chunk-my0ec787.js} +1 -1
  130. package/web/chunk-mzzaet63.js +1 -0
  131. package/web/{chunk-xjc5fmcr.js → chunk-n9v14vyd.js} +18 -18
  132. package/web/{chunk-cpshsp24.js → chunk-ncfzmf2g.js} +1 -1
  133. package/web/chunk-ny436sqg.js +1 -0
  134. package/web/chunk-ph75hddv.js +1 -0
  135. package/web/chunk-phdfyqaa.js +1 -0
  136. package/web/chunk-phxa5krt.js +1 -0
  137. package/web/{chunk-b3j07x0n.js → chunk-pjpre6de.js} +2 -2
  138. package/web/chunk-q1zxvjhs.js +2 -0
  139. package/web/{chunk-n33753da.js → chunk-qdd3bx8q.js} +1 -1
  140. package/web/{chunk-ydtrc1ay.js → chunk-qh62nkem.js} +2 -2
  141. package/web/{chunk-05mvzx00.js → chunk-qp3tjhaq.js} +1 -1
  142. package/web/chunk-r4zbw4zj.js +2 -0
  143. package/web/{chunk-g4as4zzd.js → chunk-r6kk4vp1.js} +4 -4
  144. package/web/{chunk-ppjw1mps.js → chunk-rdr6wt22.js} +4 -4
  145. package/web/chunk-ry4ycah9.js +1 -0
  146. package/web/{chunk-47mbbmst.js → chunk-sdr5wa4z.js} +3 -3
  147. package/web/chunk-sqm16fat.js +1 -0
  148. package/web/{chunk-zv73g4qq.js → chunk-td83xf12.js} +2 -2
  149. package/web/chunk-tj1fn8v2.js +1 -0
  150. package/web/{chunk-q65zxczs.js → chunk-v0wtk059.js} +4 -4
  151. package/web/{chunk-enryqmj7.js → chunk-v1hfbjz9.js} +4 -4
  152. package/web/chunk-v1qt3gq4.js +1 -0
  153. package/web/{chunk-2tsxj613.js → chunk-v34mr9ky.js} +9 -9
  154. package/web/{chunk-tgkdyxbn.js → chunk-v854w9yn.js} +1 -1
  155. package/web/{chunk-dtrh40vr.js → chunk-ve56gxq0.js} +1 -1
  156. package/web/chunk-w573ym17.js +1 -0
  157. package/web/{chunk-9kkzmss7.js → chunk-w9gnqkez.js} +3 -3
  158. package/web/{chunk-kfbgvh0c.js → chunk-wqzbxzk3.js} +1 -1
  159. package/web/{chunk-hm8thq7c.js → chunk-wvrs986a.js} +2 -2
  160. package/web/chunk-x0mjydtp.js +1 -0
  161. package/web/{chunk-7dycbjxn.js → chunk-xpecre7w.js} +4 -4
  162. package/web/{chunk-zdhyq3ch.js → chunk-xvfeq8v2.js} +7 -7
  163. package/web/{chunk-2weaa3gn.js → chunk-y2rzeb4v.js} +2 -2
  164. package/web/{chunk-tggja45g.js → chunk-yf8ykk4v.js} +4 -4
  165. package/web/{chunk-gyhr27dm.js → chunk-yjs6jmdb.js} +1 -1
  166. package/web/{chunk-dsbyfvwz.js → chunk-ym7kv2hs.js} +1 -1
  167. package/web/chunk-zhybh04p.js +1 -0
  168. package/web/index.html +1 -1
  169. package/worker.js +1 -1
  170. package/chunk-7zkswxvk.js +0 -2
  171. package/chunk-m1eam0s5.js +0 -2
  172. package/chunk-zq32mwxj.js +0 -479
  173. package/web/chunk-32zmk3f5.js +0 -1
  174. package/web/chunk-3d3wnh8a.js +0 -2
  175. package/web/chunk-6cjm2yr7.js +0 -1
  176. package/web/chunk-7ycxz39p.js +0 -1
  177. package/web/chunk-9wr33d0t.js +0 -1
  178. package/web/chunk-a4tdrxdh.js +0 -1
  179. package/web/chunk-a9fvsyc1.js +0 -1
  180. package/web/chunk-apvbvg4d.js +0 -1
  181. package/web/chunk-bkxcc7v5.js +0 -1
  182. package/web/chunk-bve354k7.js +0 -1
  183. package/web/chunk-cwpxakby.js +0 -1
  184. package/web/chunk-jd7npyv9.js +0 -8
  185. package/web/chunk-jzz5htxp.js +0 -1
  186. package/web/chunk-ka3q31t1.js +0 -1
  187. package/web/chunk-kahab58k.js +0 -1139
  188. package/web/chunk-krgvx75q.js +0 -1
  189. package/web/chunk-m7k4wr3k.js +0 -1
  190. package/web/chunk-mdj3r75b.js +0 -1
  191. package/web/chunk-nbcpbqq4.js +0 -1
  192. package/web/chunk-p1yc8hwn.js +0 -2
  193. package/web/chunk-p29brxyt.js +0 -1
  194. package/web/chunk-p8fbes0t.js +0 -1
  195. package/web/chunk-r6q1301x.js +0 -1
  196. package/web/chunk-r8kghrkb.js +0 -1
  197. package/web/chunk-rhxn7mxg.js +0 -1
  198. package/web/chunk-svqshmpg.js +0 -1
  199. package/web/chunk-swzxq7r3.css +0 -1
  200. package/web/chunk-t18tn37m.js +0 -2
  201. package/web/chunk-tbsaseer.js +0 -1
  202. package/web/chunk-v0zfnvc1.js +0 -1
  203. package/web/chunk-vj31fs16.js +0 -1
  204. package/web/chunk-vr79r8vh.js +0 -1
  205. package/web/chunk-wb9tax0m.js +0 -1
  206. package/web/chunk-x9eghjjd.js +0 -1
  207. package/web/chunk-z3ky5ews.js +0 -2
package/chunk-zq32mwxj.js DELETED
@@ -1,479 +0,0 @@
1
- // @bun
2
- import{$o,Qr,W}from"./chunk-4gtgqcct.js";import{Si,He,Et,wi,Yn,vi,_i,Ai,Pt,Ti,Ne,eo,Ke}from"./chunk-c71173py.js";import{Gn,Ci,Kr}from"./chunk-n0ybj4h9.js";import{Ie,te,Ho,zn,I,jn,ht,Me,dr,U,Le,Vn,ft,me,$t,oe,Xr,qo,Oe,re,nt,Kn,Go,be,Ii,yi,Se,Qn,d,Mi,Q,Jr,G,Li}from"./chunk-1n7dat03.js";import{Xn,M,Jn,Ve,bi,Ht,ke}from"./chunk-n2jcx65v.js";import{r,Xe}from"./chunk-bwawt15q.js";var Kg=r(function(cH,Gg){var Ov=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Zl=/[\n\r\u2028\u2029]/,_v=/[\s#!"$&'():;<=>@\\^`|~]/g;Gg.exports=function(o){var i=!1;return o.map(function(u){if(i&&typeof u==="string"&&Zl.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(Zl.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(_v,"\\$&")}if("op"in u&&typeof u.op==="string"){if(Ov.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(Zl.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 Yg=r(function(mH,Xg){var Jg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",Hg=new RegExp("^"+Jg+"$"),Wg="|&;()<> \\t",Lv="'([^']*?)'",Qg="(?:\\\\[\\s\\S]|[^\\\\'])*?",zg="\\$'"+Qg+"'",Yc=new RegExp("\\$'"+Qg+"(?:(')|\\\\?$)","g"),Nv="abeEfnrtv",Dv=`\x07\b\x1B\x1B\f
3
- \r \v`,qv=/^#$/,ed="'",Vg='"',bu="$",Ui="",Fv=4294967296;for(Xc=0;Xc<4;Xc++)Ui+=(Fv*Math.random()).toString(16);var Xc,jv=new RegExp("^"+Ui);function Uv(e,o){var i=o.lastIndex,u=[],p;while(p=o.exec(e))if(u[u.length]=p,o.lastIndex===p.index)o.lastIndex+=1;return o.lastIndex=i,u}function Bv(e,o,i){var u=typeof e==="function"?e(i):e[i];if(typeof u>"u"&&i!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+Ui+JSON.stringify(u)+Ui;return o+u}var Gv=/\\([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 Kv(e,o){var i=o.charAt(0);if(i==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(i==="x"||i==="u"||i==="U"){var p=parseInt(o.slice(1),16);if(p>1114111)return e;return String.fromCharCode.apply(null,p>65535?[55232+(p>>10),56320+(p&1023)]:[p])}if(i>="0"&&i<="7")return String.fromCharCode(parseInt(o,8)&255);var g=Nv.indexOf(o);return g<0?o:Dv.charAt(g)}function Hv(e){return e.replace(Gv,Kv).split("\x00")[0]}function Wv(e,o){return Yc.lastIndex=o,!!Yc.exec(e)[1]}function zv(e,o,i){if(!i)i={};var u=i.escape||"\\",p=i.splitUnquoted===!0?`
4
- `:typeof i.splitUnquoted==="string"?i.splitUnquoted:"",g="(\\"+u+`['"$\\`+u+Wg+"]|\\$\\$|\\$(?!"+zg.slice(2)+`)|[^\\s'"$`+Wg+"])+",y='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',b=new RegExp(["("+Jg+")","("+zg+"|"+g+"|"+y+"|"+Lv+")+"].join("|"),"g"),E=Uv(e,b);if(E.length===0)return[];if(!o)o={};var S=!1;return E.map(function(w){var R=w[0];if(!R||S)return;if(Hg.test(R))return{op:R};var A=!1,P=!1,C="",q=[],X=!1,j=null,V=!1,J;function ee(){J+=1;var pe,qe,xt=R.charAt(J);if(xt==="{"){if(J+=1,R.charAt(J)==="}")throw Error("Bad substitution: "+R.slice(J-2,J+1));var Je=1;pe=J;while(Je>0&&pe<R.length){if(R.charAt(pe)==="{"&&R.charAt(pe-1)==="$")Je+=1;else if(R.charAt(pe)==="}")Je-=1;pe+=1}if(Je!==0)throw Error("Bad substitution: "+R.slice(J));pe-=1,qe=R.slice(J,pe),J=pe}else if(/[*@#?$!-]/.test(xt))qe=xt;else{var Yt=R.slice(J);if(pe=Yt.match(/[^\w\d_]/),!pe)qe=Yt,J=R.length;else qe=Yt.slice(0,pe.index),J+=pe.index-1}return Bv(o,"",qe)}function ae(){if(j===null)return;if(j===0){if(C!=="")q[q.length]=C,C=""}else{q[q.length]=C,C="";for(var pe=1;pe<j;pe+=1)q[q.length]=""}j=null}for(J=0;J<R.length;J++){var H=R.charAt(J);if(p&&H!==bu)ae();if(V=V||!A&&(H==="*"||H==="?"),P)C+=H,P=!1;else if(A)if(H===A)A=!1;else if(A==ed)C+=H;else if(H===u)if(J+=1,H=R.charAt(J),H===Vg||H===u||H===bu)C+=H;else C+=u+H;else if(H===bu)C+=ee();else C+=H;else if(H===Vg||H===ed)A=H,X=!0;else if(Hg.test(H))return{op:R};else if(qv.test(H)){S=!0;var ue={comment:e.slice(w.index+J+1)};if(C.length)return[C,ue];return[ue]}else if(H===u)P=!0;else if(H===bu&&R.charAt(J+1)===ed&&Wv(R,J))ae(),X=!0,C+=Hv(R.slice(J+2,Yc.lastIndex-1)),J=Yc.lastIndex-1;else if(H===bu){var he=ee();if(!p)C+=he;else for(var $e=0;$e<he.length;$e+=1){var Ee=he.charAt($e);if(p.indexOf(Ee)<0)ae(),C+=Ee;else if(j===null)j=Ee===" "||Ee==="\t"||Ee===`
5
- `?0:1;else if(Ee!==" "&&Ee!=="\t"&&Ee!==`
6
- `)j+=1}}else C+=H}if(V)return{op:"glob",pattern:C};if(p){if(j!==null&&j>0){q[q.length]=C,C="";for(var se=1;se<j;se+=1)q[q.length]=""}if(C!==""||X&&q.length===0)q[q.length]=C;return q}return C}).reduce(function(w,R){if(typeof R>"u")return w;return[].concat(R).forEach(function(A){w[w.length]=A}),w},[])}Xg.exports=function(o,i,u){var p=zv(o,i,u);if(typeof i!=="function")return p;return p.reduce(function(g,y){if(typeof y==="object")return g[g.length]=y,g;var b=y.split(RegExp("("+Ui+".*?"+Ui+")","g"));if(b.length===1)return g[g.length]=b[0],g;return b.filter(Boolean).forEach(function(E){g[g.length]=jv.test(E)?JSON.parse(E.split(Ui)[1]):E}),g},[])}});var Wo={};Xe(Wo,{ArchivedError:()=>dt,BadRequestError:()=>t,BusyError:()=>ie,DEFAULT_TIMEOUT:()=>i$,FoldingPolicy:()=>Uc,MAX_ATTACHMENTS:()=>ut,MAX_TIMEOUT:()=>a$,MAX_TOOL_OUTPUT:()=>Te,NotFoundError:()=>f,PluginCheckError:()=>pt,ProcessRegistry:()=>Wt,Type:()=>io,aliased:()=>_e,budget:()=>jc,calls:()=>To,clip:()=>de,clipSaved:()=>rt,dataDir:()=>et,definePlugin:()=>k,estimateMessage:()=>F,estimateTokens:()=>D,estimateTools:()=>Ni,extensionTranscript:()=>wl,findWindowsBash:()=>tr,foldPoint:()=>qc,foldedThrough:()=>xa,formatLines:()=>Bc,gateShellCommand:()=>je,groupRuns:()=>Ks,historyTodos:()=>ir,newID:()=>ne,normalizeRunRecords:()=>Dh,processRegistry:()=>sr,project:()=>Re,projectUserText:()=>Di,releaseProcesses:()=>lr,requestBody:()=>N,resolveShellCommand:()=>Ea,retainProcesses:()=>ar,routeParam:()=>v,runShell:()=>rr,sealPoint:()=>iu,selectHistory:()=>or,sessionTools:()=>nr,staleFold:()=>xl,text:()=>c,timerClock:()=>Ce,tool:()=>x,toolSession:()=>z,transcript:()=>cu,usable:()=>ce,userTranscript:()=>Sl,validAttachment:()=>Ft,workState:()=>bl});var Uo={};Xe(Uo,{AssistantMessageEventStream:()=>M,AssistantMessageFrameEncoder:()=>SR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>RR,EventStream:()=>Xn,InMemoryCredentialStore:()=>zn,InMemoryModelsStore:()=>jn,ModelsError:()=>I,StringEnum:()=>Uq,Type:()=>io,appendAssistantMessageDiagnostic:()=>ke,calculateCost:()=>Q,clampThinkingLevel:()=>G,cleanupSessionResources:()=>Ci,collapseSystemMessages:()=>Oe,contentText:()=>dr,createAssistantMessageDiagnostic:()=>Ht,createAssistantMessageEventStream:()=>Jn,createFauxCore:()=>ER,createInitialSystemMessage:()=>Vn,createModels:()=>Qn,createProvider:()=>d,declarationsEqual:()=>Kn,defaultProviderAuthContext:()=>Ho,envApiKeyAuth:()=>h,extractDiagnosticError:()=>bi,fauxAssistantMessage:()=>No,fauxProvider:()=>Do,fauxText:()=>On,fauxThinking:()=>Oo,fauxToolCall:()=>bq,formatThrownValue:()=>Ve,getCurrentSystemMessage:()=>Xr,getCurrentSystemPrompt:()=>qo,getCurrentTools:()=>oe,getDeclaredTools:()=>be,getInitialSystemMessage:()=>me,getModelType:()=>ht,getOverflowPatterns:()=>Nq,getSupportedThinkingLevels:()=>Jr,getSystemMessageText:()=>U,getToolStateChanges:()=>Go,hasApi:()=>Mi,hasNonAdditiveToolChanges:()=>yi,hasToolRedefinitions:()=>Ii,isContextOverflow:()=>ca,isModelType:()=>Me,isRecoverableLength:()=>Lq,isRetryableAssistantError:()=>AR,lazyApi:()=>te,lazyOAuth:()=>le,lazyStream:()=>Ie,modelsAreEqual:()=>Li,normalizeContext:()=>ft,parseJsonWithRepair:()=>Qr,parseStreamingJson:()=>W,reduceAssistantMessageFrames:()=>Mq,registerSessionResourceCleanup:()=>Gn,renderSystemMessageUpdate:()=>Le,repairJson:()=>$o,resolveTranscript:()=>re,resolveTranscriptTools:()=>Se,retryAssistantCall:()=>jq,retryDelayMs:()=>kR,toToolDeclaration:()=>nt,uuidv7:()=>Kr,validateToolArguments:()=>nu,validateToolCall:()=>kU,withoutInitialSystemMessage:()=>$t});var K={};Xe(K,{Counted:()=>md,Entries:()=>ln,EntriesRegExp:()=>pd,Every:()=>an,EveryAll:()=>An,GraphemeCount:()=>wM,HasPropertyKey:()=>fe,IsArray:()=>Ge,IsBigInt:()=>Nr,IsBoolean:()=>pn,IsClassInstance:()=>hy,IsConstructor:()=>ud,IsDeepEqual:()=>Ta,IsEqual:()=>L,IsFunction:()=>ms,IsGreaterEqualThan:()=>Sa,IsGreaterThan:()=>Ki,IsInteger:()=>rm,IsLessEqualThan:()=>ps,IsLessThan:()=>Su,IsMaxLength:()=>gy,IsMinLength:()=>yy,IsMultipleOf:()=>fy,IsNull:()=>ho,IsNumber:()=>Ot,IsObject:()=>at,IsObjectNotArray:()=>Vo,IsString:()=>gt,IsSymbol:()=>cd,IsUndefined:()=>Ut,IsUnsafePropertyKey:()=>wu,IsValueLike:()=>Hi,Keys:()=>we,ShiftLeft:()=>It,Some:()=>wa,SomeAll:()=>xy,Symbols:()=>Iy,Values:()=>ld});var Yi={};Xe(Yi,{Hash:()=>Id,HashCode:()=>Zy});var _t={};Xe(_t,{ExtendsFalse:()=>Ze,ExtendsTrue:()=>Ae,ExtendsUnion:()=>Ud,IsExtendsFalse:()=>Kd,IsExtendsTrue:()=>Gd,IsExtendsTrueLike:()=>so,IsExtendsUnion:()=>Bd,Match:()=>br});var io={};Xe(io,{Any:()=>Pa,Array:()=>B,BigInt:()=>Cu,Boolean:()=>O,Call:()=>lw,Capitalize:()=>Iw,Codec:()=>lm,Conditional:()=>Aw,Constructor:()=>ds,ConstructorParameters:()=>Cw,Cyclic:()=>gs,Decode:()=>nx,DecodeBuilder:()=>pm,Dependent:()=>Xi,Encode:()=>ox,EncodeBuilder:()=>mm,Enum:()=>Gy,Evaluate:()=>Rn,Exclude:()=>vw,Extends:()=>Tn,ExtendsResult:()=>_t,Extract:()=>Ow,Function:()=>fs,Generic:()=>Xs,Identifier:()=>$u,Immutable:()=>sx,Index:()=>Dw,Infer:()=>Pu,InstanceType:()=>uT,Instantiate:()=>Po,Integer:()=>_,Interface:()=>zS,Intersect:()=>Cn,IsAny:()=>vr,IsArray:()=>wt,IsBigInt:()=>mo,IsBoolean:()=>Wn,IsCall:()=>ja,IsCodec:()=>Hn,IsConstructor:()=>en,IsCyclic:()=>Qt,IsDependent:()=>Dr,IsEnum:()=>on,IsEnumValue:()=>By,IsFunction:()=>tn,IsGeneric:()=>Aa,IsIdentifier:()=>cx,IsImmutable:()=>Zi,IsInfer:()=>nn,IsInteger:()=>fn,IsIntersect:()=>ze,IsKind:()=>Pe,IsLiteral:()=>yt,IsNever:()=>co,IsNull:()=>xs,IsNumber:()=>kr,IsObject:()=>Qe,IsOptional:()=>cn,IsParameter:()=>dx,IsReadonly:()=>ta,IsRecord:()=>Gt,IsRef:()=>qt,IsRefine:()=>dm,IsRest:()=>ni,IsSchema:()=>Cr,IsString:()=>sn,IsSymbol:()=>Is,IsTemplateLiteral:()=>ur,IsThis:()=>Am,IsTuple:()=>mt,IsUndefined:()=>Zo,IsUnion:()=>xe,IsUnknown:()=>rn,IsUnsafe:()=>cm,IsVoid:()=>po,KeyOf:()=>mT,Literal:()=>s,Lowercase:()=>bw,Mapped:()=>xT,Module:()=>iR,Never:()=>zt,NonNullable:()=>ST,Null:()=>$n,Number:()=>Y,Object:()=>l,Omit:()=>TT,Optional:()=>n,Parameter:()=>ra,Parameters:()=>AT,Partial:()=>CT,Pick:()=>NT,Readonly:()=>ix,ReadonlyObject:()=>bf,ReadonlyType:()=>FT,Record:()=>bs,RecordKey:()=>ri,RecordPattern:()=>hn,RecordValue:()=>fr,Ref:()=>un,Refine:()=>ax,Required:()=>eR,Rest:()=>oa,ReturnType:()=>rR,Script:()=>mR,String:()=>a,Symbol:()=>va,TemplateLiteral:()=>fS,This:()=>km,Tuple:()=>Ur,Uncapitalize:()=>Ew,Undefined:()=>_a,Union:()=>m,Unknown:()=>Rr,Unsafe:()=>qr,Uppercase:()=>Sw,Void:()=>Pm,With:()=>lp});var eu={};Xe(eu,{Clear:()=>Gk,Entries:()=>VF,Get:()=>XF,Has:()=>QF,IsDate:()=>Xa,IsDateTime:()=>Ep,IsDuration:()=>Sp,IsEmail:()=>wp,IsHostname:()=>vp,IsIPv4:()=>_p,IsIPv6:()=>Lp,IsIdnEmail:()=>Mp,IsIdnHostname:()=>Op,IsIri:()=>Dp,IsIriReference:()=>Np,IsJsonPointer:()=>Fp,IsJsonPointerUriFragment:()=>qp,IsRegex:()=>jp,IsRelativeJsonPointer:()=>Up,IsTime:()=>Ya,IsUri:()=>Kp,IsUriReference:()=>Bp,IsUriTemplate:()=>Gp,IsUrl:()=>Hp,IsUuid:()=>Wp,Reset:()=>Hk,Set:()=>JF,Test:()=>Kk});var Iu="shell-guard",Lg=["done","error","aborted","interrupted","waiting_user"];class t extends Error{constructor(e){super(e);this.name="BadRequestError"}}class f extends Error{constructor(e){super(e);this.name="NotFoundError"}}function Ng(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Dg(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean))}function Cv(e,o){if(e===o)return 0;let i=Array.from({length:o.length+1},(u,p)=>p);for(let u=1;u<=e.length;u++){let p=i[0]??0;i[0]=u;for(let g=1;g<=o.length;g++){let y=i[g]??0;i[g]=Math.min((i[g]??0)+1,(i[g-1]??0)+1,p+(e[u-1]===o[g-1]?0:1)),p=y}}return i[o.length]??0}function qg(e,o){let i=Ng(e);if(!i)return[];let u=Dg(e),p=[];for(let g of o){let y=g.id.indexOf("/"),b=y>=0?g.id.slice(y+1):"",S=[g.id,g.name,b].filter(Boolean).map((R)=>({compact:Ng(R),tokens:Dg(R)})).filter((R)=>R.compact.length>0),w=Number.POSITIVE_INFINITY;for(let R of S)if(R.compact===i)w=Math.min(w,0);else if(R.compact.includes(i)||i.includes(R.compact)){let A=Math.abs(R.compact.length-i.length);w=Math.min(w,1+A/Math.max(R.compact.length,i.length))}else{let A=0;for(let P of u)if(R.tokens.has(P))A++;if(A>0){let P=A/Math.max(u.size,R.tokens.size);w=Math.min(w,10+(1-P)*10)}}if(!Number.isFinite(w)&&i.length>=4){let R=Math.max(2,Math.floor(i.length*0.34));for(let A of S){if(Math.abs(A.compact.length-i.length)>R)continue;let P=Cv(i,A.compact);if(P<=R)w=Math.min(w,100+P)}}if(Number.isFinite(w))p.push({model:g,score:w})}return p.sort((g,y)=>g.score-y.score||g.model.id.localeCompare(y.model.id))}function $v(e,o,i=5){return qg(e,o).slice(0,Math.max(1,i)).map((u)=>u.model)}function Fr(e,o){let i=qg(e,o);if(i.length===0)return;let u=i.filter((g)=>g.score===0);if(u.length===1&&u[0])return u[0].model;if(u.length>1)return;let p=i.filter((g)=>g.score<10);if(p.length===1&&p[0])return p[0].model;return}function Wr(e,o){let i=[...o].sort((y,b)=>y.id.localeCompare(b.id)),u=(y)=>y.name===y.id?y.id:`${y.id} (${y.name})`,p=$v(e,i).map(u),g=i.map(u);return[`unknown model ${e}`,`closest matches: ${p.length>0?p.join(", "):"none"}`,`available models (${g.length}): ${g.length>0?g.join(", "):"none"}`,"Use one of the listed provider/model IDs."].join(`
7
- `)}var li=["openai-completions","openai-responses","anthropic-messages"];function $r(e){if(typeof e==="number")return Number.isFinite(e)&&e>0?Math.round(e):void 0;if(typeof e!=="string")return;let o=e.trim().toLowerCase();if(!o)return;let i=o.match(/^(\d+(?:\.\d+)?)\s*(k|m)?(?:i?b|tokens?)?$/);if(!i)return;let u=Number.parseFloat(i[1]??"");if(!Number.isFinite(u)||u<=0)return;let p=i[2];if(p==="k")return Math.round(u*1000);if(p==="m")return Math.round(u*1e6);return Math.round(u)}function Jl(e){if(e>=1e6&&e%1e5===0)return`${e/1e6}m`;if(e>=1000&&e%1000===0)return`${e/1000}k`;return String(e)}function vv(e){let o=e.trim();if(!o)return;let i,u,p=o,g=p.match(/\s*\[(.*?)\]\s*$/);if(g&&g.index!==void 0){p=p.slice(0,g.index).trim();let w=g[1]?.split(",").map((A)=>A.trim()).filter(Boolean)??[],R=0;for(let A of w){let P=A.indexOf("=");if(P>=0){let C=A.slice(0,P).trim().toLowerCase(),q=$r(A.slice(P+1).trim());if(C==="context"||C==="ctx"||C==="window"||C==="contextwindow")i=q;else if(C==="max"||C==="output"||C==="maxtokens")u=q}else{let C=$r(A);if(R===0)i=C;else if(R===1)u=C;R++}}}else{let w=p.match(/^(.*?=.*?):(\d+(?:\.\d+)?[kmKM]?|\d{5,})\s*$/);if(w?.[1]&&w[2])p=w[1].trim(),i=$r(w[2])}let y=p.indexOf("="),b,E;if(y<0)b=p.trim(),E=b;else b=p.slice(0,y).trim(),E=p.slice(y+1).trim()||b;if(!b)return;let S={id:b,name:E};if(i!==void 0)S.contextWindow=i;if(u!==void 0)S.maxTokens=u;return S}function er(e){return e.split(/\r?\n/).map(vv).filter((o)=>o!==void 0)}function Io(e){return e.map((o)=>{let i=o.name===o.id?o.id:`${o.id}=${o.name}`,u=[];if(o.contextWindow!==void 0)u.push(Jl(o.contextWindow));if(o.maxTokens!==void 0)if(o.contextWindow!==void 0)u.push(Jl(o.maxTokens));else u.push(`max=${Jl(o.maxTokens)}`);return u.length>0?`${i} [${u.join(", ")}]`:i}).join(`
8
- `)}var Fg=["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime","@basalt/plugin/web","@basalt/ui"];var Ln=["user","assistant","thinking","tool_input","tool_output","error","attachment","notice","extension","title"],ci=["text","regex"],ui=["best","recent"],pi=["session","none"];var Bt=4,di="https://basalt.work",mi=["https://basalt.work","https://www.basalt.work"],Hr=7420;var Ql=["auto","bash","powershell","cmd"];var Mo=["active","archived","all"],hi="session.group";var jg=["pending","in_progress","completed"],Xl="basalt-session",Qc=["image","text","path"];var Ug=["defer","always"],Bg=["global","tool","source"];function Be(e,o){if(e.toLowerCase()!=="tool_call"||!o||typeof o!=="object")return{name:e,input:o};let i=o;if(typeof i.name!=="string"||!i.name.trim())return{name:e,input:o};if(i.arguments===void 0)return{name:i.name,input:{},source:{name:"tool_call",input:o}};if(!i.arguments||typeof i.arguments!=="object"||Array.isArray(i.arguments))return{name:e,input:o};return{name:i.name,input:i.arguments,source:{name:"tool_call",input:o}}}function fi(e){return/eyJ[A-Za-z0-9+/=_-]{16,}/.exec(e)?.[0]}var ut=10,Mv=15000000;function Ft(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&Qc.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=Mv}function Yl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}var Vv=Kg(),td=Yg();import{AsyncLocalStorage as Jv}from"async_hooks";var z=new Jv;var Qv=3,Zg=160,Xv=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),Yv=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),ry=/^[A-Za-z_][A-Za-z0-9_]*=/,Zv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),eM=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),tM=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,rM=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),nM=new Set(["command","builtin","nohup","time","exec"]),oM=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir","-S","--split-string"]],["nice",["-n","--adjustment"]]]);function Zc(e){return{out:e.out,depth:e.depth+1}}function ey(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function rd(e,o,i,u){let p=e.length,g=0,y=o;while(y<p){let b=e.charAt(y);if(b==="\\"){y+=2;continue}if(b==="'"||b==='"'||b==="`"){let E=y+1;while(E<p){let S=e.charAt(E);if(S==="\\"){E+=2;continue}if(S===b)break;E++}y=E+1;continue}if(b===i)g++;else if(b===u){if(g--,g===0)return y+1}y++}return p}function sM(e){let o={text:"",subs:[],heredocs:[]},i=[],u=[],p=e.length,g=0,y=0,b=null,E=(S)=>{if(e.charAt(S)==="`"){let P=S+1;while(P<p){let C=e.charAt(P);if(C==="\\"){P+=2;continue}if(C==="`")break;P++}return o.subs.push(e.slice(S+1,P)),P<p?P+1:p}if(e.charAt(S+1)==="("){let P=rd(e,S+1,"(",")");if(e.charAt(S+2)==="(")return i.push(e.slice(S,P)),P;return o.subs.push(e.slice(S+2,P-1)),P}let R=rd(e,S+1,"{","}"),A=e.slice(S+2,R-1);for(let P=0;P<A.length;P++){let C=A.charAt(P);if(C==="\\"){P++;continue}if(C==="`"){let q=A.indexOf("`",P+1);o.subs.push(q<0?A.slice(P+1):A.slice(P+1,q)),P=q<0?A.length:q;continue}if(C==="$"&&A.charAt(P+1)==="("){let q=rd(A,P+1,"(",")");o.subs.push(A.slice(P+2,q-1)),P=q-1}}return R};while(g<p){let S=e.charAt(g);if(b==="'"){if(S==="'")b=null;i.push(S),g++;continue}if(b==='"'){if(S==="\\"){if(!'$`"\\\n'.includes(e.charAt(g+1)))i.push("\\");i.push(S,e.charAt(g+1)),g+=2;continue}if(S==='"'){b=null,i.push(S),g++;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}i.push(S),g++;continue}if(S==="'"||S==='"'){b=S,i.push(S),g++;continue}if(S==="\\"){i.push(S,e.charAt(g+1)),g+=2;continue}if(S==="`"||S==="$"&&(e.charAt(g+1)==="("||e.charAt(g+1)==="{")){g=E(g);continue}if(S==="#"){let w=i.at(-1);if(w===void 0||`
9
- ;&|()`.includes(w)){while(g<p&&e.charAt(g)!==`
10
- `)g++;continue}i.push(S),g++;continue}if(S==="<"&&e.charAt(g+1)==="<"&&e.charAt(g+2)!=="<"){let w=g+2;if(e.charAt(w)==="-")w++;i.push(e.slice(g,w));let R=w;while(R<p&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let A="";while(R<p){let P=e.charAt(R);if(P==="'"||P==='"'){let C=e.indexOf(P,R+1);if(C<0)break;A+=e.slice(R+1,C),R=C+1;continue}if(P==="\\"){A+=e.charAt(R+1),R+=2;continue}if(` \r
11
- ;&|()<>`.includes(P))break;A+=P,R++}if(A)u.push(A);g=w;continue}if(S===`
12
- `){if(u.length>0){let w=tM.test(i.slice(y).join(""));g++;for(let R of u.splice(0)){let A=g,P=p;while(g<p){let C=e.indexOf(`
13
- `,g),q=C<0?p:C;if(e.slice(g,q).trim()===R){P=g,g=C<0?p:C+1;break}g=C<0?p:C+1}if(w&&P>A)o.heredocs.push(e.slice(A,P))}}else g++;i.push(";",`
14
- `),y=i.length;continue}i.push(S),g++}return o.text=i.join(""),o}function Eu(e,o){if(o.depth>Qv)return;let i=sM(e),u;try{u=td(i.text)}catch{return}let p=[];for(let g of u){if(typeof g==="string"){p.push({kind:"word",text:g});continue}if("pattern"in g){p.push({kind:"word",text:g.pattern});continue}if("op"in g)p.push({kind:"op",text:g.op})}iM(p,o);for(let g of i.subs)Eu(g,Zc(o));for(let g of i.heredocs)Eu(g,Zc(o))}function iM(e,o){let i=[],u=()=>{if(i.length>0)aM(i,o);i=[]};for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;if(g.kind==="op"){if(Zv.has(g.text)){u();continue}if(eM.has(g.text)){if(/^\d+$/.test(i.at(-1)??""))i.pop();p++}continue}i.push(g.text)}u()}function aM(e,o){let i=0;for(;;){let y=e[i];if(y===void 0)return;if(Yv.has(y)||ry.test(y)){i++;continue}let b=cM(ey(y),e,i);if(b===i)break;i=b}let u=e[i];if(u===void 0)return;let p=ey(u),g=e.slice(i+1);if(p==="git"){pM(u,g,o);return}if(Xv.has(p)){uM(g,o);return}if(p==="powershell"||p==="pwsh")ty(g,/^-(command|c)$/i,o);if(p==="cmd")ty(g,/^\/[ck]$/i,o)}function ty(e,o,i){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let p=e.slice(u+1).join(" ");if(p.trim())Eu(p,Zc(i));return}}function uM(e,o){for(let i=0;i<e.length;i++){let u=e[i]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){i++;continue}if(u.startsWith("--"))continue;let p=/^-[a-zA-Z]*c(.*)$/.exec(u);if(p){let g=p[1]||e[i+1];if(g)Eu(g,Zc(o));return}if(u.startsWith("-")||u==="")continue;return}}function cM(e,o,i){if(nM.has(e)){let g=i+1;while(o[g]?.startsWith("-"))g++;return g}let u=oM.get(e);if(!u)return i;let p=i+1;for(;;){let g=o[p];if(g===void 0)return p;if(u.includes(g)){p+=2;continue}if(ry.test(g)||g.startsWith("-")){p++;continue}return p}}function zo(e,o){return e.some((i)=>i.length>1&&i.startsWith("-")&&!i.startsWith("--")&&i.slice(1).includes(o))}function ro(e,o){return e.some((i)=>i===`--${o}`||i.startsWith(`--${o}=`))}var mM={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(zo(e,"f")||zo(e,"i")||ro(e,"force")||ro(e,"interactive"))&&!(zo(e,"n")||ro(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>zo(e,"f")||ro(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>zo(e,"f")||ro(e,"force")||zo(e,"C")||ro(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>zo(e,"f")||ro(e,"force")||ro(e,"force-with-lease")||ro(e,"force-if-includes")||ro(e,"delete")||ro(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>ro(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>zo(e,"D")||zo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>ro(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>zo(e,"f")||ro(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(zo(e,"f")||ro(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function pM(e,o,i){let u=0;for(;;){let E=o[u];if(E===void 0)break;if(rM.has(E)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(E)||/^-[Cc].+/.test(E)||E.startsWith("-")){u++;continue}break}let p=o[u]?.toLowerCase();if(!p)return;let g=mM[p];if(!g)return;let y=g(o.slice(u+1));if(!y)return;let b=[e,...o.slice(u)].join(" ");i.out.push({rule:p,fragment:b.length>Zg?`${b.slice(0,Zg)}\u2026`:b,reason:y})}function od(e){let o={out:[],depth:0};return Eu(e,o),o.out}function ny(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 nd=new Map;function lM(e,o,i,u,p){let g=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((y)=>{let b=(S)=>{if(!nd.delete(g))return;p?.removeEventListener("abort",E),y(S)},E=()=>{oy(e,g),b("aborted")};if(nd.set(g,{session:e,finish:b}),e.appendExtension({namespace:Iu,kind:"requested",schemaVersion:1,payload:{id:g,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:S,reason:w})=>({fragment:S,reason:w})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${i}`}}),p?.aborted)E();else p?.addEventListener("abort",E,{once:!0})})}function oy(e,o){try{e.appendExtension({namespace:Iu,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Lo(e,o,i){let u=nd.get(o);if(!u||u.session!==e){if(!dM(e,o))return"unknown";return oy(e,o),"expired"}return e.appendExtension({namespace:Iu,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:i,resolvedAt:Date.now()},display:{text:i?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(i?"approved":"denied"),"answered"}function dM(e,o){let i=!1;for(let u of e.entries()){if(u.type!=="extension"||u.namespace!==Iu)continue;let p=u.payload;if(!p||typeof p!=="object"||!("id"in p)||p.id!==o)continue;if(u.kind==="requested")i=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return i}function sd(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${ny(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function je(e,o){let i=od(e);if(!i.at(0))return;let p=ny(i),g=z.getStore();if(g?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${p}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${sd(i)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let y=await lM(g,e,p,i,o);if(y==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${p} \u672A\u6267\u884C\uFF1A${y==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}import{existsSync as fM,mkdirSync as hM,writeFileSync as gM}from"fs";import{homedir as yM}from"os";import{join as Bi}from"path";function et(e=process.env){if(e.BASALT_HOME)return e.BASALT_HOME;let o=yM();if(process.platform==="win32")return Bi(e.LOCALAPPDATA??Bi(o,"AppData","Local"),"basalt");if(process.platform==="darwin")return Bi(o,"Library","Application Support","basalt");return Bi(e.XDG_DATA_HOME??Bi(o,".local","share"),"basalt")}function xM(e){return Bi(e,".basalt","tmp")}function id(e){let o=xM(e);hM(o,{recursive:!0});let i=Bi(o,".gitignore");if(!fM(i))gM(i,`*
15
- !.gitignore
16
- `);return o}function em(e){try{let o=id(e);return{TMPDIR:o,TEMP:o,TMP:o}}catch{return{}}}var cs={assign:0,create:0,clone:0,discard:0,update:0};function Gi(e,o,i){return e>=o&&e<=i}function ay(e){return e===8205}function IM(e){return Gi(e,55296,56319)}function sy(e){return Gi(e,127462,127487)}function uy(e){return Gi(e,65024,65039)}function cy(e){return Gi(e,768,879)||Gi(e,6832,6911)||Gi(e,7616,7679)||Gi(e,65056,65071)}function tm(e){return e>65535?2:1}function iy(e,o){while(o<e.length){let i=e.codePointAt(o);if(cy(i)||uy(i))o+=tm(i);else break}return o}function ad(e,o){let i=e.codePointAt(o),u=o+tm(i);u=iy(e,u);while(u<e.length-1&&ay(e.codePointAt(u))){let p=e.codePointAt(u+1);u+=1+tm(p),u=iy(e,u)}if(sy(i)&&u<e.length&&sy(e.codePointAt(u)))u+=tm(e.codePointAt(u));return u}function my(e){return e>=768&&(IM(e)||cy(e)||uy(e)||ay(e))}function py(e){let o=0,i=0;while(i<e.length)i=ad(e,i),o++;return o}function bM(e,o){let i=0,u=0;while(u<e.length)if(u=ad(e,u),++i>=o)return!0;return!1}function EM(e,o){let i=0,u=0;while(u<e.length)if(u=ad(e,u),++i>o)return!1;return!0}function ly(e,o){if(o===0)return!0;if(e.length<o)return!1;let i=0;while(!0){if(my(e.charCodeAt(i)))return bM(e,o);if(++i>=o)return!0}}function dy(e,o){if(e.length<=o)return!0;let i=0;while(!0){if(my(e.charCodeAt(i)))return EM(e,o);if(++i>o)return!1}}function Ge(e){return Array.isArray(e)}function Nr(e){return L(typeof e,"bigint")}function pn(e){return L(typeof e,"boolean")}function ud(e){if(Ut(e)||!ms(e))return!1;let o=Function.prototype.toString.call(e);if(/^class\s/.test(o))return!0;if(/\[native code\]/.test(o))return!0;return!1}function ms(e){return L(typeof e,"function")}function rm(e){return Number.isInteger(e)}function ho(e){return L(e,null)}function Ot(e){return Number.isFinite(e)}function Vo(e){return at(e)&&!Ge(e)}function at(e){return L(typeof e,"object")&&!ho(e)}function gt(e){return L(typeof e,"string")}function cd(e){return L(typeof e,"symbol")}function Ut(e){return L(e,void 0)}function L(e,o){return e===o}function Ki(e,o){return e>o}function Su(e,o){return e<o}function ps(e,o){return e<=o}function Sa(e,o){return e>=o}function fy(e,o){if(Nr(e)||Nr(o))return BigInt(e)%BigInt(o)===0n;let i=0.0000000001;if(!Ot(e))return!0;if(rm(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<i}function hy(e){if(!at(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(ho(o))return!1;return L(typeof o.constructor,"function")&&!(L(o.constructor,globalThis.Object)||L(o.constructor.name,"Object"))}function Hi(e){return Nr(e)||pn(e)||ho(e)||Ot(e)||gt(e)||Ut(e)}function wM(e){return py(e)}function gy(e,o){return dy(e,o)}function yy(e,o){return ly(e,o)}function an(e,o,i){return e.every((u,p)=>p<o||i(u,p))}function An(e,o,i){let u=!0;return e.forEach((p,g)=>{if(g>=o&&!i(p,g))u=!1}),u}function wa(e,o){return e.some((i,u)=>o(i,u))}function xy(e,o){let i=!1;return e.forEach((u,p)=>{if(o(u,p))i=!0}),i}function md(e,o){return e.reduce((i,u,p)=>o(u,p)?++i:i,0)}function It(e,o,i){return L(e.length,0)?i():o(e[0],e.slice(1))}function wu(e){return L(e,"__proto__")||L(e,"constructor")||L(e,"prototype")}function fe(e,o){return wu(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function pd(e){return we(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function ln(e){return Object.entries(e)}function we(e){return Object.getOwnPropertyNames(e)}function Iy(e){return Object.getOwnPropertySymbols(e)}function ld(e){return Object.values(e)}function TM(e,o){if(!at(o))return!1;let i=we(e);return L(i.length,we(o).length)&&i.every((u)=>Ta(e[u],o[u]))}function RM(e,o){return Ge(o)&&L(e.length,o.length)&&e.every((i,u)=>Ta(e[u],o[u]))}function Ta(e,o){return Ge(e)?RM(e,o):at(e)?TM(e,o):L(e,o)}var kM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function AM(e){return kM.test(e)}function Sn(e,o){return`(${e} && ${o})`}function xr(e,o){return`(${e} || ${o})`}function Un(e){return`!(${e})`}function nm(e){return`Array.isArray(${e})`}function by(e){return`typeof ${e} === "bigint"`}function PM(e){return`typeof ${e} === "boolean"`}function CM(e){return`Number.isInteger(${e})`}function $M(e){return`${e} === null`}function Ey(e){return`Number.isFinite(${e})`}function Sy(e){return Sn(wy(e),Un(nm(e)))}function wy(e){return`typeof ${e} === "object" && ${e} !== null`}function Ty(e){return`typeof ${e} === "string"`}function vM(e){return`typeof ${e} === "symbol"`}function dd(e){return`${e} === undefined`}function MM(e){return`typeof ${e} === "function"`}function OM(e){return`Guard.IsConstructor(${e})`}function uo(e,o){return`${e} === ${o}`}function Ry(e,o){return`${e} > ${o}`}function fd(e,o){return`${e} < ${o}`}function Wi(e,o){return`${e} <= ${o}`}function Tu(e,o){return`${e} >= ${o}`}function _M(e,o){return`Guard.IsMinLength(${e}, ${o})`}function LM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function ls(e,o,i,u){return L(o,"0")?`${e}.every((${i[0]}, ${i[1]}) => (${u}))`:`${e}.every((${i[0]}, ${i[1]}) => (${i[1]} < ${o}) || (${u}))`}function NM(e,o,i){return`${e}.some((${o[0]}, ${o[1]}) => ${i})`}function DM(e,o,i){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${i}) result = true }); return result })(${e})`}function om(e,o,i){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${i}) ? ++result : result, 0)`}function ky(e){return`Object.entries(${e})`}function zi(e){return`Object.getOwnPropertyNames(${e})`}function Vi(e,o){return L(o,'"__proto__"')||L(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function Ay(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function qM(e){return`[${e.join(", ")}]`}function Vs(e,o){return`((${e.join(", ")}) => ${o})`}function Ir(e,o){return`${e}(${o.join(", ")})`}function hd(e,o){return`new ${e}(${o.join(", ")})`}function bt(e,o){return`${e}${AM(o)?`.${o}`:`[${De(o)}]`}`}function De(e){if(!Hi(e))throw Error("Unsupported Constant");return gt(e)?JSON.stringify(e):`${e}`}function FM(e,o,i){return`(${e} ? ${o} : ${i})`}function sm(e){return`{ ${e.join("; ")}; }`}function vs(e,o){return`const ${e} = ${o}`}function Py(e,o){return`if(${e}) { ${o} }`}function im(e){return`return ${e}`}function Pn(e){return L(e.length,0)?"true":e.reduce((o,i)=>Sn(o,i))}function gd(e){return L(e.length,0)?"false":e.reduce((o,i)=>xr(o,i))}function jM(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function UM(e){return e instanceof Boolean}function BM(e){return e instanceof Number}function GM(e){return e instanceof String}function Cy(e){return globalThis.ArrayBuffer.isView(e)}function $y(e){return e instanceof globalThis.RegExp}function KM(e){return e instanceof globalThis.Date}function HM(e){return e instanceof globalThis.Set}function WM(e){return e instanceof globalThis.Map}var VM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Jo(){return VM}function Js(e){return Jo().immutableTypes?Object.freeze(e):e}function dn(e,o){return cs.assign+=1,Js({...e,...o})}function JM(e){return e}function QM(e){return fe(e,"~kind")||fe(e,"~unsafe")}function XM(e){let o={};for(let i of we(e)){if(wu(i))continue;let u=Object.getOwnPropertyDescriptor(e,i);if(u.value=Ji(u.value),L(u.enumerable,!0))o[i]=u.value;else Object.defineProperty(o,i,u)}return o}function YM(e){let o={};for(let i of we(e)){if(wu(i))continue;o[i]=Ji(e[i])}for(let i of Iy(e))o[i]=Ji(e[i]);return o}function ZM(e){return hy(e)?JM(e):QM(e)?XM(e):YM(e)}function eO(e){return e.map((o)=>Ji(o))}function tO(e){return e.slice()}function rO(e){return new RegExp(e.source,e.flags)}function nO(e){return new Map(Ji([...e.entries()]))}function oO(e){return new Set(Ji([...e.values()]))}function Ji(e){return Cy(e)?tO(e):$y(e)?rO(e):WM(e)?nO(e):HM(e)?oO(e):Ge(e)?eO(e):at(e)?ZM(e):e}function Ra(e){return cs.clone+=1,Ji(e)}function sO(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 vy(e,o){return{...e,...o}}function Ct(e,o,i={}){cs.create+=1;let u=vy(o,i),p=Jo().enumerableKind?vy(u,e):sO(u,e);return Js(p)}function Qo(e,o){cs.discard+=1;let i={};for(let u of we(e)){if(o.includes(u))continue;let p=Object.getOwnPropertyDescriptor(e,u);p.value=Ra(p.value),Object.defineProperty(i,u,p)}return Js(i)}function St(e,o,i){cs.update+=1;let u=Jo(),p=Ra(e);for(let g of Object.keys(o))Object.defineProperty(p,g,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[g]});for(let g of Object.keys(i))Object.defineProperty(p,g,{configurable:!0,enumerable:!0,writable:!0,value:i[g]});return Js(p)}function Pe(e,o){return at(e)&&fe(e,"~kind")&&L(e["~kind"],o)}function Cr(e){return at(e)}function ve(e,o,i){return Ct({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:i},{})}function Qs(e){return Pe(e,"Deferred")}function iO(e){return St(e,{"~readonly":!0},{})}function ku(e,o){return St(iO(e),{},o)}function My(e,o,i,u){let p=ge(e,o,i);return ku(p,u)}function aO(e){return St(e,{"~optional":!0},{})}function Au(e,o){return St(aO(e),{},o)}function Oy(e,o,i,u){let p=ge(e,o,i);return Au(p,u)}function B(e,o){return Ct({"~kind":"Array"},{type:"array",items:e},o)}function wt(e){return Pe(e,"Array")}function ka(e){return Qo(e,["~kind","type","items"])}function ds(e,o,i={}){return Ct({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},i)}function en(e){return Pe(e,"Constructor")}function _y(e){return Qo(e,["~kind","type","parameters","instanceType"])}function fs(e,o,i={}){return Ct({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},i)}function tn(e){return Pe(e,"Function")}function Ly(e){return Qo(e,["~kind","type","parameters","returnType"])}function un(e,o){return Ct({["~kind"]:"Ref"},{$ref:e},o)}function qt(e){return Pe(e,"Ref")}function Xs(e,o){return Ct({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Aa(e){return Pe(e,"Generic")}function Pa(e){return Ct({["~kind"]:"Any"},{},e)}function vr(e){return Pe(e,"Any")}var Ny="(?!)";function zt(e){return Ct({"~kind":"Never"},{not:{}},e)}function co(e){return Pe(e,"Never")}function hs(e,o={}){return ve("AddOptional",[e],o)}function Qi(e,o={}){return Au(e,o)}function n(e){return Qi(e)}function cn(e){return Cr(e)&&fe(e,"~optional")}function Dy(e){return we(e).filter((o)=>!cn(e[o]))}function am(e){return we(e)}function um(e){return ld(e)}function l(e,o={}){let i=Dy(e),u=i.length>0?{required:i}:{};return Ct({"~kind":"Object"},{type:"object",...u,properties:e},o)}function Qe(e){return Pe(e,"Object")}function qy(e){return Qo(e,["~kind","type","properties","required"])}function Rr(e){return Ct({["~kind"]:"Unknown"},{},e)}function rn(e){return Pe(e,"Unknown")}function gs(e,o,i){let u=we(e).reduce((p,g)=>({...p,[g]:St(e[g],{},{$id:g})}),{});return Ct({["~kind"]:"Cyclic"},{$defs:u,$ref:o},i)}function Qt(e){return Pe(e,"Cyclic")}function qr(e){return St(e,{["~unsafe"]:null},{})}function cm(e){return Vo(e)&&fe(e,"~unsafe")&&ho(e["~unsafe"])}function wn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function Pu(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p,p],1:(u)=>[u,Rr(),Rr()]});return Ct({["~kind"]:"Infer"},{type:"infer",name:o,extends:i},{})}function nn(e){return Pe(e,"Infer")}function Xi(e,o,i,u={}){return Ct({"~kind":"Dependent"},{if:e,then:o,else:i},u)}function Dr(e){return Pe(e,"Dependent")}function Fy(e){return Qo(e,["~kind","if","then","else"])}function jy(e){return Vo(e)}function Uy(e){return we(e).filter((i)=>isNaN(i)).reduce((i,u)=>[...i,e[u]],[])}function By(e){return gt(e)||Ot(e)}function Gy(e,o){let i=jy(e)?Uy(e):e;return Ct({"~kind":"Enum"},{enum:i},o)}function on(e){return Pe(e,"Enum")}function Cn(e,o={}){return Ct({"~kind":"Intersect"},{allOf:e},o)}function ze(e){return Pe(e,"Intersect")}function Ky(e){return Qo(e,["~kind","allOf"])}var yd=void 0;function uO(){try{return Wy("null")(),!0}catch{return!1}}function Hy(){if(Ut(yd))yd=uO();return yd&&Jo().useAcceleration}function Wy(...e){return new globalThis.Function(...e)}function jr(){throw Error("Unreachable")}function cO(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 mO(e){return typeof e==="number"}var Bn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Bn||(Bn={}));var Ca=BigInt("14695981039346656037"),[pO,lO]=[BigInt("1099511628211"),BigInt("18446744073709551616")],dO=Array.from({length:256}).map((e,o)=>BigInt(o)),Qy=new Float64Array(1),Xy=new DataView(Qy.buffer),Yy=new Uint8Array(Qy.buffer);function In(e){Ca=Ca^dO[e],Ca=Ca*pO%lO}function fO(e){In(Bn.Array);for(let o of e)Ys(o)}function hO(e){In(Bn.BigInt),Xy.setBigInt64(0,e);for(let o of Yy)In(o)}function Vy(e){In(Bn.Boolean),In(e?1:0)}function gO(e){In(Bn.Constructor),Ys(e.toString())}function yO(e){In(Bn.Date),Ys(e.getTime())}function xO(e){In(Bn.Function),Ys(e.toString())}function IO(e){In(Bn.Null)}function Jy(e){In(Bn.Number),Xy.setFloat64(0,e,!0);for(let o of Yy)In(o)}function bO(e){In(Bn.Object);for(let o of cO(e).sort())Ys(o),Ys(e[o])}function EO(e){In(Bn.RegExp),xd(e.toString())}var SO=new TextEncoder;function xd(e){In(Bn.String);for(let o of SO.encode(e))In(o)}function wO(e){In(Bn.Symbol),Ys(e.toString())}function TO(e){In(Bn.TypeArray);let o=new Uint8Array(e.buffer);for(let i=0;i<o.length;i++)In(o[i])}function RO(e){return In(Bn.Undefined)}function Ys(e){return Cy(e)?TO(e):KM(e)?yO(e):$y(e)?EO(e):UM(e)?Vy(e.valueOf()):GM(e)?xd(e.valueOf()):BM(e)?Jy(e.valueOf()):mO(e)?Jy(e):Ge(e)?fO(e):pn(e)?Vy(e):Nr(e)?hO(e):ud(e)?gO(e):ho(e)?IO(e):at(e)?bO(e):gt(e)?xd(e):cd(e)?wO(e):Ut(e)?RO(e):ms(e)?xO(e):jr()}function Zy(e){return Ca=BigInt("14695981039346656037"),Ys(e),Ca}function Id(e){return Zy(e).toString(16).padStart(16,"0")}function ex(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 kO=ex;function tx(){return kO}class mm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,i=Hn(o)?(g)=>this.decode(o["~codec"].decode(g)):this.decode,u=Hn(o)?(g)=>o["~codec"].encode(e(g)):e,p={decode:i,encode:u};return St(this.type,{"~codec":p},{})}}class pm{constructor(e){this.type=e}Decode(e){return new mm(this.type,e)}}function lm(e){return new pm(e)}function nx(e,o){return lm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function ox(e,o){return lm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Hn(e){return Cr(e)&&fe(e,"~codec")&&at(e["~codec"])&&fe(e["~codec"],"encode")&&fe(e["~codec"],"decode")}function sx(e){return $a(e)}function Zi(e){return Cr(e)&&fe(e,"~immutable")}function ys(e,o={}){return ve("AddReadonly",[e],o)}function ea(e,o={}){return ku(e,o)}function ix(e){return ea(e)}function ta(e){return Cr(e)&&fe(e,"~readonly")}function PO(e,o){let i=dm(e)?[...e["~refine"],o]:[o];return St(e,{"~refine":i},{})}function ax(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,()=>"Refine Error"]});return PO(o,{check:i,error:u})}function CO(e){return Vo(e)&&fe(e,"check")&&fe(e,"error")&&ms(e.check)&&ms(e.error)}function dm(e){return Cr(e)&&fe(e,"~refine")&&Ge(e["~refine"])&&an(e["~refine"],0,(o)=>CO(o))}var ux="-?(?:0|[1-9][0-9]*)n";function Cu(e){return Ct({"~kind":"BigInt"},{type:"bigint"},e)}function mo(e){return Pe(e,"BigInt")}function O(e){return Ct({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return Pe(e,"Boolean")}function $u(e){return Ct({"~kind":"Identifier"},{name:e})}function cx(e){return Pe(e,"Identifier")}var fm="-?(?:0|[1-9][0-9]*)";function _(e){return Ct({"~kind":"Integer"},{type:"integer"},e)}function fn(e){return Pe(e,"Integer")}class mx extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function $O(e){return Nr(e)?"bigint":pn(e)?"boolean":Ot(e)?"number":gt(e)?"string":(()=>{throw new mx(e)})()}function s(e,o){return Ct({"~kind":"Literal"},{type:$O(e),const:e},o)}function hm(e){return Nr(e)||pn(e)||Ot(e)||gt(e)}function px(e){return yt(e)&&Nr(e.const)}function lx(e){return yt(e)&&pn(e.const)}function gm(e){return yt(e)&&Ot(e.const)}function ym(e){return yt(e)&&gt(e.const)}function yt(e){return Pe(e,"Literal")}function $n(e){return Ct({"~kind":"Null"},{type:"null"},e)}function xs(e){return Pe(e,"Null")}var xm="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function Y(e){return Ct({"~kind":"Number"},{type:"number"},e)}function kr(e){return Pe(e,"Number")}function va(e){return Ct({"~kind":"Symbol"},{type:"symbol"},e)}function Is(e){return Pe(e,"Symbol")}function ra(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[p,g,g],1:(p)=>[p,Rr(),Rr()]});return Ct({"~kind":"Parameter"},{name:o,extends:i,equals:u},{})}function dx(e){return Pe(e,"Parameter")}var Im=".*";function a(e){return Ct({"~kind":"String"},{type:"string"},e)}function sn(e){return Pe(e,"String")}function m(e,o={}){return Ct({"~kind":"Union"},{anyOf:e},o)}function xe(e){return Pe(e,"Union")}function fx(e){return Qo(e,["~kind","anyOf"])}function vu(e){let o=hx(e);return L(o.length,2)?o[0]:[]}function vO(e){return!0}function gx(e){return It(e,(o,i)=>MO(o)?gx(i):!1,()=>!0)}function yx(e){return L(e.length,0)?!1:gx(e)}function MO(e){return xe(e)?yx(e.anyOf):yt(e)?vO(e.const):!1}function bm(e){return yx(e)}function Em(e){return Ct({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function xx(e,o,i=[]){return It(e,(u,p)=>xx(p,o,[...i,`${u}${o}`]),()=>i)}function OO(e,o){return L(e.length,0)?[`${o}`]:xx(e,o)}function Ix(e,o,i=[]){return It(o,(u,p)=>Ix(e,p,[...i,...bx(e,u)]),()=>i)}function bx(e,o){return xe(o)?Ix(e,o.anyOf):yt(o)?OO(e,o.const):jr()}function Ex(e,o){return It(o,(i,u)=>Ex(bx(e,i),u),()=>e)}function _O(e){return e.map((o)=>s(o))}function LO(e){let o=Ex([],e),i=_O(o);return m(i)}function NO(e){return L(e.length,0)?jr():L(e.length,1)&&yt(e[0])?e[0]:LO(e)}function bd(e){let o=vu(e);return L(o.length,0)?a():bm(o)?NO(o):Em(e)}function Mu(e){let o=bd(e);return ur(o)?a():o}function no(e,o){let u={[e]:o};return Ct({["~kind"]:"Record"},{type:"object",patternProperties:u})}function Sx(e){return no(Xo,e)}function wx(e){return l({true:e,false:e})}function Ur(e,o={}){let[i,u,p]=[e,e.length,!1];return Ct({["~kind"]:"Tuple"},{type:"array",additionalItems:p,items:i,minItems:u},o)}function mt(e){return Pe(e,"Tuple")}function Tx(e){return Qo(e,["~kind","type","items","minItems","additionalItems"])}function DO(e){return Qo(e,["~readonly"])}function Ed(e,o){return St(DO(e),{},o)}function Rx(e,o,i,u){let p=ge(e,o,i);return Ed(p,u)}function kx(e,o={}){return ve("RemoveReadonly",[e],o)}function Ax(e,o={}){return Ed(e,o)}function qO(e){return Qo(e,["~optional"])}function Sd(e,o){return St(qO(e),{},o)}function Px(e,o,i,u){let p=ge(e,o,i);return Sd(p,u)}function Cx(e,o={}){return ve("RemoveOptional",[e],o)}function Sm(e,o={}){return Sd(e,o)}function wd(e){return e.reduceRight((i,u,p)=>({[p]:u,...i}),{})}function $x(e){let o=wd(e.items);return l(o)}function Td(e){return Qe(e)||mt(e)}function FO(e,o){return ta(e)?ta(o)?!0:!1:!1}function jO(e,o){return cn(e)?cn(o)?!0:!1:!1}function UO(e,o){let i=FO(e,o),u=jO(e,o),p=Ar([e,o]),g=Ax(Sm(p));return i&&u?ea(Qi(g)):i&&!u?ea(g):!i&&u?Qi(g):g}function BO(e,o,i){return i in e?i in o?UO(e[i],o[i]):e[i]:(i in o)?o[i]:zt()}function GO(e,o){return[...new Set([...we(e),...we(o)])].reduce((p,g)=>({...p,[g]:BO(e,o,g)}),{})}function vx(e){return Qe(e)?e.properties:mt(e)?wd(e.items):{}}function Mx(e,o){let i=vx(e),u=vx(o),p=GO(i,u);return l(p)}function KO(e,o){let i=Ma(e,o);return L(i,_u)?e:L(i,Lu)?o:L(i,Ou)?o:zt()}function HO(e,o){let i=Td(e),u=Td(o);return i&&u?Mx(e,o):i&&!u?e:!i&&u?o:KO(e,o)}function Ox(e,o){return co(e)?e:vr(e)?e:rn(e)?o:co(o)?o:vr(o)?o:rn(o)?e:HO(e,o)}function WO(e,o){return xe(e)||xe(o)}function zO(e,o){let i=Ao(e),u=Ao(o);return WO(i,u)?Ar([i,u]):Ox(i,u)}function _x(e,o,i=[]){return It(o,(u,p)=>_x(e,p,[...i,zO(u,e)]),()=>L(i.length,0)?[e]:i)}function Lx(e,o,i=[]){return It(e,(u,p)=>Lx(p,o,[...i,...Nu([u],o)]),()=>i)}function Nu(e,o=[]){return It(e,(i,u)=>xe(i)?Nu(u,Lx(i.anyOf,o)):Nu(u,_x(i,o)),()=>o)}function VO(e,o){let i=Tn({},e,o);return so(i)?[]:[e]}function Nx(e,o,i=[]){return It(e,(u,p)=>Nx(p,o,[...i,...VO(u,o)]),()=>i)}function wm(e,o){let i=Ao(e),u=xe(i)?i.anyOf:[i],p=Nx(u,o);return oo(p)}function Yo(e,o,i){let u=Ar([e,o]),p=wm(i,e);return oo([u,p])}function Zn(e,o=[]){return It(e,(i,u)=>Zn(u,[...o,s(i)]),()=>oo(o))}function Ar(e){let o=Nu(e),i=Rd(o);return oo(i)}function vn(e){let o=Mu(e);return Ao(o)}function oo(e){let o=Rd(e);return Zs(o)}function Ao(e){return Dr(e)?Yo(e.if,e.then,e.else):on(e)?Zn(e.enum):ze(e)?Ar(e.allOf):ur(e)?vn(e.pattern):xe(e)?oo(e.anyOf):e}function Zs(e){return L(e.length,1)?e[0]:L(e.length,0)?zt():m(e)}function Dx(e,o){let i=Zn(e);return ei(i,o)}function qx(e,o){return no(ti,o)}function Fx(e,o){let i=Ar(e);return ei(i,o)}function jx(e,o){return gt(e)||Ot(e)?l({[e]:o}):L(e,!1)?l({false:o}):L(e,!0)?l({true:o}):l({})}function Ux(e,o){return no(Oa,o)}function Bx(e,o){return fe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)?no(e.pattern.toString(),o):no(Xo,o)}function Gx(e,o){let i=vu(e);return bm(i)?ei(vn(e),o):no(e,o)}function JO(e){return xe(e)?na(e.anyOf):[e]}function na(e,o=[]){return It(e,(i,u)=>na(u,[...o,...JO(i)]),()=>o)}function QO(e){return e.some((o)=>sn(o)||kr(o)||fn(o))}function XO(e,o){return L(QO(e),!0)?no(Xo,o):void 0}function YO(e,o){return e.reduce((i,u)=>yt(u)&&(gt(u.const)||Ot(u.const))?{...i,[u.const]:o}:i,{})}function ZO(e,o){let i=YO(e,o);return l(i)}function Kx(e,o){let i=na(e),u=XO(i,o);return Cr(u)?u:ZO(i,o)}function ei(e,o){return vr(e)?Sx(o):Wn(e)?wx(o):on(e)?Dx(e.enum,o):fn(e)?qx(e,o):ze(e)?Fx(e.allOf,o):yt(e)?jx(e.const,o):kr(e)?Ux(e,o):xe(e)?Kx(e.anyOf,o):sn(e)?Bx(e,o):ur(e)?Gx(e.pattern,o):l({})}function kd(e,o,i){return ct([e])?St(ei(e,o),{},i):Tm(e,o,i)}function Hx(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return kd(g,y,p)}var ti=`^${fm}$`,Oa=`^${xm}$`,Xo=`^${Im}$`;function Tm(e,o,i={}){return ve("Record",[e,o],i)}function bs(e,o,i={}){return kd(e,o,i)}function Wx(e,o){return no(e,o)}function Rm(e){return L(e,Xo)?a():L(e,ti)?_():L(e,Oa)?Y():bd(e)}function hn(e){return we(e.patternProperties)[0]}function ri(e){let o=hn(e);return Rm(o)}function fr(e){return e.patternProperties[hn(e)]}function Gt(e){return Pe(e,"Record")}function oa(e){return Ct({"~kind":"Rest"},{type:"rest",items:e},{})}function ni(e){return Pe(e,"Rest")}function km(e){return Ct({["~kind"]:"This"},{$ref:"#"},e)}function Am(e){return Pe(e,"This")}function _a(e){return Ct({"~kind":"Undefined"},{type:"undefined"},e)}function Zo(e){return Pe(e,"Undefined")}function Pm(e){return Ct({"~kind":"Void"},{type:"void"},e)}function po(e){return Pe(e,"Void")}function t_(e,o){return L(e,"Array")?B(o[0]):L(e,"Capitalize")?$m(o[0]):L(e,"ConstructorParameters")?Lm(o[0]):L(e,"Evaluate")?cE(o[0]):L(e,"Exclude")?Nm(o[0],o[1]):L(e,"Extract")?Dm(o[0],o[1]):L(e,"Index")?ju(o[0],o[1]):L(e,"InstanceType")?qm(o[0]):L(e,"Lowercase")?vm(o[0]):L(e,"NonNullable")?Fm(o[0]):L(e,"Omit")?jm(o[0],o[1]):L(e,"Parameters")?Um(o[0]):L(e,"Partial")?Bm(o[0]):L(e,"Pick")?Gm(o[0],o[1]):L(e,"Readonly")?Km(o[0]):L(e,"KeyOf")?Uu(o[0]):L(e,"Record")?Tm(o[0],o[1]):L(e,"Required")?Hm(o[0]):L(e,"ReturnType")?Wm(o[0]):L(e,"Uncapitalize")?Mm(o[0]):L(e,"Uppercase")?Om(o[0]):Fu(un(e),o)}function sa(){throw Error("Unreachable")}function Xx(e,o=[]){return It(e,(i,u)=>Xx(u,[...o,i[1]]),()=>o)}function Ms(e){return L(e.length,3)?[e[0],...Xx(e[1])]:[]}function Yx(e){return ra(e[0],e[2],e[4])}function Zx(e){return ra(e[0],e[2],e[2])}function eI(e){return ra(e[0],Rr(),e[2])}function tI(e){return ra(e,Rr(),Rr())}function rI(e){return e}function nI(e){return Ms(e)}function oI(e){return e[1]}function sI(e){return Ms(e)}function iI(e){return e[1]}function aI(e){return t_(e[0],e[1])}function uI(e){return null}function cI(e){return a()}function mI(e){return Y()}function pI(e){return O()}function lI(e){return _a()}function dI(e){return $n()}function fI(e){return _()}function hI(e){return Cu()}function gI(e){return Rr()}function yI(e){return Pa()}function xI(e){return l({})}function II(e){return zt()}function bI(e){return va()}function EI(e){return Pm()}function SI(e){return km()}function wI(e){return s(BigInt(e))}function TI(e){return s(L(e,"true"))}function RI(e){return s(parseFloat(e))}function kI(e){return s(e)}function AI(e){return e[1]}function PI(e){return s(e)}function CI(e){return L(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function $I(e){return e[1]}function vI(e){return Cm(e)}function MI(e){return L(e.length,6)?Xi(e[1],e[3],e[5]):Xi(e[1],e[3],Rr())}function OI(e){return e.length>0}function _I(e){return e.reduce((o,i)=>L(i.length,3)?[...o,[i[1]]]:[...o,[]],[])}function LI(e){return L(e.length,6)?[e[1],e[3],e[5]]:[]}function NI(e){return Ge(e)&&L(e.length,3)?e[1]:e}function DI(e){return L(e.length,2)?e[1]:[]}function zx(e,o){return o.reduce((i,u)=>{let p=u;return L(p.length,1)?ju(i,p[0]):L(p.length,0)?B(i):sa()},e)}function Vx(e,o){return L(o.length,3)?_m(e,o[0],o[1],o[2]):e}function r_(e,o){return Ge(o)&&L(o.length,0)?e:zm(e,o)}function qI(e){let[o,i,u,p,g]=e;return r_(o?Vx(Uu(zx(i,u)),p):Vx(zx(i,u),p),g)}function Ad(e,o){return L(o.length,3)?(()=>{let[i,u,p]=o,g=Ad(u,p);if(L(i,"&"))return ze(g)?Cn([e,...g.allOf]):Cn([e,g]);if(L(i,"|"))return xe(g)?m([e,...g.anyOf]):m([e,g]);sa()})():e}function FI(e){return e}function jI(e){let[o,i]=e;return Ad(o,i)}function UI(e){return e}function BI(e){let[o,i]=e;return Ad(o,i)}function GI(e){return uE(e[1])}function KI(e){return e[1]}function HI(e){return Xs(e[0],e[2])}function WI(e){return L(e.length,4)?Pu(e[1],e[3]):L(e.length,2)?Pu(e[1],Rr()):sa()}function zI(e){return e}function VI(e){return`${e}`}function JI(e){return e}function QI(e){return e}function XI(e){return fn(e[3])?ti:kr(e[3])?Oa:Is(e[3])?Xo:sn(e[3])?Xo:sa()}function YI(e){return e}function ZI(e){return e.length>0}function eb(e){return e.length>0}function tb(e){let[o,i,u,p,g]=e;return{[i]:o&&u?ys(hs(g)):o&&!u?ys(g):!o&&u?hs(g):g}}function rb(e){return e}function nb(e){return Ms(e)}function ob(e){return e.reduce((o,i)=>fe(i,ti)||fe(i,Oa)||fe(i,Xo)?[o[0],dn(o[1],i)]:[dn(o[0],i),o[1]],[{},{}])}function sb(e){return ob(e[1])}function ib(e){let[o,i]=e,u=L(we(i).length,0)?{}:{patternProperties:i};return l(o,u)}function ab(e){return L(e.length,5)?ys(hs(e[4])):L(e.length,3)?e[2]:L(e.length,4)?L(e[2],"readonly")?ys(e[3]):hs(e[3]):sa()}function ub(e){if(!Ge(e)||!L(e.length,3))return e;let[o,i,u]=e;return o&&u?ys(hs(i)):o&&!u?ys(i):!o&&u?hs(i):i}function cb(e){return L(e.length,2)?oa(e[1]):L(e.length,1)?e[0]:sa()}function mb(e){return Ms(e)}function pb(e){return Ur(e[1])}function lb(e){return ys(hs(e[4]))}function db(e){return ys(e[3])}function fb(e){return hs(e[3])}function hb(e){return e[2]}function gb(e){return e}function yb(e){return L(e.length,2)?oa(e[1]):L(e.length,1)?e[0]:sa()}function xb(e){return Ms(e)}function Ib(e){return fs(e[1],e[4])}function bb(e){return ds(e[2],e[5])}function Jx(e,o){return L(e,"remove")?kx(o):L(e,"add")?ys(o):o}function Eb(e){return L(e.length,2)&&L(e[0],"-")?"remove":L(e.length,2)&&L(e[0],"+")?"add":L(e.length,1)?"add":"none"}function Qx(e,o){return L(e,"remove")?Cx(o):L(e,"add")?hs(o):o}function Sb(e){return L(e.length,2)&&L(e[0],"-")?"remove":L(e.length,2)&&L(e[0],"+")?"add":L(e.length,1)?"add":"none"}function wb(e){return L(e.length,2)?[e[1]]:[]}function Tb(e){return Ge(e[6])&&L(e[6].length,1)?Du($u(e[3]),e[5],e[6][0],Jx(e[1],Qx(e[8],e[10]))):Du($u(e[3]),e[5],un(e[3]),Jx(e[1],Qx(e[8],e[10])))}function Rb(e){return un(e)}function kb(e){return BigInt(e)}function Ab(e){return parseFloat(e)}function Pb(e){return L(e,"true")}function Cb(e){return e}function $b(e){return null}function vb(e){return}function Mb(e){return{[e[0]]:e[2]}}function Ob(e){return Ms(e)}function n_(e){return e.reduce((o,i)=>dn(o,i),{})}function _b(e){return n_(e[1])}function Lb(e){return Ms(e)}function Nb(e){return e[1]}function Db(e){return e}function qb(e){return Cu()}function Fb(e){return a()}function jb(e){return Y()}function Ub(e){return _()}function Bb(e){return zt()}function Gb(e){return s(e)}function Kb(e){return e}function Hb(e){return m(e[1])}function Wb(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function zb(e){return[e[0],...e[1]]}function Vb(e){return e}function Jb(e){return e[1]}function Qb(e){return Ms(e)}function Xb(e){return L(e.length,2)?e[1]:[]}function Yb(e){let o=e[2],i=e[3],[u,p]=e[4],g=L(we(p).length,0)?{}:{patternProperties:p};return{[e[1]]:Xs(o,qu(i,u,g))}}function Zb(e){let o=e[2],[i,u]=e[3],p=L(we(u).length,0)?{}:{patternProperties:u};return{[e[1]]:qu(o,i,p)}}function eE(e){return{[e[1]]:Xs(e[2],e[4])}}function tE(e){return{[e[1]]:e[3]}}function rE(e){return null}function nE(e){return e}function oE(e){return Ms(e)}function sE(e){return e[1]}function iE(e){let[o,i]=[e[0],e[1]];return mE(dn(o,ob(i)[0]))}function aE(e){return e}function Bu(e){return L(e.length,2)}function Tt(e,o,i){return Bu(e)?o(e[0],e[1]):i()}function i_(e,o){return L(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Or(e,o){for(let i=0;i<e.length;i++){let u=i_(e[i],o);if(Bu(u))return u}return[]}function Pd(e,o){return Array.from({length:o-e+1},(i,u)=>String.fromCharCode(e+u))}var pE=[...Pd(97,122),...Pd(65,90)],Cd="0",$d=Pd(49,57),La=[Cd,...$d],lE=" ",Na=`
17
- `;var oi="_",Vm=".",dE="$",Jm="-";var fE="//",hE="/*",u_="*/";function gE(e){let o=e.indexOf(u_);return L(o,-1)?"":e.slice(o+2)}function yE(e){let o=e.indexOf(Na);return L(o,-1)?"":e.slice(o)}function c_(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Qm(e){let o=c_(e);return o.startsWith(hE)?Qm(gE(o.slice(2))):o.startsWith(fE)?Qm(yE(o.slice(2))):o}function bn(e){let o=e.trimStart();return o.startsWith(hE)?bn(gE(o.slice(2))):o.startsWith(fE)?bn(yE(o.slice(2))):o}function Xm(e,o){return Tt(Or([e],o),(i,u)=>[i,u],()=>["",o])}function m_(e,o){return e.includes(o)}function Da(e,o,i,u=""){return Tt(Or(e,i),(p,g)=>m_(o,p)?Da(e,o,g,u):Da(e,o,g,`${u}${p}`),()=>[u,i])}function p_(e){return Or($d,e)}var l_=[...La,oi];function d_(e){return Da(l_,[oi],e)}function f_(e){return Tt(Or([Cd],e),(o,i)=>[o,i],()=>Tt(p_(e),(o,i)=>Tt(d_(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[]))}function Ym(e){return f_(bn(e))}function h_(e){return Xm(Jm,e)}function g_(e){return Tt(h_(e),(o,i)=>Tt(Ym(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function xE(e){return g_(bn(e))}function y_(e){return Tt(xE(e),(o,i)=>Tt(Or(["n"],i),(u,p)=>[`${o}`,p],()=>[]),()=>[])}function vd(e){return y_(e)}function Md(e,o){return Or([e],o)}function Z(e,o){return L(e,"")?["",o]:e.startsWith(Na)?Md(e,Qm(o)):e.startsWith(lE)?Md(e,o):Md(e,bn(o))}var IE=[...pE,oi,dE];function x_(e){return Or(IE,e)}var I_=[...IE,...La];function bE(e,o=""){return Tt(Or(I_,e),(i,u)=>bE(u,`${o}${i}`),()=>[o,e])}function b_(e){return Tt(x_(e),(o,i)=>Tt(bE(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Br(e){return b_(bn(e))}var E_=[...La,oi];function S_(e){return Bu(Or([Vm],e))}function EE(e){return Tt(Da(E_,[oi],e),(o,i)=>L(o,"")?[]:[o,i],()=>[])}function w_(e){return Tt(Or([Vm],e),(o,i)=>Tt(EE(i),(u,p)=>[`0${o}${u}`,p],()=>[]),()=>[])}function T_(e){return Tt(Ym(e),(o,i)=>Tt(Or([Vm],i),(u,p)=>Tt(EE(p),(g,y)=>[`${o}${u}${g}`,y],()=>[`${o}`,p]),()=>[`${o}`,i]),()=>[])}function R_(e){return S_(e)?w_(e):T_(e)}function SE(e){return R_(bn(e))}function k_(e){return Xm(Jm,e)}function A_(e){return Tt(k_(e),(o,i)=>Tt(SE(i),(u,p)=>[`${o}${u}`,p],()=>[]),()=>[])}function Zm(e){return A_(bn(e))}function P_(e){return L(e,"")?[]:[e.slice(0,1),e.slice(1)]}function wE(e,o){return It(e,(i,u)=>o.startsWith(i)?!0:wE(u,o),()=>!1)}function si(e,o,i=""){return Tt(P_(o),(u,p)=>wE(e,o)?[i,o]:si(e,p,`${i}${u}`),()=>[])}function C_(e,o,i){return Tt(Or([e],i),(u,p)=>Tt(si([o],p),(g,y)=>Tt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function $_(e,o,i){return Tt(Or([e],i),(u,p)=>Tt(si([Na,o],p),(g,y)=>Tt(Or([o],y),(b,E)=>[`${g}`,E],()=>[]),()=>[]),()=>[])}function TE(e,o,i,u){return i?C_(e,o,bn(u)):$_(e,o,bn(u))}function v_(e,o){return Or(e,o)}function M_(e,o){return TE(e,e,!1,o)}function O_(e,o){return Tt(v_(e,o),(i,u)=>M_(i,`${i}${u}`),()=>[])}function ep(e,o){return O_(e,bn(o))}function RE(e,o){return Tt(si(e,o),(i,u)=>L(i,"")?[]:[i,u],()=>[])}var T=(e,o,i=()=>[])=>e.length===2?o(e):i(),L_=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([u,p])=>T(vt(p),([g,y])=>T(Z("=",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Yx(o),i]),N_=(e)=>T(T(Br(e),([o,i])=>T(Z("extends",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Zx(o),i]),D_=(e)=>T(T(Br(e),([o,i])=>T(Z("=",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[eI(o),i]),q_=(e)=>T(Br(e),([o,i])=>[tI(o),i]),PE=(e)=>T(T(L_(e),([o,i])=>[o,i],()=>T(N_(e),([o,i])=>[o,i],()=>T(D_(e),([o,i])=>[o,i],()=>T(q_(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[rI(o),i]),CE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(PE(u),([p,g])=>[[i,p],g])),([i,u])=>CE(u,[...o,i]),()=>[o,e]),F_=(e)=>T(T(T(PE(e),([o,i])=>T(CE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[nI(o),i]),Ld=(e)=>T(T(Z("<",e),([o,i])=>T(F_(i),([u,p])=>T(Z(">",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[oI(o),i]),$E=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vt(u),([p,g])=>[[i,p],g])),([i,u])=>$E(u,[...o,i]),()=>[o,e]),j_=(e)=>T(T(T(vt(e),([o,i])=>T($E(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[sI(o),i]),U_=(e)=>T(T(Z("<",e),([o,i])=>T(j_(i),([u,p])=>T(Z(">",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[iI(o),i]),B_=(e)=>T(T(Br(e),([o,i])=>T(U_(i),([u,p])=>[[o,u],p])),([o,i])=>[aI(o),i]),vE=(e)=>T(T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[uI(o),i]),ME=(e)=>T(Z("string",e),([o,i])=>[cI(o),i]),OE=(e)=>T(Z("number",e),([o,i])=>[mI(o),i]),G_=(e)=>T(Z("boolean",e),([o,i])=>[pI(o),i]),K_=(e)=>T(Z("undefined",e),([o,i])=>[lI(o),i]),H_=(e)=>T(Z("null",e),([o,i])=>[dI(o),i]),_E=(e)=>T(Z("integer",e),([o,i])=>[fI(o),i]),W_=(e)=>T(Z("bigint",e),([o,i])=>[hI(o),i]),z_=(e)=>T(Z("unknown",e),([o,i])=>[gI(o),i]),V_=(e)=>T(Z("any",e),([o,i])=>[yI(o),i]),J_=(e)=>T(Z("object",e),([o,i])=>[xI(o),i]),Q_=(e)=>T(Z("never",e),([o,i])=>[II(o),i]),LE=(e)=>T(Z("symbol",e),([o,i])=>[bI(o),i]),X_=(e)=>T(Z("void",e),([o,i])=>[EI(o),i]),Y_=(e)=>T(Z("this",e),([o,i])=>[SI(o),i]),Z_=(e)=>T(T(Z("${",e),([o,i])=>T(vt(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[AI(o),i]),Od=(e)=>T(si(["${","`"],e),([o,i])=>[PI(o),i]),NE=(e)=>T(T(T(Od(e),([o,i])=>T(Z_(i),([u,p])=>T(NE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(T(Od(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Od(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[CI(o),i]),Nd=(e)=>T(T(Z("`",e),([o,i])=>T(NE(i),([u,p])=>T(Z("`",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[$I(o),i]),eL=(e)=>T(Nd(e),([o,i])=>[vI(o),i]),tL=(e)=>T(T(T(Z("if",e),([o,i])=>T(vt(i),([u,p])=>T(Z("then",p),([g,y])=>T(vt(y),([b,E])=>T(Z("else",E),([S,w])=>T(vt(w),([R,A])=>[[o,u,g,b,S,R],A])))))),([o,i])=>[o,i],()=>T(T(Z("if",e),([o,i])=>T(vt(i),([u,p])=>T(Z("then",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>[])),([o,i])=>[MI(o),i]),rL=(e)=>T(vd(e),([o,i])=>[wI(o),i]),nL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[TI(o),i]),oL=(e)=>T(Zm(e),([o,i])=>[RI(o),i]),sL=(e)=>T(ep(["'",'"'],e),([o,i])=>[kI(o),i]),iL=(e)=>T(T(T(Z("keyof",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[OI(o),i]),DE=(e,o=[])=>T(T(T(Z("[",e),([i,u])=>T(vt(u),([p,g])=>T(Z("]",g),([y,b])=>[[i,p,y],b]))),([i,u])=>[i,u],()=>T(T(Z("[",e),([i,u])=>T(Z("]",u),([p,g])=>[[i,p],g])),([i,u])=>[i,u],()=>[])),([i,u])=>DE(u,[...o,i]),()=>[o,e]),aL=(e)=>T(DE(e),([o,i])=>[_I(o),i]),uL=(e)=>T(T(T(Z("extends",e),([o,i])=>T(vt(i),([u,p])=>T(Z("?",p),([g,y])=>T(vt(y),([b,E])=>T(Z(":",E),([S,w])=>T(vt(w),([R,A])=>[[o,u,g,b,S,R],A])))))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[LI(o),i]),cL=(e)=>T(T(T(Z("(",e),([o,i])=>T(vt(i),([u,p])=>T(Z(")",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(ME(e),([o,i])=>[o,i],()=>T(OE(e),([o,i])=>[o,i],()=>T(G_(e),([o,i])=>[o,i],()=>T(K_(e),([o,i])=>[o,i],()=>T(H_(e),([o,i])=>[o,i],()=>T(_E(e),([o,i])=>[o,i],()=>T(W_(e),([o,i])=>[o,i],()=>T(z_(e),([o,i])=>[o,i],()=>T(V_(e),([o,i])=>[o,i],()=>T(J_(e),([o,i])=>[o,i],()=>T(Q_(e),([o,i])=>[o,i],()=>T(LE(e),([o,i])=>[o,i],()=>T(X_(e),([o,i])=>[o,i],()=>T(Y_(e),([o,i])=>[o,i],()=>T(rL(e),([o,i])=>[o,i],()=>T(nL(e),([o,i])=>[o,i],()=>T(oL(e),([o,i])=>[o,i],()=>T(sL(e),([o,i])=>[o,i],()=>T(eL(e),([o,i])=>[o,i],()=>T(tL(e),([o,i])=>[o,i],()=>T(bL(e),([o,i])=>[o,i],()=>T(wL(e),([o,i])=>[o,i],()=>T(CL(e),([o,i])=>[o,i],()=>T(PL(e),([o,i])=>[o,i],()=>T(OL(e),([o,i])=>[o,i],()=>T(B_(e),([o,i])=>[o,i],()=>T(_L(e),([o,i])=>[o,i],()=>[])))))))))))))))))))))))))))),([o,i])=>[NI(o),i]),mL=(e)=>T(T(T(Z("with",e),([o,i])=>T(eS(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[DI(o),i]),qE=(e)=>T(T(iL(e),([o,i])=>T(cL(i),([u,p])=>T(aL(p),([g,y])=>T(uL(y),([b,E])=>T(mL(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[qI(o),i]),FE=(e)=>T(T(T(Z("&",e),([o,i])=>T(qE(i),([u,p])=>T(FE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[FI(o),i]),jE=(e)=>T(T(qE(e),([o,i])=>T(FE(i),([u,p])=>[[o,u],p])),([o,i])=>[jI(o),i]),UE=(e)=>T(T(T(Z("|",e),([o,i])=>T(jE(i),([u,p])=>T(UE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[UI(o),i]),tp=(e)=>T(T(jE(e),([o,i])=>T(UE(i),([u,p])=>[[o,u],p])),([o,i])=>[BI(o),i]),pL=(e)=>T(T(Z("readonly",e),([o,i])=>T(tp(i),([u,p])=>[[o,u],p])),([o,i])=>[GI(o),i]),lL=(e)=>T(T(Z("|",e),([o,i])=>T(tp(i),([u,p])=>[[o,u],p])),([o,i])=>[KI(o),i]),dL=(e)=>T(T(Ld(e),([o,i])=>T(Z("=",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[HI(o),i]),fL=(e)=>T(T(T(Z("infer",e),([o,i])=>T(Br(i),([u,p])=>T(Z("extends",p),([g,y])=>T(tp(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Z("infer",e),([o,i])=>T(Br(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>[])),([o,i])=>[WI(o),i]),vt=(e)=>T(T(fL(e),([o,i])=>[o,i],()=>T(lL(e),([o,i])=>[o,i],()=>T(pL(e),([o,i])=>[o,i],()=>T(tp(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[zI(o),i]),hL=(e)=>T(Zm(e),([o,i])=>[VI(o),i]),gL=(e)=>T(Br(e),([o,i])=>[JI(o),i]),yL=(e)=>T(ep(["'",'"'],e),([o,i])=>[QI(o),i]),xL=(e)=>T(T(Z("[",e),([o,i])=>T(Br(i),([u,p])=>T(Z(":",p),([g,y])=>T(T(_E(y),([b,E])=>[b,E],()=>T(OE(y),([b,E])=>[b,E],()=>T(ME(y),([b,E])=>[b,E],()=>T(LE(y),([b,E])=>[b,E],()=>[])))),([b,E])=>T(Z("]",E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[XI(o),i]),BE=(e)=>T(T(hL(e),([o,i])=>[o,i],()=>T(gL(e),([o,i])=>[o,i],()=>T(yL(e),([o,i])=>[o,i],()=>T(xL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[YI(o),i]),GE=(e)=>T(T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[ZI(o),i]),KE=(e)=>T(T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[eb(o),i]),HE=(e)=>T(T(GE(e),([o,i])=>T(BE(i),([u,p])=>T(KE(p),([g,y])=>T(Z(":",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[tb(o),i]),rp=(e)=>T(T(T(Z(",",e),([o,i])=>T(Z(`
18
- `,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>T(Z(`
19
- `,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(",",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
20
- `,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))))),([o,i])=>[rb(o),i]),WE=(e,o=[])=>T(T(rp(e),([i,u])=>T(HE(u),([p,g])=>[[i,p],g])),([i,u])=>WE(u,[...o,i]),()=>[o,e]),IL=(e)=>T(T(T(HE(e),([o,i])=>T(WE(i),([u,p])=>T(T(rp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[nb(o),i]),Dd=(e)=>T(T(Z("{",e),([o,i])=>T(IL(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[sb(o),i]),bL=(e)=>T(Dd(e),([o,i])=>[ib(o),i]),EL=(e)=>T(T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(Z("readonly",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[o,i],()=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>[])))),([o,i])=>[ab(o),i]),kE=(e)=>T(T(EL(e),([o,i])=>[o,i],()=>T(T(GE(e),([o,i])=>T(vt(i),([u,p])=>T(KE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>[])),([o,i])=>[ub(o),i]),zE=(e)=>T(T(T(Z("...",e),([o,i])=>T(kE(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(kE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[cb(o),i]),VE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(zE(u),([p,g])=>[[i,p],g])),([i,u])=>VE(u,[...o,i]),()=>[o,e]),SL=(e)=>T(T(T(zE(e),([o,i])=>T(VE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[mb(o),i]),wL=(e)=>T(T(Z("[",e),([o,i])=>T(SL(i),([u,p])=>T(Z("]",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[pb(o),i]),TL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(Z("readonly",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[lb(o),i]),RL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(Z("readonly",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[db(o),i]),kL=(e)=>T(T(Br(e),([o,i])=>T(Z("?",i),([u,p])=>T(Z(":",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[fb(o),i]),AL=(e)=>T(T(Br(e),([o,i])=>T(Z(":",i),([u,p])=>T(vt(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[hb(o),i]),AE=(e)=>T(T(TL(e),([o,i])=>[o,i],()=>T(RL(e),([o,i])=>[o,i],()=>T(kL(e),([o,i])=>[o,i],()=>T(AL(e),([o,i])=>[o,i],()=>[])))),([o,i])=>[gb(o),i]),JE=(e)=>T(T(T(Z("...",e),([o,i])=>T(AE(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(AE(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[])),([o,i])=>[yb(o),i]),QE=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(JE(u),([p,g])=>[[i,p],g])),([i,u])=>QE(u,[...o,i]),()=>[o,e]),XE=(e)=>T(T(T(JE(e),([o,i])=>T(QE(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[xb(o),i]),PL=(e)=>T(T(Z("(",e),([o,i])=>T(XE(i),([u,p])=>T(Z(")",p),([g,y])=>T(Z("=>",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Ib(o),i]),CL=(e)=>T(T(Z("new",e),([o,i])=>T(Z("(",i),([u,p])=>T(XE(p),([g,y])=>T(Z(")",y),([b,E])=>T(Z("=>",E),([S,w])=>T(vt(w),([R,A])=>[[o,u,g,b,S,R],A])))))),([o,i])=>[bb(o),i]),$L=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("readonly",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("readonly",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("readonly",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Eb(o),i]),vL=(e)=>T(T(T(Z("+",e),([o,i])=>T(Z("?",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("-",e),([o,i])=>T(Z("?",i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z("?",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])))),([o,i])=>[Sb(o),i]),ML=(e)=>T(T(T(Z("as",e),([o,i])=>T(vt(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[wb(o),i]),OL=(e)=>T(T(Z("{",e),([o,i])=>T($L(i),([u,p])=>T(Z("[",p),([g,y])=>T(Br(y),([b,E])=>T(Z("in",E),([S,w])=>T(vt(w),([R,A])=>T(ML(A),([P,C])=>T(Z("]",C),([q,X])=>T(vL(X),([j,V])=>T(Z(":",V),([J,ee])=>T(vt(ee),([ae,H])=>T(vE(H),([ue,he])=>T(Z("}",he),([$e,Ee])=>[[o,u,g,b,S,R,P,q,j,J,ae,ue,$e],Ee]))))))))))))),([o,i])=>[Tb(o),i]),_L=(e)=>T(Br(e),([o,i])=>[Rb(o),i]),LL=(e)=>T(vd(e),([o,i])=>[kb(o),i]),NL=(e)=>T(Zm(e),([o,i])=>[Ab(o),i]),DL=(e)=>T(T(Z("true",e),([o,i])=>[o,i],()=>T(Z("false",e),([o,i])=>[o,i],()=>[])),([o,i])=>[Pb(o),i]),qL=(e)=>T(ep(['"',"'"],e),([o,i])=>[Cb(o),i]),FL=(e)=>T(Z("null",e),([o,i])=>[$b(o),i]),jL=(e)=>T(Z("undefined",e),([o,i])=>[vb(o),i]),YE=(e)=>T(T(BE(e),([o,i])=>T(Z(":",i),([u,p])=>T(qd(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Mb(o),i]),ZE=(e,o=[])=>T(T(rp(e),([i,u])=>T(YE(u),([p,g])=>[[i,p],g])),([i,u])=>ZE(u,[...o,i]),()=>[o,e]),UL=(e)=>T(T(T(YE(e),([o,i])=>T(ZE(i),([u,p])=>T(T(rp(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Ob(o),i]),eS=(e)=>T(T(Z("{",e),([o,i])=>T(UL(i),([u,p])=>T(Z("}",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[_b(o),i]),tS=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(qd(u),([p,g])=>[[i,p],g])),([i,u])=>tS(u,[...o,i]),()=>[o,e]),BL=(e)=>T(T(T(qd(e),([o,i])=>T(tS(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Lb(o),i]),GL=(e)=>T(T(Z("[",e),([o,i])=>T(BL(i),([u,p])=>T(Z("]",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Nb(o),i]),qd=(e)=>T(T(LL(e),([o,i])=>[o,i],()=>T(NL(e),([o,i])=>[o,i],()=>T(DL(e),([o,i])=>[o,i],()=>T(qL(e),([o,i])=>[o,i],()=>T(FL(e),([o,i])=>[o,i],()=>T(jL(e),([o,i])=>[o,i],()=>T(eS(e),([o,i])=>[o,i],()=>T(GL(e),([o,i])=>[o,i],()=>[])))))))),([o,i])=>[Db(o),i]),KL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)n",e),([o,i])=>[qb(o),i]),HL=(e)=>T(Z(".*",e),([o,i])=>[Fb(o),i]),WL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,i])=>[jb(o),i]),zL=(e)=>T(Z("-?(?:0|[1-9][0-9]*)",e),([o,i])=>[Ub(o),i]),VL=(e)=>T(Z("(?!)",e),([o,i])=>[Bb(o),i]),JL=(e)=>T(RE(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,i])=>[Gb(o),i]),QL=(e)=>T(T(KL(e),([o,i])=>[o,i],()=>T(HL(e),([o,i])=>[o,i],()=>T(WL(e),([o,i])=>[o,i],()=>T(zL(e),([o,i])=>[o,i],()=>T(VL(e),([o,i])=>[o,i],()=>T(XL(e),([o,i])=>[o,i],()=>T(JL(e),([o,i])=>[o,i],()=>[]))))))),([o,i])=>[Kb(o),i]),XL=(e)=>T(T(Z("(",e),([o,i])=>T(Fd(i),([u,p])=>T(Z(")",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Hb(o),i]),rS=(e)=>T(T(T(_d(e),([o,i])=>T(Z("|",i),([u,p])=>T(rS(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T(T(_d(e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[]))),([o,i])=>[Wb(o),i]),_d=(e)=>T(T(QL(e),([o,i])=>T(Fd(i),([u,p])=>[[o,u],p])),([o,i])=>[zb(o),i]),Fd=(e)=>T(T(rS(e),([o,i])=>[o,i],()=>T(_d(e),([o,i])=>[o,i],()=>[])),([o,i])=>[Vb(o),i]),hx=(e)=>T(T(Z("^",e),([o,i])=>T(Fd(i),([u,p])=>T(Z("$",p),([g,y])=>[[o,u,g],y]))),([o,i])=>[Jb(o),i]),nS=(e,o=[])=>T(T(Z(",",e),([i,u])=>T(vt(u),([p,g])=>[[i,p],g])),([i,u])=>nS(u,[...o,i]),()=>[o,e]),YL=(e)=>T(T(T(vt(e),([o,i])=>T(nS(i),([u,p])=>T(T(Z(",",p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Qb(o),i]),oS=(e)=>T(T(T(Z("extends",e),([o,i])=>T(YL(i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[Xb(o),i]),ZL=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([u,p])=>T(Ld(p),([g,y])=>T(oS(y),([b,E])=>T(Dd(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[Yb(o),i]),eN=(e)=>T(T(Z("interface",e),([o,i])=>T(Br(i),([u,p])=>T(oS(p),([g,y])=>T(Dd(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[Zb(o),i]),tN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([u,p])=>T(Ld(p),([g,y])=>T(Z("=",y),([b,E])=>T(vt(E),([S,w])=>[[o,u,g,b,S],w]))))),([o,i])=>[eE(o),i]),rN=(e)=>T(T(Z("type",e),([o,i])=>T(Br(i),([u,p])=>T(Z("=",p),([g,y])=>T(vt(y),([b,E])=>[[o,u,g,b],E])))),([o,i])=>[tE(o),i]),nN=(e)=>T(T(T(Z("export",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[rE(o),i]),sS=(e)=>T(T(T(Z(";",e),([o,i])=>T(Z(`
21
- `,i),([u,p])=>[[o,u],p])),([o,i])=>[o,i],()=>T(T(Z(";",e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>T(T(Z(`
22
- `,e),([o,i])=>[[o],i]),([o,i])=>[o,i],()=>[]))),([o,i])=>[nE(o),i]),iS=(e,o=[])=>T(T(sS(e),([i,u])=>T(jd(u),([p,g])=>[[i,p],g])),([i,u])=>iS(u,[...o,i]),()=>[o,e]),oN=(e)=>T(T(T(jd(e),([o,i])=>T(iS(i),([u,p])=>T(T(sS(p),([g,y])=>[[g],y],()=>[[],p]),([g,y])=>[[o,u,g],y]))),([o,i])=>[o,i],()=>T([[],e],([o,i])=>[o,i],()=>[])),([o,i])=>[oE(o),i]),jd=(e)=>T(T(nN(e),([o,i])=>T(T(ZL(i),([u,p])=>[u,p],()=>T(eN(i),([u,p])=>[u,p],()=>T(tN(i),([u,p])=>[u,p],()=>T(rN(i),([u,p])=>[u,p],()=>[])))),([u,p])=>T(vE(p),([g,y])=>[[o,u,g],y]))),([o,i])=>[sE(o),i]),sN=(e)=>T(T(jd(e),([o,i])=>T(oN(i),([u,p])=>[[o,u],p])),([o,i])=>[iE(o),i]),aS=(e)=>T(T(sN(e),([o,i])=>[o,i],()=>T(dL(e),([o,i])=>[o,i],()=>T(vt(e),([o,i])=>[o,i],()=>[]))),([o,i])=>[aE(o),i]);function uS(e){let o=Nd(`\`${e}\``);return L(o.length,2)?o[0]:jr()}function aN(e){return e.join("|")}function uN(e){return e.slice(1,e.length-1)}function cN(e,o,i){return ii(o,`${i}${e}`)}function mN(e,o){return ii(e,`${o}${ux}`)}function pN(e,o){return ii(e,`${o}${fm}`)}function lN(e,o){return ii(e,`${o}${xm}`)}function dN(e,o){return Gu(m([s("false"),s("true")]),e,o)}function fN(e,o){return ii(e,`${o}${Im}`)}function hN(e,o,i){return ii(o,`${i}${uN(e)}`)}function gN(e,o,i){let u=Ku(e,{});return Gu(u,o,i)}function yN(e,o,i){let u=Zn(e);return Gu(u,o,i)}function cS(e,o,i,u=[]){return It(e,(p,g)=>cS(g,o,i,[...u,Gu(p,[],"")]),()=>ii(o,`${i}(${aN(u)})`))}function Gu(e,o,i){return on(e)?yN(e.enum,o,i):fn(e)?pN(o,i):yt(e)?cN(e.const,o,i):mo(e)?mN(o,i):Wn(e)?dN(o,i):kr(e)?lN(o,i):sn(e)?fN(o,i):ur(e)?hN(e.pattern,o,i):pS(e)?gN(e.parameters[0],o,i):xe(e)?cS(e.anyOf,o,i):Ny}function ii(e,o){return It(e,(i,u)=>Gu(i,u,o),()=>o)}function xN(e){return`^${ii(e,"")}$`}function mS(e){let o=xN(e);return Em(o)}function Ku(e,o){return ct(e)?St(mS(e),{},o):Cm(e,o)}function lS(e,o,i,u){let p=yo(e,o,i);return Ku(p,u)}function Cm(e,o={}){return ve("TemplateLiteral",[e],o)}function pS(e){return Cr(e)&&fe(e,"action")&&L(e.action,"TemplateLiteral")}function dS(e){return Ku(e,{})}function IN(e){let o=uS(e);return dS(o)}function fS(e,o={}){let i=gt(e)?IN(e):dS(e);return St(i,{},o)}function ur(e){return Pe(e,"TemplateLiteral")}function Ud(e){return Ct({["~kind"]:"ExtendsUnion"},{inferred:e})}function Bd(e){return at(e)&&fe(e,"~kind")&&fe(e,"inferred")&&L(e["~kind"],"ExtendsUnion")&&at(e.inferred)}function Ae(e){return Ct({["~kind"]:"ExtendsTrue"},{inferred:e})}function Gd(e){return at(e)&&fe(e,"~kind")&&fe(e,"inferred")&&L(e["~kind"],"ExtendsTrue")&&at(e.inferred)}function Ze(){return Ct({["~kind"]:"ExtendsFalse"},{})}function Kd(e){return at(e)&&fe(e,"~kind")&&L(e["~kind"],"ExtendsFalse")}function so(e){return Bd(e)||Gd(e)}function br(e,o,i){return so(e)?o(e.inferred):i()}function bN(e,o,i,u){return br(Rt(e,i,u),(p)=>Ae(dn(dn(e,p),{[o]:i})),()=>Ze())}function EN(e,o){return Ae(e)}function SN(e,o,i,u,p){return br(Rt(e,o,i),(g)=>br(Rt(g,o,u),(y)=>Ae(y),()=>Ze()),()=>br(Rt(e,o,p),(g)=>Ae(g),()=>Ze()))}function wN(e,o,i){let u=Zn(i);return Rt(e,o,u)}function hS(e,o,i){return It(i,(u,p)=>br(Rt(e,o,u),(g)=>hS(g,o,p),()=>Ze()),()=>Ae(e))}function TN(e,o,i){let u=vn(i);return Rt(e,o,u)}function gS(e,o,i){return It(i,(u,p)=>br(Rt(e,o,u),(g)=>Ae(g),()=>gS(e,o,p)),()=>Ze())}function Nt(e,o,i){return vr(i)?EN(e,o):Dr(i)?SN(e,o,i.if,i.then,i.else):on(i)?wN(e,o,i.enum):nn(i)?bN(e,i.name,o,i.extends):ze(i)?hS(e,o,i.allOf):ur(i)?TN(e,o,i.pattern):xe(i)?gS(e,o,i.anyOf):rn(i)?Ae(e):Ze()}function yS(e,o,i){return nn(i)?Nt(e,o,i):vr(i)?Ae(e):rn(i)?Ae(e):Ud(e)}function RN(e,o){let i=Zi(e),u=Zi(o);return i&&u?!0:!i&&u?!0:i&&!u?!1:!0}function xS(e,o,i,u){return wt(u)?RN(o,u)?Rt(e,i,u.items):Ze():Nt(e,o,u)}function IS(e,o,i){return mo(i)?Ae(e):Nt(e,o,i)}function bS(e,o,i){return Wn(i)?Ae(e):Nt(e,o,i)}function kN(e,o,i,u,p){let g=nn(u)?o:u,y=nn(u)?u:o,b=cn(o),E=cn(u);return!b&&E?Ze():br(Rt(e,g,y),(S)=>Hu(S,i,p),()=>Ze())}function AN(e,o,i,u){return It(u,(p,g)=>kN(e,o,i,p,g),()=>cn(o)?Ae(e):Ze())}function PN(e,o,i){return It(o,(u,p)=>AN(e,u,p,i),()=>Ae(e))}function Hu(e,o,i){return PN(e,o,i)}function np(e,o,i){return po(i)?Ae(e):Rt(e,o,i)}function ES(e,o,i,u){return vr(u)?Ae(e):rn(u)?Ae(e):en(u)?br(Hu(e,o,u.parameters),(p)=>np(p,i,u.instanceType),()=>Ze()):Ze()}function SS(e,o,i,u,p){return br(Rt(e,o,p),()=>Rt(e,i,p),()=>Rt(e,u,p))}function wS(e,o,i){let u=Zn(o);return Rt(e,u,i)}function TS(e,o,i,u){return vr(u)?Ae(e):rn(u)?Ae(e):tn(u)?br(Hu(e,o,u.parameters),(p)=>np(p,i,u.returnType),()=>Ze()):Ze()}function RS(e,o,i){return fn(i)?Ae(e):kr(i)?Ae(e):Nt(e,o,i)}function kS(e,o,i){let u=Ar(o);return Rt(e,u,i)}function op(e,o,i){return o===i?Ae(e):Ze()}function CN(e,o,i){return yt(i)?op(e,o,i.const):mo(i)?Ae(e):Nt(e,s(o),i)}function $N(e,o,i){return yt(i)?op(e,o,i.const):Wn(i)?Ae(e):Nt(e,s(o),i)}function vN(e,o,i){return yt(i)?op(e,o,i.const):kr(i)?Ae(e):Nt(e,s(o),i)}function MN(e,o,i){return yt(i)?op(e,o,i.const):sn(i)?Ae(e):Nt(e,s(o),i)}function AS(e,o,i){return Nr(o.const)?CN(e,o.const,i):pn(o.const)?$N(e,o.const,i):Ot(o.const)?vN(e,o.const,i):gt(o.const)?MN(e,o.const,i):jr()}function PS(e,o,i){return nn(i)?Nt(e,o,i):Ae(e)}function CS(e,o,i){return xs(i)?Ae(e):Nt(e,o,i)}function $S(e,o,i){return kr(i)?Ae(e):Nt(e,o,i)}function ON(e,o,i){return cn(o)?cn(i)?Ae(e):Ze():Ae(e)}function _N(e,o,i){return nn(i)&&co(i.extends)?Ze():br(Rt(e,o,i),(u)=>ON(u,o,i),()=>Ze())}function LN(e,o){return e.reduce((i,u)=>(u in o)?so(o[u])?{...i,...o[u].inferred}:jr():jr(),{})}function NN(e,o,i){let u={};for(let y of we(i))u[y]=y in o?_N({},o[y],i[y]):cn(i[y])?nn(i[y])?Ae(dn(e,{[i[y].name]:i[y].extends})):Ae(e):Ze();let p=ld(u).every((y)=>so(y)),g=p?LN(we(u),u):{};return p?Ae(g):Ze()}function DN(e,o,i){let u=NN(e,o,i);return so(u)?Ae(dn(e,u.inferred)):Ze()}function qN(e,o,i){return DN(e,o,i)}function FN(e,o){return we(o).reduce((i,u)=>({...i,[u]:fe(e,u)?xe(i[u])?m([...i[u].anyOf,o[u]]):m([e[u],o[u]]):o[u]}),e)}function vS(e,o,i,u){return It(o,(p,g)=>br(Rt({},e[p],i),(y)=>vS(e,g,i,FN(u,y)),()=>Ze()),()=>Ae(u))}function jN(e,o,i,u){let p=we(o);return vS(o,p,u,e)}function MS(e,o,i){return Gt(i)?jN(e,o,hn(i),fr(i)):Qe(i)?qN(e,o,i.properties):Nt(e,l(o),i)}function UN(e,o){return L(we(o).length,0)?Ae(e):Ze()}function BN(e,o,i,u,p){return Rt(e,i,p)}function OS(e,o,i,u){return Gt(u)?BN(e,Rm(o),i,Rm(hn(u)),fr(u)):Qe(u)?UN(e,u.properties):vr(u)?Ae(e):rn(u)?Ae(e):Ze()}function _S(e,o,i){return sn(i)?Ae(e):Nt(e,o,i)}function LS(e,o,i){return Is(i)?Ae(e):Nt(e,o,i)}function NS(e,o,i){let u=vn(o);return Rt(e,u,i)}function Hd(e,o){return Ct({"~kind":"Inferrable"},{name:e,type:o},{})}function Wu(e){return at(e)&&fe(e,"~kind")&&fe(e,"name")&&fe(e,"type")&&L(e["~kind"],"Inferrable")&&gt(e.name)&&at(e.type)}function Wd(e){return ni(e)?nn(e.items)?wt(e.items.extends)?Hd(e.items.name,e.items.extends.items):rn(e.items.extends)?Hd(e.items.name,e.items.extends):void 0:jr():void 0}function sp(e){return nn(e)?Hd(e.name,e.extends):void 0}function zd(e,o,i=[]){return It(e,(u,p)=>br(Rt({},u,o),()=>zd(p,o,[...i,u]),()=>{return}),()=>i)}function DS(e,o,i,u){let p=zd(i,u);return Ge(p)?Ae(dn(e,{[o]:Ur(p)})):Ze()}function ip(e,o,i,u){let p=zd(i,u);return Ge(p)?Ae(dn(e,{[o]:m(p)})):Ze()}function GN(e){return[...e].reverse()}function Vd(e,o){return o?GN(e):e}function KN(e){let o=e.length>0?e[0]:void 0,i=Cr(o)?Wd(o):void 0;return Cr(i)}function HN(e,o,i,u,p,g){return br(Rt(e,i,p),(y)=>qS(y,o,u,g),()=>Ze())}function WN(e,o,i,u,p){let g=Wd(u);return Wu(g)?DS(e,g.name,Vd(i,o),g.type):It(i,(y,b)=>HN(e,o,y,b,u,p),()=>Ze())}function zN(e,o,i,u){return It(u,(p,g)=>WN(e,o,i,p,g),()=>L(i.length,0)?Ae(e):Ze())}function qS(e,o,i,u){return zN(e,o,i,u)}function VN(e,o,i){let u=ai(e,hr([],[]),i),p=KN(u);return qS(e,p,Vd(o,p),Vd(u,p))}function FS(e,o,i){let u=sp(i);return Wu(u)?ip(e,u.name,o,u.type):It(o,(p,g)=>br(Rt(e,p,i),(y)=>FS(y,g,i),()=>Ze()),()=>Ae(e))}function jS(e,o,i){let u=ai(e,hr([],[]),o);return mt(i)?VN(e,u,i.items):wt(i)?FS(e,u,i.items):Nt(e,Ur(u),i)}function US(e,o,i){return po(i)?Ae(e):Zo(i)?Ae(e):Nt(e,o,i)}function BS(e,o,i){return It(i,(u,p)=>br(Rt(e,o,u),(g)=>Ae(g),()=>BS(e,o,p)),()=>Ze())}function Jd(e,o,i){return It(o,(u,p)=>br(BS(e,u,i),(g)=>Jd(g,p,i),()=>Ze()),()=>Ae(e))}function GS(e,o,i){let u=sp(i);return Wu(u)?ip(e,u.name,o,u.type):xe(i)?Jd(e,o,i.anyOf):Jd(e,o,[i])}function KS(e,o,i){return nn(i)?Nt(e,o,i):vr(i)?Ae(e):rn(i)?Ae(e):Ze()}function HS(e,o,i){return po(i)?Ae(e):Nt(e,o,i)}function Rt(e,o,i){return vr(o)?yS(e,o,i):wt(o)?xS(e,o,o.items,i):mo(o)?IS(e,o,i):Wn(o)?bS(e,o,i):en(o)?ES(e,o.parameters,o.instanceType,i):Dr(o)?SS(e,o.if,o.then,o.else,i):on(o)?wS(e,o.enum,i):tn(o)?TS(e,o.parameters,o.returnType,i):fn(o)?RS(e,o,i):ze(o)?kS(e,o.allOf,i):yt(o)?AS(e,o,i):co(o)?PS(e,o,i):xs(o)?CS(e,o,i):kr(o)?$S(e,o,i):Qe(o)?MS(e,o.properties,i):Gt(o)?OS(e,hn(o),fr(o),i):sn(o)?_S(e,o,i):Is(o)?LS(e,o,i):ur(o)?NS(e,o.pattern,i):mt(o)?jS(e,o.items,i):Zo(o)?US(e,o,i):xe(o)?GS(e,o.anyOf,i):rn(o)?KS(e,o,i):po(o)?HS(e,o,i):Ze()}function JN(e,o){return Ar([...e,l(o)])}function Qd(e,o,i){return ct(e)?St(JN(e,o),{},i):qu(e,o,i)}function WS(e,o,i,u,p){let g=yo(e,o,i),y=zu(e,o,u);return Qd(g,y,p)}function qu(e,o,i={}){return ve("Interface",[e,o],i)}function qa(e){return Cr(e)&&fe(e,"action")&&L(e.action,"Interface")}function zS(e,o,i={}){return Qd(e,o,i)}function QN(e,o,i){return e.includes(i)?!0:Vu([...e,i],o,o[i])}function VS(e,o,i){let u=um(i);return ia(e,o,u)}function ia(e,o,i){return It(i,(u,p)=>Vu(e,o,u)?!0:ia(e,o,p),()=>!1)}function Vu(e,o,i){return qt(i)?QN(e,o,i.$ref):wt(i)?Vu(e,o,i.items):en(i)?ia(e,o,[...i.parameters,i.instanceType]):tn(i)?ia(e,o,[...i.parameters,i.returnType]):qa(i)?VS(e,o,i.parameters[1]):ze(i)?ia(e,o,i.allOf):Qe(i)?VS(e,o,i.properties):xe(i)?ia(e,o,i.anyOf):mt(i)?ia(e,o,i.items):Gt(i)?Vu(e,o,fr(i)):!1}function JS(e,o,i){return Vu(e,o,i)}function XN(e,o){return o.reduce((i,u)=>JS([u],e,e[u])?[...i,u]:i,[])}function QS(e){let o=am(e);return XN(e,o)}function YN(e,o,i){return i.includes(o)?i:(o in e)?Ju(e,e[o],[...i,o]):jr()}function XS(e,o,i){let u=um(o);return Fa(e,u,i)}function Fa(e,o,i){return o.reduce((u,p)=>Ju(e,p,u),i)}function Ju(e,o,i){return qt(o)?YN(e,o.$ref,i):wt(o)?Ju(e,o.items,i):en(o)?Fa(e,[...o.parameters,o.instanceType],i):tn(o)?Fa(e,[...o.parameters,o.returnType],i):qa(o)?XS(e,o.parameters[1],i):ze(o)?Fa(e,o.allOf,i):Qe(o)?XS(e,o.properties,i):xe(o)?Fa(e,o.anyOf,i):mt(o)?Fa(e,o.items,i):Gt(o)?Ju(e,fr(o),i):i}function YS(e,o,i){return Ju(e,i,[o])}function ZN(e){return Pa()}function eD(e){return we(e).reduce((o,i)=>({...o,[i]:aa(e[i])}),{})}function Qu(e){return e.reduce((o,i)=>[...o,aa(i)],[])}function aa(e){return qt(e)?ZN(e.$ref):wt(e)?B(aa(e.items),ka(e)):en(e)?ds(Qu(e.parameters),aa(e.instanceType)):tn(e)?fs(Qu(e.parameters),aa(e.returnType)):ze(e)?Cn(Qu(e.allOf)):Qe(e)?l(eD(e.properties)):Gt(e)?bs(ri(e),aa(fr(e))):xe(e)?m(Qu(e.anyOf)):mt(e)?Ur(Qu(e.items)):e}function tD(e,o){return o in e?aa(e[o]):Rr()}function ZS(e){return tD(e.$defs,e.$ref)}function rD(e,o,i){let u=yo(e,hr([],[]),o),p=zu({},hr([],[]),i);return Ar([...u,l(p)])}function nD(e,o){return we(e).filter((u)=>o.includes(u)).reduce((u,p)=>{let g=e[p],y=qa(g)?rD(e,g.parameters[0],g.parameters[1]):g;return{...u,[p]:y}},{})}function ew(e,o,i){let u=YS(e,o,i),p=nD(e,u);return gs(p,o)}function tw(e,o){return o in e?qt(e[o])?tw(e,e[o].$ref):e[o]:zt()}function Es(e,o){return tw(e,o)}function rw(e){return Qt(e)?ZS(e):cm(e)?Rr():e}function Tn(e,o,i){let u=rw(o),p=rw(i);return Rt(e,u,p)}var Ou=0,Xu=1,_u=2,Lu=3;function Ma(e,o){let i=[Tn({},e,o),Tn({},o,e)];return so(i[0])&&so(i[1])?Ou:so(i[0])&&Kd(i[1])?_u:Kd(i[0])&&so(i[1])?Lu:Xu}function Xd(e,o,i=[],u=o){return It(o,(p,g)=>{let y=Ma(e,p);return L(y,_u)||L(y,Ou)?u:L(y,Xu)?Xd(e,g,[...i,p],u):Xd(e,g,i,u)},()=>[...i,e])}function oD(e,o,i){let u=Ao(e);return vr(u)?[u]:rn(u)?[u]:co(u)?ap(o,i):Qe(u)?ap(o,[...i,u]):ap(o,Xd(u,i))}function ap(e,o=[]){return It(e,(i,u)=>oD(i,u,o),()=>o)}function Rd(e){let o=ap(e);return na(o)}function Yd(e,o){return St(Ao(e),{},o)}function nw(e,o,i,u){let p=ge(e,o,i);return Yd(p,u)}function Yu(e,o=[]){return Qs(e)&&L(e.action,"Conditional")?qt(e.parameters[0])?Yu(e.parameters[2],Yu(e.parameters[3],[...o,e.parameters[0].$ref])):Yu(e.parameters[2],Yu(e.parameters[3],o)):Qs(e)&&L(e.action,"Mapped")?Qs(e.parameters[1])&&L(e.parameters[1].action,"KeyOf")&&qt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function sD(e,o){return e.reduce((i,u)=>[...i,o.includes(u.name)],[])}function iw(e,o,i=[]){return It(e,(u,p)=>It(o,(g,y)=>iw(p,y,[...i,[g,u]]),()=>i),()=>i)}function iD(e){return ur(e)?vn(e.pattern):on(e)?Zn(e.enum):e}function aD(e){let o=iD(e);return xe(o)?[...o.anyOf]:[o]}function uD(e,o){return e.reduce((i,u)=>[...i,[...u,o]],[])}function ow(e,o){return o.reduce((i,u)=>[...i,...uD(e,u)],[])}function sw(e){return e.reduce((o,i)=>L(i[0],!0)?ow(o,aD(i[1])):ow(o,[i[1]]),[[]])}function aw(e,o,i){let u=Yu(i),p=sD(e,u),g=iw(o,p);return Qs(i)&&L(i.action,"Conditional")?sw(g):Qs(i)&&L(i.action,"Mapped")?sw(g):[o]}function cD(){return["(not-resolvable)",zt()]}function mD(){return["(not-generic)",zt()]}function pD(e,o,i){return[e,Xs(o,i)]}function lD(e,o,i){return o in e?uw(e,o,e[o],i):cD()}function uw(e,o,i,u){return Aa(i)?pD(o,i.parameters,i.expression):qt(i)?lD(e,i.$ref,u):mD()}function cw(e,o,i){return uw(e,"(anonymous)",o,i)}function dD(e,o,i){if(nn(o)||ja(o)||so(Tn({},o,i)))return;let u={parameter:e,expect:i,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function mw(e,o,i,u,p){let g=ge(e,o,p);return dD(i,g,u),dn(e,{[i]:g})}function fD(e,o,i,u,p){let g=ge(e,o,i.extends),y=ge(e,o,i.equals);return It(p,(b,E)=>Zd(mw(e,o,i.name,g,b),o,u,E),()=>Zd(mw(e,o,i.name,g,y),o,u,[]))}function Zd(e,o,i,u){return It(i,(p,g)=>fD(e,o,p,g,u),()=>e)}function pw(e,o,i,u){return Zd(e,o,i,u)}var ef=0,tf=0;function hD(){if(Su(tf,Jo().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function gD(){hD(),tf++,ef++}function yD(){if(ef--,L(ef,0))tf=0}function xD(e){return Ki(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function ID(e,o){return L(xD(e),o)}function bD(e,o,i,u,p,g){gD();try{let y=pw(e,o,u,g),b=ge(y,hr([...o.callstack,i.$ref],o.visited),p);return ge(y,hr([],[]),b)}finally{yD()}}function ED(e,o,i,u,p,g){return g.reduce((y,b)=>{let E=bD(e,o,i,u,p,b);return[...y,E]},[])}function SD(e,o,i,u,p,g){let y=aw(u,g,p),b=ED(e,o,i,u,p,y);return L(b.length,1)?b[0]:oo(b)}function up(e,o,i,u){let p=yo(e,o,u),g=cw(e,i,u),y=g[0],b=g[1];return Aa(b)?ID(o,y)?Fu(un(y),p):SD(e,o,un(y),b.parameters,b.expression,p):Fu(i,p)}function Fu(e,o){return Ct({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function lw(e,o){return up({},hr([],[]),e,o)}function ja(e){return Pe(e,"Call")}function wD(e){return Qo(e,["~immutable"])}function dw(e,o){return St(wD(e),{},o)}function fw(e,o,i,u){let p=ge(e,o,i);return dw(p,u)}function hw(e,o){return e(o)}function gw(e,o){return gt(o)?s(hw(e,o)):s(o)}function yw(e,o){let i=vn(o);return Os(e,i)}function xw(e,o){let i=o.map((u)=>Os(e,u));return m(i)}function Os(e,o){return yt(o)?gw(e,o.const):ur(o)?yw(e,o.pattern):xe(o)?xw(e,o.anyOf):o}function $m(e,o={}){return ve("Capitalize",[e],o)}function Iw(e,o={}){return rf(e,o)}function vm(e,o={}){return ve("Lowercase",[e],o)}function bw(e,o={}){return nf(e,o)}function Mm(e,o={}){return ve("Uncapitalize",[e],o)}function Ew(e,o={}){return of(e,o)}function Om(e,o={}){return ve("Uppercase",[e],o)}function Sw(e,o={}){return sf(e,o)}var TD=(e)=>e[0].toUpperCase()+e.slice(1),RD=(e)=>e.toLowerCase(),kD=(e)=>e[0].toLowerCase()+e.slice(1),AD=(e)=>e.toUpperCase();function rf(e,o){return ct([e])?St(Os(TD,e),{},o):$m(e,o)}function nf(e,o){return ct([e])?St(Os(RD,e),{},o):vm(e,o)}function of(e,o){return ct([e])?St(Os(kD,e),{},o):Mm(e,o)}function sf(e,o){return ct([e])?St(Os(AD,e),{},o):Om(e,o)}function ww(e,o,i,u){let p=ge(e,o,i);return rf(p,u)}function Tw(e,o,i,u){let p=ge(e,o,i);return nf(p,u)}function Rw(e,o,i,u){let p=ge(e,o,i);return of(p,u)}function kw(e,o,i,u){let p=ge(e,o,i);return sf(p,u)}function _m(e,o,i,u,p={}){return ve("Conditional",[e,o,i,u],p)}function Aw(e,o,i,u,p={}){return af({},hr([],[]),e,o,i,u,p)}function PD(e,o,i,u,p,g){let y=Tn(e,i,u);return Bd(y)?m([ge(y.inferred,o,p),ge(e,o,g)]):Gd(y)?ge(y.inferred,o,p):ge(e,o,g)}function af(e,o,i,u,p,g,y){return ct([i,u])?St(PD(e,o,i,u,p,g),{},y):_m(i,u,p,g,y)}function Pw(e,o,i,u,p,g,y){let b=ge(e,o,i),E=ge(e,o,u);return af(e,o,b,E,p,g,y)}function Lm(e,o={}){return ve("ConstructorParameters",[e],o)}function Cw(e,o={}){return uf(e,o)}function CD(e){let o=en(e)?e.parameters:[],i=ai({},hr([],[]),o);return Ur(i)}function uf(e,o){return ct([e])?St(CD(e),{},o):Lm(e,o)}function $w(e,o,i,u){let p=ge(e,o,i);return uf(p,u)}function Nm(e,o,i={}){return ve("Exclude",[e,o],i)}function vw(e,o,i={}){return Zu(e,o,i)}function Zu(e,o,i){return ct([e,o])?St(wm(e,o),{},i):Nm(e,o,i)}function Mw(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return Zu(g,y,p)}function Dm(e,o,i={}){return ve("Extract",[e,o],i)}function Ow(e,o,i={}){return cf(e,o,i)}function $D(e,o){let i=Tn({},e,o);return so(i)?[e]:[]}function _w(e,o,i=[]){return It(e,(u,p)=>_w(p,o,[...i,...$D(u,o)]),()=>i)}function Lw(e,o){let i=Ao(e),u=xe(i)?i.anyOf:[i],p=_w(u,o);return oo(p)}function cf(e,o,i){return ct([e,o])?St(Lw(e,o),{},i):Dm(e,o,i)}function Nw(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return cf(g,y,p)}function vD(e){return e.reduce((o,i)=>hm(i)?[...o,s(i)]:o,[])}function Ua(e){let o=vD(e);return m(o)}function ju(e,o,i={}){return ve("Index",[e,o],i)}function Dw(e,o,i={}){let u=Ge(o)?Ua(o):o;return mf(e,u,i)}function qw(e,o){let i=Es(e,o);return xo(i)}function Fw(e,o,i){let u=Yo(e,o,i);return xo(u)}function MD(e,o){let i=we(e).filter((w)=>!fe(o,w)),u=we(o).filter((w)=>!fe(e,w)),p=we(e).filter((w)=>fe(o,w)),g=i.reduce((w,R)=>({...w,[R]:e[R]}),{}),y=u.reduce((w,R)=>({...w,[R]:o[R]}),{}),b=p.reduce((w,R)=>({...w,[R]:Ar([e[R],o[R]])}),{}),E=dn(g,y);return dn(E,b)}function jw(e){return e.reduce((o,i)=>MD(o,xo(i)),{})}function Uw(e){return e}function Bw(e){let o=$x(Ur(e));return xo(o)}function OD(e,o){return we(e).filter((p)=>(p in o)).reduce((p,g)=>({...p,[g]:oo([e[g],o[g]])}),{})}function Gw(e,o){return It(e,(i,u)=>Gw(u,OD(o,xo(i))),()=>o)}function Kw(e){return It(e,(o,i)=>Gw(i,xo(o)),()=>jr())}function xo(e){return Qt(e)?qw(e.$defs,e.$ref):Dr(e)?Fw(e.if,e.then,e.else):ze(e)?jw(e.allOf):xe(e)?Kw(e.anyOf):mt(e)?Bw(e.items):Qe(e)?Uw(e.properties):{}}function Ba(e){let o=xo(e);return l(o)}var _D=new RegExp("^(?:0|[1-9][0-9]*)$");function Ga(e){let o=`${e}`;return _D.test(o)?parseInt(o):e}function LD(e){return s(Ga(e))}function Hw(e){return e.map((o)=>Ww(o))}function Ww(e){return ze(e)?Cn(Hw(e.allOf)):xe(e)?m(Hw(e.anyOf)):yt(e)?LD(e.const):e}function zw(e,o){let i=Ww(o),u=Tn({},i,Y());return so(u)?e:yt(o)&&L(o.const,"length")?Y():zt()}function Vw(e,o){let i=Es(e,o);return lo(i)}function Jw(e,o,i){let u=Yo(e,o,i);return lo(u)}function Qw(e){let o=Zn(e);return lo(o)}function Xw(e){let o=Ar(e);return lo(o)}function Yw(e){return[`${e}`]}function Zw(e){let o=vn(e);return lo(o)}function eT(e){return e.reduce((o,i)=>[...o,...lo(i)],[])}function lo(e){return Qt(e)?Vw(e.$defs,e.$ref):Dr(e)?Jw(e.if,e.then,e.else):on(e)?Qw(e.enum):ze(e)?Xw(e.allOf):yt(e)?Yw(e.const):ur(e)?Zw(e.pattern):xe(e)?eT(e.anyOf):[]}function Ka(e){return lo(e)}function ec(e,o){return o.map((i)=>tc(e,i))}function tc(e,o){return wt(o)?B(tc(e,o.items)):en(o)?ds(ec(e,o.parameters),tc(e,o.instanceType)):tn(o)?fs(ec(e,o.parameters),tc(e,o.returnType)):mt(o)?Ur(ec(e,o.items)):xe(o)?m(ec(e,o.anyOf)):ze(o)?Cn(ec(e,o.allOf)):Am(o)?l(e):o}function tT(e,o){return tc(e,o)}function ND(e,o){let i=o in e?e[o]:zt();return tT(e,i)}function rT(e,o){return o.reduce((i,u)=>[...i,ND(e,u)],[])}function DD(e,o){let i=Ka(o),u=rT(e,i);return oo(u)}var qD=new RegExp(ti);function FD(e){return e.filter((i)=>qD.test(i))}function jD(e){let o=am(e),i=FD(o),u=rT(e,i);return oo(u)}function nT(e,o){return kr(o)?jD(e):DD(e,o)}function UD(e){return s(Ga(e))}function oT(e){return e.map((o)=>pf(o))}function pf(e){return ze(e)?Cn(oT(e.allOf)):xe(e)?m(oT(e.anyOf)):yt(e)?UD(e.const):e}function BD(e,o){return e.reduceRight((i,u,p)=>{let g=Tn({},s(p),o);return so(g)?[u,...i]:i},[])}function GD(e,o){let i=pf(o),u=BD(e,i);return Zs(u)}function KD(e){return Zs(e)}function sT(e,o){return yt(o)&&L(o.const,"length")?s(e.length):kr(o)||fn(o)?KD(e):GD(e,o)}function iT(e,o){return wt(e)?zw(e.items,o):Qe(e)?nT(e.properties,o):mt(e)?sT(e.items,o):zt()}function HD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function mf(e,o,i){return ct([e,o])?St(iT(HD(e),o),{},i):ju(e,o,i)}function aT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return mf(g,y,p)}function qm(e,o={}){return ve("InstanceType",[e],o)}function uT(e,o={}){return lf(e,o)}function WD(e){return en(e)?e.instanceType:zt()}function lf(e,o){return ct([e])?St(WD(e),{},o):qm(e,o)}function cT(e,o,i,u={}){let p=ge(e,o,i);return lf(p,u)}function Uu(e,o={}){return ve("KeyOf",[e],o)}function mT(e,o={}){return df(e,o)}function pT(){return m([Y(),a(),va()])}function lT(e){return Y()}function zD(e){return e.reduce((i,u)=>hm(u)?[...i,s(Ga(u))]:jr(),[])}function dT(e){let o=we(e),i=zD(o);return Zs(i)}function fT(e){return ri(e)}function hT(e){let o=e.map((i,u)=>s(u));return Zs(o)}function gT(e){return vr(e)?pT():wt(e)?lT(e.items):Qe(e)?dT(e.properties):Gt(e)?fT(e):mt(e)?hT(e.items):zt()}function VD(e){return Qt(e)||Dr(e)||ze(e)||xe(e)?Ba(e):e}function df(e,o){return ct([e])?St(gT(VD(e)),{},o):Uu(e,o)}function yT(e,o,i,u){let p=ge(e,o,i);return df(p,u)}function Du(e,o,i,u,p={}){return ve("Mapped",[e,o,i,u],p)}function xT(e,o,i,u,p={}){return ff({},hr([],[]),e,o,i,u,p)}function JD(e){let o=vn(e);return cp(o)}function QD(e){return e.reduce((o,i)=>[...o,...cp(i)],[])}function XD(e){let o=Zn(e);return cp(o)}function YD(e){return Ot(e)?[s(`${e}`)]:[s(e)]}function cp(e){return on(e)?XD(e.enum):yt(e)?YD(e.const):ur(e)?JD(e.pattern):xe(e)?QD(e.anyOf):[e]}function IT(e){return cp(e)}function ZD(e){return ur(e)?vn(e.pattern):e}function eq(e,o,i,u,p,g){let y=dn(e,{[i.name]:u}),b=ge(y,o,p),E=ZD(b),S=ge(y,o,g);return gm(E)||ym(E)?{[E.const]:S}:{}}function tq(e,o,i,u,p,g){return u.reduce((y,b)=>[...y,eq(e,o,i,b,p,g)],[])}function rq(e){return e.reduce((o,i)=>[...o,l(i)],[])}function bT(e,o,i,u,p,g){let y=IT(u),b=tq(e,o,i,y,p,g),E=rq(b);return Ar(E)}function ff(e,o,i,u,p,g,y){return ct([u])?St(bT(e,o,i,u,p,g),{},y):Du(i,u,p,g,y)}function ET(e,o,i,u,p,g,y){let b=ge(e,o,u);return ff(e,o,i,b,p,g,y)}function nq(e,o,i){let u=dn(e,o);return we(o).filter((g)=>i.includes(g)).reduce((g,y)=>({...g,[y]:ew(u,y,o[y])}),{})}function oq(e,o,i){let u=dn(e,o);return we(o).filter((g)=>!i.includes(g)).reduce((g,y)=>({...g,[y]:ge(u,hr([],[]),o[y])}),{})}function sq(e,o,i){let u=QS(o),p=nq(e,o,u),g=oq(e,o,u),y={...p,...g};return St(y,{},i)}function mp(e,o,i,u){return sq(e,i,u)}function Fm(e,o={}){return ve("NonNullable",[e],o)}function ST(e,o={}){return hf(e,o)}function iq(e){let o=m([$n(),_a()]);return Zu(e,o,{})}function hf(e,o){return ct([e])?St(iq(e),{},o):Fm(e,o)}function wT(e,o,i,u){let p=ge(e,o,i);return hf(p,u)}function jm(e,o,i={}){return ve("Omit",[e,o],i)}function TT(e,o,i={}){let u=Ge(o)?Ua(o):o;return gf(e,u,i)}function pp(e){let o=Ba(e);return Qe(o)?o.properties:jr()}function aq(e,o){return we(e).reduce((u,p)=>o.includes(p)?u:{...u,[p]:e[p]},{})}function RT(e,o){let i=pp(e),u=Ka(o),p=aq(i,u);return l(p)}function gf(e,o,i){return ct([e,o])?St(RT(e,o),{},i):jm(e,o,i)}function kT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return gf(g,y,p)}function Um(e,o={}){return ve("Parameters",[e],o)}function AT(e,o={}){return yf(e,o)}function uq(e){let o=tn(e)?e.parameters:[],i=ai({},hr([],[]),o);return Ur(i)}function yf(e,o){return ct([e])?St(uq(e),{},o):Um(e,o)}function PT(e,o,i,u){let p=ge(e,o,i);return yf(p,u)}function Bm(e,o={}){return ve("Partial",[e],o)}function CT(e,o={}){return xf(e,o)}function $T(e,o){let i=Es(e,o),u=Ss(i);return gs(dn(e,{[o]:u}),o)}function vT(e,o,i){let u=Yo(e,o,i);return Ss(u)}function MT(e){let o=Ar(e);return Ss(o)}function OT(e){let o=e.map((i)=>Ss(i));return m(o)}function _T(e){let o=we(e).reduce((u,p)=>({...u,[p]:Qi(e[p])}),{});return l(o)}function Ss(e){return Qt(e)?$T(e.$defs,e.$ref):Dr(e)?vT(e.if,e.then,e.else):ze(e)?MT(e.allOf):xe(e)?OT(e.anyOf):Qe(e)?_T(e.properties):l({})}function xf(e,o){return ct([e])?St(Ss(e),{},o):Bm(e,o)}function LT(e,o,i,u){let p=ge(e,o,i);return xf(p,u)}function Gm(e,o,i={}){return ve("Pick",[e,o],i)}function NT(e,o,i={}){let u=Ge(o)?Ua(o):o;return If(e,u,i)}function cq(e,o){return we(e).reduce((u,p)=>o.includes(p)?dn(u,{[p]:e[p]}):u,{})}function DT(e,o){let i=pp(e),u=Ka(o),p=cq(i,u);return l(p)}function If(e,o,i){return ct([e,o])?St(DT(e,o),{},i):Gm(e,o,i)}function qT(e,o,i,u,p){let g=ge(e,o,i),y=ge(e,o,u);return If(g,y,p)}function Km(e,o={}){return ve("ReadonlyObject",[e],o)}function bf(e,o={}){return Ef(e,o)}var FT=bf;function jT(e){return $a(B(e))}function UT(e,o){let i=Es(e,o),u=ws(i);return gs(dn(e,{[o]:u}),o)}function BT(e,o,i){let u=Yo(e,o,i);return ws(u)}function GT(e){let o=Ar(e);return ws(o)}function KT(e){let o=we(e).reduce((u,p)=>({...u,[p]:ea(e[p])}),{});return l(o)}function HT(e){return $a(Ur(e))}function WT(e){let o=e.map((i)=>ws(i));return m(o)}function ws(e){return wt(e)?jT(e.items):Qt(e)?UT(e.$defs,e.$ref):Dr(e)?BT(e.if,e.then,e.else):ze(e)?GT(e.allOf):Qe(e)?KT(e.properties):mt(e)?HT(e.items):xe(e)?WT(e.anyOf):e}function Ef(e,o){return ct([e])?St(ws(e),{},o):Km(e)}function zT(e,o,i,u){let p=ge(e,o,i);return Ef(p,u)}function VT(e,o,i,u){return o.visited.includes(u)?i:(u in e)?ge(e,hr(o.callstack,[...o.visited,u]),e[u]):i}function JT(e,o){let i=Es(e,o),u=Ts(i);return gs(dn(e,{[o]:u}),o)}function QT(e,o,i){let u=Yo(e,o,i);return Ts(u)}function XT(e){let o=Ar(e);return Ts(o)}function YT(e){let o=e.map((i)=>Ts(i));return m(o)}function ZT(e){let o=we(e).reduce((u,p)=>({...u,[p]:Sm(e[p])}),{});return l(o)}function Ts(e){return Qt(e)?JT(e.$defs,e.$ref):Dr(e)?QT(e.if,e.then,e.else):ze(e)?XT(e.allOf):xe(e)?YT(e.anyOf):Qe(e)?ZT(e.properties):l({})}function Hm(e,o={}){return ve("Required",[e],o)}function eR(e,o={}){return Sf(e,o)}function Sf(e,o){return ct([e])?St(Ts(e),{},o):Hm(e,o)}function tR(e,o,i,u){let p=ge(e,o,i);return Sf(p,u)}function Wm(e,o={}){return ve("ReturnType",[e],o)}function rR(e,o={}){return wf(e,o)}function mq(e){return tn(e)?e.returnType:zt()}function wf(e,o){return ct([e])?St(mq(e),{},o):Wm(e,o)}function nR(e,o,i,u={}){let p=ge(e,o,i);return wf(p,u)}function zm(e,o){return ve("With",[e,o],{})}function lp(e,o){return Tf(e,o)}function Tf(e,o){return ct([e])?St(e,{},o):zm(e,o)}function oR(e,o,i,u){let p=ge(e,o,i);return Tf(p,u)}function pq(e){return ni(e)?mt(e.items)?Rf(e.items.items):nn(e.items)?[e]:qt(e.items)?[e]:[zt()]:[e]}function Rf(e){return e.reduce((i,u)=>[...i,...pq(u)],[])}function hr(e,o){return{callstack:e,visited:o}}function ct(e){return It(e,(o,i)=>qt(o)?!1:ct(i),()=>!0)}function zu(e,o,i){return we(i).reduce((u,p)=>({...u,[p]:ge(e,o,i[p])}),{})}function ai(e,o,i){let u=yo(e,o,i);return Rf(u)}function yo(e,o,i){return i.map((u)=>ge(e,o,u))}function lq(e,o){let i=cn(e)?Au(o,{}):o,u=ta(e)?ku(i,{}):i;return Zi(e)?rc(u,{}):u}function dq(e,o,i,u,p){return L(i,"AddImmutable")?sR(e,o,u[0],p):L(i,"RemoveImmutable")?fw(e,o,u[0],p):L(i,"AddReadonly")?My(e,o,u[0],p):L(i,"RemoveReadonly")?Rx(e,o,u[0],p):L(i,"AddOptional")?Oy(e,o,u[0],p):L(i,"RemoveOptional")?Px(e,o,u[0],p):L(i,"Capitalize")?ww(e,o,u[0],p):L(i,"Conditional")?Pw(e,o,u[0],u[1],u[2],u[3],p):L(i,"ConstructorParameters")?$w(e,o,u[0],p):L(i,"Evaluate")?nw(e,o,u[0],p):L(i,"Exclude")?Mw(e,o,u[0],u[1],p):L(i,"Extract")?Nw(e,o,u[0],u[1],p):L(i,"Index")?aT(e,o,u[0],u[1],p):L(i,"InstanceType")?cT(e,o,u[0],p):L(i,"Interface")?WS(e,o,u[0],u[1],p):L(i,"KeyOf")?yT(e,o,u[0],p):L(i,"Lowercase")?Tw(e,o,u[0],p):L(i,"Mapped")?ET(e,o,u[0],u[1],u[2],u[3],p):L(i,"Module")?mp(e,o,u[0],p):L(i,"NonNullable")?wT(e,o,u[0],p):L(i,"Pick")?qT(e,o,u[0],u[1],p):L(i,"Parameters")?PT(e,o,u[0],p):L(i,"Partial")?LT(e,o,u[0],p):L(i,"Omit")?kT(e,o,u[0],u[1],p):L(i,"ReadonlyObject")?zT(e,o,u[0],p):L(i,"Record")?Hx(e,o,u[0],u[1],p):L(i,"Required")?tR(e,o,u[0],p):L(i,"ReturnType")?nR(e,o,u[0],p):L(i,"TemplateLiteral")?lS(e,o,u[0],p):L(i,"Uncapitalize")?Rw(e,o,u[0],p):L(i,"Uppercase")?kw(e,o,u[0],p):L(i,"With")?oR(e,o,u[0],u[1]):ve(i,u,p)}function fq(e,o,i){let u=qt(i)?VT(e,o,i,i.$ref):wt(i)?B(ge(e,o,i.items),ka(i)):ja(i)?up(e,o,i.target,i.arguments):en(i)?ds(yo(e,o,i.parameters),ge(e,o,i.instanceType),_y(i)):tn(i)?fs(yo(e,o,i.parameters),ge(e,o,i.returnType),Ly(i)):Dr(i)?Xi(ge(e,o,i.if),ge(e,o,i.then),ge(e,o,i.else),Fy(i)):ze(i)?Cn(yo(e,o,i.allOf),Ky(i)):Qe(i)?l(zu(e,o,i.properties),qy(i)):Gt(i)?Wx(hn(i),ge(e,o,fr(i))):ni(i)?oa(ge(e,o,i.items)):mt(i)?Ur(ai(e,o,i.items),Tx(i)):xe(i)?m(yo(e,o,i.anyOf),fx(i)):i;return lq(i,u)}function ge(e,o,i){return Qs(i)?dq(e,o,i.action,i.parameters,i.options):fq(e,o,i)}function Po(e,o){return ge(e,hr([],[]),o)}function hq(e){return St(e,{"~immutable":!0},{})}function rc(e,o){return St(hq(e),{},o)}function sR(e,o,i,u){let p=ge(e,o,i);return rc(p,u)}function uE(e,o={}){return ve("AddImmutable",[e],o)}function $a(e,o={}){return rc(e,o)}function cE(e,o={}){return ve("Evaluate",[e],o)}function Rn(e,o={}){return Yd(e,o)}function mE(e,o={}){return ve("Module",[e],o)}function iR(e,o={}){return mp({},hr([],[]),e,o)}function gq(e,o){let i=Ma(e,o);return L(i,Lu)?1:L(i,Xu)?1:0}function aR(e,o,i=[]){return It(o,(u,p)=>L(gq(e,u),1)?aR(e,p,[...i,u]):[...i,e,...o],()=>[...i,e])}function uR(e,o=[]){return It(e,(i,u)=>uR(u,aR(i,o)),()=>o)}function cR(e){return uR(e)}function mR(...e){let[o,i,u]=wn(e,{2:(y,b)=>gt(y)?[{},y,b]:[y,b,{}],3:(y,b,E)=>[y,b,E],1:(y)=>[{},y,{}]}),p=aS(i),g=Ge(p)&&L(p.length,2)?ge(o,hr([],[]),p[0]):zt();return St(g,{},u)}function h(e,o){return{name:e,login:async(i)=>{i.signal.throwIfAborted();let u=await i.prompt({type:"secret",message:`Enter ${e}`});return i.signal.throwIfAborted(),{type:"api_key",key:u}},resolve:async({ctx:i,credential:u,signal:p})=>{if(p.throwIfAborted(),u?.key)return{auth:{apiKey:u.key},env:u.env,source:"stored credential"};for(let g of o){let y=await i.env(g);if(p.throwIfAborted(),y)return{auth:{apiKey:y},source:g}}return}}}function le(e){let o,i=()=>(o??=e.load(),o);return{name:e.name,isSubscription:e.isSubscription,loginLabel:e.loginLabel,login:async(u,p)=>(await i()).login(u,p),refresh:async(u,p)=>(await i()).refresh(u,p),toAuth:async(u)=>(await i()).toAuth(u)}}var fR="faux",hR="faux",gR="faux-1",yq="Faux Model",xq="http://localhost:0",Iq=3,pR=5,hp={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function On(e){return{type:"text",text:e}}function Oo(e){return{type:"thinking",thinking:e}}function bq(e,o,i={}){return{type:"toolCall",id:i.id??Pf("tool"),name:e,arguments:o}}function Eq(e){if(typeof e==="string")return[On(e)];return Array.isArray(e)?e:[e]}function No(e,o={}){return{role:"assistant",content:Eq(e),api:fR,provider:hR,model:gR,usage:hp,stopReason:o.stopReason??"stop",...o.deferred===void 0?{}:{deferred:o.deferred},...o.errorMessage===void 0?{}:{errorMessage:o.errorMessage},...o.responseId===void 0?{}:{responseId:o.responseId},timestamp:o.timestamp??Date.now()}}function yR(e){return Math.ceil(e.length/4)}function Pf(e){return`${e}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function xR(e){if(typeof e==="string")return e;return e.map((o)=>{if(o.type==="text")return o.text;return`[image:${o.mimeType}:${o.data.length}]`}).join(`
23
- `)}function IR(e){return e.map((o)=>{if(o.type==="text")return o.text;if(o.type==="thinking")return o.thinking;return`${o.name}:${JSON.stringify(o.arguments)}`}).join(`
24
- `)}function Sq(e){return[e.toolName,...e.content.map((o)=>xR([o]))].join(`
25
- `)}function wq(e){if(e.role==="system")return[U(e),...e.toolsRemoved?.map((o)=>`tool-:${JSON.stringify(o)}`)??[],...e.toolsAdded?.map((o)=>`tool+:${JSON.stringify(o)}`)??[]].filter((o)=>o.length>0).join(`
26
- `);if(e.role==="user")return xR(e.content);if(e.role==="assistant")return IR(e.content);return Sq(e)}function bR(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 Tq(e,o){let i=0;while(i<e.length&&i<o.length&&e[i]===o[i])i++;let u=(p)=>i===p.length?"":(i>0?`
27
-
28
- `:"")+p.slice(i).join(`
29
-
30
- `);return bR(e,i)+Rq(u(e),u(o))}function Rq(e,o){let i=Math.min(e.length,o.length),u=0;while(u<i&&e[u]===o[u])u++;return u}function lR(e,o,i,u){let p=o.messages.map((A)=>`${A.role}:${wq(A)}`),g=bR(p),y=Math.ceil(g/4),b=yR(IR(e.content)),E=y,S=0,w=0,R=i?.sessionId;if(R&&i?.cacheRetention!=="none"){let A=u.get(R);if(A){let P=Tq(A,p);S=Math.ceil(P/4),w=Math.ceil((g-P)/4),E=Math.max(0,y-S)}else w=y;u.set(R,p)}return{...e,usage:{input:E,output:b,cacheRead:S,cacheWrite:w,totalTokens:E+b+S+w,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}function kf(e,o,i){let u=[],p=0;while(p<e.length){let g=o+Math.floor(Math.random()*(i-o+1)),y=Math.max(1,g*4);u.push(e.slice(p,p+y)),p+=y}return u.length>0?u:[""]}function kq(e,o,i,u){let p=structuredClone(e);return{...p,api:o,provider:i,model:u,timestamp:p.timestamp??Date.now(),usage:p.usage??hp}}function dR(e,o){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:hp,stopReason:"deferred",deferred:o,timestamp:Date.now()}}function dp(e,o,i,u){return{role:"assistant",content:[],api:o,provider:i,model:u,usage:hp,stopReason:"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function nc(e){return{...e,stopReason:"aborted",errorMessage:"Request was aborted",timestamp:Date.now()}}function Af(e,o){if(!o||o<=0)return new Promise((u)=>queueMicrotask(u));let i=yR(e)/o*1000;return new Promise((u)=>setTimeout(u,i))}async function fp(e,o,i,u,p,g){let y={...o,content:[],stopReason:"pending"};if(g?.aborted){let b=nc(y);e.push({type:"error",reason:"aborted",error:b}),e.end(b);return}e.push({type:"start",partial:{...y}});for(let b=0;b<o.content.length;b++){if(g?.aborted){let S=nc(y);e.push({type:"error",reason:"aborted",error:S}),e.end(S);return}let E=o.content[b];if(E.type==="thinking"){y.content=[...y.content,{type:"thinking",thinking:""}],e.push({type:"thinking_start",contentIndex:b,partial:{...y}});for(let S of kf(E.thinking,i,u)){if(await Af(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].thinking+=S,e.push({type:"thinking_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"thinking_end",contentIndex:b,content:E.thinking,partial:{...y}});continue}if(E.type==="text"){y.content=[...y.content,{type:"text",text:""}],e.push({type:"text_start",contentIndex:b,partial:{...y}});for(let S of kf(E.text,i,u)){if(await Af(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}y.content[b].text+=S,e.push({type:"text_delta",contentIndex:b,delta:S,partial:{...y}})}e.push({type:"text_end",contentIndex:b,content:E.text,partial:{...y}});continue}y.content=[...y.content,{type:"toolCall",id:E.id,name:E.name,arguments:{}}],e.push({type:"toolcall_start",contentIndex:b,partial:{...y}});for(let S of kf(JSON.stringify(E.arguments),i,u)){if(await Af(S,p),g?.aborted){let w=nc(y);e.push({type:"error",reason:"aborted",error:w}),e.end(w);return}e.push({type:"toolcall_delta",contentIndex:b,delta:S,partial:{...y}})}y.content[b].arguments=E.arguments,e.push({type:"toolcall_end",contentIndex:b,toolCall:E,partial:{...y}})}if(o.stopReason==="pending")throw Error("Faux response ended without a stop reason");if(o.stopReason==="error"||o.stopReason==="aborted"){e.push({type:"error",reason:o.stopReason,error:o}),e.end(o);return}e.push({type:"done",reason:o.stopReason,message:o}),e.end(o)}function ER(e){let o=e.api??Pf(fR),i=e.provider??hR,u=Math.max(1,Math.min(e.tokenSize?.min??Iq,e.tokenSize?.max??pR)),p=Math.max(u,e.tokenSize?.max??pR),g=[],y=e.tokensPerSecond,b={callCount:0,deferredFetchCount:0,cancelledDeferred:[]},E=new Map,S=new Map,R=((e.models?.length)?e.models:[{id:gR,name:yq,reasoning:!1,input:["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128000,maxTokens:16384}]).map((V)=>({id:V.id,name:V.name??V.id,api:o,provider:i,baseUrl:xq,reasoning:V.reasoning??!1,input:V.input??["text","image"],inputLimits:V.inputLimits,cost:V.cost??{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:V.contextWindow??128000,maxTokens:V.maxTokens??16384})),A=async(V,J,ee,ae)=>{let H=typeof V==="function"?await V(J,ee,b,ae):V;return lR(kq(H,o,i,ae.id),J,ee,E)},P=(V,J,ee)=>{let ae=Jn(),H=g.shift();return b.callCount++,queueMicrotask(async()=>{try{if(await ee?.onResponse?.({status:200,headers:{}},V),!H){let he=dp(Error("No more faux responses queued"),o,i,V.id);he=lR(he,J,ee,E),ae.push({type:"error",reason:"error",error:he}),ae.end(he);return}if(ee?.deferred){let he={provider:V.provider,modelId:V.id,api:V.api,id:Pf("deferred"),...e.deferred?.pollAfterMs!==void 0?{pollAfterMs:e.deferred.pollAfterMs}:{}};S.set(he.id,{handle:he,step:H,context:J,options:ee,model:V,pendingFetches:Math.max(0,Math.floor(e.deferred?.pendingFetches??0)),cancelled:!1}),await fp(ae,dR(V,he),u,p,y,ee.signal);return}let ue=await A(H,J,ee,V);await fp(ae,ue,u,p,y,ee?.signal)}catch(ue){let he=dp(ue,o,i,V.id);ae.push({type:"error",reason:"error",error:he}),ae.end(he)}}),ae},C=(V,J,ee)=>P(V,J,ee),q=(V,J,ee)=>{let ae=Jn();return b.deferredFetchCount++,queueMicrotask(async()=>{try{await ee?.onResponse?.({status:200,headers:{}},V);let H=S.get(J.id);if(!H||H.handle.provider!==J.provider||H.handle.modelId!==J.modelId||H.handle.api!==J.api)throw Error(`Unknown faux deferred response: ${J.id}`);if(H.cancelled)throw Error(`Faux deferred response was cancelled: ${J.id}`);if(H.pendingFetches>0){H.pendingFetches--,await fp(ae,dR(V,H.handle),u,p,y,ee?.signal);return}if(!H.final){let{deferred:ue,signal:he,onResponse:$e,...Ee}=H.options??{};try{H.final=await A(H.step,H.context,Ee,H.model)}catch(se){H.final=dp(se,o,i,H.model.id)}}await fp(ae,H.final,u,p,y,ee?.signal)}catch(H){let ue=dp(H,o,i,V.id);ae.push({type:"error",reason:"error",error:ue}),ae.end(ue)}}),ae},X=async(V,J,ee)=>{b.cancelledDeferred.push(structuredClone(J));let ae=S.get(J.id);if(ae)ae.cancelled=!0;await ee?.onResponse?.({status:200,headers:{}},V)};function j(V){if(!V)return R[0];return R.find((J)=>J.id===V)}return{api:o,provider:i,models:R,stream:P,streamSimple:C,fetchDeferred:q,cancelDeferred:X,getModel:j,state:b,setResponses(V){g=[...V]},appendResponses(V){g.push(...V)},getPendingResponseCount(){return g.length}}}function Do(e={}){let o=ER(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 Aq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function Pq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Cq(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 $q(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function oc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function Ha(e){oc(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function $f(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var vq=$f(W(""));function vf(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,p)=>vf(u,o[p]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let i=o;return Object.entries(e).every(([u,p])=>Object.hasOwn(i,u)&&vf(p,i[u]))}class SR{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:$q(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=Ha(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:Aq(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=Ha(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=Ha(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:Pq(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=Ha(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=Ha(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let i=$f(o.arguments),u=i===vq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":i}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Cq(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let i=W(o.catchupJson);if($f(i)!==o.snapshotArguments){let p=W(o.snapshotArguments);if(!vf(p,i))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=Ha(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(oc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){oc(e);let i=this.blocks.get(e);if(i===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(i.kind!==o)throw Error(`Assistant message block ${e} is ${i.kind}, not ${o}`);return i}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,i){let u=this.block(e,i);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let p=u.deltaChars;u.deltaChars+=o.length;let g=Math.max(0,u.coveredChars-p);if(g>=o.length)return;let y=g===0?o:o.slice(g);return i==="text"?{type:"text_delta",contentIndex:e,delta:y}:{type:"thinking_delta",contentIndex:e,delta:y}}}function Cf(e,o,i,u,p){if(oc(i),i!==e.content.length){let g=i<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${i}: ${g}`)}e.content.push(structuredClone(u)),o.set(i,p)}function ua(e,o,i,u,p){oc(i);let g=o.get(i),y=e.content[i];if(!g||!y)throw Error(`${p} frame has no started block at index ${i}`);if(g.kind!==u||y.type!==u)throw Error(`${p} frame expected ${u} block at index ${i}, found ${y.type}`);if(g.ended)throw Error(`${p} frame follows the end of block at index ${i}`);return{block:y,state:g}}function Mq(e){let o,i,u=new Map;for(let p of e){if(p.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(i!==void 0)throw Error(`${i} frame appears before the start frame`);o=structuredClone(p.partial);continue}if(!o){i??=p.type;continue}switch(p.type){case"text_start":if(p.content.type!=="text")throw Error(`text_start frame contains ${p.content.type} content`);Cf(o,u,p.contentIndex,p.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:g}=ua(o,u,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");g.text+=p.delta;break}case"text_end":{let{block:g,state:y}=ua(o,u,p.contentIndex,"text",p.type);if(g.type!=="text")throw Error("Unreachable text frame state");if(g.text=p.content,delete g.textSignature,p.textSignature!==void 0)g.textSignature=p.textSignature;y.ended=!0;break}case"thinking_start":if(p.content.type!=="thinking")throw Error(`thinking_start frame contains ${p.content.type} content`);Cf(o,u,p.contentIndex,p.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:g}=ua(o,u,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");g.thinking+=p.delta;break}case"thinking_end":{let{block:g,state:y}=ua(o,u,p.contentIndex,"thinking",p.type);if(g.type!=="thinking")throw Error("Unreachable thinking frame state");if(g.thinking=p.content,delete g.thinkingSignature,delete g.redacted,p.thinkingSignature!==void 0)g.thinkingSignature=p.thinkingSignature;if(p.redacted!==void 0)g.redacted=p.redacted;y.ended=!0;break}case"toolcall_start":if(p.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${p.toolCall.type} content`);Cf(o,u,p.contentIndex,p.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:g,state:y}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");y.json=p.json,g.arguments=W(p.json);break}case"toolcall_delta":{let{block:g,state:y}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall"||y.kind!=="toolCall")throw Error("Unreachable tool-call frame state");y.json+=p.delta;break}case"toolcall_end":{let{block:g,state:y}=ua(o,u,p.contentIndex,"toolCall",p.type);if(g.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(g.id=p.id,g.name=p.name,g.arguments=structuredClone(p.arguments),delete g.thoughtSignature,delete g.namespace,p.thoughtSignature!==void 0)g.thoughtSignature=p.thoughtSignature;if(p.namespace!==void 0)g.namespace=p.namespace;y.ended=!0;break}}}if(!o)return;for(let[p,g]of u){if(g.kind!=="toolCall"||g.ended||g.json.length===0)continue;let y=o.content[p];if(y?.type!=="toolCall")throw Error("Unreachable tool-call frame state");y.arguments=W(g.json)}return o}var wR=[/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],Oq=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,_q=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function ca(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!_q.some((u)=>u.test(e.errorMessage))){if(wR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&Oq.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 Lq(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function Nq(){return[...wR]}function TR(e){return new RegExp(e.join("|"),"i")}var Dq=TR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),qq=TR(["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"]),RR=60000;function kR(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??RR)}class gp extends Error{constructor(){super("Aborted")}}function Fq(e,o){return new Promise((i,u)=>{if(o?.aborted){u(new gp);return}let p=setTimeout(i,e);o?.addEventListener("abort",()=>{clearTimeout(p),u(new gp)},{once:!0})})}async function jq(e,o,i,u){let p=o?.enabled?o.maxRetries:0,g=0,y;for(;;){let b=await e();if(b.stopReason==="aborted"){if(y)await u?.onRetryFinished?.(!1,y.attempt);return b}if(b.stopReason!=="error"){if(y)await u?.onRetryFinished?.(!0,y.attempt);return b}if(g>=p||!AR(b)){if(y)await u?.onRetryFinished?.(!1,y.attempt,b.errorMessage);return b}g++,y={attempt:g,errorMessage:b.errorMessage||"Unknown error"};let E=kR(o,g);await u?.onRetryScheduled?.(g,p,E,y.errorMessage);try{await Fq(E,i)}catch(S){if(await u?.onRetryFinished?.(!1,g,y.errorMessage),S instanceof gp){let{errorMessage:w,...R}=b;return{...R,stopReason:"aborted"}}throw S}await u?.onRetryAttemptStart?.()}}function AR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(Dq.test(o))return!1;return qq.test(o)}function Uq(e,o){return qr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function sc(e){return fe(e,"~refine")&&Ge(e["~refine"])&&an(e["~refine"],0,(o)=>at(o)&&fe(o,"check")&&fe(o,"error")&&ms(o.check)&&ms(o.error))}function gn(e){return at(e)&&!Ge(e)}function _s(e){return pn(e)}function Ye(e){return gn(e)||_s(e)}function Wa(e){return fe(e,"additionalItems")&&Ye(e.additionalItems)}function Co(e){return fe(e,"additionalProperties")&&Ye(e.additionalProperties)}function ic(e){return fe(e,"allOf")&&Ge(e.allOf)&&e.allOf.every((o)=>Ye(o))}function ac(e){return fe(e,"$anchor")&&gt(e.$anchor)}function uc(e){return fe(e,"anyOf")&&Ge(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function yp(e){return fe(e,"const")}function Rs(e){return fe(e,"contains")&&Ye(e.contains)}function bo(e){return fe(e,"default")}function cc(e){return fe(e,"dependencies")&&at(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||Ge(o)&&o.every((i)=>gt(i)))}function mc(e){return fe(e,"dependentRequired")&&at(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>Ge(o)&&o.every((i)=>gt(i)))}function za(e){return fe(e,"dependentSchemas")&&at(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function Ls(e){return fe(e,"$dynamicAnchor")&&gt(e.$dynamicAnchor)}function pc(e){return fe(e,"$dynamicRef")&&gt(e.$dynamicRef)}function lc(e){return fe(e,"else")&&Ye(e.else)}function xp(e){return fe(e,"enum")&&Ge(e.enum)}function dc(e){return fe(e,"exclusiveMaximum")&&(Ot(e.exclusiveMaximum)||Nr(e.exclusiveMaximum))}function es(e){return fe(e,"exclusiveMinimum")&&(Ot(e.exclusiveMinimum)||Nr(e.exclusiveMinimum))}function ma(e){return fe(e,"format")&&gt(e.format)}function Eo(e){return fe(e,"$id")&&gt(e.$id)}function fc(e){return fe(e,"if")&&Ye(e.if)}function Ns(e){return fe(e,"items")&&(Ye(e.items)||Ge(e.items)&&e.items.every((o)=>Ye(o)))}function hc(e){return Ns(e)&&Ge(e.items)}function gc(e){return fe(e,"maximum")&&(Ot(e.maximum)||Nr(e.maximum))}function yc(e){return fe(e,"maxContains")&&Ot(e.maxContains)}function Va(e){return fe(e,"maxItems")&&Ot(e.maxItems)}function xc(e){return fe(e,"maxLength")&&Ot(e.maxLength)}function Ic(e){return fe(e,"maxProperties")&&Ot(e.maxProperties)}function ts(e){return fe(e,"minimum")&&(Ot(e.minimum)||Nr(e.minimum))}function Ds(e){return fe(e,"minContains")&&Ot(e.minContains)}function xi(e){return fe(e,"minItems")&&Ot(e.minItems)}function pa(e){return fe(e,"minLength")&&Ot(e.minLength)}function la(e){return fe(e,"minProperties")&&Ot(e.minProperties)}function bc(e){return fe(e,"multipleOf")&&(Ot(e.multipleOf)||Nr(e.multipleOf))}function Ec(e){return fe(e,"not")&&Ye(e.not)}function Sc(e){return fe(e,"oneOf")&&Ge(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function da(e){return fe(e,"pattern")&&(gt(e.pattern)||e.pattern instanceof RegExp)}function qs(e){return fe(e,"patternProperties")&&at(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function rs(e){return fe(e,"prefixItems")&&Ge(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function Fs(e){return fe(e,"properties")&&at(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function Ja(e){return fe(e,"propertyNames")&&(at(e.propertyNames)||Ye(e.propertyNames))}function Bq(e){return fe(e,"$recursiveAnchor")&&pn(e.$recursiveAnchor)}function wc(e){return Bq(e)&&L(e.$recursiveAnchor,!0)}function Tc(e){return fe(e,"$recursiveRef")&&gt(e.$recursiveRef)}function Rc(e){return fe(e,"$ref")&&gt(e.$ref)}function ns(e){return fe(e,"required")&&Ge(e.required)&&e.required.every((o)=>gt(o))}function kc(e){return fe(e,"then")&&Ye(e.then)}function Ac(e){return fe(e,"type")&&(gt(e.type)||Ge(e.type)&&e.type.every((o)=>gt(o)))}function Ei(e){return fe(e,"uniqueItems")&&pn(e.uniqueItems)}function Ri(e){return fe(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function ki(e){return fe(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function Gq(e){return Ri(e)||ki(e)||wa(we(e),(o)=>Ip(e[o]))}function Kq(e){return wa(e,(o)=>Ip(o))}function Ip(e){return Ge(e)?Kq(e):at(e)?Gq(e):!1}function PR(e,o){return Ip(o)||wa(we(e),(i)=>Ip(e[i]))}class Mf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ir(bt("context","Push"),[])}Pop(){return Ir(bt("context","Pop"),[])}AddIndex(e){return Ir(bt("context","AddIndex"),[e])}AddKey(e){return Ir(bt("context","AddKey"),[e])}Merge(e){return Ir(bt("context","Merge"),[e])}}class _n{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((i)=>this.GetIndices().add(i)),o.GetKeys().forEach((i)=>this.GetKeys().add(i));return!0}}class qn extends _n{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=Jo().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var bp={identifier:"External",variables:[]};function vo(e){let o=`External[${bp.variables.length}]`;return bp.variables.push(e),o}function CR(){bp.variables=[]}function $R(){return{...bp}}function vR(e,o,i,u){let p=vo(i["~refine"].map((g)=>g));return ls(p,De(0),["refinement","_"],Ir(bt("refinement","check"),[u]))}function MR(e,o,i,u){return an(i["~refine"],0,(p,g)=>p.check(u))}function OR(e,o,i,u,p,g){return An(p["~refine"],0,(y,b)=>y.check(g)||o.AddError({keyword:"~refine",schemaPath:i,instancePath:u,params:{index:b,message:y.error(g)}}))}var Hq=0;function Vt(){return`var_${Hq++}`}function Of(e){return Ns(e)&&Ge(e.items)}function Wq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=fd(g,De(i.items.length)),E=o.AddIndex(g);return ls(u,De(0),[p,g],xr(b,Sn(y,E)))}function zq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=to(e,o,i.additionalItems,p),b=fd(g,De(i.items.length));return ls(u,De(0),[p,g],xr(b,y))}function _R(e,o,i,u){if(!Of(i))return De(!0);return o.UseUnevaluated()?Wq(e,o,i,u):zq(e,o,i,u)}function LR(e,o,i,u){if(!Of(i))return!0;return an(u,0,(g,y)=>Su(y,i.items.length)||So(e,o,i.additionalItems,g)&&o.AddIndex(y))}function NR(e,o,i,u,p,g){if(!Of(p))return!0;return an(g,0,(b,E)=>{let S=`${i}/additionalItems`,w=`${u}/${E}`;return Su(E,p.items.length)||wo(e,o,S,w,p.additionalItems,b)&&o.AddIndex(E)})}function os(e){return new RegExp(e,"u")}function Vq(e,o){return!e.UseUnevaluated()&&(L(o,!0)||at(o)&&L(we(o).length,0))}function Jq(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function _f(e){let o=[];if(qs(e))o.push(...we(e.patternProperties));if(Fs(e))o.push(...we(e.properties).map(Jq));return L(o.length,0)?"(?!)":`(${o.join("|")})`}function Qq(e,o,i){return ns(o)&&Fs(o)&&!qs(o)&&L(o.additionalProperties,!1)&&L(we(o.properties).length,o.required.length)}function Xq(e,o,i){return uo(bt(Ir(bt("Object","getOwnPropertyNames"),[i]),"length"),De(o.required.length))}function Yq(e,o,i,u){let[p,g]=[Vt(),Vt()],y=vo(os(_f(i))),b=to(e,o,i.additionalProperties,`${u}[${p}]`),E=Ir(bt(y,"test"),[p]),S=o.AddKey(p),w=o.UseUnevaluated()?xr(E,Sn(b,S)):xr(E,b);return ls(zi(u),De(0),[p,g],w)}function DR(e,o,i,u){if(Vq(o,i.additionalProperties))return De(!0);return Qq(o,i,u)?Xq(o,i,u):Yq(e,o,i,u)}function qR(e,o,i,u){let p=os(_f(i));return an(we(u),0,(y,b)=>p.test(y)||So(e,o,i.additionalProperties,u[y])&&o.AddKey(y))}function FR(e,o,i,u,p,g){let y=os(_f(p)),b=[];return An(we(g),0,(S,w)=>{let R=`${i}/additionalProperties`,A=`${u}/${S}`,P=y.test(S)||wo(e,o,R,A,p.additionalProperties,g[S])&&o.AddKey(S);if(!P)b.push(S);return P})||o.AddError({keyword:"additionalProperties",schemaPath:i,instancePath:u,params:{additionalProperties:b}})}function Pi(e,o,i,u,p){let g=vs("results","[]"),y=i.map((w,R)=>vs(`context_${R}`,hd("CheckContext",[]))),b=i.map((w,R)=>vs(`condition_${R}`,Ir(Vs(["context"],Lt(e,o,w,u)),[`context_${R}`]))),E=i.map((w,R)=>Py(`condition_${R}`,Ir(bt("results","push"),[`context_${R}`]))),S=im(Sn(p,o.Merge("results")));return Ir(Vs([],sm([g,...y,...b,...E,S])),[])}function Zq(e,o,i,u){return Pi(e,o,i.allOf,u,uo(bt("results","length"),De(i.allOf.length)))}function eF(e,o,i,u){return Pn(i.allOf.map((p)=>Lt(e,o,p,u)))}function jR(e,o,i,u){return o.UseUnevaluated()?Zq(e,o,i,u):eF(e,o,i,u)}function UR(e,o,i,u){let p=i.allOf.reduce((g,y)=>{let b=new _n;return kt(e,b,y,u)?[...g,b]:g},[]);return L(p.length,i.allOf.length)&&o.Merge(p)}function BR(e,o,i,u,p,g){let y=[],b=p.allOf.reduce((S,w,R)=>{let A=`${i}/allOf/${R}`,P=new qn,C=mr(e,P,A,u,w,g);if(!C)y.push(P);return C?[...S,P]:S},[]),E=L(b.length,p.allOf.length)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E}function tF(e,o,i,u){return Pi(e,o,i.anyOf,u,Ry(bt("results","length"),De(0)))}function rF(e,o,i,u){return gd(i.anyOf.map((p)=>Lt(e,o,p,u)))}function GR(e,o,i,u){return o.UseUnevaluated()?tF(e,o,i,u):rF(e,o,i,u)}function KR(e,o,i,u){let p=i.anyOf.reduce((g,y)=>{let b=new _n;return kt(e,b,y,u)?[...g,b]:g},[]);return Ki(p.length,0)&&o.Merge(p)}function HR(e,o,i,u,p,g){let y=[],b=p.anyOf.reduce((S,w,R)=>{let A=new qn,P=`${i}/anyOf/${R}`,C=mr(e,A,P,u,w,g);if(!C)y.push(A);return C?[...S,A]:S},[]),E=Ki(b.length,0)&&o.Merge(b);if(!E)y.forEach((S)=>S.GetErrors().forEach((w)=>o.AddError(w)));return E||o.AddError({keyword:"anyOf",schemaPath:i,instancePath:u,params:{}})}function WR(e,o,i,u){return i?De(!0):De(!1)}function Lf(e,o,i,u){return i}function zR(e,o,i,u,p,g){return Lf(e,o,p,g)||o.AddError({keyword:"boolean",schemaPath:i,instancePath:u,params:{}})}function VR(e,o,i,u){return Hi(i.const)?uo(u,De(i.const)):Ay(u,vo(i.const))}function Nf(e,o,i,u){return Hi(i.const)?L(u,i.const):Ta(u,i.const)}function JR(e,o,i,u,p,g){return Nf(e,o,p,g)||o.AddError({keyword:"const",schemaPath:i,instancePath:u,params:{allowedValue:p.const}})}function QR(e){return!(Ds(e)&&L(e.minContains,0))}function nF(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Un(uo(bt(u,"length"),De(0))),b=DM(u,[p,g],Sn(Lt(e,o,i.contains,p),o.AddIndex(g)));return Sn(y,b)}function oF(e,o,i,u){let[p]=[Vt()],g=Un(uo(bt(u,"length"),De(0))),y=NM(u,[p,"_"],Lt(e,o,i.contains,p));return Sn(g,y)}function XR(e,o,i,u){if(!QR(i))return De(!0);return o.UseUnevaluated()?nF(e,o,i,u):oF(e,o,i,u)}function Df(e,o,i,u){if(!QR(i))return!0;return!L(u.length,0)&&xy(u,(p,g)=>kt(e,o,i.contains,p)&&o.AddIndex(g))}function YR(e,o,i,u,p,g){return Df(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:1}})}function ZR(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Pn(ln(i.dependencies).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Lt(e,o,b,u),w=(R)=>Pn(R.map((A)=>Vi(u,De(A))));return xr(E,Ge(b)?w(b):S)}));return xr(p,g)}function ek(e,o,i,u){let p=L(we(u).length,0),g=an(ln(i.dependencies),0,([y,b])=>!fe(u,y)||(Ge(b)?b.every((E)=>fe(u,E)):kt(e,o,b,u)));return p||g}function tk(e,o,i,u,p,g){let y=L(we(g).length,0),b=An(ln(p.dependencies),0,([E,S])=>{let w=`${i}/dependencies/${E}`;return!fe(g,E)||(Ge(S)?S.every((R)=>fe(g,R)||o.AddError({keyword:"dependencies",schemaPath:i,instancePath:u,params:{property:E,dependencies:S}})):mr(e,o,w,u,S,g))});return y||b}function rk(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Pn(ln(i.dependentRequired).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Pn(b.map((w)=>Vi(u,De(w))));return xr(E,S)}));return xr(p,g)}function nk(e,o,i,u){let p=L(we(u).length,0),g=an(ln(i.dependentRequired),0,([y,b])=>!fe(u,y)||b.every((E)=>fe(u,E)));return p||g}function ok(e,o,i,u,p,g){let y=L(we(g).length,0),b=An(ln(p.dependentRequired),0,([E,S])=>!fe(g,E)||An(S,0,(w)=>fe(g,w)||o.AddError({keyword:"dependentRequired",schemaPath:i,instancePath:u,params:{property:E,dependencies:S}})));return y||b}function sk(e,o,i,u){let p=uo(bt(zi(u),"length"),De(0)),g=Pn(ln(i.dependentSchemas).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=Lt(e,o,b,u);return xr(E,S)}));return xr(p,g)}function ik(e,o,i,u){let p=L(we(u).length,0),g=an(ln(i.dependentSchemas),0,([y,b])=>!fe(u,y)||kt(e,o,b,u));return p||g}function ak(e,o,i,u,p,g){let y=L(we(g).length,0),b=An(ln(p.dependentSchemas),0,([E,S])=>{let w=`${i}/dependentSchemas/${E}`;return!fe(g,E)||mr(e,o,w,u,S,g)});return y||b}function uk(e,o,i,u){let p=e.DynamicRef(i)??!1;return js(e,o,p,u)}function ck(e,o,i,u){let p=e.DynamicRef(i)??!1;return Ye(p)&&kt(e,o,p,u)}function mk(e,o,i,u,p,g){let y=e.DynamicRef(p)??!1;return Ye(y)&&mr(e,o,"#",u,y,g)}function pk(e,o,i,u){return gd(i.enum.map((p)=>{if(Hi(p))return uo(u,De(p));let g=vo(p);return Ay(u,g)}))}function Ff(e,o,i,u){return wa(i.enum,(p)=>Hi(p)?L(u,p):Ta(u,p))}function lk(e,o,i,u,p,g){return Ff(e,o,p,g)||o.AddError({keyword:"enum",schemaPath:i,instancePath:u,params:{allowedValues:p.enum}})}function dk(e,o,i,u){return fd(u,De(i.exclusiveMaximum))}function jf(e,o,i,u){return Su(u,i.exclusiveMaximum)}function fk(e,o,i,u,p,g){return jf(e,o,p,g)||o.AddError({keyword:"exclusiveMaximum",schemaPath:i,instancePath:u,params:{comparison:"<",limit:p.exclusiveMaximum}})}function hk(e,o,i,u){return Ry(u,De(i.exclusiveMinimum))}function Uf(e,o,i,u){return Ki(u,i.exclusiveMinimum)}function gk(e,o,i,u,p,g){return Uf(e,o,p,g)||o.AddError({keyword:"exclusiveMinimum",schemaPath:i,instancePath:u,params:{comparison:">",limit:p.exclusiveMinimum}})}var sF=[0,31,28,31,30,31,30,31,31,30,31,30,31],iF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function aF(e){return e%4===0&&(e%100!==0||e%400===0)}function Xa(e){let o=iF.exec(e);if(!o)return!1;let i=+o[1],u=+o[2],p=+o[3];return u>=1&&u<=12&&p>=1&&p<=(u===2&&aF(i)?29:sF[u])}var uF=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function Ya(e,o=!0){let i=uF.exec(e);if(!i)return!1;if(o&&!i[4]&&!i[5])return!1;let u=+i[1],p=+i[2],g=+i[3];if(u>23||p>59||g>60)return!1;if(i[5]){let w=+i[6],R=+i[7];if(w>23||R>59)return!1}if(g<60)return!0;let y=i[5]==="-"?-1:1,b=+(i[6]||0),E=+(i[7]||0);return((u*60+p-y*(b*60+E))%1440+1440)%1440===1439}function Ep(e){let o=e.split(/T/i);return o.length===2&&Xa(o[0])&&Ya(o[1])}var cF=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Sp(e){return cF.test(e)}var mF=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function wp(e){return mF.test(e)}var yk=/^(?!-).*(?<!-)$/,xk=/^(?!..--)/,Ik=/^[a-zA-Z0-9-]*$/;var Za=/[^\p{ASCII}]/u;var pF=/[0-9]/,bk=/[\u{0660}-\u{0669}]/u,lF=/[\u{06f0}-\u{06f9}]/u,dF=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,fF=/[\u{002d}\u{002b}]/u,Bf=/\p{Mn}/u,hF=/\p{Mc}/u;var Ek=/[\p{Mn}\p{Mc}\p{Me}]/u,Gf=/\p{L}/u,gF=/\p{Nd}/u,Sk=/\p{Script=Greek}/u,Tp=/\p{Script=Hebrew}/u,wk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,Tk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Kf=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,Rk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,yF=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,xF=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,kk=new RegExp([pF,lF].map((e)=>e.source).join("|"),"u"),Ak=new RegExp([Gf,fF,dF,gF,Bf,hF,yF,xF].map((e)=>e.source).join("|"),"u");function Pk(e){return yk.test(e)&&xk.test(e)&&Ik.test(e)}var ss=36,Cc=1,$c=26,bF=38,EF=700,$k=72,vk=128;function Hf(){throw null}function Rp(e){return e.toLowerCase().startsWith("xn--")}function Mk(e,o,i){e=i?Math.floor(e/EF):e>>1,e+=Math.floor(e/o);let u=0;while(e>(ss-Cc)*$c>>1)e=Math.floor(e/(ss-Cc)),u+=ss;return u+Math.floor((ss-Cc+1)*e/(e+bF))}function kp(e){let o=[],i=vk,u=0,p=$k,g=e.lastIndexOf("-");if(g>0)for(let b=0;b<g;b++){let E=e.charCodeAt(b);if(E>=128)Hf();o.push(E)}let y=g<0?0:g+1;while(y<e.length){let b=u,E=1,S=ss;while(!0){if(y>=e.length)Hf();let R=e.charCodeAt(y++),A;if(R>=97&&R<=122)A=R-97;else if(R>=48&&R<=57)A=R-48+26;else Hf();u+=A*E;let P=S<=p?Cc:S>=p+$c?$c:S-p;if(A<P)break;E*=ss-P,S+=ss}let w=o.length+1;p=Mk(u-b,w,b===0),i+=Math.floor(u/w),u%=w,o.splice(u,0,i),u++}return String.fromCodePoint(...o)}function Ck(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var SF=new RegExp(Za.source,"gu");function Ok(e){let o=e.replace(SF,""),i=o.length,u=i>0?[o,"-"]:[],p=Array.from(e,(S)=>S.codePointAt(0)),g=vk,y=0,b=$k,E=i;while(E<p.length){let S=1/0;for(let w of p)if(w>=g&&w<S)S=w;y+=(S-g)*(E+1),g=S;for(let w of p){if(w<g)y++;if(w===g){let R=y;for(let A=ss;;A+=ss){let P=A<=b?Cc:A>=b+$c?$c:A-b;if(R<P)break;let C=P+(R-P)%(ss-P);u.push(Ck(C)),R=Math.floor((R-P)/(ss-P))}u.push(Ck(R)),b=Mk(y,E+1,E===i),y=0,E++}}y++,g++}return u.join("")}var wF=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,_k=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,TF=/^(?:R|AL|AN)$/;function Lk(e){if(Rp(e))try{return Ap(kp(e.slice(4).toLowerCase()))}catch{return!1}return Ap(e)}function Nk(e){let o=String.fromCodePoint(e);return kk.test(o)?"EN":bk.test(o)?"AN":Bf.test(o)?"NSM":Tp.test(o)?"R":Tk.test(o)?"AL":Gf.test(o)?"L":"ON"}function Ap(e){for(let o of e)if(TF.test(Nk(o.codePointAt(0))))return!0;return!1}function Pp(e){let o=!1,i=_k,u=!1,p=!1,g=!0;for(let y of e){let b=Nk(y.codePointAt(0));if(g){if(b!=="L"&&b!=="R"&&b!=="AL")return!1;o=b==="R"||b==="AL",i=o?wF:_k,g=!1}if(!i.test(b))return!1;if(b==="EN")u=!0;else if(b==="AN")p=!0}if(o&&u&&p)return!1;return!0}function RF(e){return Za.test(e)&&Ok(e).length+4>63}function kF(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Cp(e){if(RF(e))return!1;if(Ap(e)&&!Pp(e))return!1;let o=[...e],i=o.map((g)=>g.codePointAt(0)),u=i.length;if(kF(o))return!1;if(Ek.test(o[0]))return!1;let p=!1;for(let g=0;g<u;g++){let y=i[g],b=o[g];if(Rk.test(b))return!1;if(!Ak.test(b))return!1;if(wk.test(b))p=!0;let E=i[g-1],S=i[g+1];switch(y){case 183:if(E!==108||S!==108)return!1;break;case 885:if(!S||!Sk.test(o[g+1]))return!1;break;case 1523:case 1524:if(!E||!Tp.test(o[g-1]))return!1;break;case 8204:if(!E||E<128&&!Kf.test(o[g-1]))return!1;break;case 8205:if(!E||!Kf.test(o[g-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!p)return!1;return!0}function $p(e){if(!Rp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let i=kp(o);if(!Za.test(i))return!1;return Cp(i)}catch{return!1}}function AF(e){return e.length>0&&e.length<=63}function PF(e){return AF(e)&&($p(e)||Pk(e))}function jk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>PF(o))}function CF(e){return e.length>0&&e.length<=63}function $F(e){return CF(e)&&($p(e)||Cp(e))}function vF(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 Uk(e){if(e.length===0||e.includes(" "))return!1;let o=vF(e);if(o.length>253)return!1;let i=o.split("."),u=i.some((p)=>Lk(p));return i.every((p)=>$F(p)&&(!u||Pp(p)))}function vp(e){return jk(e)}var MF=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Mp(e){return MF.test(e.normalize("NFC"))}function Op(e){return Uk(e)}var OF=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function _p(e){return OF.test(e)}var _F=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function Lp(e){return _F.test(e)}var LF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,NF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Np(e){return!LF.test(e)&&!NF.test(e)&&URL.canParse(e,"http://example.com")}var DF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,qF=/[\x00-\x20<>\^`{|}\\]/,FF=/%(?![0-9a-fA-F]{2})/;function jF(e){return e.length<2048?e.replace(DF,"[::1]"):e}function Dp(e){if(qF.test(e))return!1;if(FF.test(e))return!1;return URL.canParse(jF(e))}var UF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function qp(e){return UF.test(e)}var BF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Fp(e){return BF.test(e)}function jp(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var GF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Up(e){return GF.test(e)}var KF=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Bp(e){return KF.test(e)}var HF=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Gp(e){return HF.test(e)}var WF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Kp(e){return WF.test(e)}function Hp(e){return URL.canParse(e)}var zF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Wp(e){return zF.test(e)}var Er=new Map;function Gk(){Er.clear()}function VF(){return[...Er.entries()]}function JF(e,o){Er.set(e,o)}function QF(e){return Er.has(e)}function XF(e){return Er.get(e)}function Kk(e,o){return Er.get(e)?.(o)??!0}function Hk(){Gk(),Er.set("date-time",Ep),Er.set("date",Xa),Er.set("duration",Sp),Er.set("email",wp),Er.set("hostname",vp),Er.set("idn-email",Mp),Er.set("idn-hostname",Op),Er.set("ipv4",_p),Er.set("ipv6",Lp),Er.set("iri-reference",Np),Er.set("iri",Dp),Er.set("json-pointer-uri-fragment",qp),Er.set("json-pointer",Fp),Er.set("regex",jp),Er.set("relative-json-pointer",Up),Er.set("time",Ya),Er.set("uri-reference",Bp),Er.set("uri-template",Gp),Er.set("uri",Kp),Er.set("url",Hp),Er.set("uuid",Wp)}Hk();function Wk(e,o,i,u){return Ir(bt("Format","Test"),[De(i.format),u])}function zf(e,o,i,u){return Kk(i.format,u)}function zk(e,o,i,u,p,g){return zf(e,o,p,g)||o.AddError({keyword:"format",schemaPath:i,instancePath:u,params:{format:p.format}})}function Vk(e,o,i,u){let p=kc(i)?i.then:!0,g=lc(i)?i.else:!0;return FM(Lt(e,o,i.if,u),Lt(e,o,p,u),Lt(e,o,g,u))}function Jk(e,o,i,u){let p=kc(i)?i.then:!0,g=lc(i)?i.else:!0;return kt(e,o,i.if,u)?kt(e,o,p,u):kt(e,o,g,u)}function Qk(e,o,i,u,p,g){let y=kc(p)?p.then:!0,b=lc(p)?p.else:!0,E=new qn,S=mr(e,E,`${i}/if`,u,p.if,g)?mr(e,E,`${i}/then`,u,y,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"then"}}):mr(e,o,`${i}/else`,u,b,g)||o.AddError({keyword:"if",schemaPath:i,instancePath:u,params:{failingKeyword:"else"}});if(S)o.Merge([E]);return S}function YF(e,o,i,u){return Pn(i.items.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`),E=o.AddIndex(De(g));return xr(y,Sn(b,E))}))}function ZF(e,o,i,u){return Pn(i.items.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`);return xr(y,b)}))}function e1(e,o,i,u){return o.UseUnevaluated()?YF(e,o,i,u):ZF(e,o,i,u)}function t1(e,o,i,u){return an(i.items,0,(p,g)=>ps(u.length,g)||So(e,o,p,u[g])&&o.AddIndex(g))}function r1(e,o,i,u,p,g){return An(p.items,0,(y,b)=>{let E=`${i}/items/${b}`,S=`${u}/${b}`;return ps(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function n1(e,o,i,u){let p=rs(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element"),y=o.AddIndex("index");return ls(u,De(p),["element","index"],Sn(g,y))}function o1(e,o,i,u){let p=rs(i)?i.prefixItems.length:0,g=to(e,o,i.items,"element");return ls(u,De(p),["element","index"],g)}function s1(e,o,i,u){return o.UseUnevaluated()?n1(e,o,i,u):o1(e,o,i,u)}function i1(e,o,i,u){let p=rs(i)?i.prefixItems.length:0;return an(u,p,(g,y)=>So(e,o,i.items,g)&&o.AddIndex(y))}function a1(e,o,i,u,p,g){let y=rs(p)?p.prefixItems.length:0;return An(g,y,(b,E)=>{let S=`${i}/items`,w=`${u}/${E}`;return wo(e,o,S,w,p.items,b)&&o.AddIndex(E)})}function Xk(e,o,i,u){return hc(i)?e1(e,o,i,u):s1(e,o,i,u)}function Yk(e,o,i,u){return hc(i)?t1(e,o,i,u):i1(e,o,i,u)}function Zk(e,o,i,u,p,g){return hc(p)?r1(e,o,i,u,p,g):a1(e,o,i,u,p,g)}function eA(e){return Rs(e)}function tA(e,o,i,u){if(!eA(i))return De(!0);let[p]=[Vt()],g=om(u,[p,"_"],Lt(e,o,i.contains,p));return Wi(g,De(i.maxContains))}function Vf(e,o,i,u){if(!eA(i))return!0;let p=md(u,(g)=>kt(e,o,i.contains,g));return ps(p,i.maxContains)}function rA(e,o,i,u,p,g){let y=Ds(p)?p.minContains:1;return Vf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:y,maxContains:p.maxContains}})}function nA(e,o,i,u){return Wi(u,De(i.maximum))}function Jf(e,o,i,u){return ps(u,i.maximum)}function oA(e,o,i,u,p,g){return Jf(e,o,p,g)||o.AddError({keyword:"maximum",schemaPath:i,instancePath:u,params:{comparison:"<=",limit:p.maximum}})}function sA(e,o,i,u){return Wi(bt(u,"length"),De(i.maxItems))}function Qf(e,o,i,u){return ps(u.length,i.maxItems)}function iA(e,o,i,u,p,g){return Qf(e,o,p,g)||o.AddError({keyword:"maxItems",schemaPath:i,instancePath:u,params:{limit:p.maxItems}})}function aA(e,o,i,u){return LM(u,De(i.maxLength))}function Xf(e,o,i,u){return gy(u,i.maxLength)}function uA(e,o,i,u,p,g){return Xf(e,o,p,g)||o.AddError({keyword:"maxLength",schemaPath:i,instancePath:u,params:{limit:p.maxLength}})}function cA(e,o,i,u){return Wi(bt(zi(u),"length"),De(i.maxProperties))}function Yf(e,o,i,u){return ps(we(u).length,i.maxProperties)}function mA(e,o,i,u,p,g){return Yf(e,o,p,g)||o.AddError({keyword:"maxProperties",schemaPath:i,instancePath:u,params:{limit:p.maxProperties}})}function pA(e){return Rs(e)}function u1(e,o,i,u){let[p,g]=[Vt(),Vt()],y=om(u,[p,g],Sn(Lt(e,o,i.contains,p),o.AddIndex(g)));return Tu(y,De(i.minContains))}function c1(e,o,i,u){let[p]=[Vt()],g=om(u,[p,"_"],Lt(e,o,i.contains,p));return Tu(g,De(i.minContains))}function lA(e,o,i,u){if(!pA(i))return De(!0);return o.UseUnevaluated()?u1(e,o,i,u):c1(e,o,i,u)}function Zf(e,o,i,u){if(!pA(i))return!0;let p=md(u,(g,y)=>kt(e,o,i.contains,g)&&o.AddIndex(y));return Sa(p,i.minContains)}function dA(e,o,i,u,p,g){return Zf(e,o,p,g)||o.AddError({keyword:"contains",schemaPath:i,instancePath:u,params:{minContains:p.minContains}})}function fA(e,o,i,u){return Tu(u,De(i.minimum))}function eh(e,o,i,u){return Sa(u,i.minimum)}function hA(e,o,i,u,p,g){return eh(e,o,p,g)||o.AddError({keyword:"minimum",schemaPath:i,instancePath:u,params:{comparison:">=",limit:p.minimum}})}function gA(e,o,i,u){return Tu(bt(u,"length"),De(i.minItems))}function th(e,o,i,u){return Sa(u.length,i.minItems)}function yA(e,o,i,u,p,g){return th(e,o,p,g)||o.AddError({keyword:"minItems",schemaPath:i,instancePath:u,params:{limit:p.minItems}})}function xA(e,o,i,u){return _M(u,De(i.minLength))}function rh(e,o,i,u){return yy(u,i.minLength)}function IA(e,o,i,u,p,g){return rh(e,o,p,g)||o.AddError({keyword:"minLength",schemaPath:i,instancePath:u,params:{limit:p.minLength}})}function bA(e,o,i,u){return Tu(bt(zi(u),"length"),De(i.minProperties))}function nh(e,o,i,u){return Sa(we(u).length,i.minProperties)}function EA(e,o,i,u,p,g){return nh(e,o,p,g)||o.AddError({keyword:"minProperties",schemaPath:i,instancePath:u,params:{limit:p.minProperties}})}function SA(e,o,i,u){return jM(u,De(i.multipleOf))}function oh(e,o,i,u){return fy(u,i.multipleOf)}function wA(e,o,i,u,p,g){return oh(e,o,p,g)||o.AddError({keyword:"multipleOf",schemaPath:i,instancePath:u,params:{multipleOf:p.multipleOf}})}function m1(e,o,i,u){return Pi(e,o,[i.not],u,Un(uo(bt("results","length"),De(1))))}function p1(e,o,i,u){return Un(Lt(e,o,i.not,u))}function TA(e,o,i,u){return o.UseUnevaluated()?m1(e,o,i,u):p1(e,o,i,u)}function sh(e,o,i,u){let p=new _n;return!kt(e,p,i.not,u)&&o.Merge([p])}function RA(e,o,i,u,p,g){return sh(e,o,p,g)||o.AddError({keyword:"not",schemaPath:i,instancePath:u,params:{}})}function l1(e,o,i,u){return Pi(e,o,i.oneOf,u,uo(bt("results","length"),De(1)))}function d1(e,o,i,u){let[p]=[Vt()],g=qM(i.oneOf.map((b)=>Lt(e,o,b,u))),y=om(g,[p,"_"],uo(p,De(!0)));return uo(y,De(1))}function kA(e,o,i,u){return o.UseUnevaluated()?l1(e,o,i,u):d1(e,o,i,u)}function AA(e,o,i,u){let p=i.oneOf.reduce((g,y)=>{let b=new _n;return kt(e,b,y,u)?[...g,b]:g},[]);return L(p.length,1)&&o.Merge(p)}function PA(e,o,i,u,p,g){let y=[],b=[],E=p.oneOf.reduce((w,R,A)=>{let P=new qn,C=`${i}/oneOf/${A}`,q=mr(e,P,C,u,R,g);if(q)b.push(A);if(!q)y.push(P);return q?[...w,P]:w},[]),S=L(E.length,1)&&o.Merge(E);if(!S&&L(b.length,0))y.forEach((w)=>w.GetErrors().forEach((R)=>o.AddError(R)));return S||o.AddError({keyword:"oneOf",schemaPath:i,instancePath:u,params:{passingSchemas:b}})}function CA(e,o,i,u){let p=vo(gt(i.pattern)?os(i.pattern):i.pattern);return Ir(bt(p,"test"),[u])}function ih(e,o,i,u){return(gt(i.pattern)?os(i.pattern):i.pattern).test(u)}function $A(e,o,i,u,p,g){return ih(e,o,p,g)||o.AddError({keyword:"pattern",schemaPath:i,instancePath:u,params:{pattern:p.pattern}})}function vA(e,o,i,u){return Pn(ln(i.patternProperties).map(([p,g])=>{let[y,b]=[Vt(),Vt()],E=vo(os(p)),S=Un(Ir(bt(E,"test"),[y])),w=to(e,o,g,b),R=o.AddKey(y),A=o.UseUnevaluated()?xr(S,Sn(w,R)):xr(S,w);return ls(ky(u),De(0),[`[${y}, ${b}]`,"_"],A)}))}function MA(e,o,i,u){return an(ln(i.patternProperties),0,([p,g])=>{let y=os(p);return an(ln(u),0,([b,E])=>!y.test(b)||So(e,o,g,E)&&o.AddKey(b))})}function OA(e,o,i,u,p,g){return An(ln(p.patternProperties),0,([y,b])=>{let E=`${i}/patternProperties/${y}`,S=os(y);return An(ln(g),0,([w,R])=>{let A=`${u}/${w}`;return!S.test(w)||wo(e,o,E,A,b,R)&&o.AddKey(w)})})}function _A(e,o,i,u){return Pn(i.prefixItems.map((p,g)=>{let y=Wi(bt(u,"length"),De(g)),b=to(e,o,p,`${u}[${g}]`),E=o.AddIndex(De(g)),S=o.UseUnevaluated()?Sn(b,E):b;return xr(y,S)}))}function LA(e,o,i,u){return L(u.length,0)||an(i.prefixItems,0,(p,g)=>ps(u.length,g)||So(e,o,p,u[g])&&o.AddIndex(g))}function NA(e,o,i,u,p,g){return L(g.length,0)||An(p.prefixItems,0,(y,b)=>{let E=`${i}/prefixItems/${b}`,S=`${u}/${b}`;return ps(g.length,b)||wo(e,o,E,S,y,g[b])&&o.AddIndex(b)})}function zp(e,o){return e.includes(o)||Jo().exactOptionalPropertyTypes}function DA(e,o){return dd(bt(e,o))}function ah(e,o){return Ut(e[o])}function qA(e,o,i,u){let p=ns(i)?i.required:[],g=ln(i.properties).map(([y,b])=>{let E=Un(Vi(u,De(y))),S=to(e,o,b,bt(u,y)),w=o.AddKey(De(y)),R=o.UseUnevaluated()?Sn(S,w):S,A=p.includes(y)?R:xr(E,R);return zp(p,y)?A:xr(DA(u,y),A)});return Pn(g)}function FA(e,o,i,u){let p=ns(i)?i.required:[];return an(ln(i.properties),0,([y,b])=>{let E=!fe(u,y)||So(e,o,b,u[y])&&o.AddKey(y);return zp(p,y)?E:ah(u,y)||E})}function jA(e,o,i,u,p,g){let y=ns(p)?p.required:[];return An(ln(p.properties),0,([E,S])=>{let w=`${i}/properties/${E}`,R=`${u}/${E}`,A=()=>!fe(g,E)||wo(e,o,w,R,S,g[E])&&o.AddKey(E);return zp(y,E)?A():ah(g,E)||A()})}function UA(e,o,i,u){let[p,g]=[Vt(),Vt()];return ls(zi(u),De(0),[p,g],Lt(e,o,i.propertyNames,p))}function BA(e,o,i,u){return an(we(u),0,(p,g)=>kt(e,o,i.propertyNames,p))}function GA(e,o,i,u,p,g){let y=[];return An(we(g),0,(E,S)=>{let w=`${u}/${E}`,R=`${i}/propertyNames`,A=mr(e,o,R,w,p.propertyNames,E);if(!A)y.push(E);return A})||o.AddError({keyword:"propertyNames",schemaPath:i,instancePath:u,params:{propertyNames:y}})}function KA(e,o,i,u){let p=e.RecursiveRef(i)??!1;return js(e,o,p,u)}function HA(e,o,i,u){let p=e.RecursiveRef(i)??!1;return Ye(p)&&kt(e,o,p,u)}function WA(e,o,i,u,p,g){let y=e.RecursiveRef(p)??!1;return Ye(y)&&mr(e,o,"#",u,y,g)}function f1(e,o,i,u){let p=Vs(["context","value"],js(e,o,i,"value")),g=Vs(["context","value"],sm([vs("nextContext",hd("CheckContext",[])),vs("result",Ir(p,["nextContext","value"])),Py("result",o.Merge("[nextContext]")),im("result")]));return Ir(g,["context",u])}function h1(e,o,i,u){return js(e,o,i,u)}function zA(e,o,i,u){let p=e.Ref(i)??!1;return o.UseUnevaluated()?f1(e,o,p,u):h1(e,o,p,u)}function VA(e,o,i,u){let p=e.Ref(i)??!1,g=new _n,y=Ye(p)&&kt(e,g,p,u);if(y)o.Merge([g]);return y}function JA(e,o,i,u,p,g){let y=e.Ref(p)??!1,b=new qn,E=Ye(y)&&mr(e,b,"#",u,y,g);if(E)o.Merge([b]);if(!E)b.GetErrors().forEach((S)=>o.AddError(S));return E}function QA(e,o,i,u){return Pn(i.required.map((p)=>Vi(u,De(p))))}function XA(e,o,i,u){return an(i.required,0,(p)=>fe(u,p))}function YA(e,o,i,u,p,g){let y=[];return An(p.required,0,(E)=>{let S=fe(g,E);if(!S)y.push(E);return S})||o.AddError({keyword:"required",schemaPath:i,instancePath:u,params:{requiredProperties:y}})}function ZA(e,o,i,u){return L(i,"object")?Sy(u):L(i,"array")?nm(u):L(i,"boolean")?PM(u):L(i,"integer")?CM(u):L(i,"number")?Ey(u):L(i,"null")?$M(u):L(i,"string")?Ty(u):L(i,"bigint")?by(u):L(i,"constructor")?OM(u):L(i,"function")?MM(u):L(i,"symbol")?vM(u):L(i,"undefined")?dd(u):L(i,"void")?dd(u):De(!0)}function uh(e,o,i,u,p){return L(i,"object")?Vo(p):L(i,"array")?Ge(p):L(i,"boolean")?pn(p):L(i,"integer")?rm(p):L(i,"number")?Ot(p):L(i,"null")?ho(p):L(i,"string")?gt(p):L(i,"bigint")?Nr(p):L(i,"constructor")?ud(p):L(i,"function")?ms(p):L(i,"symbol")?cd(p):L(i,"undefined")?Ut(p):L(i,"void")?Ut(p):!0}function g1(e,o,i,u){return gd(i.map((p)=>ZA(e,o,p,u)))}function e0(e,o,i,u,p){return wa(i,(g)=>uh(e,o,g,u,p))}function t0(e,o,i,u){return Ge(i.type)?g1(e,o,i.type,u):ZA(e,o,i.type,u)}function r0(e,o,i,u){return Ge(i.type)?e0(e,o,i.type,i,u):uh(e,o,i.type,i,u)}function n0(e,o,i,u,p,g){return(Ge(p.type)?e0(e,o,p.type,p,g):uh(e,o,p.type,p,g))||o.AddError({keyword:"type",schemaPath:i,instancePath:u,params:{type:p.type}})}function o0(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetIndices"),[]),b=Ir(bt("indices","has"),[p]),E=Lt(e,o,i.unevaluatedItems,g),S=Ir(bt("context","AddIndex"),[p]),w=ls(u,De(0),[g,p],Sn(xr(b,E),S));return Ir(Vs(["context"],sm([vs("indices",y),im(w)])),["context"])}function s0(e,o,i,u){let p=o.GetIndices();return an(u,0,(g,y)=>(p.has(y)||kt(e,o,i.unevaluatedItems,g))&&o.AddIndex(y))}function i0(e,o,i,u,p,g){let y=o.GetIndices(),b=[];return An(g,0,(S,w)=>{let R=new qn,A=(y.has(w)||mr(e,R,i,u,p.unevaluatedItems,S))&&o.AddIndex(w);if(!A)b.push(w);return A})||o.AddError({keyword:"unevaluatedItems",schemaPath:i,instancePath:u,params:{unevaluatedItems:b}})}function a0(e,o,i,u){let[p,g]=[Vt(),Vt()],y=Ir(bt("context","GetKeys"),[]),b=Ir(bt("keys","has"),[p]),E=Ir(bt("context","AddKey"),[p]),S=Lt(e,o,i.unevaluatedProperties,g),w=ls(ky(u),De(0),[`[${p}, ${g}]`,"_"],xr(b,Sn(S,E)));return Ir(Vs(["context"],sm([vs("keys",y),im(w)])),["context"])}function u0(e,o,i,u){let p=o.GetKeys();return an(ln(u),0,([g,y])=>p.has(g)||kt(e,o,i.unevaluatedProperties,y)&&o.AddKey(g))}function c0(e,o,i,u,p,g){let y=o.GetKeys(),b=[];return An(ln(g),0,([S,w])=>{let R=new qn,A=y.has(S)||mr(e,R,i,u,p.unevaluatedProperties,w)&&o.AddKey(S);if(!A)b.push(S);return A})||o.AddError({keyword:"unevaluatedProperties",schemaPath:i,instancePath:u,params:{unevaluatedProperties:b}})}function ch(e){return!L(e.uniqueItems,!1)}function m0(e,o,i,u){if(!ch(i))return De(!0);let p=bt(hd("Set",[Ir(bt(u,"map"),[bt("Hashing","Hash")])]),"size"),g=bt(u,"length");return uo(p,g)}function p0(e,o,i,u){if(!ch(i))return!0;let p=new Set(u.map(Id)).size,g=u.length;return L(p,g)}function l0(e,o,i,u,p,g){if(!ch(p))return!0;let y=new Set,b=g.reduce((S,w,R)=>{let A=Id(w);if(y.has(A))return[...S,R];return y.add(A),S},[]);return L(b.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:i,instancePath:u,params:{duplicateItems:b}})}function vc(e,o){return Ac(e)&&(Ge(e.type)&&Ki(e.type.length,0)&&an(e.type,0,(i)=>L(i,o))||L(e.type,o))}function y1(e){return vc(e,"object")}function x1(e){return gn(e)&&(Co(e)||cc(e)||mc(e)||za(e)||Fs(e)||qs(e)||Ja(e)||la(e)||Ic(e)||ns(e)||ki(e))}function I1(e){return vc(e,"array")}function b1(e){return gn(e)&&(Wa(e)||Ns(e)||Rs(e)||yc(e)||Va(e)||Ds(e)||xi(e)||rs(e)||Ri(e)||Ei(e))}function E1(e){return vc(e,"string")}function S1(e){return gn(e)&&(pa(e)||xc(e)||ma(e)||da(e))}function w1(e){return vc(e,"number")||vc(e,"bigint")}function T1(e){return gn(e)&&(ts(e)||gc(e)||dc(e)||es(e)||bc(e))}function to(e,o,i,u){return o.UseUnevaluated()?Sn(Sn(o.Push(),Lt(e,o,i,u)),o.Pop()):Lt(e,o,i,u)}function Lt(e,o,i,u){e.Push(i);let p=[];if(_s(i))return WR(e,o,i,u);if(Ac(i))p.push(t0(e,o,i,u));if(x1(i)){let y=[];if(ns(i))y.push(QA(e,o,i,u));if(Co(i))y.push(DR(e,o,i,u));if(cc(i))y.push(ZR(e,o,i,u));if(mc(i))y.push(rk(e,o,i,u));if(za(i))y.push(sk(e,o,i,u));if(qs(i))y.push(vA(e,o,i,u));if(Fs(i))y.push(qA(e,o,i,u));if(Ja(i))y.push(UA(e,o,i,u));if(la(i))y.push(bA(e,o,i,u));if(Ic(i))y.push(cA(e,o,i,u));let b=Pn(y),E=xr(Un(Sy(u)),b);p.push(y1(i)?b:E)}if(b1(i)){let y=[];if(Wa(i))y.push(_R(e,o,i,u));if(Rs(i))y.push(XR(e,o,i,u));if(Ns(i))y.push(Xk(e,o,i,u));if(yc(i))y.push(tA(e,o,i,u));if(Va(i))y.push(sA(e,o,i,u));if(Ds(i))y.push(lA(e,o,i,u));if(xi(i))y.push(gA(e,o,i,u));if(rs(i))y.push(_A(e,o,i,u));if(Ei(i))y.push(m0(e,o,i,u));let b=Pn(y),E=xr(Un(nm(u)),b);p.push(I1(i)?b:E)}if(S1(i)){let y=[];if(xc(i))y.push(aA(e,o,i,u));if(pa(i))y.push(xA(e,o,i,u));if(ma(i))y.push(Wk(e,o,i,u));if(da(i))y.push(CA(e,o,i,u));let b=Pn(y),E=xr(Un(Ty(u)),b);p.push(E1(i)?b:E)}if(T1(i)){let y=[];if(dc(i))y.push(dk(e,o,i,u));if(es(i))y.push(hk(e,o,i,u));if(gc(i))y.push(nA(e,o,i,u));if(ts(i))y.push(fA(e,o,i,u));if(bc(i))y.push(SA(e,o,i,u));let b=Pn(y),E=xr(Un(xr(Ey(u),by(u))),b);p.push(w1(i)?b:E)}if(Rc(i))p.push(zA(e,o,i,u));if(Tc(i))p.push(KA(e,o,i,u));if(pc(i))p.push(uk(e,o,i,u));if(yp(i))p.push(VR(e,o,i,u));if(xp(i))p.push(pk(e,o,i,u));if(fc(i))p.push(Vk(e,o,i,u));if(Ec(i))p.push(TA(e,o,i,u));if(ic(i))p.push(jR(e,o,i,u));if(uc(i))p.push(GR(e,o,i,u));if(Sc(i))p.push(kA(e,o,i,u));if(Ri(i))p.push(xr(Un(nm(u)),o0(e,o,i,u)));if(ki(i))p.push(xr(Un(wy(u)),a0(e,o,i,u)));if(sc(i))p.push(vR(e,o,i,u));let g=Pn(p);return e.Pop(i),g}function So(e,o,i,u){return o.Push()&&kt(e,o,i,u)&&o.Pop()}function kt(e,o,i,u){e.Push(i);let p=_s(i)?Lf(e,o,i,u):(!Ac(i)||r0(e,o,i,u))&&(!(at(u)&&!Ge(u))||(!ns(i)||XA(e,o,i,u))&&(!Co(i)||qR(e,o,i,u))&&(!cc(i)||ek(e,o,i,u))&&(!mc(i)||nk(e,o,i,u))&&(!za(i)||ik(e,o,i,u))&&(!qs(i)||MA(e,o,i,u))&&(!Fs(i)||FA(e,o,i,u))&&(!Ja(i)||BA(e,o,i,u))&&(!la(i)||nh(e,o,i,u))&&(!Ic(i)||Yf(e,o,i,u)))&&(!Ge(u)||(!Wa(i)||LR(e,o,i,u))&&(!Rs(i)||Df(e,o,i,u))&&(!Ns(i)||Yk(e,o,i,u))&&(!yc(i)||Vf(e,o,i,u))&&(!Va(i)||Qf(e,o,i,u))&&(!Ds(i)||Zf(e,o,i,u))&&(!xi(i)||th(e,o,i,u))&&(!rs(i)||LA(e,o,i,u))&&(!Ei(i)||p0(e,o,i,u)))&&(!gt(u)||(!xc(i)||Xf(e,o,i,u))&&(!pa(i)||rh(e,o,i,u))&&(!ma(i)||zf(e,o,i,u))&&(!da(i)||ih(e,o,i,u)))&&(!(Ot(u)||Nr(u))||(!dc(i)||jf(e,o,i,u))&&(!es(i)||Uf(e,o,i,u))&&(!gc(i)||Jf(e,o,i,u))&&(!ts(i)||eh(e,o,i,u))&&(!bc(i)||oh(e,o,i,u)))&&(!Rc(i)||VA(e,o,i,u))&&(!Tc(i)||HA(e,o,i,u))&&(!pc(i)||ck(e,o,i,u))&&(!yp(i)||Nf(e,o,i,u))&&(!xp(i)||Ff(e,o,i,u))&&(!fc(i)||Jk(e,o,i,u))&&(!Ec(i)||sh(e,o,i,u))&&(!ic(i)||UR(e,o,i,u))&&(!uc(i)||KR(e,o,i,u))&&(!Sc(i)||AA(e,o,i,u))&&(!Ri(i)||(!Ge(u)||s0(e,o,i,u)))&&(!ki(i)||(!at(u)||u0(e,o,i,u)))&&(!sc(i)||MR(e,o,i,u));return e.Pop(i),p}function wo(e,o,i,u,p,g){return o.Push()&&mr(e,o,i,u,p,g)&&o.Pop()}function mr(e,o,i,u,p,g){if(o.AtCapacity())return!1;e.Push(p);let y=_s(p)?zR(e,o,i,u,p,g):!!(+(!Ac(p)||n0(e,o,i,u,p,g))&+(!(at(g)&&!Ge(g))||!!(+(!ns(p)||YA(e,o,i,u,p,g))&+(!Co(p)||FR(e,o,i,u,p,g))&+(!cc(p)||tk(e,o,i,u,p,g))&+(!mc(p)||ok(e,o,i,u,p,g))&+(!za(p)||ak(e,o,i,u,p,g))&+(!qs(p)||OA(e,o,i,u,p,g))&+(!Fs(p)||jA(e,o,i,u,p,g))&+(!Ja(p)||GA(e,o,i,u,p,g))&+(!la(p)||EA(e,o,i,u,p,g))&+(!Ic(p)||mA(e,o,i,u,p,g))))&+(!Ge(g)||!!(+(!Wa(p)||NR(e,o,i,u,p,g))&+(!Rs(p)||YR(e,o,i,u,p,g))&+(!Ns(p)||Zk(e,o,i,u,p,g))&+(!yc(p)||rA(e,o,i,u,p,g))&+(!Va(p)||iA(e,o,i,u,p,g))&+(!Ds(p)||dA(e,o,i,u,p,g))&+(!xi(p)||yA(e,o,i,u,p,g))&+(!rs(p)||NA(e,o,i,u,p,g))&+(!Ei(p)||l0(e,o,i,u,p,g))))&+(!gt(g)||!!(+(!xc(p)||uA(e,o,i,u,p,g))&+(!pa(p)||IA(e,o,i,u,p,g))&+(!ma(p)||zk(e,o,i,u,p,g))&+(!da(p)||$A(e,o,i,u,p,g))))&+(!(Ot(g)||Nr(g))||!!(+(!dc(p)||fk(e,o,i,u,p,g))&+(!es(p)||gk(e,o,i,u,p,g))&+(!gc(p)||oA(e,o,i,u,p,g))&+(!ts(p)||hA(e,o,i,u,p,g))&+(!bc(p)||wA(e,o,i,u,p,g))))&+(!Rc(p)||JA(e,o,i,u,p,g))&+(!Tc(p)||WA(e,o,i,u,p,g))&+(!pc(p)||mk(e,o,i,u,p,g))&+(!yp(p)||JR(e,o,i,u,p,g))&+(!xp(p)||lk(e,o,i,u,p,g))&+(!fc(p)||Qk(e,o,i,u,p,g))&+(!Ec(p)||RA(e,o,i,u,p,g))&+(!ic(p)||BR(e,o,i,u,p,g))&+(!uc(p)||HR(e,o,i,u,p,g))&+(!Sc(p)||PA(e,o,i,u,p,g))&+(!Ri(p)||(!Ge(g)||i0(e,o,i,u,p,g)))&+(!ki(p)||(!at(g)||c0(e,o,i,u,p,g))))&&(!sc(p)||OR(e,o,i,u,p,g));return e.Pop(p),y}var d0=[0],Vp=new Map,Mc=new Map;function R1(){return`${d0[0]++}`}function k1(e,o){if(!Vp.has(e))Vp.set(e,new Map);let i=Vp.get(e);if(i.has(o))return i.get(o);let u=R1();return i.set(o,u),u}function A1(e,o,i,u){return e.UseUnevaluated()?Ir(`check_${i}`,["context",u]):Ir(`check_${i}`,[u])}function P1(e,o,i,u){let p=Lt(e,o,i,"value");return o.UseUnevaluated()?vs(`check_${u}`,Vs(["context","value"],p)):vs(`check_${u}`,Vs(["value"],p))}function f0(){d0[0]=0,Vp.clear(),Mc.clear()}function h0(){return[...Mc.values()]}function js(e,o,i,u){let p=k1(i,e.LexicalBaseURL()),g=A1(o,i,p,u);if(Mc.has(p))return g;return Mc.set(p,""),Mc.set(p,P1(e,o,i,p)),g}function C1(e,o){return at(o)&&!wu(e)?o[e]:void 0}function $1(e,o){return e.reduce((i,u)=>C1(u,i),o)}function v1(e){if(L(e.length,0))return[];let o=e.split("/").map((i)=>i.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function M1(e,o){let i=v1(o);return $1(i,e)}var Qp="https://json-schema.org";function y0(e,o){if(at(e)&&Ls(e)&&L(e.$dynamicAnchor,o))return e;if(at(e))for(let i of we(e)){let u=y0(e[i],o);if(u)return u}return}function mh(e,o,i){if(L(e,i))return o.href;let u=gn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(Ge(e))for(let p of e){let g=mh(p,u,i);if(!Ut(g))return g}else if(at(e))for(let p of we(e)){let g=mh(e[p],u,i);if(!Ut(g))return g}return}function O1(e,o,i){if(L(e.$id,i.hash))return e;let u=new URL(i.href,o.href);if(L(o.pathname,u.pathname))return i.hash.startsWith("#")?x0(e,i):e;return}function _1(e,o,i){let u=new URL(`#${e.$anchor}`,o.href),p=new URL(i.href,o.href);return L(u.href,p.href)?e:void 0}function L1(e,o,i){let u=new URL(`#${e.$dynamicAnchor}`,o.href),p=new URL(i.href,o.href);return L(u.href,p.href)?e:void 0}function x0(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 M1(e,i)}function N1(e,o,i){if(Eo(e)){let u=O1(e,o,i);if(!Ut(u))return u}if(ac(e)){let u=_1(e,o,i);if(!Ut(u))return u}if(Ls(e)){let u=L1(e,o,i);if(!Ut(u))return u}return x0(e,i)}function D1(e,o,i){return e.reduce((u,p)=>{let g=Xp(p,o,i);return!Ut(g)?g:u},void 0)}function q1(e){return L(e,"const")||L(e,"enum")}function F1(e,o,i){return we(e).reduce((u,p)=>{if(q1(p))return u;let g=Xp(e[p],o,i);return!Ut(g)?g:u},void 0)}function Xp(e,o,i){let u=gn(e)&&Eo(e)?new URL(e.$id,o.href):o;if(gn(e)){let p=N1(e,u,i);if(!Ut(p))return p}if(Ge(e))return D1(e,u,i);if(at(e))return F1(e,u,i);return}function j1(e,o,i){return mh(e,new URL(o||".",Qp),i)}function U1(e,o,i,u){let p=Yp(e,o,i,u,!1);return gn(p)&&Eo(p)?p:void 0}function g0(e){return e.href.split("#")[0]}function B1(e,o){return fe(e,o)?e[o]:void 0}function G1(e,o,i){return Xp(e,o,i)}function K1(e,o,i){let u=g0(i);if(L(u,g0(o)))return;if(!fe(e,u))return;let p=e[u],g=gn(p)&&Eo(p)?new URL(p.$id,u):new URL(u);return L(i.hash,"")?p:Xp(p,g,i)}function H1(e,o,i,u,p){if(!u.$ref.startsWith("#"))return;if(fe(e,"$schema"))return;let g=j1(o,i,p);if(Ut(g)||L(g,i))return;return{target:p,base:g,root:o}}function W1(e,o,i){let u=e[o];if(!gn(u))return;return{target:i,base:o,root:u}}function z1(e,o,i,u,p){let g=p?W1(e.context,u,i):void 0;if(!Ut(g))return g;return H1(e.root,e.lexicalSchema,e.referenceBase,o,i)}function V1(e,o,i,u,p,g){if(Eo(p))return;let y=U1(e,o,i,u);if(!y||g.includes(y))return;return{target:p,resource:y}}function Yp(e,o,i,u,p=!0){let g=new URL(i||".",Qp),y=p&&Eo(o)?new URL(o.$id,g):g,b=new URL(u,y.href);return B1(e,u)??G1(o,y,b)??K1(e,y,b)}function J1(e,o,i,u,p,g){let y=new URL(i||".",Qp),b=p.$dynamicRef.startsWith("#")?u:o,E=Yp(e,b,i,p.$dynamicRef,!1);if(Ut(E)){let R=new URL(p.$dynamicRef,y).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let A=decodeURIComponent(R.slice(1));return g.find((C)=>L(C.$dynamicAnchor,A))??y0(o,A)}return}if(!gn(E)||!Ls(E))return E;if(new URL(p.$dynamicRef,y).hash.startsWith("#/"))return E;return g.find((R)=>L(R.$dynamicAnchor,E.$dynamicAnchor))??E}function Q1(e,o){let i=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:i,p=Yp(e.context,u,e.referenceBase,o.$ref,!1);if(!p||!gn(p))return{schema:p};let g=new URL(o.$ref,e.referenceBase).href.split("#")[0],y=!L(g,e.resourceBase),b=z1(e,o,p,g,y),E=y?V1(e.context,e.root,e.referenceBase,g,p,e.ids):void 0;return{schema:p,retrievedResource:b,resolvedResource:E}}function X1(e,o){let i=wc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Yp(e.context,i,e.lexicalBase,o.$recursiveRef,!1)}function Y1(e,o){return J1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var _r=function(e,o,i,u){if(i==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return i==="m"?u:i==="a"?u.call(e):u?u.value:o.get(e)},Sr,el,T0,fh,Zp,I0,b0,E0,S0,lh,dh,hh,gh,w0,R0;class $i{constructor(e,o){Sr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return _r(this,Sr,"m",fh).call(this,this.ids)}Push(e){if(!gn(e))return;if(Eo(e))_r(this,Sr,"m",hh).call(this,e);if(ac(e))this.anchors.push(e);if(wc(e))this.recursiveAnchors.push(e);if(Ls(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!gn(e))return;if(Eo(e))_r(this,Sr,"m",gh).call(this,e);if(ac(e))this.anchors.pop();if(wc(e))this.recursiveAnchors.pop();if(Ls(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();_r(this,Sr,"m",R0).call(this,e)}Ref(e){let o=Q1(_r(this,Sr,"m",el).call(this),e);return _r(this,Sr,"m",T0).call(this,o),o.schema}RecursiveRef(e){let o=X1(_r(this,Sr,"m",el).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=Y1(_r(this,Sr,"m",el).call(this),e);if(o)this.pendingResource=!0;return o}}Sr=new WeakSet,el=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:_r(this,Sr,"m",b0).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:_r(this,Sr,"m",I0).call(this),resourceBase:_r(this,Sr,"m",Zp).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},T0=function(o){if(!Ut(o.schema))this.pendingResource=!0;if(!Ut(o.resolvedResource))_r(this,Sr,"m",w0).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!Ut(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},fh=function(o){let i=this.retrievedFrames[this.retrievedFrames.length-1],u=i?new URL(i.base):new URL(Qp);return(i?o.slice(i.idDepth):o).reduce((g,y)=>new URL(y.$id,g),u).href},Zp=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return _r(this,Sr,"m",fh).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((i,u)=>new URL(u.$id,i),new URL(o.base)).href},I0=function(){if(this.retrievedFrames.length>0)return _r(this,Sr,"m",Zp).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return _r(this,Sr,"m",Zp).call(this)},b0=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},E0=function(o){o.forEach((i)=>_r(this,Sr,"m",lh).call(this,i,!1))},S0=function(o){o.forEach((i)=>_r(this,Sr,"m",dh).call(this,i,!1))},lh=function e(o,i=!0){if(_s(o))return;if(Ge(o))return _r(this,Sr,"m",E0).call(this,o);if(!gn(o))return;let u=o;if(!i&&Eo(u))return;if(!i&&Ls(u))this.dynamicAnchors.push(u);for(let p of we(u))_r(this,Sr,"m",e).call(this,u[p],!1)},dh=function e(o,i=!0){if(_s(o))return;if(Ge(o))return _r(this,Sr,"m",S0).call(this,o);if(!gn(o))return;let u=o;if(!i&&Eo(u))return;if(!i&&Ls(u))this.dynamicAnchors.pop();for(let p of we(u))_r(this,Sr,"m",e).call(this,u[p],!1)},hh=function(o){this.ids.push(o);let i=this.pendingResource;if(this.pendingResource=!1,i)this.resourceIds.push(o);_r(this,Sr,"m",lh).call(this,o,!0)},gh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&L(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();_r(this,Sr,"m",dh).call(this,o,!0)},w0=function(o,i){_r(this,Sr,"m",hh).call(this,i),this.resolvedResources.set(o,i)},R0=function(o){if(!this.resolvedResources.has(o))return;let i=this.resolvedResources.get(o);_r(this,Sr,"m",gh).call(this,i),this.resolvedResources.delete(o)};function Z1(e){let o=e.Functions().join(`;
31
- `),i=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${i.join("; ")} }`}function ej(e,o){return Wy("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(_n,K,eu,Yi,e.External().variables)}function tj(e){let o=new $i(e.Context(),e.Schema()),i=new _n;return(u)=>kt(o,i,e.Schema(),u)}function rj(e,o){return Hy()?ej(e,o):tj(e)}class k0{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 A0{constructor(e,o,i,u,p,g){this.context=e,this.schema=o,this.external=i,this.functions=u,this.entry=p,this.useUnevaluated=g}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=Z1(this),o=rj(this,e);return new k0(Hy(),e,o)}}function tl(...e){let[o,i]=wn(e,{2:(E,S)=>[E,S],1:(E)=>[{},E]});CR(),f0();let u=new $i(o,i),p=new Mf(PR(o,i)),g=js(u,p,i,"value"),y=h0(),b=$R();return new A0(o,i,b,y,g,p.UseUnevaluated())}function rl(...e){let[o,i,u]=wn(e,{3:(w,R,A)=>[w,R,A],2:(w,R)=>[{},w,R]}),p=new $i(o,i),g=new qn,y=mr(p,g,"#","",i,u),b=g.GetErrors(),E=tx(),S=b.map((w)=>({...w,message:E(w)}));return[y,S]}function xh(...e){let[o,i,u]=wn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),p=new $i(o,i),g=new _n;return kt(p,g,i,u)}function Xt(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return xh(o,i,u)}function ks(...e){let[o,i,u]=wn(e,{3:(y,b,E)=>[y,b,E],2:(y,b)=>[{},y,b]}),[p,g]=rl(o,i,u);return g}class fa extends Error{constructor(e,o,i){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:i,value:o},writable:!1,configurable:!1,enumerable:!1})}}function P0(e,o,i){if(!Ge(i))return i;return i.map((u)=>yn(e,o.items,u))}function C0(e,o,i){return yn({...e,...o.$defs},un(o.$ref),i)}function sj(e,o){let i=fe(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Po(e,o),p=Rn(u);return Qe(p)?lp(p,i):p}function $0(e,o,i){let u=sj(e,o);return yn(e,u,i)}function nl(e){return fe(e,"additionalProperties")?e.additionalProperties:void 0}function v0(e,o,i){if(!at(i)||Ge(i))return i;let u=nl(o);for(let p of we(i)){if(fe(o.properties,p)){i[p]=yn(e,o.properties[p],i[p]);continue}if(pn(u)&&L(u,!0)||Cr(u)&&Xt(e,u,i[p])){i[p]=yn(e,u,i[p]);continue}delete i[p]}return i}function M0(e,o,i){if(!at(i))return i;let u=nl(o),[p,g]=[new RegExp(hn(o)),fr(o)];for(let y of we(i)){if(p.test(y)){i[y]=yn(e,g,i[y]);continue}if(pn(u)&&L(u,!0)||Cr(u)&&Xt(e,u,i[y])){i[y]=yn(e,u,i[y]);continue}delete i[y]}return i}function O0(e,o,i){return fe(e,o.$ref)?yn(e,e[o.$ref],i):i}function _0(e,o,i){if(!Ge(i))return i;let u=Math.min(i.length,o.items.length);for(let p=0;p<u;p++)i[p]=yn(e,o.items[p],i[p]);return Ki(i.length,u)?i.slice(0,u):i}function Vr(e){return Ra(e)}function L0(e,o,i){for(let u of o.anyOf){let p=yn(e,u,Vr(i));if(Xt(e,u,p))return p}return i}function yn(e,o,i){return wt(o)?P0(e,o,i):Qt(o)?C0(e,o,i):ze(o)?$0(e,o,i):Qe(o)?v0(e,o,i):Gt(o)?M0(e,o,i):qt(o)?O0(e,o,i):mt(o)?_0(e,o,i):xe(o)?L0(e,o,i):i}function ij(e,o){for(let i of we(e)){if(fe(o,i))continue;o[i]=e[i]}return o}function aj(e){let o={};for(let i of we(e))o[i]=Oc(e[i]);return o}function uj(e){return Ih(cR(e))}function Ih(e){return e.map((o)=>Oc(o))}function Oc(e){let o=wt(e)?B(Oc(e.items),ka(e)):ze(e)?Cn(Ih(e.allOf)):xe(e)?m(uj(e.anyOf)):Qe(e)?l(aj(e.properties)):Gt(e)?bs(ri(e),Oc(fr(e))):mt(e)?Ur(Ih(e.items)):e;return ij(e,o)}function tu(e){return Oc(e)}function _o(...e){let[o,i,u]=wn(e,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]}),p=Jo().unionPrioritySort?tu(i):i;return yn(o,p,u)}function fo(e){return at(e)&&fe(e,"value")}function We(e){return{value:e}}function wr(){return}function cj(e){return Ge(e)?We(e):We([e])}function mj(e){return L(e,!0)?We(BigInt(1)):We(BigInt(0))}var pj=/^-?(0|[1-9]\d*)n$/,lj=/^-?(0|[1-9]\d*)\.\d+$/,dj=/^-?(0|[1-9]\d*)$/;function fj(e){return pj.test(e)}function hj(e){return lj.test(e)}function gj(e){return dj.test(e)}function yj(e){let o=e.toLowerCase();return fj(e)?We(BigInt(e.slice(0,e.length-1))):hj(e)?We(BigInt(e.split(".")[0])):gj(e)?We(BigInt(e)):L(o,"false")?We(BigInt(0)):L(o,"true")?We(BigInt(1)):wr()}function ol(e){return Nr(e)?We(e):pn(e)?mj(e):Ot(e)?We(BigInt(Math.trunc(e))):ho(e)?We(BigInt(0)):gt(e)?yj(e):Ut(e)?We(BigInt(0)):wr()}function xj(e){return L(e,BigInt(0))?We(!1):L(e,BigInt(1))?We(!0):wr()}function Ij(e){return L(e,0)?We(!1):L(e,1)?We(!0):wr()}function bj(e){return L(e.toLowerCase(),"false")?We(!1):L(e.toLowerCase(),"true")?We(!0):L(e,"0")?We(!1):L(e,"1")?We(!0):wr()}function N0(e){return Nr(e)?xj(e):pn(e)?We(e):Ot(e)?Ij(e):ho(e)?We(!1):gt(e)?bj(e):Ut(e)?We(!1):wr()}function Ej(e){return L(e,BigInt(0))?We(null):wr()}function Sj(e){return L(e,!1)?We(null):wr()}function wj(e){return L(e,0)?We(null):wr()}function Tj(e){let o=e.toLowerCase();return L(o,"undefined")||L(o,"null")||L(e,"")||L(e,"0")?We(null):wr()}function Rj(e){return Nr(e)?Ej(e):pn(e)?Sj(e):Ot(e)?wj(e):ho(e)?We(null):gt(e)?Tj(e):Ut(e)?We(null):wr()}var D0=BigInt(Number.MAX_SAFE_INTEGER),q0=BigInt(Number.MIN_SAFE_INTEGER);function kj(e){return e<=D0&&e>=q0?We(Number(e)):wr()}function Aj(e){return We(e?1:0)}function Pj(e){let o=+e;if(Ot(o))return We(o);let i=e.toLowerCase();if(L(i,"false"))return We(0);if(L(i,"true"))return We(1);let u=ol(e);if(fo(u))return u.value<=D0&&u.value>=q0?We(Number(u.value)):wr();return wr()}function bh(e){return Nr(e)?kj(e):pn(e)?Aj(e):Ot(e)?We(e):ho(e)?We(0):gt(e)?Pj(e):Ut(e)?We(0):wr()}function F0(e){return Nr(e)?We(e.toString()):pn(e)?We(e.toString()):Ot(e)?We(e.toString()):ho(e)?We("null"):gt(e)?We(e):Ut(e)?We(""):wr()}function Cj(e){return L(e,BigInt(0))?We(void 0):wr()}function $j(e){return L(e,!1)?We(void 0):wr()}function vj(e){return L(e,0)?We(void 0):wr()}function Mj(e){let o=e.toLowerCase();return L(o,"undefined")||L(o,"null")||L(e,"")||L(e,"0")?We(void 0):wr()}function j0(e){return Nr(e)?Cj(e):pn(e)?$j(e):Ot(e)?vj(e):ho(e)?We(void 0):gt(e)?Mj(e):Ut(e)?We(e):wr()}function U0(e,o,i){return cj(i).value.map((p)=>Yr(e,o.items,p))}function B0(e,o,i){let u=ol(i);return fo(u)?u.value:i}function G0(e,o,i){let u=N0(i);return fo(u)?u.value:i}function K0(e,o,i){return Yr({...e,...o.$defs},un(o.$ref),i)}function H0(e,o,i){return Yr(e,Rn(o),i)}function W0(e,o,i){let u=bh(i);return fo(u)?Math.trunc(u.value):i}function z0(e,o,i){let u=Po(e,o),p=Rn(u);return Yr(e,p,i)}function Oj(e,o,i){let u=ol(i);return fo(u)&&L(o.const,u.value)?u.value:i}function _j(e,o,i){let u=N0(i);return fo(u)&&L(o.const,u.value)?u.value:i}function Lj(e,o,i){let u=bh(i);return fo(u)&&L(o.const,u.value)?u.value:i}function Nj(e,o,i){let u=F0(i);return fo(u)&&L(o.const,u.value)?u.value:i}function V0(e,o,i){if(L(o.const,i))return i;return px(o)?Oj(e,o,i):lx(o)?_j(e,o,i):gm(o)?Lj(e,o,i):ym(o)?Nj(e,o,i):jr()}function J0(e,o,i){let u=Rj(i);return fo(u)?u.value:i}function Q0(e,o,i){let u=bh(i);return fo(u)?u.value:i}function sl(e,o,i,u){let p=we(u);for(let[g,y]of o)for(let b of p)if(!g.test(b))u[b]=Yr(e,i,u[b]);return u}function _c(e,o,i){return cn(e)&&Ut(i[o])}function Dj(e,o,i){let u=pd(o.properties),p=we(i);for(let[g,y]of u)for(let b of p){if(!g.test(b)||_c(y,b,i))continue;i[b]=Yr(e,y,i[b])}return fe(o,"additionalProperties")&&at(o.additionalProperties)?sl(e,u,o.additionalProperties,i):i}function X0(e,o,i){return Vo(i)?Dj(e,o,i):i}function qj(e,o,i){let u=pd(o.patternProperties),p=we(i);for(let[g,y]of u)for(let b of p)if(g.test(b))i[b]=Yr(e,y,i[b]);return fe(o,"additionalProperties")&&at(o.additionalProperties)?sl(e,u,o.additionalProperties,i):i}function Y0(e,o,i){return Vo(i)?qj(e,o,i):i}function Z0(e,o,i){return fe(e,o.$ref)?Yr(e,e[o.$ref],i):i}function eP(e,o,i){let u=F0(i);return fo(u)?u.value:i}function tP(e,o,i){return Yr(e,Rn(o),i)}function rP(e,o,i){if(!Ge(i))return i;for(let u=0;u<Math.min(o.items.length,i.length);u++)i[u]=Yr(e,o.items[u],i[u]);return i}function nP(e,o,i){let u=j0(i);return fo(u)?u.value:i}function oP(e,o,i){if(o.anyOf.some((y)=>Xt(e,y,i)))return i;let g=o.anyOf.map((y)=>Yr(e,y,Vr(i))).find((y)=>Xt(e,o,y));return Ut(g)?i:g}function sP(e,o,i){let u=j0(i);return fo(u)?void 0:i}function Yr(e,o,i){return wt(o)?U0(e,o,i):mo(o)?B0(e,o,i):Wn(o)?G0(e,o,i):Qt(o)?K0(e,o,i):on(o)?H0(e,o,i):fn(o)?W0(e,o,i):ze(o)?z0(e,o,i):yt(o)?V0(e,o,i):xs(o)?J0(e,o,i):kr(o)?Q0(e,o,i):Qe(o)?X0(e,o,i):Gt(o)?Y0(e,o,i):qt(o)?Z0(e,o,i):sn(o)?eP(e,o,i):ur(o)?tP(e,o,i):mt(o)?rP(e,o,i):Zo(o)?nP(e,o,i):xe(o)?oP(e,o,i):po(o)?sP(e,o,i):i}function as(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return Yr(o,i,u)}function iP(e,o,i){if(!Ge(i))return i;for(let u=0;u<i.length;u++)i[u]=xn(e,o.items,i[u]);return i}function aP(e,o,i){return xn({...e,...o.$defs},un(o.$ref),i)}function uP(e,o){if(!Ut(o))return o;return ms(e.default)?e.default():Vr(e.default)}function cP(e,o,i){let u=Po(e,o),p=Rn(u);return xn(e,p,i)}function mP(e,o,i){if(!at(i))return i;let u=we(o.properties);for(let p of u){let g=xn(e,o.properties[p],i[p]);if(Ut(g)&&(cn(o.properties[p])||!fe(o.properties[p],"default")))continue;i[p]=g}if(!Co(o)||pn(o.additionalProperties))return i;for(let p of we(i)){if(u.includes(p))continue;i[p]=xn(e,o.additionalProperties,i[p])}return i}function pP(e,o,i){if(!at(i))return i;let[u,p]=[new RegExp(hn(o)),fr(o)];for(let g of we(i)){if(!(u.test(g)&&bo(p)))continue;i[g]=xn(e,p,i[g])}if(!Co(o))return i;for(let g of we(i)){if(u.test(g))continue;i[g]=xn(e,o.additionalProperties,i[g])}return i}function lP(e,o,i){return fe(e,o.$ref)?xn(e,e[o.$ref],i):i}function dP(e,o,i){if(!Ge(i))return i;let[u,p]=[o.items,Math.max(o.items.length,i.length)];for(let g=0;g<p;g++)if(g<u.length)i[g]=xn(e,u[g],i[g]);return i}function fP(e,o,i){for(let u of o.anyOf){let p=xn(e,u,Vr(i));if(Xt(e,u,p))return p}return i}function xn(e,o,i){let u=bo(o)?uP(o,i):i;return wt(o)?iP(e,o,u):Qt(o)?aP(e,o,u):ze(o)?cP(e,o,u):Qe(o)?mP(e,o,u):Gt(o)?pP(e,o,u):qt(o)?lP(e,o,u):mt(o)?dP(e,o,u):xe(o)?fP(e,o,u):u}function Us(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return xn(o,i,u)}function ru(e){return(...o)=>{let[i,u,p]=wn(o,{3:(g,y,b)=>[g,y,b],2:(g,y)=>[{},g,y]});return e.reduce((g,y)=>y(i,u,g),p)}}function Fj(e,o,i){return o["~codec"].decode(i)}function jj(e,o,i){return o["~codec"].encode(i)}function Tr(e,o,i,u){if(!Hn(i))return u;return L(e,"Decode")?Fj(o,i,u):jj(o,i,u)}function Uj(e,o,i,u){if(!Ge(u))return u;for(let p=0;p<u.length;p++)u[p]=Pr(e,o,i.items,u[p]);return Tr(e,o,i,u)}function Bj(e,o,i,u){let p=Tr(e,o,i,u);if(!Ge(p))return p;for(let g=0;g<p.length;g++)p[g]=Pr(e,o,i.items,p[g]);return p}function hP(e,o,i,u){return L(e,"Decode")?Uj(e,o,i,u):Bj(e,o,i,u)}function gP(e,o,i,u){return u=Pr(e,{...o,...i.$defs},un(i.$ref),u),Tr(e,o,i,u)}function yP(e){return e.reduce((o,i)=>({...o,...i}),{})}function xP(e,o){for(let i of o)if(!Ta(e,i))return i;return e}function Gj(e,o,i,u){if(L(i.allOf.length,0))return Tr(e,o,i,u);let p=i.allOf.map((b)=>Pr(e,o,b,_o(b,Vr(u)))),y=p.every((b)=>at(b))?yP(p):xP(u,p);return Tr(e,o,i,y)}function Kj(e,o,i,u){if(L(i.allOf.length,0))return Tr(e,o,i,u);let p=Tr(e,o,i,u),g=i.allOf.map((b)=>Pr(e,o,b,_o(b,Vr(p))));if(g.every((b)=>at(b)))return yP(g);return xP(p,g)}function IP(e,o,i,u){return L(e,"Decode")?Gj(e,o,i,u):Kj(e,o,i,u)}function Hj(e,o,i,u){if(!Vo(u))return u;for(let p of we(i.properties)){if(!fe(u,p)||_c(i.properties[p],p,u))continue;u[p]=Pr(e,o,i.properties[p],u[p])}return Tr(e,o,i,u)}function Wj(e,o,i,u){let p=Tr(e,o,i,u);if(!Vo(p))return p;for(let g of we(i.properties)){if(!fe(p,g)||_c(i.properties[g],g,p))continue;p[g]=Pr(e,o,i.properties[g],p[g])}return p}function bP(e,o,i,u){return L(e,"Decode")?Hj(e,o,i,u):Wj(e,o,i,u)}function zj(e,o,i,u){if(!Vo(u))return u;let p=new RegExp(hn(i));for(let g of we(u)){if(!p.test(g))continue;u[g]=Pr(e,o,fr(i),u[g])}return Tr(e,o,i,u)}function Vj(e,o,i,u){let p=Tr(e,o,i,u);if(!Vo(p))return p;let g=new RegExp(hn(i));for(let y of we(p)){if(!g.test(y))continue;p[y]=Pr(e,o,fr(i),p[y])}return p}function EP(e,o,i,u){return L(e,"Decode")?zj(e,o,i,u):Vj(e,o,i,u)}function SP(e,o,i,u){return fe(o,i.$ref)?Pr(e,o,o[i.$ref],u):u}function wP(e,o,i,u){return L(e,"Decode")?Tr(e,o,i,SP(e,o,i,u)):SP(e,o,i,Tr(e,o,i,u))}function Jj(e,o,i,u){if(!Ge(u))return u;for(let p=0;p<Math.min(i.items.length,u.length);p++)u[p]=Pr(e,o,i.items[p],u[p]);return Tr(e,o,i,u)}function Qj(e,o,i,u){let p=Tr(e,o,i,u);if(!Ge(p))return u;for(let g=0;g<Math.min(i.items.length,p.length);g++)p[g]=Pr(e,o,i.items[g],p[g]);return p}function TP(e,o,i,u){return L(e,"Decode")?Jj(e,o,i,u):Qj(e,o,i,u)}function Xj(e,o,i,u){for(let p of i.anyOf){if(!Xt(o,p,u))continue;let g=Pr(e,o,p,u);return Tr(e,o,i,g)}return u}function Yj(e,o,i,u){let p=Tr(e,o,i,u);for(let g of i.anyOf){let y=Pr(e,o,g,Vr(p));if(!Xt(o,g,y))continue;return y}return p}function RP(e,o,i,u){return L(e,"Decode")?Xj(e,o,i,u):Yj(e,o,i,u)}function Pr(e,o,i,u){return wt(i)?hP(e,o,i,u):Qt(i)?gP(e,o,i,u):ze(i)?IP(e,o,i,u):Qe(i)?bP(e,o,i,u):Gt(i)?EP(e,o,i,u):qt(i)?wP(e,o,i,u):mt(i)?TP(e,o,i,u):xe(i)?RP(e,o,i,u):Tr(e,o,i,u)}class kP extends fa{constructor(e,o){super("Decode",e,o)}}function Zj(e,o,i){if(!Xt(e,o,i))throw new kP(i,ks(e,o,i));return i}function eU(e,o,i){let u=Jo().unionPrioritySort?tu(o):o;return Pr("Decode",e,u,i)}var tU=ru([(e,o,i)=>Vr(i),(e,o,i)=>Us(e,o,i),(e,o,i)=>as(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>Zj(e,o,i),(e,o,i)=>eU(e,o,i)]);function Eh(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return tU(o,i,u)}class AP extends fa{constructor(e,o){super("Encode",e,o)}}function rU(e,o,i){if(!Xt(e,o,i))throw new AP(i,ks(e,o,i));return i}function nU(e,o,i){let u=Jo().unionPrioritySort?tu(o):o;return Pr("Encode",e,u,i)}var oU=ru([(e,o,i)=>Vr(i),(e,o,i)=>nU(e,o,i),(e,o,i)=>Us(e,o,i),(e,o,i)=>as(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>rU(e,o,i)]);function Sh(...e){let[o,i,u]=wn(e,{3:(p,g,y)=>[p,g,y],2:(p,g)=>[{},p,g]});return oU(o,i,u)}function sU(e,o){return Hn(o)||Oi(e,o.items)}function iU(e,o){return Hn(o)||PP({...e,...o.$defs},un(o.$ref))}function aU(e,o){return Hn(o)||o.allOf.some((i)=>Oi(e,i))}function uU(e,o){return Hn(o)||we(o.properties).some((i)=>Oi(e,o.properties[i]))}function cU(e,o){return Hn(o)||Oi(e,fr(o))}function PP(e,o){if(wh.has(o.$ref))return!1;return wh.add(o.$ref),Hn(o)||fe(e,o.$ref)&&Oi(e,e[o.$ref])}function mU(e,o){return Hn(o)||o.items.some((i)=>Oi(e,i))}function pU(e,o){return Hn(o)||o.anyOf.some((i)=>Oi(e,i))}function Oi(e,o){return wt(o)?sU(e,o):Qt(o)?iU(e,o):ze(o)?aU(e,o):Qe(o)?uU(e,o):Gt(o)?cU(e,o):qt(o)?PP(e,o):mt(o)?mU(e,o):xe(o)?pU(e,o):Hn(o)}var wh=new Set;function Th(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return wh.clear(),Oi(o,i)}class us extends Error{constructor(e,o){super(o);this.type=e}}function CP(e,o){return ms(o.default)?o.default(o):at(o.default)?Vr(o.default):o.default}function $P(e,o){if(Ei(o)&&!bo(o))throw new us(o,"Arrays with uniqueItems constraints must specify a default annotation");let i=xi(o)?o.minItems:0;return Array.from({length:i},()=>Zr(e,o.items))}function vP(e,o){return es(o)?BigInt(o.exclusiveMinimum)+BigInt(1):ts(o)?BigInt(o.minimum):BigInt(0)}function MP(e,o){return!1}function OP(e,o){let i=Zr(e,o.instanceType);return class{constructor(){Object.assign(this,i)}}}function _P(e,o){return Zr({...e,...o.$defs},un(o.$ref))}function LP(e,o){return Zr(e,Rn(o))}function NP(e,o){let i=Zr(e,o.returnType);return()=>i}function DP(e,o){return es(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:ts(o)?o.minimum:0}function qP(e,o){let i=Po(e,o),u=Rn(i);return Zr(e,u)}function FP(e,o){return o.const}function jP(e,o){throw new us(o,"Cannot create TNever types")}function UP(e,o){return null}function BP(e,o){return es(o)&&Ot(o.exclusiveMinimum)?o.exclusiveMinimum+1:ts(o)?o.minimum:0}function GP(e,o){return(Ut(o.required)?[]:o.required).reduce((u,p)=>({...u,[p]:Zr(e,o.properties[p])}),{})}function KP(e,o){if(la(o)&&!bo(o))throw new us(o,"Record with the minProperties constraint must have a default annotation");return{}}function HP(e,o){return fe(e,o.$ref)?Zr(e,e[o.$ref]):(()=>{throw new us(o,"Unable to deref Ref")})()}function WP(e,o){if((da(o)||ma(o))&&!bo(o))throw Error("Strings with format or pattern constraints must specify default");let u=pa(o)?o.minLength:0;return"".padEnd(u)}function zP(e,o){return Symbol()}function VP(e,o){let i=Mu(o.pattern);if(sn(i))throw new us(o,"Unable to create TemplateLiteral due to infinite type expansion");return Zr(e,i)}function JP(e,o){return Array.from({length:o.minItems},(i,u)=>Zr(e,o.items[u]))}function QP(e,o){return}function XP(e,o){if(L(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Zr(e,o.anyOf[0])}function YP(e,o){return}function Zr(e,o){return bo(o)?CP(e,o):wt(o)?$P(e,o):mo(o)?vP(e,o):Wn(o)?MP(e,o):en(o)?OP(e,o):Qt(o)?_P(e,o):on(o)?LP(e,o):tn(o)?NP(e,o):fn(o)?DP(e,o):ze(o)?qP(e,o):yt(o)?FP(e,o):co(o)?jP(e,o):xs(o)?UP(e,o):kr(o)?BP(e,o):Qe(o)?GP(e,o):Gt(o)?KP(e,o):qt(o)?HP(e,o):sn(o)?WP(e,o):Is(o)?zP(e,o):ur(o)?VP(e,o):mt(o)?JP(e,o):Zo(o)?QP(e,o):xe(o)?XP(e,o):po(o)?YP(e,o):void 0}function As(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return Zr(o,i)}class il extends fa{constructor(e,o){super("Parse",e,o)}}function lU(e,o,i){if(!Xt(e,o,i))throw new il(i,ks(e,o,i));return i}var ZP=ru([(e,o,i)=>Vr(i),(e,o,i)=>Us(e,o,i),(e,o,i)=>as(e,o,i),(e,o,i)=>_o(e,o,i),(e,o,i)=>lU(e,o,i)]);var fU=l({type:s("insert"),path:a(),value:Rr()}),hU=Object({type:s("update"),path:a(),value:Rr()}),gU=l({type:s("delete"),path:a()}),OOe=m([fU,hU,gU]);class al{constructor(e,o){this.hasCodec=Th(e,o),this.buildResult=tl(e,o),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(Jo().correctiveParse)return ZP(this.Context(),this.Type(),e);throw new il(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return ks(this.Context(),this.Type(),e)}Clean(e){return _o(this.Context(),this.Type(),e)}Convert(e){return as(this.Context(),this.Type(),e)}Create(){return As(this.Context(),this.Type())}Default(e){return Us(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Eh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Sh(this.Context(),this.Type(),e):this.Parse(e)}}function kh(...e){let[o,i]=wn(e,{2:(u,p)=>[u,p],1:(u)=>[{},u]});return new al(o,i)}var tC=new WeakMap,IU=Symbol.for("TypeBox.Kind");function bU(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function EU(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 Ah(e){try{return nC(e)}catch{return}}function SU(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 wU(e,o){let i=o.properties,u=new Set(i?Object.keys(i):[]);if(i)for(let[p,g]of Object.entries(i)){if(!(p in e))continue;e[p]=ga(e[p],g)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[p,g]of Object.entries(e)){if(u.has(p))continue;e[p]=ga(g,o.additionalProperties)}}function TU(e,o){if(Array.isArray(o.items)){for(let i=0;i<e.length;i++){let u=o.items[i];if(!u)continue;e[i]=ga(e[i],u)}return}if(o.items&&typeof o.items==="object")for(let i=0;i<e.length;i++)e[i]=ga(e[i],o.items)}function rC(e,o){for(let i of o)if(Ah(i)?.Check(e))return e;for(let i of o){let u=structuredClone(e),p=ga(u,i);if(Ah(i)?.Check(p))return p}return e}function ga(e,o){let i=e;if(Array.isArray(o.allOf))for(let g of o.allOf)i=ga(i,g);if(Array.isArray(o.anyOf))i=rC(i,o.anyOf);if(Array.isArray(o.oneOf))i=rC(i,o.oneOf);let u=bU(o),p=u.length>1&&u.some((g)=>EU(i,g));if(u.length>0&&!p)for(let g of u){let y=SU(i,g);if(y!==i){i=y;break}}if(u.includes("object")&&typeof i==="object"&&i!==null&&!Array.isArray(i))wU(i,o);if(u.includes("array")&&Array.isArray(i))TU(i,o);return i}function ul(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let p=0;p<e.length;p++){let g=o.items[p];if(g)ul(e[p],g)}else if(o.items)for(let p of e)ul(p,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let i=e,u=new Set(o.required??[]);for(let[p,g]of Object.entries(o.properties)){if(!(p in i))continue;if(i[p]===null&&!u.has(p)&&typeof g.$ref!=="string"&&Ah(g)?.Check(null)===!1)delete i[p];else ul(i[p],g)}}function nC(e){let o=e,i=tC.get(o);if(i)return i;let u=kh(e);return tC.set(o,u),u}function RU(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let p=e.instancePath.replace(/^\//,"").replace(/\//g,".");return p?`${p}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function kU(e,o){let i=e.find((u)=>u.name===o.name);if(!i)throw Error(`Tool "${o.name}" not found`);return nu(i,o)}function nu(e,o){let i=structuredClone(o.arguments);ul(i,e.parameters),as(e.parameters,i);let u=nC(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(IU)){let y=ga(i,e.parameters);if(y!==i)if(typeof i==="object"&&i!==null&&typeof y==="object"&&y!==null){for(let b of Object.keys(i))delete i[b];Object.assign(i,y)}else return u.Check(y)?y:i}if(u.Check(i))return i;let p=u.Errors(i).map((y)=>` - ${RU(y)}: ${y.message}`).join(`
32
- `)||"Unknown validation error",g=`Validation failed for tool "${o.name}":
33
- ${p}
34
-
35
- Received arguments:
36
- ${JSON.stringify(o.arguments,null,2)}`;throw Error(g)}var oC;function Lc(){if(!oC)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return oC}async function sC(e,o,i,u,p,g){let y=uC(o,e),b=[...y],E={...o,messages:[...o.messages,...y]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let S of y)await u({type:"message_start",message:S}),await u({type:"message_end",message:S});return await aC(E,b,i,p,u,g??Lc()),b}async function iC(e,o,i,u,p){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let g=[],y={...e};return await i({type:"agent_start"}),await i({type:"turn_start"}),await aC(y,g,o,u,i,p??Lc()),g}async function aC(e,o,i,u,p,g){let y=e,b=i,E,S=!1,w=await b.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||w.length>0){let P=[];if(E){let J=await b.prepareNextTurn?.(E);if(J)y=J.context??y,P=J.messages??[],b={...b,model:J.model??b.model,reasoning:J.thinkingLevel===void 0?b.reasoning:J.thinkingLevel==="off"?void 0:J.thinkingLevel};if(w.length===0)w=await b.getSteeringMessages?.()||[];await p({type:"turn_start"})}for(let J of uC(y,[...P,...w]))await p({type:"message_start",message:J}),await p({type:"message_end",message:J}),y.messages.push(J),o.push(J);w=[];let C=await b.prepareRequest?.({context:y,model:b.model,thinkingLevel:b.reasoning??"off"},u);if(C)y=C.context??y,b={...b,model:C.model??b.model,reasoning:C.thinkingLevel===void 0?b.reasoning:C.thinkingLevel==="off"?void 0:C.thinkingLevel};let q=await PU(y,b,u,p,g);if(o.push(q),q.stopReason==="error"||q.stopReason==="aborted"){E={message:q,toolResults:[],context:y,newMessages:o},await b.finishTurn?.(E,u),await p({type:"turn_end",message:q,toolResults:[]}),await p({type:"agent_end",messages:o});return}let X=q.content.filter((J)=>J.type==="toolCall"),j=[];if(R=!1,X.length>0){let J=q.stopReason==="length"?await CU(X,p):await $U(y,q,b,u,p);j.push(...J.messages),R=!J.terminate;for(let ee of j)y.messages.push(ee),o.push(ee)}E={message:q,toolResults:j,context:y,newMessages:o};let V=await b.finishTurn?.(E,u);if(await p({type:"turn_end",message:q,toolResults:j}),V?.action==="end"){await p({type:"agent_end",messages:o});return}if(S=V?.action==="continue",w=await b.getSteeringMessages?.()||[],R||w.length>0)S=!1}let A=await b.getFollowUpMessages?.()||[];if(A.length>0){S=!1,w=A;continue}if(S){S=!1;continue}break}await p({type:"agent_end",messages:o})}function uC(e,o){let i=-1;for(let w=o.length-1;w>=0;w--)if(o[w].role==="system"){i=w;break}let u=o[i],p=u?o.map((w,R)=>R===i?Ph(u,AU):w):o,g=Go(oe([...e.messages,...p]),(e.tools??[]).map(nt)),y=g.toolsAdded.length===0&&g.toolsRemoved.length===0;if(u){if(y&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return p.map((w,R)=>R===i?Ph(u,g):w)}if(y)return o;let b=Ph({role:"system",content:"",timestamp:Date.now()},g),E=o.findIndex((w)=>w.role!=="system"),S=E===-1?o.length:E;return[...o.slice(0,S),b,...o.slice(S)]}var AU={toolsAdded:[],toolsRemoved:[]};function Ph(e,{toolsAdded:o,toolsRemoved:i}){let{toolsAdded:u,toolsRemoved:p,...g}=e;return{...g,...o.length>0?{toolsAdded:o}:{},...i.length>0?{toolsRemoved:i}:{}}}async function PU(e,o,i,u,p){let g=e.messages;if(o.transformContext)g=await o.transformContext(g,i);let y=await o.convertToLlm(g),b=ft({messages:y}),E=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,S=await p(o.model,b,{...o,apiKey:E,signal:i}),w=async()=>Object.assign(await S.result(),{thinkingLevel:o.reasoning??"off"}),R=null,A=!1;for await(let C of S)switch(C.type){case"start":R=C.partial,e.messages.push(R),A=!0,await u({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=C.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:C,message:{...R}});break;case"done":case"error":{let q=await w();if(A)e.messages[e.messages.length-1]=q;else e.messages.push(q);if(!A)await u({type:"message_start",message:{...q}});return await u({type:"message_end",message:q}),q}}let P=await w();if(A)e.messages[e.messages.length-1]=P;else e.messages.push(P),await u({type:"message_start",message:{...P}});return await u({type:"message_end",message:P}),P}async function CU(e,o){let i=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let p={toolCall:u,result:Gs(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Nc(p,o);let g=Ch(p);await $h(g,o),i.push(g)}return{messages:i,terminate:!1}}async function $U(e,o,i,u,p){let g=o.content.filter((b)=>b.type==="toolCall"),y=g.some((b)=>e.tools?.find((E)=>E.name===b.name)?.executionMode==="sequential");if(i.toolExecution==="sequential"||y)return vU(e,o,g,i,u,p);return MU(e,o,g,i,u,p)}async function vU(e,o,i,u,p,g){let y=[],b=[];for(let E of i){await g({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await mC(e,o,E,u,p),w;if(S.kind==="immediate")w={toolCall:E,result:S.result,isError:S.isError};else{let A=await lC(S,p,pC(E,g));w=await dC(e,o,S,A,u,p)}await Nc(w,g);let R=Ch(w);if(await $h(R,g),y.push(w),b.push(R),p?.aborted)break}return{messages:b,terminate:cC(y)}}async function MU(e,o,i,u,p,g){let y=[];for(let S of i){await g({type:"tool_execution_start",toolCallId:S.id,toolName:S.name,args:S.arguments});let w=await mC(e,o,S,u,p);if(w.kind==="immediate"){let R={toolCall:S,result:w.result,isError:w.isError};if(await Nc(R,g),y.push(R),p?.aborted)break;continue}if(y.push(async()=>{if(p?.aborted){let P={toolCall:S,result:Gs("Operation aborted"),isError:!0};return await Nc(P,g),P}let R=await lC(w,p,pC(S,g)),A=await dC(e,o,w,R,u,p);return await Nc(A,g),A}),p?.aborted)break}let b=await Promise.all(y.map((S)=>typeof S==="function"?S():Promise.resolve(S))),E=[];for(let S of b){let w=Ch(S);await $h(w,g),E.push(w)}return{messages:E,terminate:cC(b)}}function cC(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function OU(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 mC(e,o,i,u,p,g=e.tools??[]){let y=g.find((b)=>b.name===i.name);if(!y)return{kind:"immediate",result:Gs(`Tool ${i.name} not found`),isError:!0};try{let b=OU(y,i),E=nu(y,b);if(u.beforeToolCall){let S=await u.beforeToolCall({assistantMessage:o,toolCall:i,args:E,context:e},p);if(p?.aborted)return{kind:"immediate",result:Gs("Operation aborted"),isError:!0};if(S?.block){let w=Gs(S.reason||"Tool execution was blocked");if(S.terminate===!0)w.terminate=!0;return{kind:"immediate",result:w,isError:!0}}}if(p?.aborted)return{kind:"immediate",result:Gs("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:i,tool:y,args:E}}catch(b){return{kind:"immediate",result:Gs(b instanceof Error?b.message:String(b)),isError:!0}}}function pC(e,o){return(i)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:i})}async function lC(e,o,i){let u=[],p=!0,g=performance.now(),y=()=>Math.round(performance.now()-g);try{let b=await e.tool.execute(e.toolCall.id,e.args,o,(S)=>{if(!p)return;u.push(Promise.resolve(i(S)))}),E=y();return p=!1,await Promise.all(u),{result:b,isError:b.isError===!0,durationMs:E}}catch(b){let E=y();return p=!1,await Promise.all(u),{result:Gs(b instanceof Error?b.message:String(b)),isError:!0,durationMs:E}}finally{p=!1}}async function dC(e,o,i,u,p,g){let{result:y,isError:b}=u;if(p.afterToolCall)try{let E=await p.afterToolCall({assistantMessage:o,toolCall:i.toolCall,args:i.args,result:y,isError:b,context:e},g);if(E){let S=E.structuredContent??(E.content?void 0:y.structuredContent);if(y={...y,content:E.content??y.content,details:E.details??y.details,usage:E.usage??y.usage,terminate:E.terminate??y.terminate},S===void 0)delete y.structuredContent;else y.structuredContent=S;b=E.isError??b}}catch(E){y=Gs(E instanceof Error?E.message:String(E)),b=!0}return{toolCall:i.toolCall,result:y,isError:b,durationMs:u.durationMs}}function Gs(e){return{content:[{type:"text",text:e}],details:{}}}async function Nc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function Ch(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs},timestamp:Date.now()}}async function $h(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function _U(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var LU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},NU={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 DU(e){let o=e?.tools?.slice()??[],i=e?.messages?.slice()??[],u=Vn(e?.systemPrompt,o.map(nt));if(i[0]?.role!=="system"&&u)i.unshift(u);return{get systemPrompt(){return qo(i)},model:e?.model??NU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(p){o=p.slice()},get messages(){return i},set messages(p){i=p.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class vh{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class Mh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let o=e??{};this._state=DU(o.initialState),this.convertToLlm=o.convertToLlm??_U,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??Lc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new vh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new vh(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=Xr(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let i=this.normalizePromptInput(e,o);await this.runPromptMessages(i)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let i=this.followUpQueue.drain();if(i.length>0){await this.runPromptMessages(i);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let i=[{type:"text",text:e}];if(o&&o.length>0)i.push(...o);return[{role:"user",content:i,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(i)=>{await sC(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),i,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await iC(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(i)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(i,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,i=()=>{},u=new Promise((p)=>{i=p});this.activeRun={promise:u,resolve:i,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(p){await this.handleRunFailure(p,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let i={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:LU,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:i}),await this.processEvents({type:"message_end",message:i}),await this.processEvents({type:"turn_end",message:i,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[i]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let i=new Set(this._state.pendingToolCalls);i.add(e.toolCallId),this._state.pendingToolCalls=i;break}case"tool_execution_end":{let i=new Set(this._state.pendingToolCalls);i.delete(e.toolCallId),this._state.pendingToolCalls=i;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let i of this.listeners)await i(e,o)}}function _e(e,...o){return Object.assign(e,{aliases:o})}function ya(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function qU(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 fC(e,o){if(e.some((C)=>C.name===o))return o;let i=e.map((C)=>C.name),u=(C)=>i.filter((q)=>ya(q)===C),p=u(ya(o));if(p.length===1&&p[0])return p[0];if(p.length>1)return o;let g=o.split(/[.:/]/).pop()??o,y=g===o?[]:u(ya(g));if(y.length===1&&y[0])return y[0];let b=new Map;for(let C of e)for(let q of C.aliases??[]){let X=ya(q);b.set(X,(b.get(X)??new Set).add(C.name))}let E=(C)=>[...new Set([...u(C),...b.get(C)??[]])],S=E(ya(g));if(S.length===1&&S[0])return S[0];if(S.length>1)return o;let w=qU(g),R=new Set;w.forEach((C,q)=>{R.add(ya(C));let X=w[q+1];if(X)R.add(ya(C+X))});let A=new Set;for(let C of R)for(let q of E(C))A.add(q);let P=[...A];return P.length===1&&P[0]?P[0]:o}function x(e){return e}function En(e,o){let i=o.indexOf("/");if(i<=0)return;return e.getModel(o.slice(0,i),o.slice(i+1))}function tt(e){return`${e.provider}/${e.id}`}function FU(e,o,i){let u=async(g,y)=>{try{if(o){let E=g instanceof Request?g:void 0;o({at:Date.now(),method:y?.method??E?.method??"GET",url:typeof g==="string"?g:g instanceof URL?g.toString():g.url,headers:hC(y?.headers??E?.headers),body:jU(y?.body!==void 0?y.body:E?.body??void 0)})}}catch{}let b=await e(g,y);if(i)try{let E=Date.now(),{status:S,statusText:w}=b,R=hC(b.headers);if(!b.body)return i({at:E,status:S,statusText:w,headers:R,body:""}),b;let A="",P=new TextDecoder,C=new TransformStream({transform(j,V){V.enqueue(j),A+=P.decode(j,{stream:!0}),i({at:E,status:S,statusText:w,headers:R,body:A})},flush(){A+=P.decode(),i({at:E,status:S,statusText:w,headers:R,body:A})}}),q=b.body.pipeThrough(C),X=new Response(q,b);try{Object.defineProperty(X,"url",{value:b.url})}catch{}return X}catch{}return b},p=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:p})}function hC(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,p)=>{o[p]=u}),o;let i=Array.isArray(e)?e:Object.entries(e);for(let u of i)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function jU(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 UU(e,o){return fC(e,o)}function BU(e,o,i){let u=Date.now(),p=new WeakSet,g=(E)=>{if(!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;let S=Date.now(),w=Math.max(10,S-u);E.generationMs=w},y=async(E)=>{if(!i||!E||typeof E!=="object"||!("role"in E)||E.role!=="assistant")return;if(g(E),p.has(E))return;p.add(E),Object.assign(E,await i(E))},b=(E)=>{let S=E?.content;if(!Array.isArray(S))return;for(let w of S)if(w&&w.type==="toolCall"&&typeof w.name==="string")w.name=UU(o(),w.name)};return{async*[Symbol.asyncIterator](){for await(let E of e){let{partial:S,message:w}=E;b(S),await y(w),b(w),yield E}},result:async()=>{let E=await e.result();return g(E),await y(E),b(E),E}}}function Dc(e,o){let i=(o??[]).filter((b)=>b.kind==="path").map((b)=>`<file path=${JSON.stringify(b.data)} />`),u=(o??[]).filter((b)=>b.kind==="text").map((b)=>`<file name=${JSON.stringify(b.name)}>
37
- ${b.data}
38
- </file>`),p=(o??[]).filter((b)=>b.kind==="image").map((b)=>({type:"image",data:b.data,mimeType:b.mimeType})),g=(o??[]).filter((b)=>b.kind==="image"&&b.id).map((b)=>`<image id=${JSON.stringify(b.id)} name=${JSON.stringify(b.name)} />`);return{merged:[...i,...u,...g,...e.trim()?[e]:[]].join(`
39
-
40
- `),images:p}}function Oh(e,o){let{merged:i,images:u}=Dc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:i},...u]:i,timestamp:Date.now()}}function gC(e){let o=new Set;for(let b of e.tools){let E=b.name.toLowerCase();if(o.has(E))throw Error(`Tool names collide ignoring case: ${b.name}`);o.add(E)}let i=new Mh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(b,E,S)=>{let{captureRequest:w,captureResponse:R}=e,A=w||R?{...S,fetch:FU(S?.fetch??globalThis.fetch,w?(C)=>w({...C,model:tt(b)}):void 0,R?(C)=>R({...C,model:tt(b)}):void 0)}:S,P=b.api==="openai-completions"||b.api==="openai-responses"?{...b,compat:{...b.compat,supportsDeveloperRole:!1}}:b;return BU(e.models.streamSimple(P,E,A),()=>i.state.tools,e.hooks.response)},convertToLlm:(b)=>b,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:b,model:E})=>{let S=b.messages.findIndex((P)=>P.role!=="system"),w=b.messages.slice(0,S===-1?b.messages.length:S),R=e.hooks.prepare,A=e.hooks.tools?.()??b.tools;if(A){i.state.tools=A;let P=w[0];if(P?.role==="system")w[0]={...P,toolsAdded:A.map(nt),toolsRemoved:void 0}}return{context:{...b,tools:A,messages:await R(w,A,E)}}}:void 0}),u=new Map,p=new Map,g=new WeakSet,y;return i.subscribe((b)=>{if(b.type==="message_update"&&b.message.role==="assistant"){p.clear(),e.hooks.draft(yC(b.message));return}if(b.type==="tool_execution_update"){let S=u.get(b.toolCallId)??Be(b.toolName,b.args),w=Array.isArray(b.partialResult?.content)?b.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";p.set(b.toolCallId,{type:"tool_call",id:b.toolCallId,name:S.name,input:S.input,...S.source?{source:S.source}:{},output:w}),e.hooks.draft([...p.values()]);return}if(b.type==="tool_execution_end"){if(p.delete(b.toolCallId))e.hooks.draft(p.size>0?[...p.values()]:null);return}if(b.type!=="message_end")return;if(g.has(b.message)){e.steerConsumed?.(b.message);return}let E=b.message.role==="user"&&y?{type:"user",text:y.text,...y.attachments?.length?{attachments:y.attachments}:{}}:GU(b.message);if(b.message.role==="user")y=void 0;if(E?.type==="assistant"){for(let S of E.parts)if(S.type==="tool_call")u.set(S.id,S)}if(E?.type==="tool_result"){let S=u.get(E.callID);if(S?.source)Object.assign(E,{name:S.name,source:S.source})}if(E)e.hooks.message(E,b.message);if(b.message.role==="assistant")e.hooks.draft(null)}),{agent:i,prompt:(b,E)=>{y={text:b,attachments:E};let{merged:S,images:w}=Dc(b,E);return i.prompt(S,w.length>0?w:void 0)},retry:async()=>{let b=i.state.messages;if(b.at(-1)?.role==="assistant")i.state.messages=b.slice(0,-1);await i.continue()},resume:()=>i.continue(),steer:(b)=>{g.add(b),i.steer(b)},unsteer:(b)=>{let S=i.steeringQueue?.messages;if(!S)return!1;let w=S.indexOf(b);if(w<0){let A=JSON.stringify(b);w=S.findIndex((P)=>JSON.stringify(P)===A)}if(w<0)return!1;let[R]=S.splice(w,1);if(R)g.delete(R);return!0},abort:()=>i.abort()}}function _h(e){if(e?.role!=="assistant")return{reason:"done"};if(e.stopReason==="aborted")return{reason:"aborted"};if(e.stopReason==="error")return{reason:"error",error:e.errorMessage};return{reason:"done"}}function cl(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}=Be(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 yC(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...Be(o.name,o.arguments)}})}function GU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:yC(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((i)=>i.type==="image").map((i)=>({mimeType:i.mimeType,data:i.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((i)=>i.type==="text"?i.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class pt extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function k(e){return e}import{createHash as xC}from"crypto";import{existsSync as KU}from"fs";import{readFile as IC,realpath as ml}from"fs/promises";import{dirname as HU,isAbsolute as bC,relative as EC,resolve as SC,sep as wC}from"path";var TC=[...Fg];class pl extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class ll{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=HU(SC(e)),u=SC(i,o??"web.tsx");if(!o&&!KU(u))return;let p=EC(await ml(i),await ml(u));if(bC(p)||p===".."||p.startsWith(`..${wC}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let i=this.pending.get(e);if(i)return i;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let i=this.cache.get(e);if(i){let S=!0;for(let[w,R]of i.inputs){let A=await IC(w).catch(()=>{return});if(!A||xC("sha256").update(A).digest("hex")!==R){S=!1;break}}if(S)return i.source;this.cache.delete(e)}let u=await ml(o),p=new Map,g=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:TC,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(S){S.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(w)=>{if(!TC.includes(w.path))throw Error(`Unsupported shared web import: ${w.path}`);return{path:w.path,external:!0}}),S.onLoad({filter:/.*/},async(w)=>{let R=EC(u,await ml(w.path));if(bC(R)||R===".."||R.startsWith(`..${wC}`))throw Error("Plugin web imports must stay inside its plugin directory");let A=await IC(w.path);p.set(w.path,xC("sha256").update(A).digest("hex"));return})}}]}).catch((S)=>{let R=(S instanceof AggregateError?S.errors:[S]).map((A)=>A instanceof Error?A.message:String(A));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:S})});if(!g.success)throw new pl(g.logs.filter((S)=>S.level==="error").map((S)=>({file:S.position?.file??null,line:S.position?.line??null,message:S.message})));let y=g.outputs.find((S)=>S.kind==="entry-point"&&S.path.endsWith(".js")),b=g.outputs.find((S)=>S.path.endsWith(".css"));if(!y||g.outputs.some((S)=>S!==y&&S!==b))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let E=await y.text();return this.cache.set(e,{source:E,css:await b?.text(),inputs:p}),E}}function jo(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function Ps(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((i)=>i.type==="text"?i.text:"[image]").join("")}function dl(e){return e.content.flatMap((i)=>i.type==="text"&&i.text.trim()?[i.text.trim()]:[]).join(`
41
-
42
- `)}function ou(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function su(e){return e.role==="assistant"&&e.content.length>0}function To(e){let o=[],i=new Map,u=0;for(let p of e){let g=p.raw;if(g.role==="assistant"){if(su(g))u++;for(let y of g.content){if(y.type!=="toolCall")continue;let b={call:y,step:u,message:g};o.push(b),i.set(y.id,b)}}else if(g.role==="toolResult"){let y=i.get(g.toolCallId);if(y)y.result=g}}return o}var fl=new Set(["edit","write"]),RC=new Set(["grep","glob"]);function ao(e,o){let i=Be(e.name,e.arguments).input?.[o];return typeof i==="string"?i:void 0}function kC(e){return[...new Set(To(e).flatMap((o)=>fl.has(Be(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&ao(o.call,"path")?[ao(o.call,"path")]:[]))]}function Lh(e){return!e.result?"pending":e.result.isError?"error":"completed"}function hl(e){let o=[{source:"ASSISTANT_TOOL",text:`${Be(e.call.name,e.call.arguments).name}(${jo(Be(e.call.name,e.call.arguments).input)}) [${Lh(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:ou(e.result)});return o}function D(e){let o=0,i=0,u=0;for(let p of e){let g=p.codePointAt(0);if(g<=127)o++;else if(g>=19968&&g<=40959||g>=12288&&g<=12351||g>=65280&&g<=65519||g>=131072&&g<=173791)i++;else u++}return Math.max(0,Math.ceil(o/4+i+u/2))}var Nh=8192;function F(e){let o=e,i=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let p of o.content)if(p.type==="text")u+=p.text;else i++;else if(o.role==="assistant")for(let p of o.content)if(p.type==="text")u+=p.text;else if(p.type==="thinking")u+=p.thinking;else u+=`${p.name}${jo(p.arguments)}`;else if(o.role==="toolResult")for(let p of o.content)if(p.type==="text")u+=p.text;else i++;else u=jo(e);return D(u)+16+i*Nh}function Ni(e=[]){return e.reduce((o,i)=>o+D(i.name+i.description+jo(i.parameters))+16,0)}function Fn(e,o){let i=e.replace(/\s+/g," ").trim();if(D(i)<=o)return i;let u=Math.min(i.length,o*4);while(u>0&&D(i.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${i.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Ro(e,o,i=Number.POSITIVE_INFINITY){if(D(e)<=o&&e.length<=i)return e;let u=`
43
- [... omitted; use history tools for the full text ...]
44
- `,p=Math.floor((o-D(u))/2);if(p<=0)return"";let g=(y)=>{let b=0,E=Math.max(0,Math.min(e.length,p*4,Math.floor((i-u.length)/2)));while(b<E){let S=Math.ceil((b+E)/2),w=y?e.slice(-S):e.slice(0,S);if(D(w)<=p)b=S;else E=S-1}if(!b)return"";return y?e.slice(-b).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,b).replace(/[\uD800-\uDBFF]$/,"")};return`${g(!1)}${u}${g(!0)}`}function gl(e,o){if(D(e.join(`
45
- `))<=o)return e;let i=(w)=>`- [... ${w} steps omitted; use history tools for the full text ...]`,u=o-D(i(e.length)),p=[],g=[],y=0,b=0,E=e.length-1;while(b<=E){let w=p.length<=g.length,R=w?e[b]:e[E],A=D(`${R}
46
- `);if(y+A>u)break;if(y+=A,w)p.push(e[b++]);else g.unshift(e[E--])}let S=E-b+1;return[...p,...S>0?[i(S)]:[],...g]}function Ks(e){let o=[],i;for(let u of e){let p=u.entry;if(p.type==="run"&&p.state==="start"){i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);continue}if(p.type==="run"&&p.state==="end"){if(i)i.end=p.seq,i.status=WU(p.reason,i.records);i=void 0;continue}if(p.type==="extension"||!u.raw)continue;if(!i&&p.type==="user"&&p.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!i)i={id:`r${p.seq}`,start:p.seq,status:"open",records:[]},o.push(i);i.records.push(u)}for(let u of o)u.records=Dh(u.records);return o}function Dh(e){if(e.length<=1)return[...e];let o=[],i=[],u=new Set;for(let p=0;p<e.length;p++){let g=e[p];if(!g)continue;let y=g.raw?.role;if(y==="assistant"){let E=g.raw.content?.filter((S)=>S.type==="toolCall")??[];if(E.length>0)for(let S of E)u.add(S.id);if(o.push(g),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="toolResult"){let b=g.raw;if(b.toolCallId)u.delete(b.toolCallId);if(o.push(g),u.size===0&&i.length>0)o.push(...i),i=[];continue}if(y==="user"){if(o.length===0){o.push(g);continue}let b=e.slice(p+1).some((E)=>E.raw?.role==="assistant");if(u.size>0||b){i.push(g);continue}o.push(g);continue}o.push(g)}if(i.length>0)o.push(...i);return o}function WU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let i=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return i?.stopReason==="error"&&ca(i)?"interrupted":"failed";if(!i)return"completed";switch(i.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return ca(i)?"interrupted":"failed";default:return"interrupted"}}function xa(e){for(let o=e.length-1;o>=0;o--){let i=e[o]?.entry;if(i?.type==="compaction")return i.through}return 0}function yl(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&&!yl(i,o)&&i.records.some((u)=>u.entry.seq<=o))}function iu(e){let o=xa(e),u=Ks(e).findLast((p)=>p.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function xl(e){let o=xa(e);return qh(Ks(e),o)?.end}function qc(e,o){let i=xa(e),u=Ks(e).at(-1);if(!u||u.end!==void 0)return;let p=u.records.filter((w)=>w.entry.seq>i),g=[],y=new Set;for(let w of p){let R=w.raw,A=F(w.raw);if(R.role==="assistant"){for(let P of R.content)if(P.type==="toolCall")y.add(P.id)}else if(R.role==="toolResult")y.delete(R.toolCallId);if(su(R)||!g.length||R.role==="user"&&g.at(-1)?.assistant)g.push({end:w.entry.seq,tokens:A,assistant:su(R),pending:y.size});else{let P=g.at(-1);P.end=w.entry.seq,P.tokens+=A,P.pending=y.size}}let b=g.findLastIndex((w)=>w.assistant),E=0,S;for(let w=g.length-1;w>=0;w--){let R=g[w];if(w<b&&R.assistant&&R.pending===0&&(E<=o||S===void 0))S=R.end;if(E+=R.tokens,E>o&&S!==void 0)break}if(E<=o)return;return S}var AC=2000;function Di(e,o){let i=D(o);if(i<=AC)return o;let u=new TextEncoder().encode(o).length,p=o.split(`
47
- `).length,g=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${p} lines, approximately ${i} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
48
- `),y="</user-text-reference>",b=AC-D(`${g}
49
-
50
- ${y}`);if(b<=0)return o;let E=`${g}
51
- ${Ro(o,b,o.length-g.length-y.length-3)}
52
- ${y}`;return E.length<o.length&&D(E)<i?E:o}function PC(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let p=Di(e.entry.seq,o.content);return p===o.content?o:{...o,content:p}}let i=!1,u=o.content.map((p)=>{if(p.type!=="text")return p;let g=Di(e.entry.seq,p.text);if(g!==p.text)i=!0;return g===p.text?p:{...p,text:g}});return i?{...o,content:u}:o}function Fh(e,o=!1){let i=e.records.filter((P)=>P.entry.type==="user"&&!P.entry.notices&&P.raw.role==="user"),u=i.flatMap((P)=>{let C=P.raw.content;return typeof C==="string"?[]:C.filter((q)=>q.type==="image")}),p=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,g=e.status==="open"?"interrupted":e.status,y="";if(i.length){let P=o?Ro(i.map((C)=>Ps(C.raw)).join(`
53
-
54
- `),600):i.map((C,q)=>`<user-message sequence="${q+1}">
55
- ${Di(C.entry.seq,Ps(C.raw))}
56
- </user-message>`).join(`
57
-
58
- `);y=[`<chunk-input id="${e.id}" status="${g}"${o?' excerpt="true"':""}>`,P,...o?[p]:[],"</chunk-input>"].join(`
59
- `)}let E=e.records.filter((P)=>P.raw.role==="assistant").at(-1)?.raw,S=E?dl(E):"",w=[];if(g!=="completed"){let P=To(e.records),C=new Map(P.map((J)=>[J.call,J])),q=P.slice(-3),X=new Set(q.map((J)=>J.message)),j=[],V=[];for(let J of e.records){let ee=J.raw;if(ee.role!=="assistant")continue;let ae=X.has(ee);for(let H of ee.content)if(H.type==="text"&&ee!==E&&H.text.trim())if(ae)V.push(`ASSISTANT: ${Fn(H.text,50)}`);else j.push(`- ASSISTANT: ${Fn(H.text,50)}`);else if(H.type==="toolCall"){let ue=C.get(H);if(!ue)continue;if(ae){if(q.includes(ue))for(let he of hl(ue))V.push(`${he.source}: ${Ro(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else j.push(`- ${H.name}(${Fn(jo(H.arguments),40)}) [${Lh(ue)}]`)}}w.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",p,...j.length?[`Earlier steps, oldest first:
60
- ${gl(j,o?300:800).join(`
61
- `)}`]:[],...V)}let R=kC(e.records),A=[`<chunk-summary id="${e.id}" status="${g}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,S?o?Ro(S,600):S:"No final assistant response was recorded.",...w,...R.length?[`Recorded file changes:
62
- ${Ro(R.join(`
63
- `),250)}`]:[],...o&&g==="completed"?[p]:[],"</chunk-summary>"].join(`
64
- `);return{input:y,images:u,summary:A,tokens:zU(y,A,u.length)}}function zU(e,o,i){return(e?D(e)+16:0)+D(o)+16+i*Nh}var VU=["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."],JU="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.",QU=1500,XU=80,YU=240;function CC(e,o,i){let u=[],p=0,g=Math.min(o.target,o.hard);for(let b=e.length-1;b>=0;b--){let E=e[b],S=Fh(E),w=p+S.tokens>g?Fh(E,!0):void 0,R=w&&w.tokens<S.tokens?w:S;if(!(!i&&b===e.length-1&&E.status!=="completed")&&p+R.tokens>o.hard)break;p+=R.tokens,u.push({run:E,content:R})}u.reverse();let y=e.slice(0,e.length-u.length);return{visible:u,archived:y,tokens:p}}function $C(e){let{runs:o,visible:i,archived:u,partial:p}=e,g=u.flatMap((E)=>{let S=E.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>Ps(R.raw));if(!S.length)return[];let w=E===o[0]?YU:XU;return[`- ${E.id} [${E.status}]: ${Fn(S.join(" / "),w)}`]}),y=new Map(o.map((E,S)=>[E,S+1])),b=[...i.map((E)=>y.get(E)??0),...p?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...VU,...p?[JU]:[],"",`visible chunks: ${i.length+(p?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((E)=>E.id).join(", "):"none"}`,`visible sequences: ${b.length?`${b[0]}..${b.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...g.length?["archived requests, oldest first:",Ro(g.join(`
65
- `),QU)]:[],"</conversation-checkpoint>"].join(`
66
- `)}function vC(e,o){let i=e.split(`
67
- `),u=o.split(`
68
- `),p=new Set(i),g=new Set(u),y=[...i.filter((E)=>E.trim()&&!g.has(E)).map((E)=>`- ${Fn(E,40)}`),...u.filter((E)=>E.trim()&&!p.has(E)).map((E)=>`+ ${Fn(E,40)}`)],b=i.find((E)=>E.trim()&&g.has(E));return[...y.slice(0,6),...y.length>6?[`\u2026 ${y.length-6} more changed lines`]:[],...b&&y.every((E)=>E.startsWith("+"))?[`@ ${Fn(b,40)}`]:[]]}function Il(e,o){if(!o)return e;let i=o.endsWith("/")?o:`${o}/`;return e.startsWith(i)?e.slice(i.length):e}function ZU(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 eB(e,o){let i=ao(e,"path");if(fl.has(e.name)&&i)return`file:${Il(i,o)}`;let u=ao(e,"command");if(u)return`command:${u}`;return`${e.name}:${jo(e.arguments)}`}function tB(e,o){let i={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let g of To(e)){let y=u.get(g.step)??[];y.push(g),u.set(g.step,y)}let p=new Map;for(let g of e){let y=g.raw;if(!su(y))continue;let b=++i.steps,E=dl(y);if(E)i.narration.push({step:b,text:Fn(E,60)});for(let{call:S,result:w}of u.get(b)??[]){if(!w)continue;let R=Be(S.name,S.arguments),A={...S,name:R.name,arguments:R.input},P=eB(A,o),C=ou(w);if(w.isError){let ee=ao(A,"command"),ae=ee?`${A.name} \`${Fn(ee,40)}\``:`${A.name} ${P.startsWith("file:")?P.slice(5):Fn(jo(A.arguments),40)}`,H={step:b,key:P,what:ae,detail:Ro(C.trim().split(`
69
- `).slice(0,8).join(`
70
- `),200)};i.errors.push(H);let ue=p.get(P)??[];ue.push(H),p.set(P,ue);continue}for(let ee of p.get(P)??[])ee.resolved=b;p.delete(P);let q=ao(A,"path");if(fl.has(A.name)&&q){let ee=Il(q,o),ae=i.files.get(ee)??{count:0,first:b,last:b,diffs:[]};if(ae.count++,ae.last=b,ae.diffs.push({step:b,lines:A.name==="edit"?ao(A,"old_string")!==void 0?vC(ao(A,"old_string")??"",ao(A,"new_string")??""):[]:vC("",ao(A,"content")??"")}),ae.diffs.length>3)ae.diffs.shift();i.files.set(ee,ae);continue}let X=A.name==="read"?[...q?[q]:[],...ZU(A)]:[];if(X.length){for(let ee of X){let ae=Il(ee,o),H=i.reads.get(ae)??[];H.push(b),i.reads.set(ae,H)}continue}if(RC.has(A.name)){let ee=q?` in ${Il(q,o)}`:"",ae=A.name==="grep"&&ao(A,"glob")?` (${ao(A,"glob")})`:"",H=`${A.name} ${ao(A,"pattern")??""}${ee}${ae}`.replace(/\s+/g," "),ue=i.searches.get(H)??{steps:[],head:""};ue.steps.push(b),ue.head=Fn(C.trim().split(`
71
- `)[0]??"",25),i.searches.set(H,ue);continue}let j=ao(A,"command");if(j){let ee=C.trim().split(`
72
- `);i.commands.push({step:b,command:Fn(j,40),exit:"0",lines:ee.length,tail:ee.slice(-3).map((ae)=>Fn(ae,40))});continue}let V=`${A.name} ${Fn(jo(A.arguments),40)}`,J=i.other.get(V)??[];J.push(b),i.other.set(V,J)}}return i}function MC(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Fc(e,o,i){let u=(S,w)=>w===void 0||!S.length?S:gl(S,w),p=[`<work-state chunk="${o.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${o.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],g=[...e.files];p.push("",`## Modified files (${g.length})`),g.forEach(([S,w],R)=>{if(p.push(`- ${S}: ${w.count} change${w.count>1?"s":""} (step ${w.first}${w.last!==w.first?`-${w.last}`:""})`),R<g.length-i.diffFiles)return;for(let A of w.diffs)p.push(` step ${A.step}:`,...A.lines.map((P)=>` ${P}`))}),p.push("",`## Errors (${e.errors.length})`,...e.errors.map((S)=>S.resolved?`- step ${S.step} ${S.what} (resolved at step ${S.resolved})${i.lists===void 0?`: ${S.detail.replace(/\n/g,`
73
- `)}`:""}`:`- step ${S.step} ${S.what} (UNRESOLVED): ${S.detail.replace(/\n/g,`
74
- `)}`)),p.push("","## Steps",...u(e.narration.map((S)=>`- ${S.step}. ${S.text}`),i.narration));let y=[...e.reads].map(([S,w])=>`- ${S} @ ${w.join(",")}`);p.push("",`## Files read (${y.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(y,i.lists));let b=[...e.searches].map(([S,w])=>`- ${S} \u2192 ${w.head||"(no output)"} (${MC(w.steps)})`);p.push("",`## Searches (${b.length})`,...u(b,i.lists));let E=e.commands.map((S)=>[`- ${S.step}. \`${S.command}\` exit=${S.exit}, ${S.lines} output lines, last ${S.tail.length}:`,...S.tail.map((w)=>` ${w}`)].join(`
75
- `));if(p.push("",`## Commands (${E.length})`,...u(E,i.lists)),e.other.size){let S=[...e.other].map(([w,R])=>`- ${w} (${MC(R)})`);p.push("",`## Other tool calls (${S.length})`,...u(S,i.lists))}return p.push("</work-state>"),p.join(`
76
- `)}function bl(e,o,i,u){let p=tB(e,u),g=Fc(p,o,{diffFiles:Number.POSITIVE_INFINITY});if(D(g)<=i)return g;let y={...p,narration:[]};for(let S of[Number.POSITIVE_INFINITY,20,10,5]){let w=D(Fc(y,o,{diffFiles:S}));if(w>i*0.7)continue;return Fc(p,o,{narration:Math.max(500,i-w),diffFiles:S})}let b=Math.max(300,Math.floor(i*0.1)),E=D(Fc(y,o,{diffFiles:0,lists:b}));return Fc(p,o,{narration:Math.max(500,i-E),diffFiles:0,lists:b})}function El(e){return{role:"user",content:e,timestamp:0}}function jh(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function OC(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:El(e.input)}function au(e){let o=[];for(let i of e){let u=o.at(-1),p=i;if(u?.role==="user"&&p.role==="user"){let g=(y)=>typeof y.content==="string"?[{type:"text",text:y.content}]:y.content;o[o.length-1]={...p,content:[...g(u),{type:"text",text:`
77
-
78
- `},...g(p)]};continue}o.push(i)}return o}function _C(e){let o=[],i=new Map;for(let u of e){let p=u;if(p.role==="toolResult"){if(!i.has(p.toolCallId))continue;let g=i.get(p.toolCallId);if(g===void 0)i.set(p.toolCallId,o.length),o.push(u);else o[g]=u;continue}if(p.role==="assistant"){if(i=new Map,p.stopReason!=="error"&&p.stopReason!=="aborted"){for(let g of p.content)if(g.type==="toolCall")i.set(g.id,void 0)}}else if(p.role==="user")i=new Map;o.push(u)}return o}function rB(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Re(e,o,i,u={}){let p=xa(e),g=Ks(e),y=g.filter((Ee)=>yl(Ee,p)),b=qh(g,p),E=[],S=[],w=0;for(let Ee of g){if(yl(Ee,p))continue;let se=[];for(let pe of Ee.records){if(Ee===b&&pe.entry.seq<=p)continue;let qe=pe.raw.role==="user"?PC(pe):pe.raw;w+=F(qe),E.push(qe),se.push(qe)}if(u.inspect&&se.length)S.push({id:`recent-${Ee.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Ee.id}`,tokens:se.reduce((pe,qe)=>pe+F(qe),0),detail:JSON.stringify(se,rB,2)})}if(!y.length&&!b)return{items:S,messages:au(E),visible:0,archived:0,open:w,tokens:w,untrimmed:w};let R=CC(y,i,!!b),{visible:A,archived:P}=R,C=R.tokens,q=[],X="",j="";if(b){let Ee=b.records.filter((pe)=>pe.entry.seq<=p),se=Ee.filter((pe)=>pe.entry.type==="user"&&!pe.entry.notices&&pe.raw.role==="user");if(se.length){X=[`<chunk-input id="${b.id}" status="partial">`,...se.map((qe,xt)=>`<user-message sequence="${xt+1}">
79
- ${Di(qe.entry.seq,Ps(qe.raw))}
80
- </user-message>`),"</chunk-input>"].join(`
81
- `);let pe=se.flatMap((qe)=>{let xt=qe.raw.content;return typeof xt==="string"?[]:xt.filter((Je)=>Je.type==="image")});q.push(pe.length?{role:"user",content:[{type:"text",text:X},...pe],timestamp:0}:El(X))}j=bl(Ee,b,i.index,u.cwd),q.push(jh(j,o))}let V=e.flatMap((Ee)=>{let se=Ee.raw;if(Ee.entry.seq>p||se?.role!=="toolResult"||se.toolName!=="skill")return[];return[El(se.content.filter((pe)=>pe.type==="text").map((pe)=>pe.text).join(`
82
- `))]}),J="",ee=()=>{J=$C({runs:y,visible:A.map((se)=>se.run),archived:P,partial:!!b,tokens:C,budget:i});let Ee=[El(J)];for(let{content:se}of A){if(se.input)Ee.push(OC(se));Ee.push(jh(se.summary,o))}return[...Ee,...V,...q]},ae=(Ee)=>Ee.reduce((se,pe)=>se+F(pe),0),H=ee(),ue=ae(H)+w,he=ue,{trim:$e}=u;while($e&&$e.fixed+ue>$e.limit){let Ee=b||A.at(-1)?.run.status==="completed"?A:A.slice(0,-1);if(!Ee.length)break;let se=0,pe=0;for(let qe of Ee)if(pe++,se+=qe.content.tokens,se>=$e.fixed+ue-$e.limit)break;P=[...P,...A.slice(0,pe).map((qe)=>qe.run)],A=A.slice(pe),C-=se,H=ee(),ue=ae(H)+w}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:F(H[0]),detail:J},...A.map(({run:Ee,content:se})=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"sealed",tokens:(se.input?F(OC(se)):0)+F(jh(se.summary,o)),detail:[se.input,se.summary].filter(Boolean).join(`
83
-
84
- `)})),...P.map((Ee)=>({id:Ee.id,label:`Chunk ${Ee.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...b?[{id:b.id,label:`Chunk ${b.id}`,state:"folded",tokens:ae(q),detail:[X,j].filter(Boolean).join(`
85
-
86
- `)}]:[],...S]:[],messages:au([...H,...E]),visible:A.length,archived:P.length,open:w,tokens:ue,untrimmed:he}}function ce(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Uh=0.97,nB=0.97,LC=0.5,oB=0.05,sB=20000,iB=24000;function jc(e){return{target:sB,hard:iB,index:Math.floor(ce(e)*oB)}}function Bh(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class Uc{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,i=()=>{return}){this.records=e;this.fold=o;this.cwd=i}budget(e){return jc(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(ce(e)*Uh/this.ratio)}prepare(e,o,i,u){let p=ce(i),g=jc(i),y=e.reduce((H,ue)=>H+F(ue),0)+Ni(o),b=this.records().at(-1)?.entry.seq??0,E=()=>u?[...u,...this.records().filter((H)=>H.entry.seq>b)]:this.records(),S=()=>Re(E(),i,g,{cwd:this.cwd(),trim:{fixed:y,limit:Math.floor(p*Uh/this.ratio)}}),w=E().findLast((H)=>H.raw?.role==="assistant"),R=w?E().filter((H)=>H.entry.seq>w.entry.seq&&H.raw):[],A=w?.raw,P=()=>w!==void 0&&(w.entry.seq===this.reshapedAfter||E().some((H)=>H.entry.type==="compaction"&&H.entry.seq>w.entry.seq)),C=this.dueSeal(i);if(C!==void 0)this.fold(C,!1),this.reshapedAfter=w?.entry.seq??-1;let q=S(),X=R.reduce((H,ue)=>H+F(ue.raw),0);if(this.lastEstimate===0&&w&&A&&!P()){let H=A.usage.input+A.usage.cacheRead+A.usage.cacheWrite,ue=y+q.untrimmed-F(A)-X;if(H>0&&ue>0)this.ratio=Math.min(2,Math.max(0.5,H/ue))}let V=((H)=>{let ue=y+H.untrimmed,he=y+H.tokens;return((w&&A&&!P()&&Bh(A)>0?Bh(A)+Math.round(this.ratio*X):void 0)??Math.round(ue*this.ratio))-Math.round((ue-he)*this.ratio)})(q);if(V>p*nB){let H=V-q.open*this.ratio,ue=Math.max(1000,Math.floor((p*LC-H-g.index)/this.ratio)),he=w?.entry.seq??-1,$e=E().findLast((qe)=>qe.entry.type==="compaction"&&qe.entry.partial)?.entry.seq??-1,Ee=Math.max(this.lastFoldSeq,$e),pe=(Ee>0?E().filter((qe)=>qe.entry.seq>Ee&&qe.raw?.role==="assistant").length:999)<=1;if(!pe||this.consecutivePartialFolds<2){let qe=qc(E(),ue);if(qe!==void 0)this.fold(qe,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=pe?this.consecutivePartialFolds+1:1,q=S()}}else this.consecutivePartialFolds=0;this.lastEstimate=y+q.tokens;let J=q.messages,ee=y+q.tokens;if(Math.round(ee*this.ratio)>p)J=aB(J,Math.floor((p-y)/this.ratio)),ee=y+J.reduce((H,ue)=>H+F(ue),0);return this.lastEstimate=ee,{messages:au([...e,...J]),estimate:ee}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((i)=>i.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(xl(o)===void 0){let i=o.findLast((b)=>b.raw?.role==="assistant"),u=i?.raw,p=i!==void 0&&(i.entry.seq===this.reshapedAfter||o.some((b)=>b.entry.type==="compaction"&&b.entry.seq>i.entry.seq)),y=(i?o.filter((b)=>b.entry.seq>i.entry.seq&&b.raw):[]).reduce((b,E)=>b+F(E.raw),0);if(p||!u||Bh(u)+y<Math.floor(ce(e)*Uh))return}return iu(o)}recover(e){let o=ce(e),i=jc(e),u=Re(this.records(),e,i,{cwd:this.cwd()}),p=Math.floor((o*LC-(o-u.open*this.ratio)-i.index)/this.ratio),g=qc(this.records(),p);if(g===void 0)return!1;return this.fold(g,!0),this.reshapedAfter=this.records().findLast((y)=>y.raw?.role==="assistant")?.entry.seq??-1,!0}}function aB(e,o){let i=e.reduce((p,g)=>p+F(g),0);if(i<=o)return e;let u=[];for(let p of e){let g=p;if(g.role!=="toolResult"||i<=o){u.push(p);continue}let y=F(p);if(y<=1500){u.push(p);continue}let b=Math.max(500,Math.floor(y/2)),E=g.content.map((R)=>{if(R.type!=="text")return R;return{...R,text:Ro(R.text,b)}}),S={...g,content:E},w=F(S);i-=y-w,u.push(S)}return u}var uB=2000;function uu(e,o){let i=[];for(let u of o.replace(/\r\n/g,`
87
- `).split(`
88
- `))for(let p=0;p<Math.max(u.length,1);){let g=Math.min(u.length,p+uB);if(g<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(g-1)))g--;i.push({source:e,text:u.slice(p,g)}),p=g>p?g:p+1}return i}function cu(e){let o=[],i=To(e.records),u=new Map(i.map((g)=>[g.call,g])),p=new Set(i.flatMap((g)=>g.result?[g.result]:[]));for(let g of e.records){let y=g.raw;if(y.role==="user")o.push(...uu(g.entry.type==="user"&&g.entry.notices?"NOTICE":"USER",Ps(y)));else if(y.role==="assistant"){for(let b of y.content)if(b.type==="text"&&b.text.trim())o.push(...uu("ASSISTANT",b.text));else if(b.type==="toolCall"){let E=u.get(b);if(E)for(let S of hl(E))o.push(...uu(S.source,S.text))}}else if(y.role==="toolResult"&&!p.has(y))o.push(...uu(y.isError?"TOOL_ERROR":"TOOL_OUTPUT",ou(y)))}return o.map((g,y)=>({chunk:e.id,line:y,...g}))}function Sl(e,o){let i=e.find((u)=>u.entry.seq===o);if(i?.entry.type!=="user"||i.entry.notices||!i.raw||i.raw.role!=="user")return;return uu("USER",Ps(i.raw)).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function wl(e,o){let i=e.find((u)=>u.entry.seq===o)?.entry;if(i?.type!=="extension"||!i.display)return;return uu("EXTENSION",i.display.text).map((u,p)=>({chunk:`seq ${o}`,line:p,...u}))}function Bc(e,o=""){return e.map((i,u)=>{let p=e[u-1],g=p&&p.source===i.source&&p.chunk===i.chunk&&p.line===i.line-1;return`${o}${g?`${i.line}:`:`${i.line} ${i.source}:`} ${i.text}`}).join(`
89
- `)}import{join as $g}from"path";import{existsSync as e$}from"fs";import{realpath as t$}from"fs/promises";import{dirname as r$,isAbsolute as RB,join as n$,relative as kB,resolve as Jh,sep as AB}from"path";import{existsSync as cB,watch as mB}from"fs";import{readdir as pB,stat as lB}from"fs/promises";import{basename as Gh,dirname as dB,join as NC,resolve as fB}from"path";class Kh{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,i,u=150){this.host=e;this.slots=o;this.watching=i;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let i=[],u=[];for(let b of[...new Set(e)]){let E;try{E=await pB(b)}catch(S){if(S instanceof Error&&"code"in S&&S.code==="ENOENT")continue;throw S}for(let S of E.sort()){let w=NC(b,S),R=(await lB(w)).isDirectory()?NC(w,"index.ts"):w;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(A){let P=Gh(R)==="index.ts"?Gh(dB(R)):Gh(R,".ts");if(this.slots.has(P))throw Error(`Duplicate plugin: ${P}`);let C={id:P,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${P}; repair the file and reload`)}};i.push({definition:C,path:R}),this.slots.set(P,{definition:C,path:R,enabled:!0,discoveryFailed:!0,error:A instanceof Error?A.message:String(A)})}}}let p=o.filter((b)=>![...u,...i].some((E)=>E.definition.id===b.definition.id)),g=[...p,...u],y=this.order(g.map(({definition:b})=>b));for(let b of y){let E=g.find((w)=>w.definition===b)?.path,S=p.some((w)=>w.definition===b);try{await this.host.install(b,E,S)}catch(w){this.slots.set(b.id,{definition:b,path:E,builtin:S,enabled:!0,error:w instanceof Error?w.message:String(w)})}}if(this.watching())for(let b of[...g,...i]){if(!cB(b.path))continue;let E=mB(b.path,()=>{let S=b.definition.id,w=this.debounceTimers.get(S);if(w)clearTimeout(w);let R=setTimeout(()=>{this.debounceTimers.delete(S),this.host.reload(S).catch((A)=>{let P=this.slots.get(S);if(P)P.error=A instanceof Error?A.message:String(A)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(S,R)});E.on("error",(S)=>{let w=this.slots.get(b.definition.id);if(w)w.error=S.message,this.host.changed()}),this.watchers.push(E)}}order(e,o=!1){let i=new Map;for(let b of e){if(this.validate(b),i.has(b.id)||!o&&this.slots.has(b.id))throw Error(`Duplicate plugin: ${b.id}`);i.set(b.id,b)}let u=[],p=new Set,g=new Set,y=(b)=>{if(g.has(b.id))return;if(p.has(b.id))throw Error(`Plugin dependency cycle: ${b.id}`);p.add(b.id);for(let E of b.deps??[]){let S=i.get(E);if(S)y(S);else if(!this.slots.has(E))throw Error(`Missing plugin dependency: ${E}`)}p.delete(b.id),g.add(b.id),u.push(b)};for(let b of e)y(b);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${fB(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 DC(e,o,i=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,p;try{return await Promise.race([i?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((g,y)=>{p=setTimeout(()=>{u.abort(),y(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(p)}}import{AsyncLocalStorage as hB}from"async_hooks";import{isDeepStrictEqual as qC}from"util";var Ia=new hB;function Cs(){let e=Ia.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function mu(e){let o=structuredClone(e),i=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let p of Object.values(u))i(p)};return i(o),o}function FC(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let E of["seq","time","session_id","raw"])if(E in o)throw Error(`Entry replacement contains protected field: ${E}`);let i=JSON.parse(JSON.stringify(o,(E,S)=>{if(typeof S==="function"||typeof S==="symbol"||typeof S==="number"&&!Number.isFinite(S))throw Error("Entry replacement must contain JSON values");return S}));if(!i||typeof i!=="object"||Array.isArray(i))throw Error("Entry replacement must serialize to a body");let u=i,p=[];switch(e.type){case"user":p.push("text","attachments");break;case"assistant":p.push("parts","error");break;case"tool_result":p.push("output","images");break;case"extension":p.push("payload","display");break;case"notice_pending":p.push("notice");break;case"run":if(e.state==="end")p.push("error");break;case"compaction":break}let g={...e};for(let E of new Set([...Object.keys(e),...Object.keys(u)])){if(!p.includes(E)&&!qC(g[E],u[E]))throw Error(`Entry replacement changed protected field: ${E}`);if(["seq","time","session_id","raw"].includes(E))throw Error(`Entry replacement contains protected field: ${E}`)}let y=(E)=>E===void 0||typeof E==="string",b=!0;switch(e.type){case"user":b=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((E)=>E&&typeof E.name==="string"&&typeof E.mimeType==="string"&&Qc.includes(E.kind)&&typeof E.data==="string"));break;case"assistant":b=y(u.error)&&Array.isArray(u.parts)&&u.parts.every((E)=>E&&(["text","thinking"].includes(E.type)&&typeof E.text==="string"||E.type==="tool_call"&&typeof E.id==="string"&&typeof E.name==="string"&&("input"in E)));break;case"tool_result":b=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((E)=>E&&typeof E.mimeType==="string"&&typeof E.data==="string"));break;case"extension":{let E=u.display;b="payload"in u&&(E===void 0||E!==null&&typeof E==="object"&&("text"in E)&&typeof E.text==="string"&&(!("title"in E)||y(E.title)));break}case"notice_pending":{let S=["text"],w=g.notice,R=u.notice;if(b=!!R&&typeof R==="object"&&!Array.isArray(R),!b)break;let A=R;for(let P of new Set([...Object.keys(w),...Object.keys(A)]))if(S.includes(P)){if(typeof A[P]!=="string")b=!1}else if(!qC(w[P],A[P]))b=!1;break}case"run":b=y(u.error);break;case"compaction":break}if(!b)throw Error("Invalid entry replacement content");return i}function jC(e,o,i,u,p,g){let y=u;for(let b of i.generations)for(let E of b.hooks.get("entry.before_append")??[]){if(b.disabled)break;let S={phase:"before",violated:!1};try{let w=Ia.run(S,()=>{let R=mu(y),A=performance.now(),P=E(R,{sessionID:p,seq:g});if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")throw Promise.resolve(P).catch(()=>{}),Error("entry.before_append must be synchronous");let C=P===void 0?void 0:FC(y,P);if(S.violated)throw Error("entry.before_append attempted a database write");return{validated:C,slow:performance.now()-A>e}});if(w.validated&&JSON.stringify(w.validated)!==JSON.stringify(y))y=w.validated;if(w.slow)throw Error("entry.before_append exceeded budget");b.beforeFailures=0,b.failures=0}catch(w){b.failures=b.beforeFailures++,o(b,w)}}return y}function gB(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return mu(o);return structuredClone(o)}async function UC(e,o,i,u,p,g,y,b,E="end"){let S=g;for(let w of u){if(w.disabled)continue;let R=w.hooks.get(p)??[];for(let A of R){if(w.disabled)break;let P=w.hookOptions.get(A);if(p==="prompt.fragments"&&(P?.promptPosition??"end")!==E)continue;let C=p==="prompt.fragments"?JSON.stringify([y?.id,S]):void 0,q=C===void 0?void 0:w.promptCache.get(A)?.get(C);try{let X=gB(p,S),j=P?.timeoutMs,V=typeof j==="function"?j({runtime:e.runtime,session:y,connection:b}):j,J=await o((ee)=>A(X,{runtime:e.runtime,session:y,connection:b,signal:ee}),V);if(C!==void 0){let ee=J===void 0?S:J;if(!Array.isArray(ee)||ee.some((H)=>typeof H!=="string"))throw Error("Prompt fragments must be strings");if(q&&JSON.stringify(q)!==JSON.stringify(ee))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let ae=w.promptCache.get(A)??new Map;ae.set(C,[...ee]),w.promptCache.set(A,ae)}if(w.failures=0,J!==void 0&&p!=="entry.after_append")S=J}catch(X){if(q)S=structuredClone(q);if(i(w,X),P?.errorMode==="propagate")throw X}}}return S}class Gc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,i,u,p="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,i,u,p)}has(e,o){return this.generations.some((i)=>!i.disabled&&(i.hooks.get(e)??[]).some((u)=>o===void 0||(i.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...i)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...i)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((i)=>i(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let i of this.generations){if(i.disabled)continue;for(let u of i.historyResolvers){let p=u(e,o);if(p)return p}}}policy(e){return this.generations.findLast((o)=>!o.disabled&&o.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as yB}from"fs";import{dirname as xB,resolve as BC}from"path";var Hh=new WeakMap;function GC(e){return[...e].map((o)=>{let i=Boolean(o.path&&(Boolean(o.definition.webEntry)||yB(BC(xB(BC(o.path)),"web.tsx"))));if(o.current&&!Hh.has(o.current))Hh.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?Hh.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 Wh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,i){this.host=e;this.deadline=o;this.fail=i}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,i){let u=this.host.pin(),p=(async()=>{try{let g=[];for(let y of u.generations){if(y.disabled)continue;for(let b of y.hooks.get(e)??[]){let E=y.hookOptions.get(b)?.timeoutMs,S=typeof E==="function"?E({runtime:this.host.runtime,session:o,connection:i}):E;g.push(this.deadline((w)=>b(o,{runtime:this.host.runtime,session:o,connection:i,signal:w}),S,!0).catch((w)=>this.fail(y,w)))}}await Promise.all(g)}finally{await u.release()}})();this.pending.add(p),p.then(()=>this.pending.delete(p),()=>this.pending.delete(p))}finishEntry(e,o,i){let u=i===void 0?void 0:mu(i),p=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await Ia.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,p),this.pending.add(p);let g=()=>{if(this.pending.delete(p),this.entryQueues.get(o)===p)this.entryQueues.delete(o)};p.then(g,g)}}function KC(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 IB(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 bB(e,o){let i=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!i)throw Error("Completion session not found");let u=o.model??i?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let p=En(e.options.models,u);if(!p&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!p){let g=(await e.models()).models.filter((b)=>b.available===!0),y=p?tt(p):u;if(!g.some((b)=>b.id===y)){let b=g[0];if(b)p=En(e.options.models,b.id)}}if(!p)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return p}async function HC(e,o){IB(o);let i=await bB(e,o),u=o.maxTokens??Math.min(i.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>i.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let p="",g=!1;try{let y=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],b=e.options.models.streamSimple(i,{messages:y},{maxTokens:u,signal:o.signal});for await(let E of b){if(o.signal?.aborted)throw Error("cancelled");if(E.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${KC(E.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(E.type==="text_delta")p+=E.delta;if(E.type==="done"){if(E.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(E.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${E.reason}\uFF09`);g=!0}}}catch(y){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${KC(y instanceof Error?y.message:String(y))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!g)throw Error("Model completion ended without a stop response; retry");return{text:p,model:tt(i)}}var EB=["active","archived","all"];function WC(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function SB(e){let{projectID:o,children:i,archive:u,since:p}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(i!==void 0&&typeof i!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!EB.includes(u))throw Error("sessions archive must be active, archived or all");if(p!==void 0&&!Number.isFinite(p))throw Error("sessions since must be a finite timestamp in milliseconds")}function wB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function zC(e){function o(i,u={}){let{types:p,bodies:g}=u;if(p!==void 0&&!Array.isArray(p))throw Error("sessions types must be an array");let y=WC(u.limit),b=u.after??0;if(!Number.isSafeInteger(b)||b<0)throw Error("sessions after must be a non-negative integer");let E=(e.get(i)?.entries(b)??[]).filter((S)=>p===void 0||p.includes(S.type)).slice(0,y);return structuredClone(g===!1?E.map(wB):E)}return{list(i={}){SB(i);let u=i.limit===void 0?void 0:WC(i.limit),p=e.list(i.children??!1,{archive:i.archive}).filter((g)=>i.projectID===void 0||g.projectID===i.projectID).filter((g)=>i.since===void 0||g.created>=i.since);return structuredClone(u===void 0?p:p.slice(0,u))},get(i){return structuredClone(e.get(i)?.info())},entries:o}}async function VC(e,o,i,u,p,g){let y={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},b=e.runtime.store.db,E=new Map,S=!1,w=!0,R=()=>{if(!w||y.disposed)throw Error("Plugin registration scope is closed")},A=(j,V)=>{if(R(),!S){E.set(j,V);return}if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)},P={get:(j)=>{R();let V=E.has(j)?E.get(j):b.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,j)?.value;return V==null?void 0:JSON.parse(V)},set:(j,V)=>{let J=JSON.stringify(V);if(J===void 0)throw Error("Plugin KV values must be JSON serializable");A(j,J)},delete:(j)=>A(j,null)},C=()=>{if(R(),S)throw Error("Register resources during setup only")},q=[...o.migrations??[]].sort((j,V)=>j.version-V.version),X=new Set;try{for(let j of q){if(!Number.isSafeInteger(j.version)||j.version<1||X.has(j.version))throw Error("Plugin migration versions must be unique positive integers");if(X.add(j.version),b.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,j.version))continue;b.transaction(()=>{if(j.sql!==void 0)b.run(j.sql);else j.up({...P,db:b});for(let[V,J]of E)if(J===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,V);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,V,J);b.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,j.version)})(),e.runtime.store.invalidateEntryCache(),E.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:zC(e.runtime),complete:(j)=>HC(e.runtime,j),kv:P,database:b,broadcast:(j)=>{e.runtime.emitEvent(j)},registerInputGate:(j)=>{C(),y.gates.push(j)},registerNoticeSource:(j,V)=>{if(C(),!j||!Number.isSafeInteger(V.textLimit)||V.textLimit<1||!Number.isSafeInteger(V.summaryLimit)||V.summaryLimit<1)throw Error("Notice source limits must be positive integers");y.noticeSources.set(j,{...V})},provide:(j,V)=>{if(C(),j.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(y.services.has(j.name))throw Error(`Duplicate plugin service: ${j.name}`);if(!j.validate(V))throw Error(`Invalid plugin service: ${j.name}`);y.services.set(j.name,V)},on:(j,V,J)=>{if(C(),J?.promptPosition&&j!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let ee=y.hooks.get(j)??[];if(ee.push(V),y.hooks.set(j,ee),J)y.hookOptions.set(V,J)},registerHistoryResolver:(j)=>{C(),y.historyResolvers.push(j)},registerTool:(j,V)=>{if(C(),!j.name||["toolsearch","tool_search","tool_call"].includes(j.name.toLowerCase())||TB(e,p,o.id).has(j.name.toLowerCase())||y.tools.some((ee)=>ee.name.toLowerCase()===j.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${j.name}`);let J=i?"always":"defer";if(typeof V?.defer==="boolean")J=V.defer?"defer":"always";else if(V?.defer!==void 0)J=V.defer;y.tools.push({...j,defer:J,source:`plugin:${o.id}`,group:V?.group,aliases:V?.aliases,builtin:i})},registerRoute:(j)=>{if(C(),!(j.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((V)=>j.path===V||j.path.startsWith(`${V}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(j.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(y.routes.some((V)=>V.path===j.path&&V.method===j.method))throw Error("Duplicate plugin route");y.routes.push(j)},registerWebSocket:(j)=>{if(C(),!j.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(y.websockets.some((V)=>V.path===j.path))throw Error("Duplicate plugin WebSocket route");y.websockets.push(j)},registerCommand:(j)=>{C(),y.commands.push(j)},registerWebContribution:(j)=>{C(),y.web.push(j)},registerToolPolicy:(j,V)=>{C(),y.policies.set(j,V)},appendExtension:(j,V)=>{if(Cs(),R(),!S)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(j,V)},onDeactivate:(j)=>{C(),y.deactivators.push(j)},onDispose:(j)=>{C(),y.disposers.push(j)}})),b.transaction(()=>{for(let[j,V]of E)if(V===null)b.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,j);else b.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,j,V)})(),E.clear(),S=!0,y}catch(j){throw w=!1,await g(y),j}}function TB(e,o,i){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((p)=>p.name)].map((p)=>p.toLowerCase()));for(let[p,g]of o){if(p===i)continue;for(let y of g.current?.tools??[])u.add(y.name.toLowerCase())}return u}class zh{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 JC(e,o,i,u){for(let p of o){let g=p.current;if(!g||g.disabled||g.retired)continue;let y=g.websockets.find((b)=>b.path===u);if(!y)continue;return{connect:(b)=>{let E=!1;g.references++,g.connections.add(b);let S={send:(R)=>{if(E||g.retired||g.disabled)return;b.send(R)},close:(R,A)=>b.close(R,A)},w=async(R)=>{if(E||g.retired||g.disabled){b.close(1012,"Plugin unavailable");return}try{await i(R),g.failures=0}catch(A){if(g.failures++,g.error=A instanceof Error?A.message:String(A),b.close(1011,"Plugin callback failed"),g.failures>=e.failureThreshold){g.disabled=!0;for(let P of g.connections)P.close(1011,"Plugin disabled")}}};return{open:()=>w(()=>y.open?.(S)),message:(R)=>w(()=>y.message(S,R)),close:async()=>{if(E)return;E=!0,g.connections.delete(b);try{await i(()=>y.close?.(S))}catch(R){g.error=R instanceof Error?R.message:String(R)}finally{g.references--,await e.collect(g)}}}}}}return}function Vh(e,o){let i=e.split("/"),u=new URL(o.url).pathname.split("/");if(i.length!==u.length)return;let p={};return i.every((y,b)=>{let E=u[b];if(E===void 0)return!1;if(!y.startsWith(":"))return E===y;try{p[y.slice(1)]=decodeURIComponent(E)}catch{return!1}return E.length>0})?p:void 0}async function QC(e,o,i,u,p){let g=e.pin();try{let y=g.generations.find((b)=>b.definition.id===i)?.commands.find((b)=>b.id===u);if(!y)throw new f("Plugin command is unavailable");return await o(()=>y.execute(p))}finally{await g.release()}}function XC(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((p)=>p.method===o.method&&Vh(p.path,o)!==void 0))}finally{i.release()}}function YC(e,o){let i=e.pin();try{return i.generations.some((u)=>u.routes.some((p)=>p.public===!0&&p.method===o.method&&Vh(p.path,o)!==void 0))}finally{i.release()}}async function ZC(e,o,i){let u=e.pin(),p=!0;try{for(let g of u.generations)for(let y of g.routes){if(y.method!==i.method)continue;let b=Vh(y.path,i);if(b){let E=await o(()=>y.handler(i,b),y.timeoutMs);if(!E)return;if(E.body&&E.body instanceof ReadableStream){p=!1;let S=!1,w=()=>{if(S)return;S=!0,u.release()},R=E.body.getReader(),A=new ReadableStream({async pull(P){try{let{done:C,value:q}=await R.read();if(C)P.close(),w();else P.enqueue(q)}catch(C){P.error(C),w()}},async cancel(P){try{await R.cancel(P)}finally{w()}}});return new Response(A,{status:E.status,statusText:E.statusText,headers:E.headers})}return E}}return}finally{if(p)await u.release()}}class Qh{runtime;options;slots=new Map;retirement=new zh(this.deadline.bind(this));observers=new Wh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new ll;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 Kh(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let i=o.current.services.get(e.name);if(!e.validate(i))throw new f(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return i}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((i)=>i(e)))}noticeSource(e){return[...this.slots.values()].findLast((i)=>i.enabled&&i.current&&!i.current.disabled&&i.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let i=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==i)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let i of e)this.directories.add(Jh(i));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await t$(e),i=[...this.directories,n$(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>n$(u.directory,".basalt","plugins"))];for(let u of i){if(!e$(u))continue;let p=kB(await t$(u),o);if(p&&p!==".."&&!p.startsWith(`..${AB}`)&&!RB(p)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),i=await this.checkEntry(o);if(!i.ok)throw new pt(i.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((i)=>i.level==="error").map((i)=>({file:i.position?.file??null,line:i.position?.line??null,column:i.position?.column??null,message:i.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,i=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,i)})}async installDefinition(e,o,i=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),p={definition:e,path:o,builtin:i,enabled:u?.enabled!==0};if(p.enabled)p.current=await this.stage(e,i);this.slots.set(e.id,p)}reload(e){return this.exclusive(async()=>{let o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let b=await this.checkEntry(o.path);if(!b.ok)throw new pt(b.errors)}let i=o.builtin&&!e$(o.path)?o.definition:await this.catalog.read(o.path);if(i.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((b)=>b.definition.id===e?i:b.definition),!0),p=await this.stage(i),g=o.current;o.definition=i,o.current=p,o.error=void 0,o.discoveryFailed=!1;let y=new Map(this.slots);this.slots.clear();for(let b of u){let E=y.get(b.id);if(E)this.slots.set(b.id,E)}if(g)await this.retirement.retire(g)}catch(i){throw o.error=i instanceof Error?i.message:String(i),i}})}setEnabled(e,o){return this.exclusive(async()=>{let i=this.require(e);if(o===i.enabled&&(!o||i.current&&!i.current.disabled))return;if(!o){for(let y of this.slots.values())if(y.enabled&&y.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${y.definition.id}`)}let u=o&&i.discoveryFailed&&i.path?await this.catalog.read(i.path):i.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let p=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let g=i.current;if(i.definition=u,o)i.discoveryFailed=!1;if(i.enabled=o,i.current=p,i.error=void 0,g)await this.retirement.retire(g)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let i of e.deps??[])if(i===e.id||!this.slots.get(i)?.current||this.slots.get(i)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${i}`);return VC(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,i){this.observers.notify(e,o,i)}resolveHistory(e,o){for(let i of this.slots.values()){if(!i.enabled||!i.current||i.current.disabled)continue;for(let u of i.current.historyResolvers){let p=u(e,o);if(p)return p}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Gc(this,e)}async invoke(e,o,i,u,p,g="end"){return UC(this,this.deadline.bind(this),this.fail.bind(this),e,o,i,u,p,g)}pinEntry(e){if(Ia.getStore()?.phase==="after")return;let o;for(let i of this.slots.values()){let u=i.current;if(!i.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Gc(this,o)}beforeEntry(e,o,i,u){return jC(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 DC(e,o,i)}appendExtension(e,o){return Cs(),new Promise((i)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let p=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),i(p)})}list(){return GC(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,r$(Jh(o.path)));return{ok:!0}}catch(o){if(o instanceof pl)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,r$(Jh(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 QC(this,this.deadline.bind(this),e,o,i)}hasRoute(e){return XC(this,e)}isPublicRoute(e){return YC(this,e)}route(e){return ZC(this,this.deadline.bind(this),e)}websocket(e){return JC(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 o$}from"fs";import{join as PB}from"path";var CB=500,$B=1000,vB=3600000,MB=5000,OB=2000,_B=3,LB=1073741824;class Xh{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;constructor(e){this.options=e;if(this.indexPath=PB(e.dataDir,Si),this.features={...wi(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,i=o?.backfill;if(!o||!i)return{...e,state:"backfilling"};if(i.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(i.total,i.done),indexed:i.done,state:i.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=o$(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=o$(this.options.store.path).size}catch{}return Math.max(LB,Math.round(e*0.6))}async setEnabled(e){if(this.closed||e===this.enabledFlag)return;if(this.enabledFlag=e,this.failure=void 0,this.restarts=0,e){if(this.clearTimer)clearInterval(this.clearTimer);if(this.clearTimer=void 0,this.usable)this.start();else this.idleMaintenance()}else await this.stopWorker(),this.idleMaintenance();this.pushStatus()}async rebuild(){if(!this.usable)return;await this.stopWorker(),Yn(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.worker;if(!o)return e();Atomics.store(this.flags,He,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,Et,0,MB);try{return e()}finally{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=vi(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,He,0),Atomics.store(this.flags,Et,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,i=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),i&&this.restarts<_B&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,He,0),Atomics.notify(this.flags,He);let o=new Promise((i)=>{this.stopped=i});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(OB)]),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,CB-(performance.now()-this.lastPrune));this.pruneTimer=setTimeout(()=>{this.pruneTimer=void 0,this.prune()},e),this.pruneTimer.unref?.()}prune(){let e=this.engineStatus?.queueDone??0;if(e<=this.pruned)return;this.lastPrune=performance.now();try{this.options.store.db.query("DELETE FROM search_queue WHERE id <= ?").run(e),this.pruned=e}catch{}}idleMaintenance(){if(this.engineStatus=void 0,!this.enabledFlag)Yn(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),vB),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,$B-(performance.now()-this.lastPush)),i=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),p=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(p===this.lastPushed)return;this.lastPushed=p,this.lastPush=performance.now(),e(u)};if(o===0)i();else this.statusTimer=setTimeout(i,o),this.statusTimer.unref?.()}}import{existsSync as du,mkdirSync as BB,readdirSync as l$,readFileSync as u$,realpathSync as Yh,statSync as Pl,writeFileSync as Zh}from"fs";import{dirname as Al,isAbsolute as eg,relative as d$,resolve as GB}from"path";import{existsSync as Kc}from"fs";import{dirname as jB,join as lu}from"path";import{mkdirSync as NB,writeFileSync as DB}from"fs";import{tmpdir as qB}from"os";import{join as s$}from"path";var Tl=2000,Te=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function pu(e,o){return e.map((i,u)=>{let p=i.length>Tl?`${i.slice(0,Tl)}\u2026 [line truncated]`:i;return`${String(o+u).padStart(6)} ${p}`}).join(`
90
- `)}function de(e,o){if(e.length<=o)return e;let i=Math.floor(o*0.4),u=o-i,p=e.length-i-u,g=e.slice(i,e.length-u).split(`
91
- `).length-1;return`${e.slice(0,i)}
92
-
93
- \u2026 [${p} characters, ~${g} lines omitted] \u2026
94
-
95
- ${e.slice(-u)}`}var FB=0;function rt(e,o,i){if(e.length<=o)return e;let u=de(e,o);try{let p=i?id(i):s$(qB(),"basalt-output");NB(p,{recursive:!0});let g=s$(p,`${process.pid}-${Date.now().toString(36)}-${FB++}.txt`);return DB(g,e),`${u}
96
- [Full output saved to ${g}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var i$=120000,a$=600000,ba;function UB(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function tr(){if(ba!==void 0)return ba||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let p=lu(u,"bash.exe");if(UB(p))continue;if(Kc(p))return ba=p,p}for(let u of o){let p=lu(u,"git.exe");if(Kc(p)){let g=jB(u),y=lu(g,"bin","bash.exe");if(Kc(y))return ba=y,y;let b=lu(g,"usr","bin","bash.exe");if(Kc(b))return ba=b,b}}let i=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?lu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?lu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of i)if(Kc(u))return ba=u,u;ba="";return}class Rl{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let i=0;while(i<o.length){if(o[i]<128){i+=1;continue}let p=o[i+1];if(p===void 0)break;let g=p>=48&&p<=57?4:2;if(i+g>o.length)break;i+=g}return this.gbkPending=o.slice(i),this.gbk.decode(o.subarray(0,i))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let i=new Uint8Array(this.sniffPending.length+e.length);if(i.set(this.sniffPending),i.set(e,this.sniffPending.length),i.length<2)return this.sniffPending=i,"";this.sniffPending=void 0;let u=i[0]===255&&i[1]===254,p=!1;for(let g=1;g<i.length;g+=2)if(i[g]===0){p=!0;break}this.isUtf16=u||p,o=i}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function Ea(e,o){let i=process.platform==="win32",u=o??"auto";if(!i)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[tr()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let p=tr();if(p)return{argv:[p,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function rr(e,o){let i=await je(e,o.signal);if(i)return{output:i,code:126,timedOut:!1};let{argv:u,isWindows:p}=Ea(e,o.shell),g=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!p,windowsHide:!0,env:{...process.env,...em(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...p?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((ee)=>ee.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),y=!1,b=()=>{try{if(p)g.kill();else process.kill(-g.pid,"SIGKILL")}catch{}},E=setTimeout(()=>{y=!0,b()},o.timeout);o.signal?.addEventListener("abort",b,{once:!0});let S=Te*2,w="",R="",A=0,P=0,C="",q=(ee=!1)=>{let ae=A-w.length-R.length,H=ae>0?`${w}
97
- \u2026 [${ae} characters omitted] \u2026
98
- ${R}`:w+R;if(!ee)return de(H,Te);return rt(C.length===A?C:H,Te,o.cwd)},X=()=>{let ee=new Rl;return async(ae)=>{for await(let ue of ae){let he=ee.decode(ue);if(A+=he.length,C.length<4000000)C+=he;if(w.length<S)w+=he;else R=(R+he).slice(-S);if(o.onOutput){let $e=performance.now();if($e-P>=80)P=$e,o.onOutput(q())}}let H=ee.flush();if(H){if(A+=H.length,C.length<4000000)C+=H;if(w.length<S)w+=H;else R=(R+H).slice(-S)}}},j=Promise.all([X()(g.stdout),X()(g.stderr)]),V=await g.exited;if(clearTimeout(E),o.signal?.removeEventListener("abort",b),await Promise.race([j.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
99
- [background processes are still running; their later output is not captured]`;return{output:q(!0),code:y?null:V,timedOut:y}}class tg{seen=new Map;mark(e,o=Pl(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return Pl(e).mtimeMs!==o?"changed":void 0}}var c$=2000,KB=500,HB=10485760,kl=20,WB=6,zB=40000,VB=80000;function JB(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 f$(e,o,i=[],u){let p=(C)=>eg(C)?C:GB(e,C),g=(C)=>{let q=d$(e,C);return q&&!q.startsWith("..")&&!eg(q)?q:C},y=(C)=>{let q=C;while(!du(q)&&Al(q)!==q)q=Al(q);let X=Yh(q);if(i.some((j)=>du(j)&&p$(Yh(j),X))&&!p$(Yh(e),X))throw Error("External directories are read-only")},b=(C,q,X)=>{let j=p(C);if(!du(j))throw Error(`No such file or directory: ${j}${ZB(j)}`);let V=Pl(j);if(V.isDirectory()){let pe=l$(j,{withFileTypes:!0}).map((Je)=>Je.isDirectory()?`${Je.name}/`:Je.name).sort(),qe=pe.slice(0,KB),xt=pe.length-qe.length;return c(`${qe.join(`
100
- `)}${xt>0?`
101
- \u2026 and ${xt} more entries`:""}`||"(empty directory)").content}let J=u$(j),ee=JB(J);if(ee){if(V.size>HB)throw Error(`${j} exceeds the 10 MB image limit (${V.size} bytes)`);return o.mark(j),[{type:"text",text:`Read image ${g(j)} (${ee}, ${V.size} bytes)`},{type:"image",data:J.toString("base64"),mimeType:ee}]}if(J.subarray(0,8192).includes(0))throw Error(`${j} looks like a binary file (${V.size} bytes)`);o.mark(j);let ae=J.toString("utf8");if(!ae)return c("(empty file)").content;let H=ae.replace(/\r?\n$/,"").split(/\r?\n/),ue=(q??1)-1;if(ue>=H.length)throw Error(`offset ${q} is past the end of the file (${H.length} lines)`);let he=Math.min(H.length,ue+(X??c$)),$e=0,Ee=ue;while(Ee<he){let pe=H[Ee]?.length??0;if(Ee>ue&&$e+pe>zB)break;$e+=pe,Ee++}let se=pu(H.slice(ue,Ee),ue+1);if(Ee<he)se+=`
102
-
103
- (Showing lines ${ue+1}-${Ee} of ${H.length} (truncated at line ${Ee} due to safety budget). Use offset/limit to read specific windows.)`;else if(ue>0||Ee<H.length)se+=`
104
-
105
- (Showing lines ${ue+1}-${Ee} of ${H.length}. Use offset/limit to read other parts.)`;return c(se).content},E=x({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
106
- - path may be absolute or relative to the working directory.
107
- - By default reads up to ${c$} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
108
- - Lines longer than ${Tl} characters are truncated.
109
- - Reading a directory lists its entries (directories end with /).
110
- - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
111
- - To read several files at once, give paths instead of path (up to ${kl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
112
- - Always read a file before editing or overwriting it.`,parameters:l({path:n(a({description:"File or directory path"})),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"})),paths:n(B(l({path:a({description:"File or directory path"}),offset:n(_({minimum:1,description:"1-based line number to start from"})),limit:n(_({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:kl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(C,q){let X=[...q.path!==void 0?[{path:q.path,offset:q.offset,limit:q.limit}]:[],...q.paths??[]];if(X.length===0)throw Error("Give path, or paths to read several files");if(X.length===1){let ae=X[0];return{content:b(ae.path,ae.offset,ae.limit),details:void 0}}if(X.length>kl)throw Error(`Read at most ${kl} paths per call`);let j=[],V=[],J=0,ee=(ae)=>{let H=j.at(-1);if(ae.type==="text"&&H?.type==="text")H.text+=`
113
-
114
- ${ae.text}`;else j.push(ae)};for(let ae of X){let H=`==> ${g(p(ae.path))} <==`;if(J>=VB){ee({type:"text",text:`${H}
115
- (Skipped due to total read safety budget; read in separate calls)`});continue}try{let ue=b(ae.path,ae.offset,ae.limit);for(let he=0;he<ue.length;he++){let $e=ue[he];if(!$e)continue;if($e.type==="text")J+=$e.text.length,ee(he===0?{...$e,text:`${H}
116
- ${$e.text}`}:$e);else ee($e)}}catch(ue){let he=ue instanceof Error?ue.message:String(ue);V.push(he),ee({type:"text",text:`${H}
117
- Error: ${he}`})}}if(V.length===X.length)throw Error(V.join(`
118
- `));return{content:j,details:void 0}}}),S=async(C,q,X,j)=>{let V=j?.update,J=await rr(C,{cwd:e,timeout:120000,signal:X,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:V?(he)=>V(c(`${j.prefix}
119
-
120
- $ ${C}
121
- ${he.trimEnd()}`)):void 0}),ee=J.output.trimEnd()||"(no output)",ae=J.timedOut?"killed after 120s timeout":J.code===0?"exit code 0":`exit code ${J.code}`,H=J.timedOut||J.code!==0,ue=H?`
122
- ${q}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
123
-
124
- $ ${C}
125
- ${ee}
126
- [${ae}]${ue}`,failed:H}},w=(C,q=!1)=>{let X=o.check(C);if(X==="changed")return`Note: ${g(C)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(X==="unread"&&q)return`Note: ${g(C)} existed and had not been read; it was replaced whole.`;return},R=x({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
127
- - An existing file is replaced whole, including changes made since you last read it.
128
- - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
129
- - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
130
- - Do not create documentation or README files unless asked.`,parameters:l({path:a({description:"File path"}),content:a({description:"The full file content"}),then_run:n(a({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(C,q,X,j){let V=p(q.path);y(V);let J=du(V),ee;if(J){if(Pl(V).isDirectory())throw Error(`${V} is a directory`);ee=w(V,!0)}BB(Al(V),{recursive:!0}),Zh(V,q.content),o.mark(V);let ae=q.content?q.content.split(`
131
- `).length:0,H=`${J?"Overwrote":"Created"} ${g(V)} (${ae} lines)${ee?`
132
- ${ee}`:""}`;if(q.then_run){let ue=await S(q.then_run,`${g(V)} was written as given`,X,{prefix:H,update:j});if(H+=ue.out,ue.failed)return{...c(H),isError:!0}}return c(H)}}),A=(C,q,X,j)=>{let V=p(C);if(!du(V))throw Error(`File not found: ${V} (use write to create it)`);y(V);let J=w(V),ee=u$(V,"utf8"),ae=ee,H=ae.includes(`\r
133
- `),ue=[],he=[],$e=0,Ee=0;return q.forEach((se,pe)=>{let qe=j?`edits[${X+pe}]: `:"";try{if(se.old_string===se.new_string)throw Error(`${qe}old_string and new_string are identical`);if(!se.old_string)throw Error(`${qe}old_string is empty (use write to create or replace a whole file)`);let xt=H&&!se.old_string.includes(`\r
134
- `),Je=xt?se.old_string.replace(/\n/g,`\r
135
- `):se.old_string,Yt=xt?se.new_string.replace(/\n/g,`\r
136
- `):se.new_string,Fe=QB(ae,Je).map((At)=>[At,At+Je.length]);if(Fe.length===0)Fe=XB(ae,Je);if(Fe.length===0)throw Error(`${qe}old_string not found in ${g(V)}; read the relevant lines and copy the exact text.${YB(ae,Je)}`);if(Fe.length>1&&!se.replace_all){let At=Fe.map(([st])=>m$(ae,st)).join(", ");throw Error(`${qe}old_string occurs ${Fe.length} times (lines ${At}); add surrounding lines to make it unique, or set replace_all.`)}let Ue=m$(ae,Fe[0][0]),Dt=se.replace_all?Fe:[Fe[0]],lt="",Mt=0;for(let[At,st]of Dt)lt+=ae.slice(Mt,At)+Yt,Mt=st;ae=lt+ae.slice(Mt),$e++,Ee+=Dt.length;let yr=ae.split(/\r?\n/),pr=Ue+Yt.split(/\r?\n/).length-1,jt=Math.max(1,Ue-1),ot=Math.min(yr.length,pr+1);if(ot-jt+1<=WB+2)ue.push(pu(yr.slice(jt-1,ot),jt));else ue.push(`${pu(yr.slice(jt-1,Ue+1),jt)}
137
- \u2026 (${pr-Ue-3} lines as given)
138
- ${pu(yr.slice(pr-2,ot),pr-1)}`)}catch(xt){he.push(xt instanceof Error?xt.message:String(xt))}}),{path:V,original:ee,content:ae,echoes:ue,applied:$e,total:Ee,count:q.length,note:J,failed:he}},P=x({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
139
- - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
140
- - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
141
- - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
142
- - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
143
- - To create a file use write; to delete or move files use bash.
144
- - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
145
- - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(a({description:"File path (the default for edits items without their own path)"})),old_string:n(a({description:"The exact text to replace (only when edits is absent)"})),new_string:n(a({description:"The replacement text (only when edits is absent)"})),replace_all:n(O({description:"Replace every occurrence (default false)"})),edits:n(B(l({path:n(a({description:"The file of this replacement, when it is not path"})),old_string:a({description:"The exact text to replace"}),new_string:a({description:"The replacement text"}),replace_all:n(O({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(a({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(C,q,X,j){let V=q.edits&&q.edits.length>0?q.edits.map((se)=>({path:se.path??q.path,step:se})):q.old_string!==void 0&&q.new_string!==void 0?[{path:q.path,step:{old_string:q.old_string,new_string:q.new_string,replace_all:q.replace_all}}]:[];if(V.length===0)throw Error("Give old_string and new_string, or edits");let J=V.length>1,ee=new Map;V.forEach((se,pe)=>{if(!se.path)throw Error(`${J?`edits[${pe}]: `:""}path is required`);let qe=p(se.path),xt=ee.get(qe)??{raw:se.path,steps:[],offset:pe};xt.steps.push(se.step),ee.set(qe,xt)});let ae=[],H=[];for(let se of ee.values())try{let pe=A(se.raw,se.steps,se.offset,J);if(pe.applied>0)ae.push(pe);H.push(...pe.failed)}catch(pe){let qe=pe instanceof Error?pe.message:String(pe);H.push(`${J?`edits[${se.offset}]: `:""}${qe}`)}if(ae.length===0)throw Error(H.join(`
146
- `));let ue=[];try{for(let se of ae)Zh(se.path,se.content),ue.push(se)}catch(se){for(let pe of ue)Zh(pe.path,pe.original);throw se}for(let se of ae)o.mark(se.path);let $e=ae.map((se)=>{let pe=se.total===1?"1 occurrence":`${se.total} occurrences`,qe=se.note?`
147
- ${se.note}`:"";if(!J)return`Edited ${g(se.path)} (${pe}).${qe}
148
- ${se.echoes[0]}`;let xt=se.failed.length>0?`, ${se.failed.length} failed`:"";return`Edited ${g(se.path)} (${se.applied} edits${xt}, ${pe}). Regions are shown as they were right after each edit; later edits may shift line numbers.${qe}
149
- ${se.echoes.map((Je,Yt)=>`--- edit ${Yt+1}
150
- ${Je}`).join(`
151
- `)}`}).join(`
152
-
153
- `),Ee=!1;if(q.then_run){let se=await S(q.then_run,"The edits above were applied",X,{prefix:$e,update:j});if($e+=se.out,se.failed)Ee=!0}if(H.length>0)$e+=`
154
-
155
- ${H.length===1?"1 edit":`${H.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
156
- - ${H.join(`
157
- - `)}`,Ee=!0;return Ee?{...c($e),isError:!0}:c($e)}});return[_e(E,"cat","view","read_file","view_file","open_file","open"),_e(R,"write_file","create_file","new_file","save_file"),_e(P,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function QB(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 m$(e,o){let i=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)i++;return i}function XB(e,o){let i=o.replace(/\r?\n$/,"").split(/\r?\n/).map((E)=>E.trimEnd()),u=[],p=e.split(`
158
- `),g=0;for(let E of p)u.push(g),g+=E.length+1;let y=p.map((E)=>E.replace(/\r$/,"").trimEnd()),b=[];for(let E=0;E+i.length<=y.length;E++)if(i.every((S,w)=>y[E+w]===S)){let S=E+i.length-1,w=u[S]+p[S].replace(/\r$/,"").length,R=o.endsWith(`
159
- `)&&w<e.length?e[w]==="\r"?2:1:0;b.push([u[E],w+R]),E+=i.length-1}return b}function YB(e,o){let i=(b)=>b.replace(/\s+/g," ").trim(),u=i(o);if(!u)return"";let p=e.split(/\r?\n/),g=o.split(/\r?\n/).length;for(let b=0;b+g<=p.length;b++)if(i(p.slice(b,b+g).join(`
160
- `))===u)return` A match ignoring whitespace exists at line ${b+1}; copy the exact indentation and line breaks from the read output:
161
- ${de(pu(p.slice(b,b+g),b+1),4000)}`;let y=o.split(/\r?\n/).find((b)=>b.trim())?.trim();if(y){let b=p.findIndex((E)=>E.includes(y));if(b!==-1)return` Its first line appears at line ${b+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function ZB(e){let o=Al(e);if(!du(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let p=l$(o).filter((g)=>{let y=g.toLowerCase().replace(/\.[^.]*$/,"");return y&&(y.includes(u)||u.includes(y))}).slice(0,5);return p.length?`. Did you mean: ${p.join(", ")}?`:""}function p$(e,o){let i=d$(e,o);return i===""||!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&i!==".."&&!eg(i)}var rg=20,ng=80,eG=5,tG=(e)=>e!==void 0&&e>0?e:void 0;function h$(e,o){let i=Sl(e,o)??wl(e,o);if(!i)throw Error(`No user message with seq ${o}`);return i}function Cl(e,o){let i=(y)=>{if(o)return o(y);if(y.source&&y.source!=="self"||y.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(y)=>{let b=i(y),E=tG(y.seq);return{scope:b,seq:E,runs:()=>Ks(b.records),reference:`session_id=${b.sessionID}`,both:E!==void 0&&y.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
162
- `:""}},p=x({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
163
- - Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
164
- - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),pattern:a({minLength:1,description:"Text to search for"}),also:n(B(a({minLength:1}),{maxItems:eG,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(a({description:"Only search this chunk"})),seq:n(_({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(O({description:"Default false"})),head_limit:n(_({minimum:1,maximum:rg,description:`Hits to return (default ${rg})`})),offset:n(_({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(y,b){let{scope:E,seq:S,runs:w,reference:R,both:A}=u(b),P;if(S!==void 0)P=[h$(E.records,S)];else{let ue=w(),he=b.chunk_id?ue.filter(($e)=>$e.id===b.chunk_id):ue;if(b.chunk_id&&!he.length)throw Error(`No chunk ${b.chunk_id}. Chunk IDs look like r12.`);P=he.map(cu)}let C=(ue)=>b.case_sensitive?ue:ue.toLowerCase(),q=[b.pattern,...(b.also??[]).filter(Boolean)].map(C),X=b.head_limit??rg,j=b.offset??0,V=[],J=new Map,ee=0;for(let ue of P)ue.forEach((he,$e)=>{let Ee=C(he.text);if(!q.every((pe)=>Ee.includes(pe)))return;if(J.set(he.chunk,(J.get(he.chunk)??0)+1),ee++,ee<=j||V.length>=X)return;let se=ue.slice(Math.max(0,$e-2),$e+3);V.push(`${R} chunk ${he.chunk} line ${he.line}:
165
- ${Bc(se," ")}`)});if(!ee)return c(`${A}No matches`);if(!V.length)return c(`${A}No matches at offset ${j} (total ${ee})`);let ae=ee-j-V.length,H=J.size>1?` (all matches by chunk: ${[...J].map(([ue,he])=>`${ue} ${he}`).join(", ")})`:"";return c(`${A}${V.join(`
166
-
167
- `)}${ae>0?`
168
-
169
- \u2026 ${ae} more matches${H}; continue with offset=${j+V.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),g=x({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(a()),session_id:n(a({description:"Source session ID from the reference"})),chunk_id:n(a({description:"Chunk to read"})),seq:n(_({description:"User message to read (from a user-text-reference)"})),offset:n(_({minimum:0,description:"First line (default 0)"})),limit:n(_({minimum:1,maximum:ng,description:`Lines to return (default ${ng})`}))}),async execute(y,b){let{scope:E,seq:S,runs:w,reference:R,both:A}=u(b),P;if(S!==void 0)P=h$(E.records,S);else if(b.chunk_id){let j=w().find((V)=>V.id===b.chunk_id);if(!j)throw Error(`No chunk ${b.chunk_id}. Chunk IDs look like r12.`);P=cu(j)}else{let j=w().map((V)=>`${R} ${V.id} (${V.status}, ${cu(V).length} lines)`);return c(j.length?`Pass chunk_id or seq. Chunks in this session:
170
- ${j.join(`
171
- `)}`:"This session has no history yet")}let C=b.offset??0,q=P.slice(C,C+(b.limit??ng));if(!q.length)return c(`No lines at offset ${C} (total ${P.length})`);let X=P.length-C-q.length;return c(`${A}${R} ${S!==void 0?`seq=${S}`:b.chunk_id}
172
- ${Bc(q)}${X>0?`
173
-
174
- \u2026 ${X} more lines; continue with offset=${C+q.length}`:""}`)}});return[p,g]}import{statSync as rG}from"fs";import{isAbsolute as g$,relative as nG,resolve as y$}from"path";var $l=200,oG=30000,vl=Bun.which("rg");async function og(e,o,i){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:i,windowsHide:!0}),[p,g,y]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(y>1)throw Error(g.trim()||`${e[0]} exited with ${y}`);return p}function x$(e){let o=(g)=>g?g$(g)?g:y$(e,g):e,i=(g)=>{let y=nG(e,g);return y&&!y.startsWith("..")&&!g$(y)?y:g},u=x({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
175
- - Respects .gitignore and skips .git. Use it instead of find or ls -R.
176
- - To search file contents, use grep.`,parameters:l({pattern:a({description:"Glob pattern, matched relative to path"}),path:n(a({description:"Directory to search (default: working directory)"}))}),async execute(g,y,b){let E=o(y.path),S;if(vl)S=(await og([vl,"--files","--hidden","--glob","!.git","--glob",y.pattern],E,b)).split(`
177
- `).filter(Boolean);else{S=[];for await(let P of new Bun.Glob(y.pattern).scan({cwd:E,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(P))S.push(P)}if(!S.length)return c("No files found");let w=S.map((P)=>{let C=y$(E,P);try{return{path:C,time:rG(C).mtimeMs}}catch{return{path:C,time:0}}});w.sort((P,C)=>C.time-P.time);let R=w.slice(0,$l).map((P)=>i(P.path)),A=S.length-R.length;return c(`${R.join(`
178
- `)}${A>0?`
179
- \u2026 ${A} more files; narrow the pattern`:""}`)}}),p=x({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
180
- - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
181
- - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
182
- - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
183
- - Use this instead of running grep or rg through bash.`,parameters:l({pattern:a({description:"Regular expression"}),path:n(a({description:"File or directory to search (default: working directory)"})),glob:n(a({description:"Only search files matching this glob"})),output:n(m([s("files"),s("content"),s("count")],{description:"Output mode (default files)"})),ignore_case:n(O()),context:n(_({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(g,y,b){let E=o(y.path),S=y.output??"files",w;if(vl){let P=[vl,"--hidden","--glob","!.git","--max-columns","400","--max-columns-preview"];if(y.ignore_case)P.push("-i");if(y.glob)P.push("--glob",y.glob);if(S==="files")P.push("-l");else if(S==="count")P.push("-c");else if(P.push("-n","--no-heading"),y.context)P.push("-C",String(y.context));P.push("--",y.pattern,E),w=await og(P,e,b)}else{let P=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(y.ignore_case)P.push("-i");if(y.glob)P.push(`--include=${y.glob}`);if(S==="files")P.push("-l");else if(S==="count")P.push("-c");else if(P.push("-n"),y.context)P.push(`-C${y.context}`);P.push("--",y.pattern,E),w=await og(P,e,b)}let R=`${e}/`,A=w.split(`
184
- `).filter(Boolean).map((P)=>P.startsWith(R)?P.slice(R.length):P).filter((P)=>S!=="count"||!P.endsWith(":0"));if(!A.length)return c("No matches");if(S==="files"&&A.length>$l)return c(`${A.slice(0,$l).join(`
185
- `)}
186
- \u2026 ${A.length-$l} more files; narrow the search`);return c(rt(A.join(`
187
- `),oG,e))}});return[_e(u,"find","find_files","list_files","file_search","ls","list","list_dir"),_e(p,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function I$(e){return _e(x({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
188
- Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
189
- - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
190
- - Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
191
- - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:B(l({content:a({minLength:1,description:"What to do, in imperative form"}),status:m(jg.map((o)=>s(o)))}))}),async execute(o,i){let u=i.todos.map((y)=>({content:y.content,status:y.status}));e(u);let p=u.filter((y)=>y.status==="completed").length,g=u.find((y)=>y.status==="in_progress");return c(`Todo list updated (${p}/${u.length} completed${g?`; in progress: ${g.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function b$(e){let o=ce(e);return{target:o,hard:o,index:o}}class Ml{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},i){this.records=e;this.cwd=o;if(i)this.defaultPolicy=new Uc(e,i,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??b$(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??ce(e)}prepare(e,o,i,u,p=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,i,u);let g=e.reduce((S,w)=>S+F(w),0)+Ni(o),y=Math.max(0,ce(i)*this.recoveryRatio-g),b=Re(u??this.records(),i,b$(i),{cwd:this.cwd()}).messages,E=b.reduce((S,w)=>S+F(w),0);if(p&&E>y)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(E>y&&b.length>1){let S=b.shift();if(S)E-=F(S);while(b[0]?.role==="toolResult"){let w=b.shift();if(w)E-=F(w)}}if(E>y){let S=b.at(-1),w=S&&"content"in S&&typeof S.content==="string"?S.content:"[Context omitted: use history tools to retrieve earlier messages.]";b.length=0;let R=w;while(R&&F({role:"user",content:R,timestamp:0})>y)R=R.slice(Math.ceil(R.length/2));if(R)b.push({role:"user",content:R,timestamp:0});E=b.reduce((A,P)=>A+F(P),0)}return this.lastMessageCount=b.length,{messages:[...e,...b],estimate:g+E}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as E$,readFileSync as sG}from"fs";import{homedir as iG}from"os";import{dirname as aG,join as S$}from"path";var uG=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
192
-
193
- # How to work
194
-
195
- - Complete the task end to end. Keep going until the user's request is fully resolved before ending your turn: investigate, make the change, verify it. Do not stop halfway to report a plan or ask "should I continue?" when the next step is clear.
196
- - Ask the user only when you are genuinely blocked: the request is ambiguous in a way that changes the outcome, or the action is destructive or irreversible. Otherwise make a reasonable choice, state the assumption briefly, and proceed.
197
- - If the user only asks a question or asks for a plan or review, answer it; do not start changing files. For a review, lead with findings: bugs, risks, behavior regressions and missing tests, ordered by severity with file:line. Keep any summary short and after the findings.
198
- - Do not use the todo tool for a single deliverable, even a complex one (implementing a feature, fixing a bug, writing a module and its tests): work through it directly with a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later. Never make reading, environment checks or the final summary into items, and update it only together with your next action, never as a turn of its own.
199
-
200
- # Making changes
201
-
202
- - Investigate before changing anything. Find the relevant code with grep/glob, read it, and understand how it is used. Edit from what you have actually seen: a read, or grep output with enough context to copy the text exactly.
203
- - Verify unfamiliar technical entities instead of recalling them. When a task involves a library, API, tool or version you do not confidently recognize, check the project first: package manifests and lockfiles, \`--version\`, or the installed sources. A fluent answer built on an outdated memory looks right and is wrong. Never guess URLs; use only ones the user or the project gave you.
204
- - Follow the conventions of the existing code: style, naming, structure, libraries, error handling, comment density, test layout. Before using a library, confirm the project already depends on it.
205
- - Fix the root cause, not the symptom. Keep changes minimal and focused on the task; do not refactor, rename or "clean up" unrelated code, and do not add features that were not requested. Between two correct approaches, prefer the smaller one. Do not add backward-compatibility code unless something concrete needs it (persisted data, shipped behavior, external consumers, an explicit requirement).
206
- - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
207
- - Do not add comments that narrate the change ("added this", "fixed bug"). Comment only where the code is not self-explanatory, in the style of the surrounding code.
208
-
209
- # Verifying
210
-
211
- - Verify behaviour the way the user would see it. When asked to test a feature, or after a change with user-visible effects, run the real thing first: start the app or server with bash background=true, exercise the changed path (curl an endpoint, run the CLI with real input, or drive a web UI with the browser tools: open, act, then browser_screenshot and look at the image), and confirm the result matches the requirement. Unit tests complement this; they do not replace it, and "the tests pass" is not evidence the feature works.
212
- - For code with no runnable surface (a library, a refactor, types, build config), or when the app cannot be started here, run the most specific tests, type checker, linter or build instead \u2014 find how in the project's README, package scripts, Makefile or CI config \u2014 and say what you could not exercise.
213
- - Once the change is verified, stop: re-verify only after new changes, failures or a concrete unresolved concern. Do not re-run a check that already passed when nothing it covers has changed. Kill servers and close pages you started.
214
- - Do not re-read a file after your own edit or re-check mkdir/delete/move results: an edit result already shows the new content, and a failing call reports an error. Re-read only if someone else changed the file.
215
- - When a step fails, read the error and diagnose why before retrying. Do not loop on the same failing approach; after two failed attempts, step back and reconsider. If a tool call is blocked, do not retry it unchanged; follow the stated reason or ask the user.
216
-
217
- # Tools
218
-
219
- - Tool calls are the only way to act; describing an action does not perform it.
220
- - Use the dedicated tools for files: read to view (paths reads several files in one call), edit for replacements (give edits for several changes, even across files), write to create or rewrite a file, grep to search contents, glob to find files. A quick read-only look (ls, cat, sed -n) may share a bash command with other work, such as listing a directory while checking tool versions; to only view or edit a file, use read and edit.
221
- - Create files you will keep or edit later with write, passing then_run to run them or their tests in the same step. A file written by a bash heredoc has not been read through the tools, so a later edit of it costs an extra step; a heredoc is fine for a throwaway script that the same command runs.
222
- - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
223
- - In bash, search with rg / rg --files when it exists (much faster than grep/find). Do not join commands with echo or printf separators such as an echo '====' line; the output gets noisy. Do not use python or other scripts just to print or edit file contents when read, edit will do. Backticks and $() inside a command still execute, so escape text carefully.
224
- - Put every tool call you already know into one response. Independent reads and searches run in parallel; calls that change things (edit, write, bash) run one after another in the order you give them, so you can edit a file and run its tests in the same response. Put all replacements of one logical change (for example an import, a helper and its call sites, plus the matching test) into one edit call's edits and pass then_run with the test command, instead of one edit per spot followed by a separate test run. Pass then_run to write as well. When probing behaviour, batch the checks into one script instead of one command each.
225
- - Use bash for builds, tests, git, package managers and running programs. Each bash call starts in the project directory; use absolute or project-relative paths and chain dependent steps with &&.
226
- - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished, including dev servers you start to verify a change. Do not busy-wait or poll repeatedly.
227
-
228
- # Honesty
229
-
230
- - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
231
- - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
232
- - When the user asks you to run something, run it, even when you can predict the result.
233
- - If a step failed, was skipped or could not be verified, say which one and why.
234
-
235
- # Safety
236
-
237
- - Do not run destructive or irreversible commands (rm -rf on broad paths, git reset --hard, git push --force, dropping databases, killing unrelated processes) unless the user explicitly asked for exactly that.
238
- - Never commit, push, create branches or rewrite git history unless the user asks. If asked to commit, write a concise message that explains why, matching the repository's existing style.
239
- - Do not revert or overwrite changes you did not make; the user may be editing files at the same time. If a file changed unexpectedly, read it again and work with the new content.
240
- - Never print, log or commit secrets such as API keys, tokens or passwords.
241
-
242
- # Communication
243
-
244
- - Reply in the same language the user writes in.
245
- - Be concise and direct. No filler, no flattery, no restating the request. Do not narrate every tool call: a short sentence before a batch of related actions, and in a long run a brief progress note every few calls, is enough.
246
- - Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
247
- - Do not use emojis unless the user does or asks for them.
248
- - When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
249
- - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,cG=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
250
-
251
- # Tools
252
-
253
- - Use read to view files, edit to change them and write to create them; use grep/glob to search contents and find files in the working directory.
254
- - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
255
- - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
256
- - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
257
- - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
258
-
259
- # Communication
260
-
261
- - Reply in the same language the user writes in.
262
- - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
263
- - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,mG=["AGENTS.md","CLAUDE.md"],pG=20000;function w$(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?uG:cG}],i=[];if(e.globalInstructions?.trim())i.push(sg("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of lG(e.project.directory))i.push(sg(u.path,u.content));if(e.project.instructions.trim())i.push(sg(`Project "${e.project.name}" instructions`,e.project.instructions))}if(i.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
264
-
265
- # Instructions from the user and project
266
-
267
- The following instructions were written by the user or the project maintainers. Follow them; they override the defaults above when they conflict. More specific (deeper directory) instructions take precedence over general ones.
268
-
269
- ${i.join(`
270
-
271
- `)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
272
-
273
- ${dG(e)}`}),o}function sg(e,o){return`<instructions source="${e}">
274
- ${de(o.trim(),pG)}
275
- </instructions>`}function lG(e){let o=[],i=e;for(let u=0;u<20;u++){for(let g of mG){let y=S$(i,g);if(E$(y)){try{o.unshift({path:y,content:sG(y,"utf8")})}catch{}break}}if(E$(S$(i,".git"))||i===iG())break;let p=aG(i);if(p===i)break;i=p}return o}function dG(e){let o=e.now??new Date,i=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),p=e.project?.directory??process.cwd(),{shellName:g}=Ea("",e.shell),y=[`Working directory: ${p}`,`Shell: ${g}`,`Date: ${i} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)y.push(e.git??"Git: not a git repository");return`<environment>
276
- ${y.join(`
277
- `)}
278
- </environment>`}async function T$(e){let o=async(...b)=>{try{let E=Bun.spawn(["git",...b],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,windowsHide:!0}),[S,w]=await Promise.all([new Response(E.stdout).text(),E.exited]);return w===0?S.trim():void 0}catch{return}},i=await o("rev-parse","--abbrev-ref","HEAD");if(i===void 0)return;let[u="",p=""]=await Promise.all([o("status","--short"),o("log","--oneline","-5")]),g=u?u.split(`
279
- `):[],y=g.length>30?[...g.slice(0,30),`\u2026 ${g.length-30} more`]:g;return[`Git branch: ${i}`,`Git status at session start:${y.length?`
280
- ${y.join(`
281
- `)}`:" clean"}`,p?`Recent commits:
282
- ${p}`:"Recent commits: none"].join(`
283
- `)}function nr(e){let i=(e.hasCompacted?e.hasCompacted():e.records().some((p)=>p.entry.type==="compaction"))?Cl(e.records,e.history):[],u=e.directory??process.cwd();return[...f$(u,new tg,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...x$(u),I$(e.onTodos),...i]}class qi{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!Bg.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Ug.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let i=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete i[u];else i[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let p=u,g=p.source??"core",y=u.name.toLowerCase(),b=p.defer??"always",E="suggestion";if(o.global)b=o.global,E="global";if(Object.hasOwn(o.sources,g))b=o.sources[g]??b,E="source";if(Object.hasOwn(o.tools,y))b=o.tools[y]??b,E="tool";if(g==="core"||p.builtin&&p.defer!=="defer")b="always",E="suggestion";return{name:u.name,source:g,mode:b,origin:E,deferred:b==="defer"}})}}function ig(e){return{name:e.name,description:e.description,parameters:e.parameters}}function ag(e,o){if(!o)return e;let i=Array.isArray(o.type)?o.type:[o.type],u=e;if(i.includes("number")||i.includes("integer")){let p=typeof u==="string"&&u.trim()?Number(u):u;if(typeof p!=="number"||!Number.isFinite(p))return u;let g=p;if(typeof o.maximum==="number"&&g>o.maximum)g=o.maximum;if(typeof o.minimum==="number"&&g<o.minimum)g=o.minimum;return g===p?u:g}if(typeof u==="string"&&(i.includes("object")||i.includes("array")))try{let p=JSON.parse(u),g=Array.isArray(p);if(typeof p==="object"&&p!==null&&!g&&i.includes("object")||g&&i.includes("array"))u=p}catch{}if(Array.isArray(u)){let p=o.items;if(!p||typeof p!=="object"||Array.isArray(p))return u;return u.map((g)=>ag(g,p))}if(typeof u==="object"&&u!==null&&o.properties){let p={...u};for(let[g,y]of Object.entries(o.properties))if(g in p)p[g]=ag(p[g],y);return p}return u}function fG(e){let o=e.prepareArguments;return{...e,prepareArguments:(i)=>{let u=ag(i,e.parameters);return o?o(u):u}}}function hG(e,o,i){let u=e.prepareArguments?e.prepareArguments(i):i;return nu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class ug{retrieved=new Map;stub(e,o){let i=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${i}
284
- (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,p,g,y)=>{let b=JSON.stringify(ig(e)),E;try{E=hG(e,u,p??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
285
- Schema: ${b}`),isError:!0}}let S=await e.execute(u,E,g,y),w=S.content.map((R)=>R.type==="text"?{...R,text:rt(R.text,Te,o)}:R);return{...S,content:w}}}}assemble(e,o,i,u){let p=e.map(fG),g=new Set(o.filter((b)=>b.deferred).map((b)=>b.name));if(!g.size)return p;let y=p.filter((b)=>g.has(b.name)&&i(b.name)).sort((b,E)=>b.name<E.name?-1:b.name>E.name?1:0);return[...p.filter((b)=>!g.has(b.name)),...y.map((b)=>this.stub(b,u)),_e(x({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:a(),max_results:n(_({minimum:1,maximum:100}))}),execute:async(b,E)=>{let S=E.query.trim().toLowerCase(),w=S.startsWith("select:")?S.slice(7).split(",").map((A)=>A.trim()):void 0,R=y.filter((A)=>i(A.name)&&(w?w.includes(A.name.toLowerCase()):`${A.name} ${A.description}`.toLowerCase().includes(S))).slice(0,E.max_results??5);return c(JSON.stringify(R.map((A)=>{let P=JSON.stringify(ig(A)),C=this.retrieved.get(A.name);if(C?.schema===P)return{name:A.name,status:"\u5DF2\u53D6\u56DE",callID:C.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(A.name,{schema:P,callID:b}),ig(A)})))}}),"tool_search")]}}async function Ol(e,o,i){let u=await o.setup(e),p=i?.has("projection.policy")?await i.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!i)return u;if(i.has("session.setup"))u=await i.invoke("session.setup",u,e);if(i.has("tools.configure"))u=await i.invoke("tools.configure",u,e);let g=u.systemPrompt,y=u.systemParts?.at(-1);if(y?.label==="\u8FD0\u884C\u73AF\u5883"&&i.has("prompt.fragments","before-environment")){let w=await i.invoke("prompt.fragments",[],e,void 0,"before-environment"),R=g.length-y.detail.length;g=g.slice(0,R)+w.join("")+y.detail}let b=await i.invoke("prompt.fragments",[],e),E=[...u.tools,...i.tools()],S=i.has("tools.visible")?await i.invoke("tools.visible",E,e):E;return{...u,systemPrompt:g+b.join(""),tools:S}}var gG=3,R$={attempts:1/0,delayMs:2000},yG=/\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 xG(e,o){if(e.stopReason!=="error")return!1;if(ca(e,o))return!1;return!yG.test(e.errorMessage??"")}function k$(e,o,i){if(ca(e,o))return!0;if(i?.preserveHistory!==!0)return!1;return e.errorMessage===(i.overflowError??"Context exceeds the request budget")}function IG(e,o){return new Promise((i,u)=>{if(o.aborted)return u(o.reason);let p=setTimeout(()=>{o.removeEventListener("abort",g),i()},e),g=()=>{clearTimeout(p),u(o.reason)};o.addEventListener("abort",g,{once:!0})})}async function A$(e,o,i,u,p,g,y,b,E=!1){let S=E?void 0:await o?.invoke("run.start",{text:g},e);if(S)g=S.text;if(b.throwIfAborted(),g===void 0)await u.resume();else await u.prompt(g,y);let w=0,R=0;while(w<gG){let q=e.records.findLast((j)=>j.raw?.role==="assistant")?.raw;if(q?.stopReason!=="error")return;if(!k$(q,p.contextWindow,i)){if(!xG(q,p.contextWindow)||R>=R$.attempts)return;R++,await IG(R$.delayMs,b),await u.retry();continue}if(!e.context.recover(p)){if(i?.preserveHistory===!0)throw Error(i.overflowError??"Context exceeds the request budget");return}b.throwIfAborted(),w++,await u.retry()}let P=e.records.findLast((C)=>C.raw?.role==="assistant")?.raw;if(i?.preserveHistory===!0&&P?.stopReason==="error"&&k$(P,p.contextWindow,i))throw Error(i.overflowError??"Context exceeds the request budget")}async function P$(e,o,i,u,p,g){g.throwIfAborted();let y,b;try{b=await Promise.race([Ol(e,o,i()),new Promise((A,P)=>{y=()=>P(g.reason),g.addEventListener("abort",y,{once:!0})})])}finally{if(y)g.removeEventListener("abort",y)}g.throwIfAborted();let E=i(),S=(A)=>{if(!E)return A;return{...A,execute:async(P,C,q,X)=>{let j=u()??b.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),V=j?E.policy(j):void 0;if(j&&!V?.(A.name,e))throw Error(`Tool ${A.name} is unavailable under tool policy ${j}`);let J=await E.invoke("tool.before_call",{name:A.name,callID:P,args:C},e);if(J.block)throw Error(J.block);let ee=await z.run(e,()=>A.execute(P,J.args,q,X));return E.invoke("tool.after_result",ee,e)}}};if(E)b.tools=b.tools.map(S);let w=b.tools,R=()=>{if(!w.some((P)=>P.name==="history_grep")){if(e.records.some((C)=>C.entry.type==="compaction")){let q=Cl(()=>e.records,(X)=>e.resolveHistory(X)).map(S);for(let X of q)if(!w.some((j)=>j.name===X.name))w.push(X)}}let A=new qi(o.store).partition(w);return b.tools=p.assemble(w,A,(P)=>e.permitsTool(P),b.cwd),b.tools};return b.tools=R(),{setup:b,executionTools:w,assemble:R}}function C$(e,o,i,u,p,g,y){return{response:async(b)=>{let E=await o()?.invoke("model.after_response",b,e)??b;if(E.role==="assistant")for(let S of E.content){if(S.type!=="toolCall"||S.name.toLowerCase()!=="tool_call")continue;let w=S.arguments.name;if(typeof w==="string"){let R=y.find((A)=>A.name.toLowerCase()===w.toLowerCase());S.arguments.name=R?.name??w}}return E},payload:(b)=>o()?.invoke("model.before_request",b,e)??Promise.resolve(b),transformContext:(b)=>o()?.invoke("transformContext",b,e)??Promise.resolve(b),boundary:async()=>{if(u())return!0;let b=await o()?.invoke("step.after",{notices:[]},e);for(let S of b?.notices??[])e.notice(S);await g.work;let E=await g.flushNotices();if(E&&!p())e.agent?.steer(E)},prepare:async(b,E,S)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let w=await o()?.invoke("model.check",{},e);if(w?.error)throw Error(w.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let j of R?.notices??[])e.notice(j);await g.work,await g.flushNotices();let A=await o()?.invoke("projection.before",e.records,e),P=await o()?.invoke("projection.prefix",[],e)??[],C=e.context.prepare([...b,...P],E,S,A,i()?.preserveHistory===!0);if(i()?.preserveHistory===!0&&C.estimate>ce(S))throw Error(i()?.overflowError??"Context exceeds the request budget");let q=C.messages,X=await o()?.invoke("projection.after",q,e)??q;return au(_C(X))}}}async function $$(e,o,i){let u=o.store.pendingNotices(e.id);if(!u.length)return;let p=u,g=o.plugins?.pin();try{if(g){let P=await g.invoke("notice.deliver",u,e);p=u.map((C,q)=>({...C,text:P[q]?.text??C.text}))}}finally{await g?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let y=p.map((P)=>P.text).join(`
286
- `),b=p.map((P)=>o.plugins?.noticeSource(P.sourceKind)),E=Math.max(800,...b.map((P)=>P?.summaryLimit??800)),S=y.length>E?`
287
- [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${b.find((P)=>P?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
288
- ${y.slice(0,E)}${S}`,A={role:"user",content:R,timestamp:Date.now()};return i({type:"user",text:R,notices:u.map(({text:P,...C})=>C)},A),A}class cg{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,i,u,p,g,y,b){this.session=e;this.context=o;this.isStopped=i;this.isRunning=u;this.waiting=p;this.start=g;this.invalidateAgent=y;this.append=b}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let i of e){if(i.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:i.dedupeKey,sourceKind:i.sourceKind,sourceID:i.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((i)=>i.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((i)=>{this.failure=i}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=$$(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 bG=new Set(["authorization","proxy-authorization","x-api-key","api-key","x-goog-api-key","x-auth-token","x-amz-security-token","cookie","set-cookie"]);function mg(e){let o={};for(let[i,u]of Object.entries(e)){if(!bG.has(i.toLowerCase())){o[i]=u;continue}let p=/^bearer\s+/i.exec(u)?.[0];o[i]=p?`${p}***`:"***"}return o}function v$(e,o,i,u){let g=(i.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:i.systemPrompt}]).map((H,ue)=>({id:`system-${ue}`,label:H.label,detail:H.detail,tokens:D(H.detail)+(ue===0?16:0)})),y=i.tools.map((H)=>{let ue=H,he=ue.defer==="defer"||H.description.includes("(Parameters not inlined: use toolsearch");return{name:H.name,description:H.description,group:ue.group??"\u5185\u7F6E",schema:H.parameters,deferred:he}});g.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Ni(i.tools),detail:JSON.stringify(y,null,2)});let b=g.reduce((H,ue)=>H+ue.tokens,0),E=u!==void 0?e.records.filter((H)=>H.entry.seq<=u):e.records,S=Re(E,o,e.context.budget(o),{inspect:!0,cwd:i.cwd,trim:{fixed:b,limit:e.context.previewLimit(o)}}),w,R=0,A=0;for(let H of E){if(H.raw?.role!=="assistant")continue;let ue=H.raw.usage;w??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},w.input+=ue.input,w.output+=ue.output,w.cacheRead+=ue.cacheRead,w.cacheWrite+=ue.cacheWrite,w.cost+=ue.cost.total;let he=H.entry.generationMs??H.raw.generationMs;if(typeof he==="number"&&he>0&&ue.output>0)R+=he,A+=ue.output}if(w){let H=w.input+w.cacheRead+w.cacheWrite;if(H>0)w.cacheHitRate=w.cacheRead/H}if(w&&R>0&&A>0)w.generationMs=R,w.tps=Number((A/(R/1000)).toFixed(1));let P=b+S.tokens,C=e.context.calibrationRatio??1,q=Math.round(P*C),X=E.findLast((H)=>H.raw?.role==="assistant"),j=X?.raw,J=(X?E.filter((H)=>H.entry.seq>X.entry.seq&&H.raw):E.filter((H)=>H.raw)).length>0,ee,ae;if(j){let H=j.usage,ue=H.input+H.cacheRead+H.cacheWrite;if(ue>0)ee=ue,ae=H.cacheRead/ue}return{contextWindow:o.contextWindow,usableWindow:ce(o),items:[...g,...S.items],calibratedTokens:q,calibrationRatio:C,lastInputTokens:ee,lastCacheHitRate:ae,hasPendingOutput:J,tools:y,usage:w}}class dt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class ie extends Error{constructor(e="session"){super(`${e} is busy`)}}var pg="medium";class _l{row;ctx;events;notices;lease;policyID;discovery=new ug;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Ol(this,this.ctx,e);return new qi(this.ctx.store).partition(o.tools).filter((i)=>this.permitsTool(i.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new ie;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,i){this.row=e;this.ctx=o;this.events=i;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new cg(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let p=this.entries(0,["extension","run"]),g=p.findLast((b)=>b.type==="extension"&&b.namespace==="session"&&b.kind==="stop_requested"),y=p.findLast((b)=>b.type==="run"&&b.state==="start");if(g&&g.seq>(y?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let b=this.records.some((S)=>S.entry.seq>u.seq&&S.entry.type==="user"),E=o.store.pendingNotices(e.id).some((S)=>S.wake&&S.recovery!=="discard");if(!this.stopped&&(b||E))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new Ml(()=>this.records,()=>this.cwd,(b,E)=>this.appendCompaction(b,E)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=En(this.ctx.models,this.row.model);if(!e)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");return e}lastModelRequest(){let e=this.lastRequestSnapshot;return e?{...e,headers:mg(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:mg(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??pg}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:i,model:u,thinking:p,metadata:g,created:y,updated:b,todos:E}=this.row;return{id:e,title:o,projectID:i,model:u,thinking:p??pg,metadata:g,created:y,updated:b,archivedAt:this.row.archivedAt,status:this.status,todos:E,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let i=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,i,e)}entriesAround(e,o,i){return this.ctx.store.entriesAround(this.row.id,e,o,i)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,i=!0){return this.ctx.store.entries(this.row.id,e,o,i)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let i=En(this.ctx.models,this.row.model);if(!i)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),p;try{p=this.setup??await Ol(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)p.tools=this.discovery.assemble(p.tools,new qi(this.ctx.store).partition(p.tools),(y)=>this.permitsTool(y),p.cwd);let g=v$(this,i,p,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:g};return g})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new dt}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!En(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,Yl(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=Yl(o),u=Oh(e,i),p=this.append({type:"user",text:e,...i?.length?{attachments:i}:{}},u);if(this.recallableSteers.set(p.seq,u),this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((g)=>g.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let i=o.raw,u=this.pendingSteers.indexOf(i);if(u<0){let g=JSON.stringify(i);u=this.pendingSteers.findIndex((y)=>JSON.stringify(y)===g)}let p=!1;if(u>=0)this.pendingSteers.splice(u,1),p=!0;else p=this.agent?.unsteer(i)??!1;if(!p)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,i]of this.recallableSteers){if(i!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,i){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&i===void 0)throw new ie;if(e!==void 0)this.stopped=!1;let u=En(this.ctx.models,this.row.model);if(!u&&i===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let p=new AbortController;if(this.starting=p,!this.row.title&&e!==void 0)this.row={...this.row,title:EG(e,o)},this.ctx.store.updateSession(this.row);let g=i??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let y=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=y.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(p.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(i!==void 0){let b=this.records.filter((R)=>R.entry.seq>g),E=b.filter((R)=>R.entry.type==="user"&&!R.raw);if(E.length>1)return{reason:"interrupted"};let S=E[0];if(S?.entry.type==="user"){if(b.some((R)=>R.entry.seq>S.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=S.entry.text,o=S.entry.attachments,this.pendingUserSeq=S.entry.seq}for(let R of To(b.filter((A)=>A.raw))){if(R.result)continue;let A=R.message.stopReason;if(A==="error"||A==="aborted")continue;let{body:P,raw:C}=cl(R.call);this.append(P,C)}if(!S&&this.waitingForInput())return{reason:"waiting_user"};let w=this.records.findLast((R)=>R.entry.seq>g&&R.raw)?.raw;if(!S&&w?.role==="assistant")return _h(w);if(!S&&!w&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let y=await this.prepareAgent(u,p.signal);p.signal.throwIfAborted();while(this.pendingSteers.length>0){let b=this.pendingSteers.shift();if(b)y.steer(b)}return await A$(this,this.lease,this.setup,y,u,e,o,p.signal,i!==void 0&&e===void 0),_h(this.records.findLast((b)=>b.entry.seq>g&&b.raw?.role==="assistant")?.raw)}).then((y)=>p.signal.aborted?{reason:"aborted"}:y,(y)=>p.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(y)}).then(async(y)=>{try{if(!this.suspended&&y.reason!=="interrupted"){if(!p.signal.aborted&&this.waitingForInput())y={reason:"waiting_user"};if(y.reason!=="interrupted")y=await this.lease?.invoke("run.end",{reason:y.reason,error:y.error},this)??y}}catch(b){y={reason:"error",error:String(b)}}finally{try{await this.lease?.release()}catch(b){y={reason:"error",error:String(b)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...y});let b=En(this.ctx.models,this.row.model);if(b)this.context.settle(b)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:i,executionTools:u,assemble:p}=await P$(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=gC({models:this.ctx.models,model:e,systemPrompt:i.systemPrompt,tools:i.tools,history:this.records.filter((g)=>!this.pendingSteers.includes(g.raw)).flatMap((g)=>g.raw?[g.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??pg,captureRequest:(g)=>{this.lastRequestSnapshot=g},captureResponse:(g)=>{this.lastResponseSnapshot=g},steerConsumed:(g)=>this.markSteerConsumed(g),hooks:{tools:p,...C$(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(g,y)=>{if(this.suspended&&y.role==="assistant"&&(y.stopReason==="aborted"||y.stopReason==="error"))return;if(y.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,y);let b=this.loaded?.find((E)=>E.entry.seq===this.pendingUserSeq);if(b)b.raw=y;this.pendingUserSeq=void 0;return}if(y.role==="assistant")this.context.calibrate(y);this.append(g,y)},draft:(g)=>{this.draftParts=g,this.events.draft(g)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let i=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...i?{saved:i}:{}})}measureCompactionSavings(e,o){let i=En(this.ctx.models,this.row.model);if(!i)return;let u=this.context.budget(i),p=Re(this.records,i,u,{cwd:this.cwd}).tokens,g={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},y=Re([...this.records,g],i,u,{cwd:this.cwd}).tokens;return{before:p,after:y}}compact(){this.assertWritable();let e=iu(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let i=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(i.type==="user"&&!(("notices"in i)&&i.notices))this.row={...this.row,updated:i.time};return this.refreshEntries(),i}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function EG(e,o){let u=(e.trim()||o?.map((p)=>p.name).join(" ")||"").split(`
289
- `)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var O$=new Set(["user","assistant","tool_result","run","compaction"]),SG=new Set(["user","assistant","toolResult"]);function _$(e,o,i){return{format:Xl,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...i?{project:i}:{},records:o.filter((u)=>O$.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function Bo(e){if(!gr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===Xl)return wG(e);if(gr(e.info)&&Array.isArray(e.messages))return RG(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 wG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!gr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let i=0,u=e.records.flatMap((p,g)=>{let y=`records[${g}]`;if(!gr(p)||!gr(p.entry))throw new t(`${y} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let b=p.entry;if(b.type==="notice_pending"||b.type==="extension")return[];if(typeof b.type!=="string"||!O$.has(b.type))throw new t(`${y} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(b.type)}`);let{seq:E,time:S}=b;if(typeof E!=="number"||!Number.isSafeInteger(E)||E<=i)throw new t(`${y} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof S!=="number"||!Number.isFinite(S))throw new t(`${y} \u7F3A\u5C11\u6709\u6548\u7684 time`);i=E,TG(b,y);let w=p.raw;if(w!==void 0&&!(gr(w)&&typeof w.role==="string"&&SG.has(w.role)))throw new t(`${y} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:b,...w===void 0?{}:{raw:w}}]});return{title:Lr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(N$):[],created:Hs(o.created)??Date.now(),updated:Hs(o.updated)??Date.now(),needsRaw:!1,records:u}}function TG(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"&&Lg.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 RG(e){let o=e.info,i=gr(o.time)?o.time:{},u=gr(o.model)?o.model:void 0,p=e.messages.filter(gr).sort(kG),g=[],y=0,b=0,E=(X,j)=>{b=Math.max(b,j??b),y+=1,g.push({entry:{...X,seq:y,time:b}})},S=!1,w=(X,j)=>{if(!S)return;S=!1,E({type:"run",state:"end",reason:X,...j?{error:j}:{}},void 0)};for(let X of p){let j=gr(X.info)?X.info:{},V=Array.isArray(X.parts)?X.parts.filter(gr):[],J=Hs(gr(j.time)?j.time.created:void 0);if(j.role==="user"){w("done");let ee=AG(V);if(!ee)continue;E({type:"run",state:"start"},J),E(ee,J),S=!0}else if(j.role==="assistant"){if(!S)E({type:"run",state:"start"},J),S=!0;$G(j,V,E);let ee=L$(j.error);if(ee)w(ee.aborted?"aborted":"error",ee.aborted?void 0:ee.message)}}w("done");let R=p.findLast((X)=>gr(X.info)&&X.info.role==="assistant"),A=gr(R?.info)?R.info:void 0,P=Lr(u?.providerID)||Lr(A?.providerID),C=Lr(u?.id)||Lr(A?.modelID),q=P&&C?`${P}/${C}`:void 0;return{title:Lr(o.title),model:q,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(N$):[],created:Hs(i.created)??g[0]?.entry.time??Date.now(),updated:Hs(i.updated)??g.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:g}}function kG(e,o){let i=(p)=>(gr(p.info)&&gr(p.info.time)?Hs(p.info.time.created):void 0)??0,u=(p)=>gr(p.info)?Lr(p.info.id):"";return i(e)-i(o)||u(e).localeCompare(u(o))}function AG(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Lr(u.text)).join(`
290
-
291
- `),i=e.flatMap((u)=>u.type==="file"?PG(u):[]);if(!o.trim()&&i.length===0)return;return{type:"user",text:o,...i.length?{attachments:i}:{}}}function PG(e){let o=Lr(e.mime)||"application/octet-stream",i=Lr(e.filename)||"file",u=Lr(e.url),p=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(p){let g=p[3]??"";if(o.startsWith("image/"))return[{name:i,mimeType:o,kind:"image",data:p[2]?g:btoa(g)}];if(o.startsWith("text/")||o==="application/json"){let y=p[2]?new TextDecoder().decode(Uint8Array.from(atob(g),(b)=>b.charCodeAt(0))):g;return[{name:i,mimeType:o,kind:"text",data:y}]}return[]}if(u.startsWith("file://"))try{return[{name:i,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function CG(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 $G(e,o,i){let u=`${Lr(e.providerID)}/${Lr(e.modelID)}`,p=L$(e.error),g=CG(o);g.forEach((y,b)=>{let E=y.flatMap((R)=>{if(R.type==="reasoning")return Lr(R.text).trim()?[{type:"thinking",text:Lr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Lr(R.text).trim()?[{type:"text",text:Lr(R.text)}]:[];return[{type:"tool_call",id:M$(R.callID),name:Lr(R.tool),input:gr(R.state)&&gr(R.state.input)?R.state.input:{}}]}),S=b===g.length-1,w=vG(y);i({type:"assistant",parts:E,model:u,...S&&p&&!p.aborted?{error:p.message}:{}},w);for(let R of y){if(R.type!=="tool")continue;let A=gr(R.state)?R.state:{},P=A.status==="error",C=A.status==="pending"||A.status==="running",q=P?[Lr(A.output),Lr(A.error)].filter(Boolean).join(`
292
- `):C?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Lr(A.output);i({type:"tool_result",callID:M$(R.callID),name:Lr(R.tool),output:q,isError:P||C},Hs(gr(A.time)?A.time.end:void 0))}})}function M$(e){return Lr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function L$(e){if(!gr(e))return;let o=gr(e.data)?e.data:{};return{message:Lr(o.message)||Lr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function vG(e){for(let o of e){let i=gr(o.time)?Hs(o.time.start):gr(o.state)?MG(o.state):void 0;if(i!==void 0)return i}return}function MG(e){return gr(e.time)?Hs(e.time.start):void 0}function N$(e){if(!gr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function D$(e,o){let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let p=u.time;switch(u.type){case"user":return{entry:u,raw:OG(u,p)};case"assistant":{let g=u.parts.flatMap((b)=>{if(b.type==="text")return[{type:"text",text:b.text}];if(b.type==="thinking")return[];return[{type:"toolCall",id:b.id,name:b.name,arguments:_G(b.input)}]}),y=g.some((b)=>b.type==="toolCall");return{entry:u,raw:{role:"assistant",content:g,api:o.api,provider:o.provider,model:o.id,usage:i,stopReason:u.error?"error":y?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:p}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:p}};default:return{entry:u}}})}function OG(e,o){let i=(e.attachments??[]).flatMap((g)=>g.kind==="path"?[`<file path=${JSON.stringify(g.data)} />`]:g.kind==="text"?[`<file name=${JSON.stringify(g.name)}>
293
- ${g.data}
294
- </file>`]:[]),u=(e.attachments??[]).filter((g)=>g.kind==="image").map((g)=>({type:"image",data:g.data,mimeType:g.mimeType})),p=[...i,...e.text.trim()?[e.text]:[]].join(`
295
-
296
- `);return{role:"user",content:u.length?[{type:"text",text:p},...u]:p,timestamp:o}}function gr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Lr(e){return typeof e==="string"?e:""}function Hs(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function _G(e){return gr(e)?e:{}}function or(e,o){let i=e.at(-1)?.entry.seq??0,u,p,g;for(let{entry:S}of e){if(S.type==="run"&&S.state==="start")u=S.seq;if(S.seq===o)if(S.type==="user"&&!S.notices)i=(u??S.seq)-1;else p=u;if(S.type==="run"&&S.state==="end"){if(p!==void 0&&u===p)g=S.seq;u=void 0}}let y=e.find((S)=>S.entry.seq===o)?.entry;if(o!==void 0&&!y)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(y&&!(y.type==="user"&&!y.notices)){if(p!==void 0&&g===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");i=g??y.seq}else if(o===void 0&&u!==void 0)i=e.findLast(({entry:S})=>S.type==="run"&&S.state==="end")?.entry.seq??0;let b=e.filter(({entry:S})=>S.seq<=i&&(S.type!=="compaction"||S.through<=i)),E=new Map(b.map(({entry:S},w)=>[S.seq,w+1]));return b.map((S,w)=>{let R=structuredClone(S);if(R.entry.seq=w+1,R.entry.type==="compaction"){let A=R.entry.through,P=b.findLast(({entry:C})=>C.seq<=A);R.entry.through=P?E.get(P.entry.seq)??0:0}return R})}function ir(e){let o=new Map,i=[];for(let u of e){if(u.type==="assistant"){for(let y of u.parts)if(y.type==="tool_call"&&y.name==="todo")o.set(y.id,y.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let p=o.get(u.callID);if(!p||typeof p!=="object"||!("todos"in p)||!Array.isArray(p.todos))continue;let g=[];for(let y of p.todos){if(!y||typeof y!=="object"||!("content"in y)||typeof y.content!=="string"||!("status"in y)||y.status!=="pending"&&y.status!=="in_progress"&&y.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");g.push({content:y.content,status:y.status})}i=g}return i}import{Buffer as j$}from"buffer";import{createHash as LG}from"crypto";import{isDeepStrictEqual as Ll}from"util";var Nl="@blob:";function fu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function q$(e,o,i){if(typeof e!=="string"||e.length<256||e.startsWith(Nl))return;let u=j$.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let p=LG("sha256").update(u).digest("hex");return i.put(p,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Nl}${p}`}function F$(e,o){if(typeof e!=="string"||!e.startsWith(Nl))return;let i=o.get(e.slice(Nl.length));if(i===void 0)return;return j$.from(i.buffer,i.byteOffset,i.byteLength).toString("base64")}function Dl(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let g=q$(p.data,p.mimeType,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((p)=>{let g=q$(p.data,p.mimeType,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,images:u}}return e}function Fi(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let i=!1,u=e.attachments.map((p)=>{if(p.kind!=="image")return p;let g=F$(p.data,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let i=!1,u=e.images.map((p)=>{let g=F$(p.data,o);if(g===void 0)return p;return i=!0,{...p,data:g}});if(!i)return e;return{...e,images:u}}return e}function Hc(e,o){if(!fu(o))return o;if(e.type==="user"){let{merged:i,images:u}=Dc(e.text,e.attachments),p=u.length>0?[{type:"text",text:i},...u]:i,g=Object.keys(o),{role:y,timestamp:b,content:E}=o;if(g.length===3&&y==="user"&&typeof b==="number"&&"content"in o&&Ll(E,p))return{role:"user",timestamp:b};return o}if(e.type==="tool_result"){let{role:i,toolCallId:u,toolName:p,isError:g,timestamp:y,content:b}=o;if(i!=="toolResult"||u!==e.callID||typeof p!=="string"||g!==e.isError||typeof y!=="number")return o;let E=[{type:"text",text:e.output},...(e.images??[]).map((V)=>({type:"image",mimeType:V.mimeType,data:V.data}))];if("details"in o?!Ll(o.details,e.meta):e.meta!==void 0)return o;let{role:w,toolCallId:R,toolName:A,content:P,details:C,isError:q,timestamp:X,...j}=o;if(Ll(b,E))return{role:"toolResult",...p!==e.name?{toolName:p}:{},...j,timestamp:y};if(Array.isArray(b)){let V=e.images??[],J=0,ee=!0,ae=b.map((H)=>{if(fu(H)&&H.type==="image"){let ue=V[J++],he=Object.keys(H);if(ue&&he.length===3&&H.mimeType===ue.mimeType&&H.data===ue.data)return{type:"image",mimeType:H.mimeType};ee=!1}return H});if(ee&&J===V.length)return{role:"toolResult",...p!==e.name?{toolName:p}:{},content:ae,...j,timestamp:y}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let p=!1,g=u.map((y,b)=>{let E=e.parts[b];if(fu(y)){if(y.type==="text"&&E?.type==="text"&&y.text===E.text){p=!0;let S={...y};return delete S.text,S}if(y.type==="thinking"&&E?.type==="thinking"&&y.thinking===E.text){p=!0;let S={...y};return delete S.thinking,S}if(y.type==="toolCall"&&E?.type==="tool_call"&&y.id===E.id&&y.name===E.name&&"arguments"in y&&Ll(y.arguments,E.input)){p=!0;let S={...y};return delete S.id,delete S.name,delete S.arguments,S}}return y});if(!p)return o;return{...o,content:g}}return o}function lg(e,o){if(!fu(o))return o;if(e.type==="user"){let{role:i,timestamp:u}=o;if(i==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:p,images:g}=Dc(e.text,e.attachments);return{role:"user",content:g.length>0?[{type:"text",text:p},...g]:p,timestamp:u}}return o}if(e.type==="tool_result"){let{role:i,timestamp:u}=o;if(i==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:g,toolName:y,content:b,timestamp:E,...S}=o,w;if(Array.isArray(b)){let R=e.images??[],A=0;w=b.map((P)=>{if(fu(P)&&P.type==="image"&&!("data"in P)){let C=R[A++];if(C)return{type:"image",mimeType:P.mimeType,data:C.data}}return P})}else w=[{type:"text",text:e.output},...(e.images??[]).map((R)=>({type:"image",mimeType:R.mimeType,data:R.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof y==="string"?y:e.name,content:w,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...S,timestamp:u}}return o}if(e.type==="assistant"){let{role:i,content:u}=o;if(i!=="assistant"||!Array.isArray(u))return o;let p=!1,g=u.map((y,b)=>{let E=e.parts[b];if(fu(y)){if(y.type==="text"&&!("text"in y)&&E?.type==="text"){p=!0;let{type:S,...w}=y;return{type:S,text:E.text,...w}}if(y.type==="thinking"&&!("thinking"in y)&&E?.type==="thinking"){p=!0;let{type:S,...w}=y;return{type:S,thinking:E.text,...w}}if(y.type==="toolCall"&&!("arguments"in y)&&E?.type==="tool_call"){p=!0;let{type:S,...w}=y;return{type:S,id:E.id,name:E.name,arguments:structuredClone(E.input),...w}}}return y});if(!p)return o;return{...o,content:g}}return o}function U$(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),i=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(E,S,w){o.run(E,S,w)},get(E){return i.get(E)?.data}},p=e.query("SELECT session_id, seq, body, raw FROM entries").all(),g=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),y=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),b=0;return e.transaction(()=>{for(let E of p){let S;try{S=JSON.parse(E.body)}catch{continue}let w=Fi(S,u),R=Dl(w,u),A=R===S?E.body:JSON.stringify(R),P=E.raw;if(E.raw!==null)try{let C=JSON.parse(E.raw),q=lg(w,C),X=Hc(w,q);P=JSON.stringify(X)}catch{P=E.raw}if(A!==E.body)g.run(A,P,E.session_id,E.seq),b++;else if(P!==E.raw)y.run(P,E.session_id,E.seq),b++}})(),b}import{Database as NG}from"bun:sqlite";import{chmodSync as B$,existsSync as DG,mkdirSync as qG}from"fs";import{dirname as FG}from"path";var dg=[`
297
- CREATE TABLE projects (
298
- id TEXT PRIMARY KEY,
299
- name TEXT NOT NULL,
300
- directory TEXT NOT NULL UNIQUE,
301
- instructions TEXT NOT NULL DEFAULT '',
302
- created INTEGER NOT NULL,
303
- updated INTEGER NOT NULL
304
- );
305
- CREATE TABLE automations (
306
- id TEXT PRIMARY KEY,
307
- project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
308
- name TEXT NOT NULL,
309
- prompt TEXT NOT NULL,
310
- schedule TEXT NOT NULL,
311
- model TEXT NOT NULL,
312
- enabled INTEGER NOT NULL,
313
- created INTEGER NOT NULL,
314
- updated INTEGER NOT NULL,
315
- next_run INTEGER,
316
- last_run INTEGER,
317
- last_session_id TEXT
318
- );
319
- CREATE TABLE sessions (
320
- id TEXT PRIMARY KEY,
321
- project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
322
- automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
323
- title TEXT NOT NULL DEFAULT '',
324
- model TEXT NOT NULL,
325
- todos TEXT NOT NULL DEFAULT '[]',
326
- created INTEGER NOT NULL,
327
- updated INTEGER NOT NULL
328
- );
329
- CREATE INDEX sessions_project ON sessions(project_id);
330
- CREATE TABLE entries (
331
- session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
332
- seq INTEGER NOT NULL,
333
- time INTEGER NOT NULL,
334
- body TEXT NOT NULL,
335
- raw TEXT,
336
- PRIMARY KEY (session_id, seq)
337
- ) WITHOUT ROWID;
338
- `,"","","",`
339
- ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
340
- ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
341
- ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
342
- CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
343
- ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
344
- ALTER TABLE sessions ADD COLUMN notice_floor_seq INTEGER NOT NULL DEFAULT 0;`,"ALTER TABLE sessions ADD COLUMN truncation_epoch INTEGER NOT NULL DEFAULT 0;",`CREATE TABLE plugin_kv (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
345
- PRIMARY KEY (namespace, key));
346
- CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
347
- PRIMARY KEY (namespace, version));
348
- CREATE TABLE plugin_settings (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL);`,"ALTER TABLE sessions ADD COLUMN thinking TEXT;","ALTER TABLE sessions ADD COLUMN metadata TEXT;","ALTER TABLE sessions ADD COLUMN archived_at INTEGER;",`CREATE TABLE search_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, seq INTEGER NOT NULL);
349
- CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
350
- INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
351
- END;
352
- CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
353
- INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
354
- END;
355
- CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
356
- INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
357
- END;
358
- CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
359
- INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
360
- END;
361
- CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
362
- INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
363
- END;
364
- CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
365
- INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
366
- END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
367
- WHERE json_extract(body,'$.type')='compaction';
368
- CREATE TABLE IF NOT EXISTS blobs (
369
- hash TEXT PRIMARY KEY,
370
- mime TEXT NOT NULL,
371
- data BLOB NOT NULL
372
- ) WITHOUT ROWID;
373
- CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`,"ALTER TABLE projects ADD COLUMN position INTEGER NOT NULL DEFAULT 0;","ALTER TABLE projects ADD COLUMN closed_at INTEGER;"];var jG=[20,50,100,200,400,800];function UG(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 fg(e){let o=0;while(!0)try{return e()}catch(i){let u=jG[o];if(u===void 0||!UG(i))throw i;o++,Bun.sleepSync(u)}}function G$(e,o){if(e!==":memory:")qG(FG(e),{recursive:!0});let i=new NG(e,{create:!0,strict:!0}),u=(g,y=!0)=>new Proxy(function(...b){return Reflect.apply(g,this,b)},{apply(b,E,S){Cs();let w=o.length===0&&!i.inTransaction,R=y?Reflect.get(g,"immediate"):void 0,A=()=>{let P=[];o.push(P);let C=!1;try{let q=typeof R==="function"?Reflect.apply(R,g,S):Reflect.apply(b,E,S);return C=!0,q}finally{o.pop();let q=o.at(-1);if(C&&q)q.push(...P);else for(let X of P)if(C)X.commit();else X.rollback()}};return w?fg(A):A()},get(b,E){let S=Reflect.get(g,E);if(["deferred","immediate","exclusive"].includes(String(E))&&typeof S==="function")return u(S,!1);return S}}),p=new Proxy(i,{get(g,y){let b=Reflect.get(g,y,g);if(typeof b!=="function")return b;return(...E)=>{Cs();let R=(y==="run"||y==="exec")&&o.length===0&&!i.inTransaction?fg(()=>Reflect.apply(b,g,E)):Reflect.apply(b,g,E);if(y==="transaction"&&typeof R==="function")return u(R,!0);if(y!=="query"&&y!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(A,P,C){let q=Reflect.get(A,P,A);if(typeof q!=="function")return q;return(...X)=>{Cs();let J=(P==="run"||P==="get"||P==="all"||P==="values")&&o.length===0&&!i.inTransaction?fg(()=>Reflect.apply(q,A,X)):Reflect.apply(q,A,X);return J===A?C:J}}})}}});if(e!==":memory:")B$(e,384);if(p.run("PRAGMA journal_mode = WAL"),p.run("PRAGMA synchronous = FULL"),p.run("PRAGMA foreign_keys = ON"),p.run("PRAGMA busy_timeout = 10000"),p.run("PRAGMA mmap_size = 268435456"),BG(p),p.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),p.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let g of["-wal","-shm"]){let y=e+g;if(DG(y))B$(y,384)}return p}function BG(e,o=dg){let{user_version:i}=e.query("PRAGMA user_version").get();if(i>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${i} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=i;u<o.length;u++)e.transaction(()=>{let p=o[u]??"",g=Array.isArray(p)?p:u>=4?GG(p):[p];for(let y of g)try{if(y.trim())e.run(y)}catch(b){if(!(b instanceof Error)||!/already exists|duplicate column name/i.test(b.message))throw b}e.run(`PRAGMA user_version = ${u+1}`)})()}function GG(e){let o=[],i=0,u=0,p=[],g=!1,y=0,b=(E)=>{let S=e.slice(i,E).trim();if(S)o.push(S);i=E+1,p=[],g=!1,y=0};while(u<e.length){let E=e[u];if(E==="'"||E==='"'||E==="`"||E==="["){let S=E==="["?"]":E;u++;while(u<e.length)if(e[u]===S)if(S!=="]"&&e[u+1]===S)u+=2;else break;else u++;u++;continue}if(E==="-"&&e[u+1]==="-"){let S=e.indexOf(`
374
- `,u);u=S===-1?e.length:S+1;continue}if(E==="/"&&e[u+1]==="*"){let S=e.indexOf("*/",u+2);u=S===-1?e.length:S+2;continue}if(/[A-Za-z_]/.test(E)){let S=u+1;while(S<e.length&&/[A-Za-z0-9_$]/.test(e[S]))S++;let w=e.slice(u,S).toUpperCase();if(p.length<3)p.push(w),g=p[0]==="CREATE"&&(p[1]==="TRIGGER"||p[2]==="TRIGGER");if(g){if(w==="BEGIN"||w==="CASE"&&y>0)y++;else if(w==="END"&&y>0)y--}u=S;continue}if(E===";"&&y===0)b(u);u++}return b(e.length),o}var ql=({position:e,closed_at:o,...i})=>({...i,closedAt:o??null}),Fl=(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 hg=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=G$(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(ql)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?ql(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?ql(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[i,u]of e.entries())o.run(i,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){this.db.query("DELETE FROM projects WHERE id = ?").run(e)}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(Fl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(Fl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(Fl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,i){this.insertSessionWithRecords(o,or(this.records(e),i))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let i=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:p}of o){let{seq:g,time:y,...b}=u,E=b,S=Dl(E,this.blobs),w=p===void 0?null:JSON.stringify(Hc(E,p));i.run(e.id,g,y,JSON.stringify(S),w)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let i=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)i.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.query("DELETE FROM sessions WHERE id = ?").run(e)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,i,u){Cs();let p=this.plugins,g=p?.pinEntry(i),y;try{return y=this.db.transaction(()=>{let b=Math.max(o??0,this.lastSeq(e)+1),S=(g&&p?p.beforeEntry(g,i,e,b):void 0)??i,w=JSON.stringify(S),R=g?JSON.parse(w):S,A={...R,seq:b,time:Date.now()},P=Dl(R,this.blobs),C=P===R&&!g?w:JSON.stringify(P),q=u===void 0?null:JSON.stringify(Hc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,b,A.time,C,q),A.type==="user"&&!(("notices"in A)&&A.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(A.time,e);return this.cacheAppended(e,A,C),A})(),y}finally{if(g&&p){let b={commit:()=>p.finishEntry(g,e,y),rollback:()=>p.finishEntry(g,e)},E=this.entryTransactions.at(-1);if(E)E.push(b);else b.commit()}}}setEntryRaw(e,o,i){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let p=Fi(JSON.parse(u.body),this.blobs),g=Hc(p,i);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(g),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,i,u=!0){let p=i?.every((y)=>hg.has(y))?this.cachedEntries(e):void 0;if(p&&i)return p.filter((b)=>b.seq>o&&i.includes(b.type)).map((b)=>({...u?Fi(b,this.blobs):b}));return(i?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...i):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((y)=>({...Fi(JSON.parse(y.body),u?this.blobs:void 0),seq:y.seq,time:y.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let i=[...hg],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${i.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...i).map((p)=>({...JSON.parse(p.body),seq:p.seq,time:p.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,i){let u=this.smallEntries.get(e);if(!u||!hg.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(i),seq:o.seq,time:o.time})}entriesRange(e,o,i=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,i).map((u)=>({...Fi(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let i=this.lastSeq(e),u=(E)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,E),p=u(o),g=p?.type==="run"&&p.state==="start"?o+1:o;if(g>=i)return i;let y=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,g,g);if(!y)return i;if(y.end)return y.seq;let b=u(y.seq-1);return b?.type==="run"&&b.state==="start"&&y.seq-1>g?y.seq-2:y.seq-1}entriesAround(e,o,i,u){let p=this.lastSeq(e);if(p===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let g=Math.min(Math.max(1,o),p),y=this.alignToUser(e,Math.max(1,g-i)),b=this.alignToTurnEnd(e,Math.min(p,g+u));return this.window(e,y,b,p)}entriesFrom(e,o,i){let u=this.lastSeq(e),p=Math.max(1,o);if(p>u)return{entries:[],from:p,to:u,hasBefore:u>0,hasAfter:!1};let g=this.alignToTurnEnd(e,Math.min(u,p+i-1));return this.window(e,p,g,u)}window(e,o,i,u){let p=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,i+1),from:o,to:i,hasBefore:p!==null,hasAfter:i<u}}replayStart(e,o,i){let u=this.lastSeq(e),p=this.lastEntry(e,"compaction"),g=p?.type==="compaction"?p.through+1:1,y=Math.max(1,u-i+1,Math.min(g,u-o+1));return this.alignToUser(e,y)}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((i)=>{let u=Fi(JSON.parse(i.body),this.blobs);return{entry:{...u,seq:i.seq,time:i.time},...i.raw===null?{}:{raw:lg(u,JSON.parse(i.raw))}}})}lastEntry(e,o){let i=this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return i?{...Fi(JSON.parse(i.body),this.blobs),seq:i.seq,time:i.time}:void 0}async enqueueNotice(e,o){let i=this.truncationEpoch(e),u=o;if(this.plugins){let p=this.plugins.pin();try{let g=await p.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(g===null)return!1;o={...g,dedupeKey:u.dedupeKey,wake:u.wake&&g.wake,recovery:u.recovery}}finally{await p.release()}}return this.db.transaction(()=>{let p=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!p||p.truncation_epoch!==i)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((b)=>b.type==="notice_pending"&&b.notice.dedupeKey===o.dedupeKey||b.type==="user"&&b.notices?.some((E)=>E.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,i=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let g of i)if(g.type==="user"&&g.notices)for(let y of g.notices)u.add(y.dedupeKey);else if(g.type==="extension"&&g.namespace==="basalt.notice"&&g.kind==="discarded"&&g.payload&&typeof g.payload==="object"&&"dedupeKey"in g.payload&&typeof g.payload.dedupeKey==="string")u.add(g.payload.dedupeKey);let p=[];for(let g of i)if(g.type==="notice_pending"&&!u.has(g.notice.dedupeKey))p.push(g.notice);return p}}function ne(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as KG,readdirSync as H$,statSync as W$}from"fs";import{join as z$}from"path";function Wc(e){try{return W$(e).size}catch{return 0}}function V$(e){try{return Math.round(W$(e).mtimeMs)}catch{return}}function J$(e){let o=0,i=0;try{let u=H$(e,{withFileTypes:!0});for(let p of u){let g=z$(e,p.name);if(p.isDirectory()){let y=J$(g);o+=y.bytes,i+=y.files}else if(p.isFile())o+=Wc(g),i+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:i}}function HG(e){if(!KG(e))return[];try{return H$(e,{withFileTypes:!0}).flatMap((o)=>{let i=z$(WG(e),o.name),u=V$(i);if(o.isDirectory()){let p=J$(i);return[{name:o.name,kind:"directory",bytes:p.bytes,files:p.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Wc(i),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,i)=>i.bytes-o.bytes||o.name.localeCompare(i.name))}catch{return[]}}function WG(e){return e}function Ws(e,o){let i=e.db.query(`PRAGMA ${o}`).get();if(!i)return 0;let u=Object.values(i)[0];return typeof u==="number"?u:0}function K$(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 zG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},VG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function JG(e){let o=new Map;try{let i=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let g of u)i.set(g.name,g.tbl_name);let p=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let g of p){let y=i.get(g.name)??g.name;if(y.startsWith("sqlite_autoindex_")){let E=y.slice(17),S=E.lastIndexOf("_");if(S>0)y=E.slice(0,S)}let b=o.get(y)??{bytes:0,pages:0};o.set(y,{bytes:b.bytes+(Number(g.bytes)||0),pages:b.pages+(Number(g.pages)||0)})}}catch{}return o}function QG(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,i=e.db.query(`SELECT
375
- count(*) AS total,
376
- sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
377
- sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
378
- sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
379
- sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
380
- FROM sessions`).get(),u=e.db.query(`SELECT
381
- count(*) AS total,
382
- coalesce(sum(octet_length(body)), 0) AS body_bytes,
383
- coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
384
- min(time) AS oldest_time,
385
- max(time) AS newest_time
386
- FROM entries`).get(),g=e.db.query(`SELECT
387
- coalesce(json_extract(body, '$.type'), 'unknown') AS type,
388
- count(*) AS count,
389
- coalesce(sum(octet_length(body)), 0) AS body_bytes,
390
- coalesce(sum(octet_length(raw)), 0) AS raw_bytes
391
- FROM entries
392
- GROUP BY type
393
- ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((E)=>({type:String(E.type||"unknown"),count:Number(E.count)||0,bodyBytes:Number(E.body_bytes)||0,rawBytes:Number(E.raw_bytes)||0})),y=g.find((E)=>E.type==="compaction")?.count??0,b=[];try{let E=new Map,S=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let A of S)E.set(A.namespace,Number(A.max_ver)||0);let w=e.db.query(`SELECT
394
- namespace,
395
- count(*) AS keys,
396
- coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
397
- FROM plugin_kv
398
- GROUP BY namespace
399
- ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let A of w){R.add(A.namespace);let P=E.get(A.namespace);b.push({namespace:A.namespace,keys:Number(A.keys)||0,bytes:Number(A.bytes)||0,...P!==void 0?{migrationVersion:P}:{}})}for(let[A,P]of E.entries())if(!R.has(A))b.push({namespace:A,keys:0,bytes:0,migrationVersion:P})}catch{}return{projectCount:o,mainSessionCount:Number(i?.main_count)||0,subSessionCount:Number(i?.sub_count)||0,forkedSessionCount:Number(i?.forked_count)||0,automationSessionCount:Number(i?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:y,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:g,pluginNamespaces:b}}function Ul(e,o){let i=Ws(e,"page_size"),u=Ws(e,"page_count"),p=Ws(e,"freelist_count"),g=e.db.query("PRAGMA journal_mode").get(),y=e.db.query("SELECT sqlite_version() AS v").get(),b=Ws(e,"synchronous"),E=Ws(e,"auto_vacuum"),S=Ws(e,"cache_size"),w=S<0?Math.abs(S)*1024:S*i,R=Ws(e,"foreign_keys")===1,A=Ws(e,"busy_timeout"),P=K$(e,"encoding")??"UTF-8",C=K$(e,"quick_check(1)")??"ok",q=e.path!==":memory:"?V$(e.path):void 0,X=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),j=JG(e),V=HG(o);return{dataDir:o,databasePath:e.path,dataBytes:V.reduce((J,ee)=>J+ee.bytes,0),database:{size:Wc(e.path),walSize:Wc(`${e.path}-wal`),shmSize:Wc(`${e.path}-shm`),sqliteVersion:y?.v??"unknown",journalMode:g?.journal_mode??"unknown",synchronous:zG[b]??String(b),foreignKeys:R,busyTimeout:A,encoding:P,autoVacuum:VG[E]??String(E),cacheSizeBytes:w,pageSize:i,pageCount:u,freelistCount:p,reclaimableBytes:p*i,schemaVersion:Ws(e,"user_version"),...q!==void 0?{lastModified:q}:{},integrity:C},analytics:QG(e),entries:V,tables:X.map(({name:J,sql:ee})=>{let ae=J.replaceAll('"','""'),H=e.db.query(`SELECT count(*) AS count FROM "${ae}"`).get().count,ue=e.db.query(`PRAGMA table_info("${ae}")`).all().map((se)=>se.name),he=e.db.query(`PRAGMA index_list("${ae}")`).all().length,$e=Boolean(ee&&/WITHOUT\s+ROWID/i.test(ee)),Ee=j.get(J);return{name:J,rows:H,...Ee?{bytes:Ee.bytes,pages:Ee.pages}:{},indexes:he,columns:ue,withoutRowid:$e}})}}function XG(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let i=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let g of i)for(let y of g.body.matchAll(/@blob:([0-9a-f]{64})/g)){let b=y[1];if(b)u.add(b)}let p=[];for(let g of o)if(!u.has(g.hash))p.push(g.hash);if(p.length===0)return 0;try{e.db.transaction(()=>{let g=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let y of p)g.run(y)})()}catch{return 0}return p.length}function Q$(e,o,i){let u=Ul(e,o);if(i.vacuum)U$(e.db),e.invalidateEntryCache(),XG(e),e.db.run("VACUUM");if(i.checkpoint||i.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:Ul(e,o)}}var YG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Bl{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(YG.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 X$(e,o){let i=Jr(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:i.length>0?i:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function Y$(e,o){let u=(await e.options.models.getAvailable().catch(()=>[])).map((g)=>({...X$(tt(g),g),available:!0})),p=new Set(u.map((g)=>g.id));for(let g of[o,...e.list(!0,{archive:"all"}).map((y)=>y.model)]){if(p.has(g))continue;let y=En(e.options.models,g);if(!y)continue;p.add(g),u.push({...X$(g,y),available:!1})}return{models:u}}function Z$(e,o){if(typeof o!=="string"||!En(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as ZG,statSync as eK}from"fs";import{basename as tK,resolve as rK}from"path";class gg{runtime;sessions;emit;arm;constructor(e,o,i,u){this.runtime=e;this.sessions=o;this.emit=i;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new f("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=rK(e.directory.trim());if(!ZG(o)||!eK(o).isDirectory())throw new t(`${o} is not a directory on the server`);let i=this.runtime.store.projectByDirectory(o);if(i){if(i.closedAt!==null)return this.updateProject(i.id,{closed:!1});return i}let u=Date.now(),p={id:ne("p"),name:e.name?.trim()||tK(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(p),this.emit({type:"project",project:p}),p}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let p of this.sessions.values())if(p.projectID===e)p.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((p)=>typeof p==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((p)=>p.id)),i=new Set(e);if(!(i.size===e.length&&i.size===o.size&&e.every((p)=>o.has(p))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),i=[...this.sessions.values()].filter((p)=>p.projectID===e);if(i.some((p)=>p.status==="busy"))throw new ie("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let p of i)p.close(),this.runtime.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as wK,readFileSync as TK}from"fs";import{homedir as RK}from"os";import{join as hu}from"path";var iv=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),nK={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"]},oK=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),Ig={'"':['"'],"\u201C":["\u201D",'"']},yg=(e)=>e!==void 0&&/\s/.test(e),av=(e)=>[...new Set(e)],zc=(e)=>[...e].length;var sK={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function iK(e,o){let i=e.trim().toLowerCase(),u=new Date(o),p=u.getFullYear(),g=u.getMonth(),y=u.getDate();if(i==="today")return{start:new Date(p,g,y).getTime(),end:new Date(p,g,y+1).getTime()};if(i==="yesterday")return{start:new Date(p,g,y-1).getTime(),end:new Date(p,g,y).getTime()};let b=/^(\d+)(h|d|w|mo|y)$/.exec(i);if(b)return{start:o-Number(b[1])*sK[b[2]]};if(/^\d{4}$/.test(i))return{start:new Date(Number(i),0,1).getTime(),end:new Date(Number(i)+1,0,1).getTime()};let E=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(i);if(!E)return null;let S=Number(E[1]),w=Number(E[3]);if(w<1||w>12)return null;if(E[4]===void 0){if(E[5]!==void 0)return null;return{start:new Date(S,w-1,1).getTime(),end:new Date(S,w,1).getTime()}}let R=Number(E[4]),A=Number(E[5]??0),P=Number(E[6]??0),C=Number(E[7]??0);if(A>23||P>59||C>59)return null;let q=new Date(S,w-1,R,A,P,C);if(q.getMonth()!==w-1||q.getDate()!==R)return null;if(E[5]!==void 0)return{start:q.getTime()};return{start:q.getTime(),end:new Date(S,w-1,R+1).getTime()}}var aK=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),bg=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),Eg=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function xg(e,o,i,u,p,g){let y=i.trim(),b=(S,w)=>e.diagnostics.push({code:S,message:w,filter:o});if(!y)return b("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return b("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let E=p?[y]:y.split(",").map((S)=>S.trim()).filter(Boolean);switch(o){case"in":case"project":for(let S of E){let w=S.toLowerCase();if(o==="in"&&w==="this")e.currentSession=!0;else if(o==="in"&&w==="title")e.fields.push("title");else e.projectID.push(S)}return;case"session":for(let S of E)if(S.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(S);return;case"from":case"role":for(let S of E){let w=nK[S.toLowerCase()];if(w)e.fields.push(...w);else b("bad_filter_value",`${o}:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...E);return;case"model":e.model.push(...E);return;case"is":for(let S of E){let w=S.toLowerCase();if(w==="error")e.isError=!u;else if(w==="archived")e.archived=!u;else if(w==="compacted")e.compacted=!u;else b("bad_filter_value",`is:${S} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let S=iK(y,g);if(!S)return b("bad_filter_value",`${o}:${y} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=bg(e.after,S.start);else if(o==="before")e.before=Eg(e.before,S.start);else if(e.after=bg(e.after,S.start),S.end!==void 0)e.before=Eg(e.before,S.end)}}}function uK(e,o){let i={},u=(C,q)=>{let X=av([...C??[],...q]);return X.length?X:void 0},p=u(e?.projectID,o.projectID),g=u(e?.sessionID,o.sessionID),y=u(e?.fields,o.fields),b=u(e?.tools,o.tools),E=u(e?.model,o.model);if(p)i.projectID=p;if(g)i.sessionID=g;if(y)i.fields=y;if(b)i.tools=b;if(E)i.model=E;let S=o.isError??e?.isError,w=o.archived??e?.archived,R=o.compacted??e?.compacted;if(S!==void 0)i.isError=S;if(w!==void 0)i.archived=w;if(R!==void 0)i.compacted=R;let A=bg(e?.after,o.after),P=Eg(e?.before,o.before);if(A!==void 0)i.after=A;if(P!==void 0)i.before=P;if(A!==void 0&&P!==void 0&&A>=P)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return i}function ev(e,o){let i=Ig[e[o]]??['"'],u="",p=o+1;while(p<e.length){let g=e[p],y=e[p+1];if(g==="\\"&&y!==void 0&&(y==="\\"||y==='"'||y==="\u201C"||y==="\u201D")){u+=y,p+=2;continue}if(i.includes(g))return{text:u,next:p+1,closed:!0};u+=g,p++}return{text:u,next:p,closed:!1}}function tv(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let i=e.slice(0,-1).map((p)=>p.esc||!/[A-Za-z]/.test(p.c)?"":p.c).join("");if(i.length!==e.length-1)return;let u=i.toLowerCase();return iv.has(u)?u:void 0}function rv(e,o,i){let u=e==="word"&&!i&&zc(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:i,fuzzy:u}}function cK(e,o){let i=[],u=e.length,p=0;while(p<u){if(yg(e[p])){p++;continue}let g=!1;if(e[p]==="-"){if(p+1>=u||yg(e[p+1])){p++;continue}g=!0,p++}if(Ig[e[p]]){let P=ev(e,p);if(p=P.next,!P.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let C=P.text.trim();if(C)i.push({kind:"term",negated:g,term:rv("phrase",C,!1)});continue}let y=[],b;while(p<u&&!yg(e[p])){let P=e[p],C=e[p+1];if(P==="\\"&&C!==void 0&&oK.has(C)){y.push({c:C,esc:!0}),p+=2;continue}let q=Ig[P]?tv(y):void 0;if(q){let X=ev(e,p);if(p=X.next,!X.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});b={key:q,value:X.text,quoted:!0};break}y.push({c:P,esc:!1}),p++}if(b){i.push({kind:"filter",negated:g,...b});continue}let E=y.findIndex((P,C)=>C>0&&!P.esc&&(P.c===":"||P.c==="\uFF1A")),S=E>0?tv(y.slice(0,E+1)):void 0;if(S){i.push({kind:"filter",negated:g,key:S,value:y.slice(E+1).map((P)=>P.c).join(""),quoted:!1});continue}if(!g&&y.length===2&&y.every((P)=>!P.esc)&&y[0]?.c==="O"&&y[1]?.c==="R"){i.push({kind:"or"});continue}let w=y[y.length-1],R=y.length>1&&w!==void 0&&!w.esc&&w.c==="*",A=(R?y.slice(0,-1):y).map((P)=>P.c).join("");if(A)i.push({kind:"term",negated:g,term:rv("word",A,R)})}return i}var mK=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function nv(e){let o=[];return{rest:e.replace(mK,(u,p,g,y,b)=>{let E=y.toLowerCase();if(!iv.has(E))return u;let S=b.startsWith('"')&&b.length>=2;return o.push({key:E,value:S?b.slice(1,-1).replace(/\\(["\\])/g,"$1"):b,negated:g==="-",quoted:S}),p}).trim(),filters:o}}var ov={n:`
400
- `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function pK(e){let o=[...e],i=0,u=(w)=>{let R=o.slice(i,i+w).join("");if(R.length!==w||!/^[0-9a-fA-F]+$/.test(R))return;return i+=w,String.fromCodePoint(Number.parseInt(R,16))},p=()=>{let w=o[i++];if(w===void 0)return{kind:"lit",ch:"\\"};if(w in ov)return{kind:"lit",ch:ov[w]};if("dDwWsS".includes(w))return{kind:"any"};if(w==="b"||w==="B")return{kind:"zero"};if(w>="1"&&w<="9"){while(o[i]!==void 0&&/\d/.test(o[i]))i++;return{kind:"any"}}if(w==="k"||w==="p"||w==="P"){let R=o[i];if(R==="<"||R==="{"){let A=R==="<"?">":"}",P=o.indexOf(A,i);i=P<0?o.length:P+1}return{kind:"any"}}if(w==="c")return i++,{kind:"any"};if(w==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(w==="u"){if(o[i]==="{"){let A=o.indexOf("}",i),P=A<0?"":o.slice(i+1,A).join("");if(/^[0-9a-fA-F]{1,6}$/.test(P)&&Number.parseInt(P,16)<=1114111)return i=A+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(P,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:w}},g=()=>{if(o[i]==="^")i++;while(i<o.length&&o[i]!=="]")i+=o[i]==="\\"?2:1;return i++,{kind:"any"}},y=()=>{let w="capture";if(o[i]==="?"){let A=o[i+1],P=o[i+2];if(A===":")w="plain",i+=2;else if(A==="="||A==="!")w="look",i+=2;else if(A==="<"&&(P==="="||P==="!"))w="look",i+=3;else if(A==="<"){let C=o.indexOf(">",i);i=C<0?o.length:C+1}else{w="opaque";while(i<o.length&&o[i]!==":"&&o[i]!==")")i++;if(o[i]===":")i++}}let R=S();if(o[i]===")")i++;if(w==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:w==="opaque"}},b=()=>{let w=o[i],R=1,A=!0;if(w==="*"||w==="?")R=0,i++;else if(w==="+")i++;else if(w==="{"){let P=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(i,i+24).join(""));if(!P)return{quantified:!1,min:1};R=Number(P[1]),i+=P[0].length}else return{quantified:!1,min:1};if(o[i]==="?")i++;return{quantified:A,min:R}},E=()=>{let w=[];while(i<o.length){let R=o[i];if(R==="|"||R===")")break;i++;let A;if(R==="(")A=y();else if(R==="[")A=g();else if(R==="\\")A=p();else if(R===".")A={kind:"any"};else if(R==="^"||R==="$")A={kind:"zero"};else if(R==="*"||R==="+"||R==="?")A={kind:"zero"};else A={kind:"lit",ch:R};w.push({atom:A,...b()})}return w};function S(){let w=[E()];while(o[i]==="|")i++,w.push(E());return w}return S()}function sv(e){let o=[],i="",u=()=>{if(i)o.push([i]);i=""},p=(g)=>{for(let y of g){let b=y.atom;if(b.kind==="lit")if(y.min>=1){if(i+=b.ch,y.quantified)u()}else u();else if(b.kind==="group"&&!b.opaque&&y.min>=1)if(b.alts.length===1&&!y.quantified)p(b.alts[0]);else u(),o.push(...uv(b.alts));else u()}};return p(e),u(),o}function uv(e){if(e.length===1)return sv(e[0]);let o=[];for(let i of e){let u=sv(i).filter((p)=>p.length===1).map((p)=>p[0]);if(!u.length)return[];o.push(u.reduce((p,g)=>zc(g)>zc(p)?g:p))}return[av(o)]}var lK=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function dK(e){return!/^\s*$/.test(e)&&(zc(e)>=2||lK.test(e))}function fK(e){let o;try{o=uv(pK(e))}catch{return[]}let i=o.filter((E)=>E.every(dK)),u=i.filter((E)=>E.length===1).map((E)=>E[0]),p=i.filter((E)=>{if(E.length!==1)return!0;let S=E[0];return!u.some((w)=>w!==S&&w.includes(S))}),g=new Set,y=p.filter((E)=>{let S=JSON.stringify(E);if(g.has(S))return!1;return g.add(S),!0}),b=(E)=>Math.min(...E.map(zc));return y.sort((E,S)=>b(S)-b(E))}function hK(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 gK(e,o){let i=`m${o?"":"i"}`;try{return new RegExp(e,`${i}u`),{flags:`${i}u`}}catch{}try{return new RegExp(e,i),{flags:i}}catch(u){let p=u instanceof Error?u.message:String(u),g="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(p))g="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(p))g="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(p))g="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(p))g="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${g}`}}}function Gl(e,o={}){let i=o.now??Date.now(),u=e.q??"",p=aK(),g=p.diagnostics,y,b=[];if(e.mode==="regex"){let q=nv(u);for(let X of q.filters)xg(p,X.key,X.value,X.negated,X.quoted,i);y=q.rest}else{let q=nv(u),X=/^\/([\s\S]+)\/$/.exec(q.rest);if(X){for(let j of q.filters)xg(p,j.key,j.value,j.negated,j.quoted,i);y=X[1]}else{b=[{include:[],exclude:[]}];for(let j of cK(u,g)){let V=b[b.length-1];if(j.kind==="or")b.push({include:[],exclude:[]});else if(j.kind==="filter")xg(p,j.key,j.value,j.negated,j.quoted,i);else(j.negated?V.exclude:V.include).push(j.term)}b=b.filter((j)=>j.include.length||j.exclude.length)}}let E=b.flatMap((q)=>[...q.include,...q.exclude]),S=y!==void 0?hK(y):E.some((q)=>/\p{Lu}/u.test(q.text)),w=e.caseSensitive??S,R=e.caseSensitive===void 0&&S,A,P;if(y){let q=gK(y,w);if("message"in q)P={code:"bad_regex",message:q.message};else{let X=fK(y);A={source:y,flags:q.flags,literals:X,deepScan:X.length===0}}}let C=uK(e.filters,p);return{mode:y!==void 0?"regex":"text",branches:b,...A?{regex:A}:{},filters:C,currentSession:p.currentSession,caseSensitive:w,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:b.some((q)=>q.include.some((X)=>X.fuzzy)),hasPositive:A!==void 0||b.some((q)=>q.include.length>0),hasFilters:Object.keys(C).length>0||p.currentSession,...P?{error:P}:{},diagnostics:g}}var wg={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},cv=new WeakMap;function mv(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,i=cv.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 cv.set(e,{version:o,terms:u}),u}var Sg=32,yK=1024,Vc=(e)=>`"${e.replaceAll('"','""')}"`;function xK(e,o){let i=Array.from({length:o.length+1},(u,p)=>p);for(let u=0;u<e.length;u++){let p=[u+1];for(let g=0;g<o.length;g++)p.push(Math.min((p[g]??0)+1,(i[g+1]??0)+1,(i[g]??0)+Number(e[u]!==o[g])));i=p}return i[o.length]??e.length}function Tg(e,o){let i=Pt(o.trim());if(!i||i.length>64)return[];let u=mv(e),p=u.filter((b)=>b.t.startsWith(i)).slice(0,8).map((b)=>b.t);if(p.length>=8||i.length<4)return p;let g=i.length>=8?2:1,y=[];for(let b of u){if(Math.abs(b.t.length-i.length)>g)continue;if(xK(i,b.t)<=g)y.push(b.t);if(y.length>=8)break}return[...new Set([...p,...y])].slice(0,8)}function pv(e,o){let i=!1,u=[],p=[],g=o.filters,y=(X,j)=>{if(!j?.length)return;p.push(`${X} IN (${j.map(()=>"?").join(",")})`),u.push(...j)};if(y("s.project_id",g.projectID),g.sessionID?.length){p.push(`(${g.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let X of g.sessionID)u.push(X,X)}if(g.archived!==void 0)p.push(`s.archived_at IS ${g.archived?"NOT ":""}NULL`);let b=p.length?p.join(" AND "):"1",E=[...u];if(y("r.kind",g.fields?.map((X)=>Ne[X])),y("r.tool",g.tools),g.model?.length){p.push(`(${g.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let X of g.model)u.push(X,X)}if(g.isError!==void 0)p.push("r.err = ?"),u.push(Number(g.isError));if(g.compacted!==void 0)p.push(`(r.seq>0 AND r.seq<=COALESCE((
401
- SELECT max(json_extract(body,'$.through')) FROM store.entries
402
- WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
403
- ),0)) = ?`),u.push(Number(g.compacted));if(g.after!==void 0)p.push("r.time >= ?"),u.push(g.after);if(g.before!==void 0)p.push("r.time < ?"),u.push(g.before);let S=e.query("SELECT v FROM meta WHERE k='layout'").get(),w=S&&JSON.parse(S.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),A=(X)=>{let j=(ee)=>{let ae=Pt(ee);if(!X&&w){if([...ae].length<3){let se=[...ae].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(ae,`${ae}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(ae);if([...ae].length===1&&se.length>Sg)se.length=Sg,i=!0;if(!se.length)return Vc("__basalt_no_short_match__");return`(${se.map((pe)=>Vc(pe.term)).join(" OR ")})`}return Vc(ae)}let H=/^[\p{Script=Latin}\p{N}]+$/u.test(ee)?[ae]:Ti(ee),ue=H.filter((se)=>!/^[a-z0-9]{1,2}$/.test(se)),he=ue.length?ue:H;if(!he.length){R=!0;return}let $e=he.map((se,pe)=>{let qe=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(se),xt=he.length>2&&pe>0&&pe<he.length-1;if(qe||xt){let Fe=e.query("SELECT n FROM term WHERE t=?").get(se)?.n??0;return{expression:Vc(se),frequency:Fe}}let Je=[se],Yt=0;for(let Fe of mv(e)){if(!Fe.t.includes(se))continue;if(Yt+=Fe.n,Fe.t!==se)Je.push(Fe.t);if(Je.length>=Sg){i=!0;break}}return{expression:`(${Je.map(Vc).join(" OR ")})`,frequency:Yt}});return $e.sort((se,pe)=>se.frequency-pe.frequency),`(${$e.slice(0,($e[0]?.frequency??1/0)<=yK?1:2).map((se)=>se.expression).join(" AND ")})`},V=o.regex?o.regex.literals:o.branches.map((ee)=>ee.include.map((ae)=>ae.text));if(o.regex){let ee=V.map((ae)=>ae.map(j));if(ee.some((ae)=>ae.some((H)=>!H)))return;return ee.map((ae)=>`(${ae.join(" OR ")})`).join(" AND ")||void 0}let J=V.map((ee)=>{let ae=ee.filter((H)=>!/^[a-z0-9]{1,2}$/i.test(H));return(ae.length?ae:ee).map(j)});if(J.some((ee)=>!ee.length||ee.some((ae)=>!ae)))return;return J.map((ee)=>`(${ee.join(" AND ")})`).join(" OR ")||void 0},P=A(!1),C=A(!0),q=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:P,out:C,scan:R,where:p.length?p.join(" AND "):"1",bindings:u,forks:q,sessionWhere:b,sessionBindings:E,partial:i,candidateLimit:o.branches.some((X)=>X.include.length>0&&X.include.every((j)=>[...j.text].length<2))?512:void 0}}function lv(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 Kl(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(wg).map(([i,u])=>`WHEN ${Ne[i]} THEN ${u}`).join(" ")} ELSE 1 END) *
404
- (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function dv(e,o,i,u){let p=Math.max(0,u-i)/86400000;return Math.max(0.000000001,-e)*wg[o]*(0.3+0.7/(1+p/30))}function Rg(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 Ag=512;function fv(e,o,i){let u=performance.now(),p=o.partial;Pg(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[g,y]of[["fts",o.msg],["fts_out",o.out]]){if(!y)continue;let b=o.candidateLimit??2000,E=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
405
- ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(y,o.candidateLimit?b+1:b);if(o.candidateLimit&&E.length>b)E.length=b,p=!0;else if(!o.candidateLimit&&E.length===b){let w=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${g} WHERE ${g} MATCH ?
406
- AND rowid NOT IN (SELECT value FROM json_each(?))`).all(y,JSON.stringify(E.map((R)=>R.doc)));for(let R of w)E.push(R)}let S=lv(E);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
407
- FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(S))}return i?.("match",performance.now()-u),p}function hv(e,o,i,u,p){let g=performance.now();if(o.candidateLimit){let b=e.query(`
408
- SELECT r.session_id,r.seq,${Kl(u)} AS score
409
- FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
410
- ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
411
- WHERE ${o.where} LIMIT ${o.candidateLimit+1}
412
- `).all(...o.bindings);if(b.length>o.candidateLimit)b.length=o.candidateLimit,o.partial=!0;let E=new Map;for(let S of b){let w=i?S.seq:0,R=JSON.stringify([S.session_id,w]),A=E.get(R);if(!A||S.score>A.score)E.set(R,{...S,seq:w})}return p?.("filter",performance.now()-g),[...E.values()].sort((S,w)=>w.score-S.score||(S.session_id<w.session_id?-1:Number(S.session_id>w.session_id))||w.seq-S.seq)}let y=e.query(`
413
- SELECT r.session_id,${i?"r.seq":"0"} AS seq,max(${Kl(u)}) AS score
414
- FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
415
- ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
416
- WHERE ${o.where}
417
- GROUP BY r.session_id${i?",r.seq":""}
418
- ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
419
- `).all(...o.bindings);return p?.("filter",performance.now()-g),y}var gv=new WeakMap,IK=`WITH RECURSIVE lineage(child,ancestor,through) AS (
420
- SELECT id,forked_from_id,forked_from_seq FROM store.sessions
421
- WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
422
- UNION
423
- SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
424
- FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
425
- WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
426
- )`;function Pg(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(`${IK} 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();gv.set(e,new Map(i.map((u)=>[u.ancestor,u.through])))}function kg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
427
- SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
428
- JOIN store.sessions ps ON ps.id=pr.session_id
429
- WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
430
- AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
431
- AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
432
- SELECT 1 FROM store.entries original JOIN store.entries copied
433
- ON copied.session_id=r.session_id AND copied.seq=r.seq
434
- WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
435
- ))
436
- ))`}function yv(e,o,i,u,p){let g=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let y=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,b=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
437
- INSERT INTO temp.search_window SELECT r.* FROM ref r ${y>4000?"INDEXED BY ref_time":""}
438
- ${b} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${kg(o)}
439
- ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${u} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],i);let E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(E===u){let S=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(S)e.query(`
440
- INSERT INTO temp.search_window SELECT r.* FROM ref r ${b}
441
- WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
442
- AND ${o.where} AND ${kg(o)} AND NOT EXISTS (
443
- SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
444
- )`).run(S.session_id,S.seq,...o.bindings,...o.forks?o.bindings:[]),E=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return p?.("filter",performance.now()-g),E}function xv(e,o,i,u,p,g,y){let b=performance.now(),E=o.group==="none",S=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",w=e.query(`
445
- SELECT r.session_id,${E?"r.seq":"0"} AS seq,
446
- max(${Kl(p)}) AS relevance,max(r.time) AS time
447
- FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
448
- WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
449
- GROUP BY r.session_id${E?",r.seq":""}
450
- ORDER BY ${S},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(g),u,i);return y?.("group",performance.now()-b),w}function Iv(e,o,i,u,p,g){let y=performance.now(),b=p?o:{...o,forks:!1},E=e.query(`
451
- SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
452
- ${b.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
453
- WHERE r.session_id=? ${u?"AND r.seq=?":""}
454
- AND ${o.where} AND ${kg(b)}
455
- ${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(i.session_id,...u?[i.seq]:[],...o.bindings,...b.forks?o.bindings:[]);return g?.("filter",performance.now()-y),E}function Cg(e,o,i,u){if(!o.forks)return[];let p=gv.get(e)?.get(i.session_id);if(p===void 0||i.seq>p)return[];return e.query(`
456
- SELECT DISTINCT r.session_id,s.title,e.body
457
- FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
458
- CROSS JOIN ref r ON r.session_id=l.child
459
- JOIN store.sessions s ON s.id=r.session_id
460
- LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
461
- WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(i.session_id,i.doc,i.seq,i.part,...o.bindings).filter((g)=>{if(i.seq===0)return g.title===u;if(!g.body)return!1;let y=JSON.parse(g.body);return Ke(y,!0).some((b)=>b.part===i.part&&b.kind===eo[i.kind]&&b.text===u)}).map((g)=>g.session_id)}function bK(e,o){let i=o?e:Pt(e);if(i.length===e.length)return{normalized:i,starts:void 0,ends:void 0};let u="",p=[],g=[],y=0;for(let b of e){let E=o?b:Pt(b);u+=E;for(let S=0;S<E.length;S++)p.push(y),g.push(y+b.length);y+=b.length}return{normalized:u,starts:p,ends:g}}function Hl(e,o){if(o.regex){let E=new RegExp(o.regex.source,`${o.regex.flags}g`),S=[];for(let w of e.matchAll(E)){if(o.wholeWord&&!bv(e,w.index,w.index+w[0].length))continue;S.push([w.index,w.index+w[0].length])}return S.length?S:void 0}let{normalized:i,starts:u,ends:p}=bK(e,o.caseSensitive),g=(E)=>{let S=o.caseSensitive?E.text:Pt(E.text),w=[],R=i.indexOf(S);while(R>=0&&S){let A=u?u[R]:R,P=p?p[R+S.length-1]:R+S.length,C=A===0||A!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(A-1,A))||/[a-z0-9][A-Z]/.test(e.slice(A-1,A+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(E.text));if(A!==void 0&&P!==void 0&&(!E.prefix||C)&&(!o.wholeWord||bv(e,A,P)))w.push([A,P]);R=i.indexOf(S,R+Math.max(1,S.length))}return w};if(!o.branches.length)return[];let y=[],b=!1;for(let E of o.branches){if(E.exclude.some((w)=>g(w).length))continue;let S=E.include.map(g);if(S.some((w)=>!w.length))continue;b=!0,y.push(...S.flat())}return b?y:void 0}function bv(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 Wl(e,o){let i=e.split(`
462
- `),u=new Set,p=0,g=i.map((y,b)=>{let E=p;if(o.some(([S,w])=>S<=E+y.length&&w>=E))for(let S=Math.max(0,b-1);S<=Math.min(i.length-1,b+1);S++)u.add(S);return p+=y.length+1,E});if(!u.size)u.add(0);return[...u].sort((y,b)=>y-b).slice(0,5).map((y)=>{let b=i[y]??"",E=g[y]??0,S=o.filter(([P,C])=>C>E&&P<E+b.length),w=Math.max(0,(S[0]?.[0]??E)-E-100),R=b.slice(w,w+300),A=S.map(([P,C])=>[Math.max(0,P-E-w),Math.min(R.length,C-E-w)]);return{text:R,line:y+1,ranges:A.filter(([P,C])=>P<C)}})}var Ev=3;function EK(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 Sv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function SK(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let i=JSON.parse(Buffer.from(e,"base64url").toString());if(i&&typeof i==="object"&&"offset"in i&&"key"in i&&"now"in i&&i.key===o&&typeof i.offset==="number"&&Number.isSafeInteger(i.offset)&&i.offset>=0&&typeof i.now==="number"&&Number.isFinite(i.now)){let u="window"in i?i.window:0,p="seen"in i?i.seen:[],g="emitted"in i?i.emitted:[],y="after"in i?i.after:void 0;if(y!==void 0&&!EK(y))throw Error("invalid best cursor");let b=(E)=>Array.isArray(E)&&E.every((S)=>typeof S==="string"&&S.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&b(p)&&b(g))return{offset:i.offset,key:o,now:i.now,window:u,seen:p,emitted:g,after:y}}}catch{}throw Error("invalid search cursor")}function Nn(e,o){let i=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return SK(e.cursor,i)}async function Gr(e,o,i){let u="search"in e?e.search:e,p=performance.now(),g=(Fe)=>{if(!i.signal?.aborted)i.onEvent(Fe)};if(i.signal?.aborted)return;let y=Nn(o,i.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let b=Gl(o,{now:y.now});if(b.error){g({type:"error",...b.error});return}if(b.currentSession){if(!i.sessionID){g({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}b.filters.sessionID=[i.sessionID]}if(!o.deep&&b.regex?.deepScan){g({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),i.signal?.aborted)return;let E=performance.now(),S=u.withIndex((Fe)=>pv(Fe,b));if(!S){g({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}i.onTiming?.("plan",performance.now()-E);let w=S.partial,R=y.after,A=new Map,P=new Map,C=[],q=!1,X=new Map,j=new WeakMap,V=new Map,J=new Map,{offset:ee,window:ae}=y,H=[...y.seen],ue=[...y.emitted],he=!1,$e=Math.max(1,Math.min(200,o.limit??30)),Ee=Math.min(S.candidateLimit??2000,o.group==="none"?Ag:Math.min(2000,Math.max(Ag,$e*32))),se=(Fe,Ue)=>{let Dt=A.get(Ue);if(Dt)return Dt;let lt=Fe.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(Ue);if(lt)A.set(Ue,lt);return lt??void 0},pe=(Fe,Ue,Dt)=>{if(i.allowedSessionIDs&&!i.allowedSessionIDs.has(Ue.session_id))return;if(i.excludeEntry?.sessionID===Ue.session_id&&i.excludeEntry.seq===Ue.seq)return;let lt=se(Fe,Ue.session_id);if(!lt)return;let Mt=eo[Ue.kind];if(!Mt)return;let yr=lt.title;if(Ue.seq!==0){let st=`${Ue.session_id}:${Ue.seq}`,Jt=J.get(st);if(!Jt){let mn=Dt?void 0:Fe.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(Ue.session_id,Ue.seq);if(!Dt&&!mn)return;let Kt=Dt??JSON.parse(mn?.body??"null");Jt=Ke(Kt,!0),J.set(st,Jt)}let Zt=Jt.find((mn)=>mn.part===Ue.part&&mn.kind===Mt);if(!Zt)return;yr=Zt.text}let pr=Hl(yr,b);if(!pr)return;let jt=P.get(lt.id);if(jt===void 0)jt=Fe.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(lt.id)?.through??0,P.set(lt.id,jt);let ot=Ue.seq>0&&Ue.seq<=jt;if(b.filters.compacted!==void 0&&ot!==b.filters.compacted)return;let At={sessionID:lt.id,seq:Ue.seq,time:Ue.time,field:Mt,tool:Ue.tool??void 0,isError:Boolean(Ue.err),model:Ue.model??void 0,snippet:[],score:dv(Ue.relevance,Mt,Ue.time,y.now),flags:{archived:lt.archived_at!==null,compacted:ot,partial:yr.length>_i+Ai}};return X.set(At,{text:yr,ranges:pr}),C.push(At),q=!0,V.set(At,{doc:Ue.doc,part:Ue.part}),At},qe=(Fe)=>{let Ue=performance.now(),Dt=[...Fe].sort((ot,At)=>ot.time-At.time||ot.sessionID.localeCompare(At.sessionID)),lt=[],Mt=new Map;for(let ot of Dt){let At=V.get(ot),Jt=A.get(ot.sessionID),Zt=new Set;while(Jt?.forked_from_id&&Jt.forked_from_seq!==null&&ot.seq<=Jt.forked_from_seq&&!Zt.has(Jt.id))Zt.add(Jt.id),Jt=A.get(Jt.forked_from_id)??u.withIndex((ko)=>se(ko,Jt?.forked_from_id??""));let mn=`${Jt?.id??ot.sessionID}:${ot.seq}:${At?.part}:${At?.doc}`,Kt=Mt.get(mn);if(Kt){if(Kt.sessionID!==ot.sessionID)Kt.forks=[...new Set([...Kt.forks??[],ot.sessionID])]}else Mt.set(mn,ot),lt.push(ot)}let yr=[],pr=new Map,jt=new Map;for(let ot of lt){let At=`${ot.sessionID}:${ot.seq}`,st=jt.get(At);if(!st){jt.set(At,ot),j.set(ot,[ot]);continue}let Jt=[...j.get(st)??[st],ot],Zt=ot.score>st.score?ot:st;if(Zt.forks=[...new Set([...st.forks??[],...ot.forks??[]])],!Zt.forks.length)Zt.forks=void 0;Zt.flags={archived:st.flags.archived||ot.flags.archived,compacted:st.flags.compacted||ot.flags.compacted,partial:st.flags.partial||ot.flags.partial},jt.set(At,Zt),j.set(Zt,Jt)}for(let ot of Rg([...jt.values()],o.sort??"best")){let At=A.get(ot.sessionID);if(!At)continue;let st=o.group==="none"?void 0:pr.get(At.id);if(!st)st={session:{id:At.id,title:At.title,projectID:At.project_id,updated:At.updated},hits:[],more:0,...w&&o.group!=="none"?{moreIsLowerBound:!0}:{}},yr.push(st),pr.set(At.id,st);if(st.hits.length<Ev||o.group==="none")st.hits.push(ot);else st.more++}return i.onTiming?.("group",performance.now()-Ue),yr},xt=(Fe)=>{for(let Ue of Fe)for(let Dt of Ue.hits){if(i.allowedSessionIDs&&Dt.forks)Dt.forks=Dt.forks.filter((yr)=>i.allowedSessionIDs?.has(yr));let lt=performance.now(),Mt=new Map;for(let yr of j.get(Dt)??[Dt]){let pr=X.get(yr);if(!pr)continue;for(let jt of Wl(pr.text,pr.ranges)){let ot=`${jt.line}:${jt.text}`,At=Mt.get(ot);if(!At)Mt.set(ot,jt);else At.ranges=[...new Map([...At.ranges,...jt.ranges].map((st)=>[st.join(":"),st])).values()]}}Dt.snippet=[...Mt.values()],i.onTiming?.("snippet",performance.now()-lt)}},Je=o.deep||S.scan,Yt=(Fe,Ue)=>{let Dt=se(Fe,Ue.session_id);if(!Dt)return[];let lt=Iv(Fe,S,Ue,o.group==="none",Dt.forked_from_id!==null,i.onTiming);if(S.candidateLimit&&lt.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Mt=C.length,yr=performance.now();for(let pr of lt){if(i.signal?.aborted)break;let jt=pe(Fe,pr);if(!jt)continue;let ot=Cg(Fe,S,pr,X.get(jt)?.text??"");if(ot.length)jt.forks=ot}return i.onTiming?.("body",performance.now()-yr),C.slice(Mt)};if(Je){w=!1;let Fe=[],Ue=new Set,Dt=u.withIndex((st)=>{Pg(st,S);for(let Kt of st.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())A.set(Kt.id,Kt);let Jt=new Set(st.query(`SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}`).all(...S.sessionBindings).map((Kt)=>Kt.id)),Zt=(Kt)=>{if(Ue.has(Kt.id))return;Ue.add(Kt.id);let ko=Kt.forked_from_id?A.get(Kt.forked_from_id):void 0;if(ko)Zt(ko);if(Jt.has(Kt.id))Fe.push(Kt)};for(let Kt of A.values())Zt(Kt);return(st.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
463
- SELECT s.id FROM store.sessions s WHERE ${S.sessionWhere}
464
- )`).get(...S.sessionBindings)?.n??0)+Jt.size})??0,lt=0,Mt=0,yr=0;if(b.regex?.deepScan)g({type:"groups",groups:[]});let pr=new Set,jt=new Set,ot=new Map,At=()=>{let st=qe(C),Jt=[];for(let Zt of st){let mn=Zt.session.id,Kt=o.group==="none"?void 0:ot.get(mn);if(o.group!=="none"&&jt.has(mn)&&!Kt)continue;if(!Kt){if(jt.add(mn),Mt<y.offset){Mt++;continue}if(yr>=$e){he=!0;break}yr++,ee++}if(o.group!=="none"){let ko=(Kt?.count??0)+Zt.hits.length+Zt.more;Zt.hits=Zt.hits.slice(0,Ev-(Kt?.shown??0));let gu=(Kt?.shown??0)+Zt.hits.length;Zt.more=ko-gu,ot.set(mn,{shown:gu,count:ko})}Jt.push(Zt)}if(Jt.length)xt(Jt),g({type:"groups",groups:Jt});C.length=0,X.clear(),V.clear(),J.clear()};for(let st of Fe){if(i.signal?.aborted||he)break;let Jt=-1,Zt;for(;;){if(i.signal?.aborted||he)break;let mn=u.withIndex((Kt)=>{let ko=Kt.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(st.id,Math.max(0,Jt));if(Jt<0)ko.unshift({seq:0,time:st.updated,body:null});for(let ji of ko){if(i.signal?.aborted)break;let yu=ji.body?JSON.parse(ji.body):void 0;if(yu?.type==="assistant")Zt=yu.model;let Pv=yu?Ke(yu,!0):[{part:0,kind:"title",text:st.title}];for(let Ko of Pv){if(i.signal?.aborted)break;let $s={session_id:st.id,seq:ji.seq,part:Ko.part,doc:Number(BigInt(Bun.hash(Ko.text))&0x1fffffffffffffn),kind:Ne[Ko.kind],tool:Ko.tool??null,err:Number(Ko.err??!1),model:Ko.model??(Ko.tool?Zt:void 0)??null,time:ji.time,relevance:-1};if(!Kt.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
465
- JOIN store.sessions s ON s.id=r.session_id WHERE ${S.where}`).get($s.session_id,$s.seq,$s.kind,$s.tool,$s.err,$s.model,$s.time,...S.bindings))continue;let zs=st,vg=new Set;while(zs.forked_from_id&&zs.forked_from_seq!==null&&ji.seq<=zs.forked_from_seq&&!vg.has(zs.id)){vg.add(zs.id);let xu=A.get(zs.forked_from_id);if(!xu)break;zs=xu}let Mg=`${zs.id}:${ji.seq}:${Ko.part}:${Bun.hash(Ko.text)}`;if(pr.has(Mg))continue;let Og=pe(Kt,$s,yu);if(Og){if(pr.add(Mg),S.forks){let xu=Kt.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(st.id,ji.seq,Ko.part);if(xu){let _g=Cg(Kt,S,{...$s,doc:xu.doc},Ko.text);if(_g.length)Og.forks=_g}}}}}let gu=ko.at(-1);if(gu)Jt=gu.seq;return ko.length});if(mn===void 0){g({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(lt+=mn,g({type:"progress",scanned:lt,total:Dt}),i.signal?.aborted)return;if(At(),!mn||he)break;await Bun.sleep(0)}}}else u.withIndex((Fe)=>{if(w=fv(Fe,S,i.onTiming)||w,b.regex?b.regex.literals.every((lt)=>lt.some((Mt)=>[...Mt].length<3)):b.branches.some((lt)=>lt.include.length>0&&lt.include.every((Mt)=>[...Mt.text].length<3)))Fe.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let lt=hv(Fe,S,o.group==="none",y.now,i.onTiming);if(w||=S.partial,S.candidateLimit&&lt.length>S.candidateLimit)lt.length=S.candidateLimit,w=!0;let Mt=[];for(let pr of lt){if(i.signal?.aborted)return;let jt=Mt[$e]?.key.score;if(jt!==void 0&&pr.score+0.000000000001<jt)break;let ot=C.length,At=Yt(Fe,pr);C.splice(ot);let st=Rg([...At],"best")[0];if(!st)continue;let Jt={score:st.score,sessionID:st.sessionID,seq:o.group==="none"?st.seq:0};if(y.after&&Sv(Jt,y.after)<=0)continue;if(Mt.push({key:Jt,hits:At}),Mt.sort((Zt,mn)=>Sv(Zt.key,mn.key)),Mt.length>$e+1)Mt.length=$e+1}he=Mt.length>$e;let yr=Mt.slice(0,$e);for(let pr of yr)C.push(...pr.hits);R=yr.at(-1)?.key;return}let Dt=0;for(;;){if(i.signal?.aborted)return;let lt=yv(Fe,S,ae,Ee,i.onTiming),Mt=S.candidateLimit!==void 0&&ae+lt>=S.candidateLimit;w||=Mt;let yr=xv(Fe,o,ee,$e-Dt+1,y.now,H,i.onTiming);he=yr.length>$e-Dt;let pr=yr.slice(0,$e-Dt);if(!pr.length){if(lt<Ee||Mt){he=!1;break}ae+=lt,ee=0,H=[...new Set([...H,...ue])],ue=[];continue}for(let jt of pr)if(ee++,Yt(Fe,jt).length){if(Dt++,o.group!=="none")ue.push(jt.session_id)}if(Dt>=$e){he||=!Mt&&lt>=Ee;break}if(!he){if(lt<Ee||Mt)break;ae+=lt,ee=0,H=[...new Set([...H,...ue])],ue=[]}}});if(i.signal?.aborted)return;if(!Je){let Fe=qe(C);xt(Fe),g({type:"groups",groups:Fe})}if(!q){let Fe=b.branches.flatMap((Ue)=>Ue.include).find((Ue)=>Ue.fuzzy)?.text;if(Fe)g({type:"suggest",terms:u.withIndex((Ue)=>Tg(Ue,Fe))??[]})}g({type:"done",cursor:he?Buffer.from(JSON.stringify(!Je&&o.sort!=="recent"?{...y,offset:0,window:0,seen:[],emitted:[],after:R}:{...y,offset:ee,window:ae,seen:H,emitted:ue})).toString("base64url"):void 0,tookMs:performance.now()-p,partial:w,index:u.status()})}function Fo(e,o){return e.withIndex((i)=>Tg(i,o))??[]}function wv(e,o,i){let u=x({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(m([a({maxLength:2000}),$n()])),scope:n(m([s("session"),s("project"),s("all"),s(""),$n()])),fields:n(m([B(qr({type:"string",enum:[...Ln]})),$n()])),tool:n(m([a(),$n()])),isError:n(m([O(),$n()])),after:n(m([a(),Y(),$n()])),before:n(m([a(),Y(),$n()])),limit:n(m([_(),$n()])),session:n(m([a(),$n()])),seq:n(m([_(),$n()])),around:n(m([_(),$n()]))}),async execute(p,g,y){let b={query:g.query?.trim(),scope:g.scope||void 0,fields:g.fields?.length?g.fields:void 0,tool:g.tool?.trim(),isError:g.isError??void 0,after:g.after??void 0,before:g.before??void 0,limit:g.limit||void 0,session:g.session?.trim(),seq:g.seq??void 0,around:g.around??void 0},E=b.query?.trim(),S=!E&&Boolean(b.session?.trim())&&Number.isSafeInteger(b.seq)&&(b.seq??0)>=1;if(S&&b.around!==void 0&&(!Number.isInteger(b.around)||b.around<0||b.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(b.scope&&!["session","project","all"].includes(b.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(y?.aborted)throw Error("History search cancelled");let w=e.sessions().find((se)=>se.id===i);if(!w)throw Error("History session is unavailable");let R=(se)=>{if(se===void 0||se===0||typeof se==="string"&&!se.trim())return;if(typeof se==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(se))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let pe=typeof se==="number"?se:Date.parse(se);if(!Number.isFinite(pe)||Math.abs(pe)>8640000000000000){if(typeof se==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return pe},A=S?void 0:R(b.after),P=S?void 0:R(b.before);if(A!==void 0&&P!==void 0&&A>=P)throw Error("after must precede before");let C=[];if(S&&b.session&&b.seq!==void 0){if(!e.sessions().find((Je)=>Je.id===b.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let pe=b.around??3,qe=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(b.session,Math.max(1,b.seq-pe),b.seq+pe);if(!qe.some((Je)=>Je.seq===b.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:qe.map((Je)=>{let Yt={...JSON.parse(Je.body),seq:Je.seq,time:Je.time};return`[seq=${Je.seq}]
466
- ${Ke(Yt,!0).map((Fe)=>`${Fe.kind}: ${Fe.kind==="error"?Fe.text.replace(/^(?:error:\s*)+/i,""):Fe.text}`).join(`
467
- `).slice(0,4000)}`}).join(`
468
-
469
- `)||"No history content"}],details:{groups:C,count:qe.length}}}if(!E)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let q=Number.isFinite(b.limit)?Math.max(1,Math.min(30,Math.trunc(b.limit??10))):10,X=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(i)?.seq,j=new Set(e.sessions().filter((se)=>{if(b.scope==="session")return se.id===i;if((b.scope??"project")==="project"&&w.projectID)return se.projectID===w.projectID;return!0}).map((se)=>se.id)),V={q:E,filters:{tools:b.tool?.trim()?[b.tool.trim()]:void 0,isError:b.isError,after:A,before:P},group:"none",limit:q},J=Gl(V);if(J.error)throw Error(J.error.message);if(b.fields?.length){if(J.filters.fields=b.fields.filter((se)=>(se in Ne)),J.filters.fields.length!==b.fields.length)throw Error("Unknown search field")}if((b.scope??"project")==="session")J.filters.sessionID=[i];else if((b.scope??"project")==="project"&&w.projectID)J.filters.projectID=[w.projectID];let ee=o.status().state!=="ready",ae=!1;if(!ee){let se=J.filters.fields??Object.keys(Ne).filter((xt)=>(xt in Ne)),pe=se.filter((xt)=>xt!=="title"),qe=pe.length?[pe]:[];if(se.includes("title"))qe.push(["title"]);for(let xt of qe){if(C.length>=q&&ae)break;if(await Gr(o,{...V,limit:Math.max(1,q-C.length),filters:{...J.filters,fields:xt}},{signal:y,excludeEntry:X===void 0?void 0:{sessionID:i,seq:X},sessionID:i,allowedSessionIDs:j,onEvent(Je){if(Je.type==="groups")C.push(...Je.groups);if(Je.type==="done")ae||=Boolean(Je.cursor)||Je.partial;if(Je.type==="error")if(Je.code==="unavailable")ee=!0;else throw Error(Je.message)}}),ee)break}}let H=[],ue=0;if(ee){C.length=0;let se=performance.now()+2000;e:for(let pe of e.sessions()){if(!j.has(pe.id))continue;if(J.filters.sessionID&&!J.filters.sessionID.includes(pe.id))continue;if(J.filters.projectID&&(!pe.projectID||!J.filters.projectID.includes(pe.projectID)))continue;let qe=Number.MAX_SAFE_INTEGER,xt=!0;for(;;){let Je=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(pe.id,qe);if(xt)Je.push({body:"null",seq:0,time:pe.updated}),xt=!1;if(!Je.length)break;for(let Yt of Je){if(Yt.seq>0)qe=Yt.seq;if(y?.aborted)throw Error("History search cancelled");if(ue>=1e4||performance.now()>se){ae=!0;break e}if(ue++,pe.id===i&&Yt.seq===X)continue;if(J.filters.after!==void 0&&Yt.time<J.filters.after||J.filters.before!==void 0&&Yt.time>=J.filters.before)continue;let Fe=Yt.seq===0?[{part:0,kind:"title",text:pe.title,tool:void 0,err:!1}]:Ke(JSON.parse(Yt.body),!0);for(let Ue of Fe){if(J.filters.fields&&!J.filters.fields.includes(Ue.kind))continue;if(J.filters.tools&&(!Ue.tool||!J.filters.tools.includes(Ue.tool)))continue;if(J.filters.isError!==void 0&&Boolean(Ue.err)!==J.filters.isError)continue;let Dt=Hl(Ue.text,J);if(!Dt)continue;if(C.length>=q&&Ue.kind!=="title"){ae=!0;break e}(Ue.kind==="title"?H:C).push({session:{id:pe.id,title:pe.title,projectID:pe.projectID,updated:pe.updated},more:0,hits:[{sessionID:pe.id,seq:Yt.seq,time:Yt.time,field:Ue.kind,tool:Ue.tool,isError:Boolean(Ue.err),snippet:Wl(Ue.text,Dt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(y?.aborted)throw Error("History search cancelled");if(H.length>Math.max(0,q-C.length))ae=!0;if(C.push(...H.slice(0,q)),C.sort((se,pe)=>Number(se.hits[0]?.field==="title")-Number(pe.hits[0]?.field==="title")),C.length>q)ae=!0;C.length=Math.min(C.length,q);let he=new Map;for(let se of C)for(let pe of se.hits){let qe=he.get(se.session.id)??[];qe.push(`[${se.session.title.replace(/[\r\n]/g," ")} \xB7 ${pe.sessionID} \xB7 ${pe.seq} \xB7 ${new Date(pe.time).toISOString()} \xB7 ${pe.field}${pe.tool?`/${pe.tool}`:""}]
470
- ${pe.snippet.slice(0,3).map((xt)=>{let Je=xt.text;for(let[Yt,Fe]of[...xt.ranges].sort((Ue,Dt)=>Dt[0]-Ue[0]))Je=`${Je.slice(0,Yt)}\u3010${Je.slice(Yt,Fe)}\u3011${Je.slice(Fe)}`;return Je}).join(`
471
- `)}`),he.set(se.session.id,qe)}let $e="";if(ee){if($e="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")$e="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let Ee=C.reduce((se,pe)=>se+pe.hits.length,0);return{content:[{type:"text",text:[$e,ee&&ae?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${ue} \u6761`:"",[...he.values()].map((se)=>se.join(`
472
-
473
- `)).join(`
474
-
475
- `),Ee===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${Ee} \u6761\uFF1B${ae?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
476
- `)}],details:{groups:C,count:Ee}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}async function Tv(e,o){let i=o.projectID?e.store.project(o.projectID):void 0,u=i?.directory??process.cwd(),g=o.info().kind==="sub",y=()=>g||o.records.some((S)=>S.entry.type==="compaction"),b=e.options.tools??nr({directory:i?.directory,records:()=>o.records,history:(S)=>e.resolveHistory(o.id,S),onTodos:(S)=>o.setTodos(S),shell:()=>e.serverShell(),hasCompacted:y});if(e.options.tools===void 0)b.push(wv(e.store,e.search,o.id));let E=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:w$({project:i,globalInstructions:AK(e),git:i?await T$(i.directory):void 0,shell:e.serverShell()});return{systemPrompt:E.map((S)=>S.detail).join(""),systemParts:E,tools:[...b,...e.tools.snapshot()],cwd:u}}var kK=[hu(".basalt","AGENTS.md"),hu(".agents","AGENTS.md"),hu(".opencode","AGENTS.md"),hu(".claude","CLAUDE.md"),hu(".codex","AGENTS.md")];function AK(e){let o=e.options.homeDir??RK();for(let i of kK){let u=hu(o,i);try{if(wK(u))return TK(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 gg(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new jl($g(e.dataDir,"basalt.db")),this.plugins=new Qh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Bl(this.plugins,()=>this.builtinToolNames()),this.search=new Xh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(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??[$g(this.options.dataDir,"plugins"),...this.projects().map((e)=>$g(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 Y$(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{...Ul(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>Q$(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((i)=>e||i.info().parentID===null).map((i)=>i.info()).filter((i)=>{let u=o.archive??"active";return u==="all"||i.archivedAt!==null===(u==="archived")}).sort((i,u)=>u.updated-i.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let i=this.get(e);if(!i)throw new t("History session is unavailable");return i.resolveHistory(o)}openStoredSession(e,o="restore"){let i=this.open(e,o);return this.sessions.set(e.id,i),this.emit({type:"session",session:i.info()}),i}create(e={}){let o=e.model??this.defaultModel;if(!En(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let i=Date.now(),u={id:ne("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:i,updated:i,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let p=this.open(u);return this.sessions.set(u.id,p),this.emit({type:"session",session:p.info()}),p}copyHistory(e,o,i){o={...o,archivedAt:null},this.store.copySession(e,o,i);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new f("no such session");let i=o.info(),u=i.projectID?this.store.project(i.projectID):void 0;return _$(i,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let i=[o.model,e.model,this.defaultModel].find((y)=>y!==void 0&&En(this.options.models,y)!==void 0),u=i?En(this.options.models,i):void 0;if(!i||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let p={id:ne("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:i,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(p,e.needsRaw?D$(e.records,u):e.records);let g=this.open(p);return this.sessions.set(p.id,g),this.emit({type:"session",session:g.info()}),g}truncateHistory(e,o){let i=this.sessions.get(e.id);if(!i)throw new f("no such session");if(i.assertWritable(),i.status==="busy")throw new ie;if(!En(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);i.close();for(let y of this.sessions.values()){if(y.info().parentID!==e.id)continue;if(y.status==="busy")y.abort();y.close()}this.store.truncateSession(e,o);let u=[],p=this.store.lastEntry(e.id,"run");if(p?.type==="run"&&p.state==="start"){let y=this.store.records(e.id,p.seq).filter((b)=>b.raw);for(let b of To(y)){if(b.result)continue;let{body:E,raw:S}=cl(b.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,E,S))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let g=this.open(e,"replay");this.sessions.set(e.id,g),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let y of u)this.emit({type:"entry",sessionID:e.id,entry:y});return g}setArchived(e,o){let i=this.sessions.get(e);if(!i)throw new f("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 p=this.sessionTree(i);if(p.some((g)=>g.status==="busy"))throw new ie;if(i.isArchived===o)return i.info();this.store.setArchived(p.map((g)=>g.id),o?Date.now():null);for(let g of p)g.refreshArchive();for(let g of p)g.archiveChanged();return i.info()}sessionTree(e){let o=[e];for(let i=0;i<o.length;i++){let u=o[i];if(!u)continue;for(let p of this.sessions.values())if(p.info().parentID===u.id)o.push(p)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new f("no such session");if(o.status==="busy")throw new ie;let i=this.sessionTree(o).slice(1),u=()=>{for(let p of i)p.close(),this.plugins.notify("session.delete",p),this.sessions.delete(p.id),this.emit({type:"removed",kind:"session",id:p.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!i.length)return u();o.close();for(let p of i)p.close(),p.abort();return Promise.all(i.map((p)=>p.idle())).then(u)}open(e,o="create"){let i=e.id,u=new _l(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(p)=>Tv(this,p)},{entry:(p)=>{this.emit({type:"entry",sessionID:i,entry:p})},entryRemoved:(p)=>{this.emit({type:"entry_removed",sessionID:i,seq:p})},aborted:()=>{this.emit({type:"aborted",sessionID:i})},draft:(p)=>this.emit({type:"draft",sessionID:i,parts:p}),changed:()=>{let p=this.sessions.get(i);if(p)this.emit({type:"session",session:p.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new qi(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!Ql.includes(e))throw new t(`Invalid shell type; must be ${Ql.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return Z$(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(i){console.error("runtime listener failed",i)}}}var Ce={now:()=>Date.now(),after(e,o){let i=setTimeout(o,e);return()=>clearTimeout(i)}};var Rv=1048576,kv=8;class Wt{cwd;outputLimit;terminal;shellPreference;jobs=new Map;closed=!1;constructor(e,o=30000,i,u){this.cwd=e;this.outputLimit=o;this.terminal=i;this.shellPreference=u}setTerminalObserver(e){this.terminal=e}start(e,o,i){let u=i?.observer,p=i?.clock??Ce;if(this.closed)throw Error("\u540E\u53F0\u4EFB\u52A1\u6CE8\u518C\u8868\u5DF2\u5173\u95ED");if(!i?.shellGuardApproved){let X=od(e);if(X.length>0)throw Error(sd(X))}if(this.list().filter((X)=>X.state==="running").length>=kv)throw Error(`\u540E\u53F0\u4EFB\u52A1\u5E76\u53D1\u6570\u5DF2\u8FBE\u4E0A\u9650\uFF08${kv}\uFF09`);let y=typeof this.shellPreference==="function"?this.shellPreference():this.shellPreference,{argv:b,isWindows:E}=Ea(e,y),S=Bun.spawn(b,{cwd:this.cwd,stdin:i?.stdin?"pipe":"ignore",stdout:"pipe",stderr:"pipe",detached:!E,windowsHide:!0,env:{...process.env,...em(this.cwd)}}),w={id:`j${crypto.randomUUID()}`,command:e,cwd:this.cwd,proc:S,started:p.now(),state:"running",code:null,output:"",readAt:0,dropped:0,unreadDroppedBytes:0,done:Promise.resolve(),waiters:[]};this.jobs.set(w.id,w);let R=()=>{for(let X of w.waiters.splice(0))X()},A=async(X,j)=>{let V=new Rl;for await(let ee of X){let ae=V.decode(ee);w.output+=ae,u?.output(ae,j);let H=Buffer.from(w.output);if(H.length>Rv){let ue=H.length-Rv;while(ue<H.length&&(H[ue]??0)>>6===2)ue++;let he=H.subarray(ue).toString(),$e=w.output.length-he.length;w.unreadDroppedBytes+=Buffer.byteLength(w.output.slice(Math.max(0,w.readAt-w.dropped),$e)),w.output=he,w.dropped+=$e}R()}let J=V.flush();if(w.output+=J,J)u?.output(J,j)},P,C=Promise.all([A(S.stdout,"stdout"),A(S.stderr,"stderr")]).catch((X)=>{P=X,this.kill(w)}),q=!1;if(w.done=(async()=>{if(w.code=await S.exited,w.timer?.(),this.kill(w),await C,P)throw P;if(w.state==="running")w.state="exited";if(q=!0,u?.end(w.state,w.code),!u&&w.state!=="killed")this.terminal?.(w);R()})().catch((X)=>{if(w.state="exited",w.output+=`
477
- [\u540E\u53F0\u4EFB\u52A1\u5904\u7406\u5931\u8D25: ${String(X)}]`,!q)u?.end(w.state,w.code);if(u)throw X;if(!u)this.terminal?.(w,X);R()}),o!==void 0)w.timer=p.after(o,()=>{if(w.state==="running")w.state="timeout",this.kill(w)});return w}find(e){let o=this.jobs.get(e);if(!o)throw Error(`\u540E\u53F0\u4EFB\u52A1\u4E0D\u5B58\u5728: ${e}`);return o}kill(e){try{if(process.platform==="win32"){let o=Bun.spawnSync(["taskkill","/PID",String(e.proc.pid),"/T","/F"],{windowsHide:!0});if(o.exitCode!==0&&o.exitCode!==128&&e.proc.exitCode===null)throw Error("\u65E0\u6CD5\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B\u6811\uFF0C\u8BF7\u68C0\u67E5\u8FDB\u7A0B\u6743\u9650")}else process.kill(-e.proc.pid,"SIGKILL")}catch(o){if(!(o instanceof Error&&("code"in o)&&o.code==="ESRCH"))throw o}}list(){return[...this.jobs.values()].map((e)=>({id:e.id,command:e.command,state:e.state,code:e.code,started:e.started}))}async read(e,o,i=0,u=!1,p){let g=this.find(e),y=o?new RegExp(o):void 0,b=Date.now()+i;p?.throwIfAborted();while(g.state==="running"){p?.throwIfAborted();let A=g.output.slice(Math.max(0,g.readAt-g.dropped));if((y?y.test(A):!u)||Date.now()>=b)break;await new Promise((P,C)=>{let q=()=>{clearTimeout(j);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);C(p?.reason)},X=()=>{clearTimeout(j),p?.removeEventListener("abort",q);let V=g.waiters.indexOf(X);if(V>=0)g.waiters.splice(V,1);P()},j=setTimeout(X,Math.max(0,b-Date.now()));g.waiters.push(X),p?.addEventListener("abort",q,{once:!0})})}p?.throwIfAborted();let E=g.unreadDroppedBytes;g.unreadDroppedBytes=0;let S=g.output.slice(Math.max(0,g.readAt-g.dropped));g.readAt=g.dropped+g.output.length;let w=S.slice(-this.outputLimit),R=E+Buffer.byteLength(S.slice(0,S.length-w.length));return{job:g,output:`${R?`[truncated ${R} bytes]
478
- `:""}${w}`}}async write(e,o,i=!1,u){let p=this.find(e);if(p.state!=="running")throw Error(`\u540E\u53F0\u4EFB\u52A1\u5DF2\u7ED3\u675F: ${e}`);let g=p.proc.stdin;if(!g||typeof g==="number")throw Error(`\u540E\u53F0\u4EFB\u52A1\u672A\u5F00\u653E stdin: ${e}`);if(o){let y=await je(o,u);if(y)throw Error(y);g.write(o)}if(i)await g.end();else await g.flush()}async stop(e){let o=this.find(e);if(o.state==="running")o.state="killed",this.kill(o);return await o.done,{id:o.id,state:o.state,code:o.code}}async idle(){await Promise.all([...this.jobs.values()].map((e)=>e.done))}close(){this.closed=!0;for(let e of this.jobs.values())if(e.state==="running")e.state="killed",this.kill(e)}}var zl=new WeakMap,Vl=new WeakMap;function sr(e,o){let i=zl.get(e);if(!i)i=o(),zl.set(e,i);return i}function ar(e){Vl.set(e,(Vl.get(e)??0)+1)}function lr(e,o){let i=(Vl.get(o)??1)-1;if(Vl.set(o,i),i>0)return!1;if(o.close(),zl.get(e)===o)zl.delete(e);return!0}async function N(e){let o=await e.json();if(!o||typeof o!=="object"||Array.isArray(o))throw new t("expected a JSON object");return o}function v(e,o){let i=e[o];if(!i)throw new t(`${o} is required`);return i}var Dn=100,cr=1e4,PK=60000,CK=200,kn=()=>a(),Av=()=>n(_({minimum:1,maximum:cr})),Jc=()=>n(a({minLength:1,maxLength:128})),$K=m([l({click:m([kn(),l({selector:kn()})])}),l({type:l({label:kn(),text:kn()})}),l({waitText:kn(),timeoutMs:Av()}),l({expectText:kn(),within:n(kn())}),l({waitSelector:kn(),timeoutMs:Av()}),l({expectCount:l({selector:kn(),n:_({minimum:0})})}),l({snapshot:l({selector:kn(),depth:n(_({minimum:0,maximum:CK}))})}),l({expectCalls:l({onOpen:n(B(kn())),onClose:n(_({minimum:0}))})}),l({expectValue:l({label:kn(),value:kn()})})]),vK=l({status:_({minimum:100,maximum:599}),body:Rr(),delayMs:n(_({minimum:0,maximum:cr}))}),MK=m([s("paths"),s("request"),s("verify"),s("ui_test"),s("list"),s("docs"),s("check"),s("load"),s("reload"),s("enable"),s("disable")]),OK=m([s("page"),s("tab"),s("card"),s("sidebar")]),gi=l({action:MK,path:n(a({minLength:1,maxLength:4096})),method:n(kn()),body:n(bs(kn(),Rr())),importTimeoutMs:n(_({minimum:1,maximum:cr})),timeoutMs:n(_({minimum:1,maximum:PK})),sessionID:Jc(),scope:n(m([s("user"),s("all")])),id:Jc(),slot:Jc(),view:Jc(),codeBlock:Jc(),kind:n(OK),props:n(bs(kn(),Rr())),context:n(bs(kn(),Rr())),steps:n(B($K,{maxItems:Dn})),mockRoutes:n(bs(kn(),vK)),topic:n(a({maxLength:100})),grep:n(a({minLength:1,maxLength:200}))});
479
- export{t,f,Fr,Wr,li,$r,er,Io,Ln,ci,ui,pi,Bt,di,mi,Hr,Mo,hi,Be,fi,ut,Ft,z,Lo,je,et,B,n,l,qr,O,_,s,Y,a,m,h,le,On,Oo,No,Do,Uo,_e,x,tt,pt,k,D,F,Re,ce,Te,c,de,rt,tr,rr,nr,dt,ie,Bo,or,ir,ne,Nn,Gr,Fo,zr,Ce,Wt,sr,ar,lr,N,v,Wo,Dn,cr,gi};